context-doctor 0.47.0 → 0.49.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 (84) hide show
  1. package/README.md +17 -14
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +68 -26
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/budget.d.ts +5 -2
  9. package/dist/budget.js +21 -7
  10. package/dist/cache.js +3 -3
  11. package/dist/cachemisses.d.ts +3 -0
  12. package/dist/cachemisses.js +8 -0
  13. package/dist/cachettl.js +6 -2
  14. package/dist/ccost.d.ts +160 -0
  15. package/dist/ccost.js +304 -0
  16. package/dist/cli.js +154 -32
  17. package/dist/cline.d.ts +41 -0
  18. package/dist/cline.js +174 -0
  19. package/dist/coldresume.d.ts +11 -0
  20. package/dist/coldresume.js +3 -3
  21. package/dist/coldreturns.d.ts +145 -0
  22. package/dist/coldreturns.js +282 -0
  23. package/dist/compactcost.d.ts +10 -4
  24. package/dist/compactcost.js +12 -7
  25. package/dist/compactwindow.js +2 -2
  26. package/dist/copilotusage.d.ts +78 -0
  27. package/dist/copilotusage.js +193 -0
  28. package/dist/doctor.d.ts +6 -0
  29. package/dist/doctor.js +17 -4
  30. package/dist/fix.d.ts +35 -4
  31. package/dist/fix.js +55 -8
  32. package/dist/install.js +2 -0
  33. package/dist/limits.d.ts +222 -14
  34. package/dist/limits.js +684 -33
  35. package/dist/mcp.d.ts +4 -0
  36. package/dist/mcp.js +142 -98
  37. package/dist/mcpclient.js +73 -42
  38. package/dist/mcpdefer.d.ts +47 -0
  39. package/dist/mcpdefer.js +91 -0
  40. package/dist/mod/api.d.ts +72 -2
  41. package/dist/mod/api.js +5 -1
  42. package/dist/mod/logic.d.ts +281 -0
  43. package/dist/mod/logic.js +336 -0
  44. package/dist/mod/register.d.ts +35 -2
  45. package/dist/mod/register.js +283 -6
  46. package/dist/modelids.d.ts +58 -0
  47. package/dist/modelids.js +133 -1
  48. package/dist/modmeasure.d.ts +6 -4
  49. package/dist/modmeasure.js +8 -4
  50. package/dist/opencode.d.ts +57 -0
  51. package/dist/opencode.js +234 -0
  52. package/dist/orgrates.d.ts +7 -0
  53. package/dist/orgrates.js +19 -0
  54. package/dist/overhead.d.ts +3 -0
  55. package/dist/overhead.js +5 -1
  56. package/dist/pricing.d.ts +59 -2
  57. package/dist/pricing.js +139 -12
  58. package/dist/proxy.d.ts +8 -1
  59. package/dist/proxy.js +13 -1
  60. package/dist/savings.d.ts +5 -1
  61. package/dist/savings.js +11 -5
  62. package/dist/scan.d.ts +3 -1
  63. package/dist/scan.js +8 -1
  64. package/dist/sessionprice.d.ts +5 -0
  65. package/dist/sessionprice.js +5 -1
  66. package/dist/spend.d.ts +86 -3
  67. package/dist/spend.js +240 -23
  68. package/dist/spendplace.d.ts +40 -0
  69. package/dist/spendplace.js +93 -0
  70. package/dist/spendteam.d.ts +160 -0
  71. package/dist/spendteam.js +286 -0
  72. package/dist/starts.d.ts +106 -0
  73. package/dist/starts.js +406 -0
  74. package/dist/statusline.d.ts +2 -2
  75. package/dist/statusline.js +2 -2
  76. package/dist/subagentmodel.js +9 -7
  77. package/dist/subagentpay.d.ts +31 -2
  78. package/dist/subagentpay.js +232 -68
  79. package/dist/subagents.js +3 -3
  80. package/dist/tasks.js +3 -2
  81. package/dist/tooloutput.js +5 -5
  82. package/dist/usagepane.d.ts +77 -0
  83. package/dist/usagepane.js +287 -0
  84. package/package.json +6 -3
package/dist/spend.js CHANGED
@@ -47,20 +47,25 @@ import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, ro
47
47
  import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV } from "./progresssummaries.js";
48
48
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
49
49
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
50
- import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
50
+ import { copilotCalls } from "./copilotusage.js";
51
+ import { CLAUDE_PLACE_ROWS, placeAt, repoName } from "./spendplace.js";
52
+ import { opencodeCalls } from "./opencode.js";
53
+ import { clineCalls } from "./cline.js";
54
+ import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, priceEndWord, requestCost } from "./pricing.js";
51
55
  import { managedSourcesLine, orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
56
+ import { compareSessions, renderComparison } from "./ccost.js";
52
57
  /**
53
58
  * What spend's dollars are: each request as it was billed (its tier, fast mode,
54
59
  * US-only, web searches) at list rates, or at the organization's rates.
55
60
  * "At list prices" was true before those were priced; it no longer is.
56
61
  */
57
- const spendBasis = () => (orgRates() ? priceBasis() : "as billed at list rates");
62
+ export const spendBasis = () => (orgRates() ? priceBasis() : "as billed at list rates");
58
63
  import { pick, prescan, rowsOf } from "./scan.js";
59
64
  import { formatTokens } from "./tokens.js";
60
65
  import { withInvocation } from "./invocation.js";
61
66
  const DAY = 86_400_000;
62
- export const TOOLS = ["claude", "codex", "gemini", "cursor"];
63
- export const TOOL_NAME = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", cursor: "Cursor" };
67
+ export const TOOLS = ["claude", "codex", "gemini", "cursor", "copilot", "opencode", "cline"];
68
+ export const TOOL_NAME = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", cursor: "Cursor", copilot: "Copilot CLI", opencode: "OpenCode", cline: "Cline" };
64
69
  /**
65
70
  * A project folder's name (its path with "-" for separators, as Claude Code
66
71
  * names its projects/ folders) less the home folder: "-Users-<you>-" on
@@ -91,6 +96,15 @@ function label(item, c) {
91
96
  item.modifiers = c.modifiers;
92
97
  return item;
93
98
  }
99
+ /** `a` less `b`, part by part. */
100
+ function minus(a, b) {
101
+ a.fastUsd -= b.fastUsd;
102
+ a.geoUsd -= b.geoUsd;
103
+ a.longUsd -= b.longUsd;
104
+ a.webSearchUsd -= b.webSearchUsd;
105
+ a.webSearches -= b.webSearches;
106
+ return a;
107
+ }
94
108
  /** `priceAs`: the id to price it by, when the model's own name is not one the table knows (Cursor's names for Claude). */
95
109
  function priced(base, u, priceAs = base.model) {
96
110
  const c = requestCost(priceAs, u, base.ts);
@@ -105,7 +119,7 @@ function priced(base, u, priceAs = base.model) {
105
119
  * Claude Code's requests between `since` and `until`, main threads and
106
120
  * subagents, over `tops` (default: every transcript written since `since`).
107
121
  */
108
- export function claudeSpend(since, until = Infinity, tops, onProgress) {
122
+ export function claudeSpend(since, until = Infinity, tops, onProgress, place = false) {
109
123
  const out = [];
110
124
  const runRows = new Set();
111
125
  const files = claudeUsageFiles(since, tops);
@@ -120,16 +134,26 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
120
134
  }
121
135
  const project = claudeProject(f.top);
122
136
  const session = basename(f.top, ".jsonl");
137
+ // Where each request ran (`--by repo`, `--by branch`): the transcript's folder and branch at the time.
138
+ let places = [];
139
+ if (place)
140
+ try {
141
+ places = rowsOf(f.file, CLAUDE_PLACE_ROWS);
142
+ }
143
+ catch { /* none */ }
123
144
  for (const r of reqs) {
124
145
  const price = r.rates;
146
+ // The iterations its top-level usage leaves out are items of their own, each on its own model: the request's item is the rest.
147
+ const extra = r.extra ?? [];
148
+ const own = { usd: r.usd - extra.reduce((n, x) => n + x.usd, 0), promptUsd: r.promptUsd - extra.reduce((n, x) => n + x.promptUsd, 0), webSearchUsd: r.modifiers.webSearchUsd - extra.reduce((n, x) => n + x.modifiers.webSearchUsd, 0) };
125
149
  // claudeFileUsage priced it (requestCost: writes by TTL, its modifiers); the split is what the drivers show.
126
150
  const inputUsd = price ? (r.input * price.inputPerM) / 1e6 : 0;
127
151
  const readUsd = price ? (r.read * price.cacheReadPerM) / 1e6 : 0;
128
152
  const item = {
129
153
  tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
130
- usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd - r.modifiers.webSearchUsd), priced: Boolean(price),
154
+ usd: own.usd, inputUsd, readUsd, writeUsd: Math.max(0, own.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, own.usd - own.promptUsd - own.webSearchUsd), priced: Boolean(price),
131
155
  };
132
- label(item, r);
156
+ label(item, { estimated: r.estimated, changedOn: r.changedOn, modifiers: extra.reduce((m, x) => minus(m, x.modifiers), { ...r.modifiers }) });
133
157
  if (r.compaction)
134
158
  item.compaction = true;
135
159
  if (r.model)
@@ -140,7 +164,41 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
140
164
  item.subagent = true;
141
165
  if (r.uuid)
142
166
  item.key = r.uuid;
167
+ if (places.length) {
168
+ const at = placeAt(places, r.ts);
169
+ if (at.cwd)
170
+ item.cwd = at.cwd;
171
+ if (at.branch)
172
+ item.branch = at.branch;
173
+ }
143
174
  out.push(item);
175
+ for (const [j, x] of extra.entries()) {
176
+ const xi = {
177
+ tool: "claude", ts: r.ts, project, session, input: x.input, read: x.read, write: x.write, output: x.output,
178
+ usd: x.usd, inputUsd: 0, readUsd: 0, writeUsd: 0, outputUsd: 0, priced: x.priced, iteration: x.type,
179
+ };
180
+ const c = x.priced ? requestCost(x.model, { input_tokens: x.input, cache_read_input_tokens: x.read, cache_creation_input_tokens: x.write, output_tokens: x.output }, r.ts) : undefined;
181
+ if (c) {
182
+ xi.inputUsd = c.inputUsd;
183
+ xi.readUsd = c.readUsd;
184
+ xi.outputUsd = c.outputUsd;
185
+ xi.writeUsd = Math.max(0, x.promptUsd - c.inputUsd - c.readUsd);
186
+ }
187
+ label(xi, x);
188
+ if (x.model)
189
+ xi.model = x.model;
190
+ if (item.workflow)
191
+ xi.workflow = item.workflow;
192
+ else if (item.subagent)
193
+ xi.subagent = true;
194
+ if (item.cwd)
195
+ xi.cwd = item.cwd;
196
+ if (item.branch)
197
+ xi.branch = item.branch;
198
+ if (r.uuid)
199
+ xi.key = `${r.uuid}#${j + 1}`;
200
+ out.push(xi);
201
+ }
144
202
  }
145
203
  }
146
204
  onProgress?.(files.length, files.length);
@@ -167,7 +225,7 @@ function spawnedBy(p) {
167
225
  * every token_count event's last request and running total.
168
226
  */
169
227
  export const CODEX_SPEND_ROWS = {
170
- id: "codex-spend.3",
228
+ id: "codex-spend.4",
171
229
  init: () => ({}),
172
230
  line(line, row, out, st) {
173
231
  if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
@@ -187,6 +245,8 @@ export const CODEX_SPEND_ROWS = {
187
245
  const parent = spawnedBy(p);
188
246
  if (typeof p.id === "string")
189
247
  out.push({ k: "meta", id: p.id, ...(parent ? { parent } : {}) });
248
+ if (typeof p.git?.branch === "string" && p.git.branch)
249
+ out.push({ k: "branch", branch: p.git.branch });
190
250
  }
191
251
  if (e.type === "session_meta" || e.type === "turn_context") {
192
252
  if (typeof p.cwd === "string")
@@ -208,11 +268,15 @@ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0
208
268
  /** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
209
269
  export function codexFileSpend(file, since, until = Infinity) {
210
270
  const out = [];
211
- let model, cwd;
271
+ let model, cwd, branch;
212
272
  let total = -1;
213
273
  for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
214
274
  if (r.k === "meta")
215
275
  continue;
276
+ if (r.k === "branch") {
277
+ branch = branch ?? r.branch;
278
+ continue;
279
+ }
216
280
  if (r.k === "cwd") {
217
281
  cwd = cwd ?? r.cwd;
218
282
  continue;
@@ -230,7 +294,7 @@ export function codexFileSpend(file, since, until = Infinity) {
230
294
  if (!Number.isFinite(ts) || ts < since || ts > until || isUnbilledModel(model))
231
295
  continue;
232
296
  const u = openAIUsage(r.u);
233
- out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { model } : {}), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), ...(r.key ? { key: r.key } : {}) }, u));
297
+ out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { model } : {}), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), ...(r.key ? { key: r.key } : {}), ...(cwd ? { cwd } : {}), ...(branch ? { branch } : {}) }, u));
234
298
  }
235
299
  return out;
236
300
  }
@@ -496,10 +560,52 @@ export function cursorSpend(since, until = Infinity) {
496
560
  // No cache split: every input token at the uncached rate. Cursor's own
497
561
  // names for Claude ("claude-4.6-opus-high-thinking") are priced as the
498
562
  // Claude id they stand for, shown as Cursor wrote them.
499
- out.push(priced({ tool: "cursor", ts: r.ts, project: r.folder ? projectName(r.folder) : "(no folder)", session: r.composerId, ...(r.model ? { model: r.model } : {}), input: r.input, read: 0, write: 0, output: r.output }, { input_tokens: r.input, output_tokens: r.output }, cursorClaudeId(r.model) ?? r.model));
563
+ out.push(priced({ tool: "cursor", ts: r.ts, project: r.folder ? projectName(r.folder) : "(no folder)", session: r.composerId, ...(r.model ? { model: r.model } : {}), input: r.input, read: 0, write: 0, output: r.output, ...(r.folder ? { cwd: r.folder } : {}) }, { input_tokens: r.input, output_tokens: r.output }, cursorClaudeId(r.model) ?? r.model));
500
564
  }
501
565
  return out;
502
566
  }
567
+ // ---------------------------------------------------------------------------
568
+ // Copilot CLI
569
+ // ---------------------------------------------------------------------------
570
+ /**
571
+ * Copilot CLI's model calls (copilotusage.ts), each priced at its model's
572
+ * list price where the table has one, else counted. What Copilot bills is
573
+ * its AI credits and premium requests, kept beside the price, not in it.
574
+ */
575
+ export function copilotSpend(since, until = Infinity, home = homedir()) {
576
+ return copilotCalls(since, until, home).filter((c) => !isUnbilledModel(c.model)).map((c) => {
577
+ const it = priced({ tool: "copilot", ts: c.ts, project: c.cwd ?? c.gitRoot ? projectName((c.cwd ?? c.gitRoot)) : "copilot", session: c.session, model: c.model, input: c.input, read: c.read, write: c.write, output: c.output }, { input_tokens: c.input, cache_read_input_tokens: c.read, cache_creation_input_tokens: c.write, output_tokens: c.output });
578
+ if (c.credits !== undefined)
579
+ it.credits = c.credits;
580
+ if (c.premium !== undefined)
581
+ it.premium = c.premium;
582
+ if (c.cwd)
583
+ it.cwd = c.cwd;
584
+ if (c.gitRoot)
585
+ it.root = c.gitRoot;
586
+ if (c.branch)
587
+ it.branch = c.branch;
588
+ return it;
589
+ });
590
+ }
591
+ // ---------------------------------------------------------------------------
592
+ // OpenCode and Cline
593
+ // ---------------------------------------------------------------------------
594
+ /** A call's tokens as recorded usage: input uncached, cache reads and writes apart. */
595
+ const asUsage = (c) => ({ input_tokens: c.input, cache_read_input_tokens: c.read, cache_creation_input_tokens: c.write, output_tokens: c.output });
596
+ /** OpenCode's model calls (opencode.ts), each at its model's list price. Throws SqliteUnavailableError when its database cannot be read here. */
597
+ export function opencodeSpend(since, until = Infinity, home = homedir()) {
598
+ const { calls, sqlite } = opencodeCalls(since, until, home);
599
+ // A compaction is a measured request here (its own tokens), not Claude Code's estimate: no `compaction` mark.
600
+ const items = calls.filter((c) => !isUnbilledModel(c.model)).map((c) => priced({ tool: "opencode", ts: c.ts, project: c.cwd ? projectName(c.cwd) : "opencode", session: c.session, ...(c.model ? { model: c.model } : {}), input: c.input, read: c.read, write: c.write, output: c.output, key: c.id, ...(c.cwd ? { cwd: c.cwd } : {}), ...(c.root ? { root: c.root } : {}) }, asUsage(c)));
601
+ if (!sqlite)
602
+ throw Object.assign(new SqliteUnavailableError("reading OpenCode's opencode.db needs SQLite: Node 22.13+ or the sqlite3 command"), { items });
603
+ return items;
604
+ }
605
+ /** Cline's requests (cline.ts), each at its model's list price; one with no model is counted, not priced. */
606
+ export function clineSpend(since, until = Infinity, home = homedir()) {
607
+ return clineCalls(since, until, home).filter((c) => !isUnbilledModel(c.model)).map((c) => priced({ tool: "cline", ts: c.ts, project: c.cwd ? projectName(c.cwd) : "cline", session: c.session, ...(c.model ? { model: c.model } : {}), input: c.input, read: c.read, write: c.write, output: c.output, ...(c.cwd ? { cwd: c.cwd } : {}) }, asUsage(c)));
608
+ }
503
609
  /** The local calendar day of `ts`, "YYYY-MM-DD". */
504
610
  export function localDay(ts) {
505
611
  const d = new Date(ts);
@@ -508,7 +614,8 @@ export function localDay(ts) {
508
614
  function add(map, key, it) {
509
615
  const r = map.get(key) ?? map.set(key, { usd: 0, requests: 0, byTool: {} }).get(key);
510
616
  r.usd += it.usd;
511
- r.requests++;
617
+ if (!it.iteration)
618
+ r.requests++;
512
619
  r.byTool[it.tool] = (r.byTool[it.tool] ?? 0) + it.usd;
513
620
  }
514
621
  /** "1 run", "12 runs": workflow runs. */
@@ -517,6 +624,8 @@ const runsText = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "run" : "runs"
517
624
  export function summarizeSpend(items, days, since, until, skipped = []) {
518
625
  const tools = new Map();
519
626
  const projects = new Map(), models = new Map(), daily = new Map();
627
+ const repos = new Map(), branches = new Map();
628
+ let byPlace = false, byBranch = false;
520
629
  const sessions = new Map();
521
630
  const sessionModels = new Map();
522
631
  const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
@@ -524,11 +633,19 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
524
633
  const mods = { ...NO_MODIFIERS };
525
634
  const changed = new Map();
526
635
  const compactions = { requests: 0, usd: 0 };
636
+ const iterations = {};
527
637
  for (const it of items) {
528
638
  if (it.compaction) {
529
639
  compactions.requests++;
530
640
  compactions.usd += it.usd;
531
641
  }
642
+ if (it.iteration) {
643
+ const x = (iterations[it.iteration] ??= { calls: 0, usd: 0, models: [] });
644
+ x.calls++;
645
+ x.usd += it.usd;
646
+ if (it.model && !x.models.includes(it.model))
647
+ x.models.push(it.model);
648
+ }
532
649
  if (it.modifiers)
533
650
  addModifiers(mods, it.modifiers);
534
651
  if (it.changedOn) {
@@ -539,13 +656,18 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
539
656
  }
540
657
  const t = tools.get(it.tool) ?? tools.set(it.tool, { tool: it.tool, name: TOOL_NAME[it.tool], usd: 0, requests: 0, tokens: { input: 0, read: 0, write: 0, output: 0 }, unpriced: 0, unpricedTokens: 0, unpricedModels: [], ...(it.tool === "cursor" ? { estimate: true } : {}), ...(it.tool === "claude" ? { subagentUsd: 0 } : {}) }).get(it.tool);
541
658
  t.usd += it.usd;
542
- t.requests++;
659
+ if (!it.iteration)
660
+ t.requests++;
543
661
  t.tokens.input += it.input;
544
662
  t.tokens.read += it.read;
545
663
  t.tokens.write += it.write;
546
664
  t.tokens.output += it.output;
547
665
  if (it.subagent)
548
666
  t.subagentUsd = (t.subagentUsd ?? 0) + it.usd;
667
+ if (it.credits !== undefined)
668
+ t.credits = (t.credits ?? 0) + it.credits;
669
+ if (it.premium !== undefined)
670
+ t.premium = (t.premium ?? 0) + it.premium;
549
671
  if (it.workflow) {
550
672
  t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
551
673
  runs.add(it.workflow);
@@ -567,6 +689,13 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
567
689
  e.models.push(m);
568
690
  }
569
691
  add(projects, it.project, it);
692
+ if (it.repo !== undefined) {
693
+ byPlace = true;
694
+ if (it.branch)
695
+ byBranch = true;
696
+ add(repos, it.repo, it);
697
+ add(branches, `${it.repo}\u0000${it.branch ?? ""}`, it);
698
+ }
570
699
  add(models, it.model ?? "unknown", it);
571
700
  add(daily, localDay(it.ts), it);
572
701
  parts.inputUsd += it.inputUsd;
@@ -576,7 +705,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
576
705
  const sk = `${it.tool}\u0000${it.session}`;
577
706
  const s = sessions.get(sk) ?? sessions.set(sk, { tool: it.tool, project: it.project, session: it.session, usd: 0, requests: 0, first: it.ts, last: it.ts }).get(sk);
578
707
  s.usd += it.usd;
579
- s.requests++;
708
+ if (!it.iteration)
709
+ s.requests++;
580
710
  s.first = Math.min(s.first, it.ts);
581
711
  s.last = Math.max(s.last, it.ts);
582
712
  if (it.model) {
@@ -600,15 +730,20 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
600
730
  return {
601
731
  days, since, until,
602
732
  usd: items.reduce((n, it) => n + it.usd, 0),
603
- requests: items.length,
733
+ requests: items.filter((it) => !it.iteration).length,
604
734
  tools: TOOLS.filter((t) => tools.has(t)).map((t) => tools.get(t)).sort(byUsd),
605
735
  projects: [...projects].map(([project, r]) => ({ project, ...r })).sort(byUsd),
736
+ ...(byPlace ? {
737
+ repos: [...repos].map(([repo, r]) => ({ repo, ...r })).sort(byUsd),
738
+ ...(byBranch ? { branches: [...branches].map(([k, r]) => { const [repo, branch] = k.split("\u0000"); return { repo, ...(branch ? { branch } : {}), ...r }; }).sort(byUsd) } : {}),
739
+ } : {}),
606
740
  models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
607
741
  daily: days_,
608
742
  parts,
609
743
  ...(anyModifier(mods) ? { modifiers: mods } : {}),
610
744
  ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
611
745
  ...(compactions.requests ? { compactions } : {}),
746
+ ...(Object.keys(iterations).length ? { iterations } : {}),
612
747
  sessions: [...sessions.values()].sort(byUsd),
613
748
  skipped,
614
749
  };
@@ -627,16 +762,50 @@ function claudeProgressSummaries(since, until, tops, o) {
627
762
  * --json died on a string too long), and 1e9 days fell off the calendar.
628
763
  */
629
764
  export const MAX_SPEND_DAYS = 3650;
630
- /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
631
- export function spendReport(days = 30, opts = {}) {
765
+ /**
766
+ * One Claude Code session's comparison with Claude Code's own figure (ccost.ts):
767
+ * its transcript and its subagents', to its last `cost-state`. Undefined when
768
+ * it has none, or cannot be read.
769
+ */
770
+ export function claudeCodeSession(top) {
771
+ try {
772
+ return compareSessions([top], claudeSpend(0, Infinity, [top]))[0];
773
+ }
774
+ catch {
775
+ return undefined;
776
+ }
777
+ }
778
+ /**
779
+ * A session's requests priced past the day their model's price ended or
780
+ * changed, said as `spend` says it: which price, and the one used instead.
781
+ * Undefined when none (or the transcript cannot be read).
782
+ */
783
+ export function sessionPriceEnded(top) {
784
+ try {
785
+ const items = claudeSpend(0, Infinity, [top]).filter((it) => it.changedOn);
786
+ if (!items.length)
787
+ return undefined;
788
+ const n = items.length;
789
+ return `${n.toLocaleString("en-US")} ${n === 1 ? "request" : "requests"} (${usd(items.reduce((s, it) => s + it.usd, 0))}) priced past the day ${n === 1 ? "its" : "their"} model's price ended or changed: ${priceChangedText(items.map((it) => [it.model ?? "unknown", it.changedOn]))}.`;
790
+ }
791
+ catch {
792
+ return undefined;
793
+ }
794
+ }
795
+ /** Every request of the last `days` days, every tool on this machine, and what could not be read. */
796
+ export function collectSpend(days = 30, opts = {}) {
632
797
  days = Math.min(days, MAX_SPEND_DAYS);
633
798
  const until = opts.now ?? Date.now();
634
799
  const since = until - days * DAY;
635
800
  const home = opts.home ?? homedir();
801
+ const place = opts.by === "repo" || opts.by === "branch";
636
802
  // A subagent's transcript read once for its usage and its timeline (the progress summaries).
637
803
  if (opts.progress !== false)
638
804
  prescan([{ paths: claudeUsageFiles(since, opts.claudePaths).filter((f) => f.subagent && !f.run).map((f) => f.file), extractors: [USAGE_ROWS, PROGRESS_ROWS] }]);
639
- const items = [...claudeSpend(since, until, opts.claudePaths, opts.onProgress), ...codexSpend(since, until, home), ...geminiSpend(since, until, home)];
805
+ // Grouped by where it ran: each transcript read once for its usage and its places.
806
+ if (place)
807
+ prescan([{ paths: claudeUsageFiles(since, opts.claudePaths).map((f) => f.file), extractors: [USAGE_ROWS, CLAUDE_PLACE_ROWS] }]);
808
+ const items = [...claudeSpend(since, until, opts.claudePaths, opts.onProgress, place), ...codexSpend(since, until, home), ...geminiSpend(since, until, home), ...copilotSpend(since, until, home)];
640
809
  const skipped = [];
641
810
  try {
642
811
  items.push(...cursorSpend(since, until));
@@ -645,13 +814,43 @@ export function spendReport(days = 30, opts = {}) {
645
814
  if (e instanceof SqliteUnavailableError)
646
815
  skipped.push({ tool: "cursor", reason: "reading Cursor's history needs SQLite: Node 22.13+ or the sqlite3 command" });
647
816
  }
817
+ try {
818
+ items.push(...opencodeSpend(since, until, home));
819
+ }
820
+ catch (e) {
821
+ // Its JSON files still count; its database needs SQLite.
822
+ items.push(...(e.items ?? []));
823
+ if (e instanceof SqliteUnavailableError)
824
+ skipped.push({ tool: "opencode", reason: "reading OpenCode's opencode.db needs SQLite: Node 22.13+ or the sqlite3 command" });
825
+ }
826
+ items.push(...clineSpend(since, until, home));
827
+ // A request's repository: its git root's or folder's (spendplace.ts), else its project as named here.
828
+ if (place)
829
+ for (const it of items) {
830
+ it.repo = it.root || it.cwd ? repoName((it.root ?? it.cwd), home) : it.project;
831
+ if (opts.by === "repo")
832
+ delete it.branch;
833
+ }
834
+ return { items, days, since, until, skipped };
835
+ }
836
+ /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
837
+ export function spendReport(days = 30, opts = {}) {
838
+ const { items, since, until, skipped, days: d } = collectSpend(days, opts);
839
+ days = d;
648
840
  const report = summarizeSpend(items, days, since, until, skipped);
841
+ // Claude Code's own figure beside ours, on the sessions wholly in the window that recorded one.
842
+ const tops = [...new Set(claudeUsageFiles(since, opts.claudePaths).filter((f) => !f.subagent).map((f) => f.top))];
843
+ const gaps = compareSessions(tops, items, since, until);
844
+ if (gaps.length)
845
+ report.claudeCode = { ccUsd: gaps.reduce((n, g) => n + g.ccUsd, 0), ourUsd: gaps.reduce((n, g) => n + g.ourUsd, 0), sessions: gaps };
649
846
  const progress = opts.progress === false ? undefined : claudeProgressSummaries(since, until, opts.claudePaths, opts.progress);
650
847
  return progress ? { ...report, progressSummaries: progress } : report;
651
848
  }
652
849
  // ---------------------------------------------------------------------------
653
850
  // Rendering
654
851
  // ---------------------------------------------------------------------------
852
+ /** What an iteration type is, in the report's words. */
853
+ const ITERATION_NAME = { advisor_message: ["advisor call", "advisor calls"], message: ["attempt a fallback model replaced", "attempts a fallback model replaced"], fallback_message: ["fallback attempt replaced again", "fallback attempts replaced again"], compaction: ["server-side compaction", "server-side compactions"] };
655
854
  export const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n > 0 && n < 0.005 ? "<$0.01" : `$${n.toFixed(2)}`);
656
855
  const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "");
657
856
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
@@ -666,11 +865,13 @@ export function modifiersText(m) {
666
865
  m.longUsd > 0 ? `long-prompt tier +${usd(m.longUsd)}` : "",
667
866
  ].filter(Boolean).join(", ");
668
867
  }
669
- /** The full report, kept within 80 columns. `top`: rows per list. */
868
+ /** AI credits or premium requests: whole above 100, else to two places. */
869
+ const creditsText = (n) => (n >= 100 ? Math.round(n).toLocaleString("en-US") : String(Math.round(n * 100) / 100));
870
+ /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
670
871
  export function renderSpend(r, top = 8) {
671
872
  const lines = [];
672
873
  if (r.requests === 0) {
673
- lines.push(`No usage in the last ${r.days} days from Claude Code, Codex, Gemini CLI or Cursor on this machine.`);
874
+ lines.push(`No usage in the last ${r.days} days from ${TOOLS.map((t) => TOOL_NAME[t]).join(", ").replace(/, ([^,]+)$/, " or $1")} on this machine.`);
674
875
  for (const s of r.skipped)
675
876
  lines.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
676
877
  return lines.join("\n");
@@ -686,7 +887,7 @@ export function renderSpend(r, top = 8) {
686
887
  lines.push("─".repeat(60));
687
888
  for (const t of r.tools) {
688
889
  const unit = t.tool === "cursor" ? "replies" : "requests";
689
- const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.workflowUsd ? `workflows ${usd(t.workflowUsd)} (${runsText(t.workflowRuns ?? 0)})` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
890
+ const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.credits !== undefined ? `${creditsText(t.credits)} AI credits` : "", t.workflowUsd ? `workflows ${usd(t.workflowUsd)} (${runsText(t.workflowRuns ?? 0)})` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
690
891
  const note = notes.length ? ` ${notes.join(", ")}` : "";
691
892
  lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
692
893
  }
@@ -700,14 +901,19 @@ export function renderSpend(r, top = 8) {
700
901
  lines.push(` … and ${more} more`);
701
902
  };
702
903
  const toolsOf = (byTool) => (r.tools.length > 1 ? TOOLS.filter((t) => (byTool[t] ?? 0) > 0).map((t) => TOOL_NAME[t]).join(", ") : undefined);
703
- list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
904
+ if (r.branches)
905
+ list("By branch", r.branches.slice(0, top).map((b) => ({ name: `${b.repo} ${b.branch ?? "(no branch)"}`, usd: b.usd, tail: toolsOf(b.byTool) })), r.branches.length - top);
906
+ else if (r.repos)
907
+ list("By repository", r.repos.slice(0, top).map((p) => ({ name: p.repo, usd: p.usd, tail: toolsOf(p.byTool) })), r.repos.length - top);
908
+ else
909
+ list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
704
910
  // A model with no list price reads "not priced", not a $0.00 that looks free.
705
911
  const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
706
912
  // One priced by its family's row reads as the estimate it is.
707
913
  const estimatedModels = new Set(r.tools.flatMap((t) => t.estimated?.models ?? []));
708
914
  // One priced past the day its price changed, likewise.
709
915
  const changedOn = new Map((r.priceChanged ?? []).map((c) => [c.model, c.on]));
710
- list("By model", r.models.slice(0, top).map((m) => ({ name: m.model, usd: m.usd, ...(m.usd === 0 && unpricedModels.has(m.model) ? { tail: `not priced, ${m.requests.toLocaleString("en-US")} ${m.requests === 1 ? "request" : "requests"}` } : estimatedModels.has(m.model) ? { tail: "estimate: its family's price" } : changedOn.has(m.model) ? { tail: `estimate: price changed ${changedOn.get(m.model)}` } : {}) })), r.models.length - top);
916
+ list("By model", r.models.slice(0, top).map((m) => ({ name: m.model, usd: m.usd, ...(m.usd === 0 && unpricedModels.has(m.model) ? { tail: `not priced, ${m.requests.toLocaleString("en-US")} ${m.requests === 1 ? "request" : "requests"}` } : estimatedModels.has(m.model) ? { tail: "estimate: its family's price" } : changedOn.has(m.model) ? { tail: `estimate: price ${priceEndWord(m.model)} ${changedOn.get(m.model)}` } : {}) })), r.models.length - top);
711
917
  // The last two weeks of the window, a bar each, scaled to the busiest.
712
918
  const recent = r.daily.slice(-14);
713
919
  const peak = Math.max(...recent.map((d) => d.usd), 0);
@@ -725,6 +931,9 @@ export function renderSpend(r, top = 8) {
725
931
  // A compaction's own request is in no row's usage: estimated from the context it read and the summary it wrote.
726
932
  if (r.compactions)
727
933
  lines.push(` Of it, ${r.compactions.requests.toLocaleString("en-US")} Claude Code ${r.compactions.requests === 1 ? "compaction's own request" : "compactions' own requests"} ${usd(r.compactions.usd)}, an estimate (no row records their usage)`);
934
+ // Calls inside a request that its usage totals leave out: the advisor's, an attempt a fallback replaced.
935
+ for (const [type, x] of Object.entries(r.iterations ?? {}))
936
+ lines.push(` Of it, ${x.calls.toLocaleString("en-US")} ${ITERATION_NAME[type]?.[x.calls === 1 ? 0 : 1] ?? `"${type}" iterations`} ${usd(x.usd)} (${x.models.slice(0, 2).join(", ")}), beyond their requests' usage totals`);
728
937
  const claude = r.tools.find((t) => t.tool === "claude");
729
938
  if (claude?.subagentUsd)
730
939
  lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
@@ -765,10 +974,18 @@ export function renderSpend(r, top = 8) {
765
974
  }
766
975
  if (r.tools.some((t) => t.estimate))
767
976
  notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
977
+ const copilot = r.tools.find((t) => t.tool === "copilot");
978
+ if (copilot) {
979
+ // What Copilot itself counts, beside the tokens at list price: its plan bills credits, not tokens.
980
+ const counted = [copilot.credits !== undefined ? `${creditsText(copilot.credits)} AI credits (${usd(copilot.credits / 100)} at $0.01)` : "", copilot.premium !== undefined ? `${creditsText(copilot.premium)} premium requests` : ""].filter(Boolean);
981
+ notes.push(`Copilot CLI: its tokens at list price${counted.length ? `; Copilot counted ${counted.join(" and ")}` : ""}.`);
982
+ }
768
983
  for (const s of r.skipped)
769
984
  notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
770
985
  if (notes.length)
771
986
  lines.push("", ...notes);
987
+ if (r.claudeCode)
988
+ lines.push("", ...renderComparison(r.claudeCode.sessions));
772
989
  lines.push("", "As an API key is billed; on a subscription the same tokens come out");
773
990
  lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
774
991
  return withInvocation(lines.map((l) => l.trimEnd()).join("\n"));
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Where a request ran, for `spend --by repo` and `--by branch`: the folder
3
+ * and the git branch each tool records, and the repository a folder is in.
4
+ *
5
+ * - Claude Code writes `cwd` and `gitBranch` on every row of a transcript;
6
+ * CLAUDE_PLACE_ROWS keeps each change, so a request takes the place in
7
+ * effect when it was made (a session that switched branch is split).
8
+ * - Codex: `session_meta`'s `cwd` and `git.branch` (CODEX_SPEND_ROWS).
9
+ * - Copilot CLI: `session.start`'s `context` (`cwd`, `gitRoot`, `branch`).
10
+ * - OpenCode: a message's `path` (`cwd`, `root`); Cline, Cursor: the folder.
11
+ *
12
+ * A folder's repository is the nearest folder above it holding `.git`, up to
13
+ * (not including) the home folder; a git worktree (`.git` a file naming
14
+ * `<repo>/.git/worktrees/<name>`) is its main repository, so Claude Code's
15
+ * agent worktrees count as the repository they were cut from. A folder gone
16
+ * from disk is walked up the same way (its parents may still be there). Its
17
+ * name is the folder's base name: what `spend --export` carries, never a path.
18
+ */
19
+ import type { Extractor } from "./scan.js";
20
+ /**
21
+ * What `spend --by` takes from a Claude Code transcript: each change of
22
+ * folder or branch, with the time of the row that made it. No text.
23
+ */
24
+ export declare const CLAUDE_PLACE_ROWS: Extractor<{
25
+ c?: string;
26
+ b?: string;
27
+ }>;
28
+ /** The place in effect at `ts` among a transcript's changes (oldest first): the last made at or before it, else the first. */
29
+ export declare function placeAt(changes: Array<{
30
+ ts: string;
31
+ c?: string;
32
+ b?: string;
33
+ }>, ts: number): {
34
+ cwd?: string;
35
+ branch?: string;
36
+ };
37
+ /** A folder's repository name (see above); the folder's own name when it is in none. "(home)" for the home folder itself. */
38
+ export declare function repoName(folder: string, home?: string): string;
39
+ /** Forget what repoName worked out (tests). */
40
+ export declare function clearRepoNames(): void;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Where a request ran, for `spend --by repo` and `--by branch`: the folder
3
+ * and the git branch each tool records, and the repository a folder is in.
4
+ *
5
+ * - Claude Code writes `cwd` and `gitBranch` on every row of a transcript;
6
+ * CLAUDE_PLACE_ROWS keeps each change, so a request takes the place in
7
+ * effect when it was made (a session that switched branch is split).
8
+ * - Codex: `session_meta`'s `cwd` and `git.branch` (CODEX_SPEND_ROWS).
9
+ * - Copilot CLI: `session.start`'s `context` (`cwd`, `gitRoot`, `branch`).
10
+ * - OpenCode: a message's `path` (`cwd`, `root`); Cline, Cursor: the folder.
11
+ *
12
+ * A folder's repository is the nearest folder above it holding `.git`, up to
13
+ * (not including) the home folder; a git worktree (`.git` a file naming
14
+ * `<repo>/.git/worktrees/<name>`) is its main repository, so Claude Code's
15
+ * agent worktrees count as the repository they were cut from. A folder gone
16
+ * from disk is walked up the same way (its parents may still be there). Its
17
+ * name is the folder's base name: what `spend --export` carries, never a path.
18
+ */
19
+ import { existsSync, readFileSync, statSync } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { basename, dirname, join, resolve } from "node:path";
22
+ /**
23
+ * What `spend --by` takes from a Claude Code transcript: each change of
24
+ * folder or branch, with the time of the row that made it. No text.
25
+ */
26
+ export const CLAUDE_PLACE_ROWS = {
27
+ id: "claude-place.1",
28
+ init: () => ({}),
29
+ line(line, row, out, st) {
30
+ if (!line.includes('"cwd"') && !line.includes('"gitBranch"'))
31
+ return;
32
+ let e;
33
+ try {
34
+ e = row();
35
+ }
36
+ catch {
37
+ return;
38
+ }
39
+ const c = typeof e?.cwd === "string" && e.cwd ? e.cwd : undefined;
40
+ const b = typeof e?.gitBranch === "string" && e.gitBranch ? e.gitBranch : undefined;
41
+ if ((c === undefined || c === st.c) && (b === undefined || b === st.b))
42
+ return;
43
+ if (c !== undefined)
44
+ st.c = c;
45
+ if (b !== undefined)
46
+ st.b = b;
47
+ out.push({ ts: typeof e.timestamp === "string" ? e.timestamp : "", ...(st.c ? { c: st.c } : {}), ...(st.b ? { b: st.b } : {}) });
48
+ },
49
+ };
50
+ /** The place in effect at `ts` among a transcript's changes (oldest first): the last made at or before it, else the first. */
51
+ export function placeAt(changes, ts) {
52
+ let at = changes[0];
53
+ for (const p of changes) {
54
+ const t = Date.parse(p.ts);
55
+ if (Number.isFinite(t) && t > ts)
56
+ break;
57
+ at = p;
58
+ }
59
+ return at ? { ...(at.c ? { cwd: at.c } : {}), ...(at.b ? { branch: at.b } : {}) } : {};
60
+ }
61
+ const memo = new Map();
62
+ /** A folder's repository name (see above); the folder's own name when it is in none. "(home)" for the home folder itself. */
63
+ export function repoName(folder, home = homedir()) {
64
+ const hit = memo.get(folder);
65
+ if (hit !== undefined)
66
+ return hit;
67
+ const top = resolve(home);
68
+ let name;
69
+ for (let d = resolve(folder); d !== top && dirname(d) !== d; d = dirname(d)) {
70
+ const git = join(d, ".git");
71
+ if (!existsSync(git))
72
+ continue;
73
+ name = basename(d);
74
+ try {
75
+ if (statSync(git).isFile()) {
76
+ // A worktree: "gitdir: <repo>/.git/worktrees/<name>".
77
+ const m = /^gitdir:\s*(.+?)[\\/]\.git[\\/]worktrees[\\/][^\\/]+\s*$/m.exec(readFileSync(git, "utf8"));
78
+ if (m)
79
+ name = basename(m[1]);
80
+ }
81
+ }
82
+ catch { /* unreadable: the folder's own name */ }
83
+ break;
84
+ }
85
+ if (name === undefined)
86
+ name = resolve(folder) === top ? "(home)" : basename(resolve(folder)) || folder;
87
+ memo.set(folder, name);
88
+ return name;
89
+ }
90
+ /** Forget what repoName worked out (tests). */
91
+ export function clearRepoNames() {
92
+ memo.clear();
93
+ }