context-doctor 0.48.0 → 0.49.1

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 (77) hide show
  1. package/README.md +16 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +195 -0
  10. package/dist/ccost.js +400 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/install.js +1 -1
  28. package/dist/limits.d.ts +232 -14
  29. package/dist/limits.js +739 -33
  30. package/dist/mcp.js +19 -19
  31. package/dist/mcpdefer.d.ts +47 -0
  32. package/dist/mcpdefer.js +91 -0
  33. package/dist/mod/api.d.ts +72 -2
  34. package/dist/mod/api.js +5 -1
  35. package/dist/mod/logic.d.ts +289 -16
  36. package/dist/mod/logic.js +362 -38
  37. package/dist/mod/register.d.ts +37 -2
  38. package/dist/mod/register.js +290 -9
  39. package/dist/modmeasure.d.ts +6 -4
  40. package/dist/modmeasure.js +8 -4
  41. package/dist/opencode.d.ts +57 -0
  42. package/dist/opencode.js +234 -0
  43. package/dist/orgrates.d.ts +7 -0
  44. package/dist/orgrates.js +19 -0
  45. package/dist/overhead.d.ts +3 -0
  46. package/dist/overhead.js +5 -1
  47. package/dist/pricing.d.ts +59 -2
  48. package/dist/pricing.js +130 -10
  49. package/dist/proxy.d.ts +8 -1
  50. package/dist/proxy.js +13 -1
  51. package/dist/savings.d.ts +5 -1
  52. package/dist/savings.js +11 -5
  53. package/dist/scan.d.ts +3 -1
  54. package/dist/scan.js +8 -1
  55. package/dist/sessionprice.d.ts +5 -0
  56. package/dist/sessionprice.js +5 -1
  57. package/dist/sidecost.d.ts +65 -0
  58. package/dist/sidecost.js +117 -0
  59. package/dist/spend.d.ts +94 -3
  60. package/dist/spend.js +251 -23
  61. package/dist/spendplace.d.ts +40 -0
  62. package/dist/spendplace.js +93 -0
  63. package/dist/spendteam.d.ts +160 -0
  64. package/dist/spendteam.js +286 -0
  65. package/dist/starts.d.ts +106 -0
  66. package/dist/starts.js +406 -0
  67. package/dist/statusline.d.ts +2 -2
  68. package/dist/statusline.js +2 -2
  69. package/dist/subagentmodel.js +9 -7
  70. package/dist/subagentpay.d.ts +31 -2
  71. package/dist/subagentpay.js +232 -68
  72. package/dist/subagents.js +3 -3
  73. package/dist/tasks.js +3 -2
  74. package/dist/tooloutput.js +5 -5
  75. package/dist/usagepane.d.ts +77 -0
  76. package/dist/usagepane.js +287 -0
  77. package/package.json +1 -1
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,18 +134,30 @@ 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;
159
+ if (r.unsettled)
160
+ item.unsettled = r.unsettled;
135
161
  if (r.model)
136
162
  item.model = r.model;
137
163
  if (f.run)
@@ -140,7 +166,41 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
140
166
  item.subagent = true;
141
167
  if (r.uuid)
142
168
  item.key = r.uuid;
169
+ if (places.length) {
170
+ const at = placeAt(places, r.ts);
171
+ if (at.cwd)
172
+ item.cwd = at.cwd;
173
+ if (at.branch)
174
+ item.branch = at.branch;
175
+ }
143
176
  out.push(item);
177
+ for (const [j, x] of extra.entries()) {
178
+ const xi = {
179
+ tool: "claude", ts: r.ts, project, session, input: x.input, read: x.read, write: x.write, output: x.output,
180
+ usd: x.usd, inputUsd: 0, readUsd: 0, writeUsd: 0, outputUsd: 0, priced: x.priced, iteration: x.type,
181
+ };
182
+ 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;
183
+ if (c) {
184
+ xi.inputUsd = c.inputUsd;
185
+ xi.readUsd = c.readUsd;
186
+ xi.outputUsd = c.outputUsd;
187
+ xi.writeUsd = Math.max(0, x.promptUsd - c.inputUsd - c.readUsd);
188
+ }
189
+ label(xi, x);
190
+ if (x.model)
191
+ xi.model = x.model;
192
+ if (item.workflow)
193
+ xi.workflow = item.workflow;
194
+ else if (item.subagent)
195
+ xi.subagent = true;
196
+ if (item.cwd)
197
+ xi.cwd = item.cwd;
198
+ if (item.branch)
199
+ xi.branch = item.branch;
200
+ if (r.uuid)
201
+ xi.key = `${r.uuid}#${j + 1}`;
202
+ out.push(xi);
203
+ }
144
204
  }
145
205
  }
146
206
  onProgress?.(files.length, files.length);
@@ -167,7 +227,7 @@ function spawnedBy(p) {
167
227
  * every token_count event's last request and running total.
168
228
  */
169
229
  export const CODEX_SPEND_ROWS = {
170
- id: "codex-spend.3",
230
+ id: "codex-spend.4",
171
231
  init: () => ({}),
172
232
  line(line, row, out, st) {
173
233
  if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
@@ -187,6 +247,8 @@ export const CODEX_SPEND_ROWS = {
187
247
  const parent = spawnedBy(p);
188
248
  if (typeof p.id === "string")
189
249
  out.push({ k: "meta", id: p.id, ...(parent ? { parent } : {}) });
250
+ if (typeof p.git?.branch === "string" && p.git.branch)
251
+ out.push({ k: "branch", branch: p.git.branch });
190
252
  }
191
253
  if (e.type === "session_meta" || e.type === "turn_context") {
192
254
  if (typeof p.cwd === "string")
@@ -208,11 +270,15 @@ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0
208
270
  /** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
209
271
  export function codexFileSpend(file, since, until = Infinity) {
210
272
  const out = [];
211
- let model, cwd;
273
+ let model, cwd, branch;
212
274
  let total = -1;
213
275
  for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
214
276
  if (r.k === "meta")
215
277
  continue;
278
+ if (r.k === "branch") {
279
+ branch = branch ?? r.branch;
280
+ continue;
281
+ }
216
282
  if (r.k === "cwd") {
217
283
  cwd = cwd ?? r.cwd;
218
284
  continue;
@@ -230,7 +296,7 @@ export function codexFileSpend(file, since, until = Infinity) {
230
296
  if (!Number.isFinite(ts) || ts < since || ts > until || isUnbilledModel(model))
231
297
  continue;
232
298
  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));
299
+ 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
300
  }
235
301
  return out;
236
302
  }
@@ -496,10 +562,52 @@ export function cursorSpend(since, until = Infinity) {
496
562
  // No cache split: every input token at the uncached rate. Cursor's own
497
563
  // names for Claude ("claude-4.6-opus-high-thinking") are priced as the
498
564
  // 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));
565
+ 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
566
  }
501
567
  return out;
502
568
  }
569
+ // ---------------------------------------------------------------------------
570
+ // Copilot CLI
571
+ // ---------------------------------------------------------------------------
572
+ /**
573
+ * Copilot CLI's model calls (copilotusage.ts), each priced at its model's
574
+ * list price where the table has one, else counted. What Copilot bills is
575
+ * its AI credits and premium requests, kept beside the price, not in it.
576
+ */
577
+ export function copilotSpend(since, until = Infinity, home = homedir()) {
578
+ return copilotCalls(since, until, home).filter((c) => !isUnbilledModel(c.model)).map((c) => {
579
+ 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 });
580
+ if (c.credits !== undefined)
581
+ it.credits = c.credits;
582
+ if (c.premium !== undefined)
583
+ it.premium = c.premium;
584
+ if (c.cwd)
585
+ it.cwd = c.cwd;
586
+ if (c.gitRoot)
587
+ it.root = c.gitRoot;
588
+ if (c.branch)
589
+ it.branch = c.branch;
590
+ return it;
591
+ });
592
+ }
593
+ // ---------------------------------------------------------------------------
594
+ // OpenCode and Cline
595
+ // ---------------------------------------------------------------------------
596
+ /** A call's tokens as recorded usage: input uncached, cache reads and writes apart. */
597
+ const asUsage = (c) => ({ input_tokens: c.input, cache_read_input_tokens: c.read, cache_creation_input_tokens: c.write, output_tokens: c.output });
598
+ /** OpenCode's model calls (opencode.ts), each at its model's list price. Throws SqliteUnavailableError when its database cannot be read here. */
599
+ export function opencodeSpend(since, until = Infinity, home = homedir()) {
600
+ const { calls, sqlite } = opencodeCalls(since, until, home);
601
+ // A compaction is a measured request here (its own tokens), not Claude Code's estimate: no `compaction` mark.
602
+ 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)));
603
+ if (!sqlite)
604
+ throw Object.assign(new SqliteUnavailableError("reading OpenCode's opencode.db needs SQLite: Node 22.13+ or the sqlite3 command"), { items });
605
+ return items;
606
+ }
607
+ /** Cline's requests (cline.ts), each at its model's list price; one with no model is counted, not priced. */
608
+ export function clineSpend(since, until = Infinity, home = homedir()) {
609
+ 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)));
610
+ }
503
611
  /** The local calendar day of `ts`, "YYYY-MM-DD". */
504
612
  export function localDay(ts) {
505
613
  const d = new Date(ts);
@@ -508,7 +616,8 @@ export function localDay(ts) {
508
616
  function add(map, key, it) {
509
617
  const r = map.get(key) ?? map.set(key, { usd: 0, requests: 0, byTool: {} }).get(key);
510
618
  r.usd += it.usd;
511
- r.requests++;
619
+ if (!it.iteration)
620
+ r.requests++;
512
621
  r.byTool[it.tool] = (r.byTool[it.tool] ?? 0) + it.usd;
513
622
  }
514
623
  /** "1 run", "12 runs": workflow runs. */
@@ -517,6 +626,8 @@ const runsText = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "run" : "runs"
517
626
  export function summarizeSpend(items, days, since, until, skipped = []) {
518
627
  const tools = new Map();
519
628
  const projects = new Map(), models = new Map(), daily = new Map();
629
+ const repos = new Map(), branches = new Map();
630
+ let byPlace = false, byBranch = false;
520
631
  const sessions = new Map();
521
632
  const sessionModels = new Map();
522
633
  const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
@@ -524,11 +635,25 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
524
635
  const mods = { ...NO_MODIFIERS };
525
636
  const changed = new Map();
526
637
  const compactions = { requests: 0, usd: 0 };
638
+ const unsettled = { replies: 0, tokens: 0, usd: 0 };
639
+ const iterations = {};
527
640
  for (const it of items) {
528
641
  if (it.compaction) {
529
642
  compactions.requests++;
530
643
  compactions.usd += it.usd;
531
644
  }
645
+ if (it.unsettled) {
646
+ unsettled.replies++;
647
+ unsettled.tokens += it.unsettled;
648
+ unsettled.usd += it.output > 0 ? (it.outputUsd * it.unsettled) / it.output : 0;
649
+ }
650
+ if (it.iteration) {
651
+ const x = (iterations[it.iteration] ??= { calls: 0, usd: 0, models: [] });
652
+ x.calls++;
653
+ x.usd += it.usd;
654
+ if (it.model && !x.models.includes(it.model))
655
+ x.models.push(it.model);
656
+ }
532
657
  if (it.modifiers)
533
658
  addModifiers(mods, it.modifiers);
534
659
  if (it.changedOn) {
@@ -539,13 +664,18 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
539
664
  }
540
665
  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
666
  t.usd += it.usd;
542
- t.requests++;
667
+ if (!it.iteration)
668
+ t.requests++;
543
669
  t.tokens.input += it.input;
544
670
  t.tokens.read += it.read;
545
671
  t.tokens.write += it.write;
546
672
  t.tokens.output += it.output;
547
673
  if (it.subagent)
548
674
  t.subagentUsd = (t.subagentUsd ?? 0) + it.usd;
675
+ if (it.credits !== undefined)
676
+ t.credits = (t.credits ?? 0) + it.credits;
677
+ if (it.premium !== undefined)
678
+ t.premium = (t.premium ?? 0) + it.premium;
549
679
  if (it.workflow) {
550
680
  t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
551
681
  runs.add(it.workflow);
@@ -567,6 +697,13 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
567
697
  e.models.push(m);
568
698
  }
569
699
  add(projects, it.project, it);
700
+ if (it.repo !== undefined) {
701
+ byPlace = true;
702
+ if (it.branch)
703
+ byBranch = true;
704
+ add(repos, it.repo, it);
705
+ add(branches, `${it.repo}\u0000${it.branch ?? ""}`, it);
706
+ }
570
707
  add(models, it.model ?? "unknown", it);
571
708
  add(daily, localDay(it.ts), it);
572
709
  parts.inputUsd += it.inputUsd;
@@ -576,7 +713,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
576
713
  const sk = `${it.tool}\u0000${it.session}`;
577
714
  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
715
  s.usd += it.usd;
579
- s.requests++;
716
+ if (!it.iteration)
717
+ s.requests++;
580
718
  s.first = Math.min(s.first, it.ts);
581
719
  s.last = Math.max(s.last, it.ts);
582
720
  if (it.model) {
@@ -600,15 +738,21 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
600
738
  return {
601
739
  days, since, until,
602
740
  usd: items.reduce((n, it) => n + it.usd, 0),
603
- requests: items.length,
741
+ requests: items.filter((it) => !it.iteration).length,
604
742
  tools: TOOLS.filter((t) => tools.has(t)).map((t) => tools.get(t)).sort(byUsd),
605
743
  projects: [...projects].map(([project, r]) => ({ project, ...r })).sort(byUsd),
744
+ ...(byPlace ? {
745
+ repos: [...repos].map(([repo, r]) => ({ repo, ...r })).sort(byUsd),
746
+ ...(byBranch ? { branches: [...branches].map(([k, r]) => { const [repo, branch] = k.split("\u0000"); return { repo, ...(branch ? { branch } : {}), ...r }; }).sort(byUsd) } : {}),
747
+ } : {}),
606
748
  models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
607
749
  daily: days_,
608
750
  parts,
609
751
  ...(anyModifier(mods) ? { modifiers: mods } : {}),
610
752
  ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
611
753
  ...(compactions.requests ? { compactions } : {}),
754
+ ...(unsettled.replies ? { unsettled } : {}),
755
+ ...(Object.keys(iterations).length ? { iterations } : {}),
612
756
  sessions: [...sessions.values()].sort(byUsd),
613
757
  skipped,
614
758
  };
@@ -627,16 +771,50 @@ function claudeProgressSummaries(since, until, tops, o) {
627
771
  * --json died on a string too long), and 1e9 days fell off the calendar.
628
772
  */
629
773
  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 = {}) {
774
+ /**
775
+ * One Claude Code session's comparison with Claude Code's own figure (ccost.ts):
776
+ * its transcript and its subagents', to its last `cost-state`. Undefined when
777
+ * it has none, or cannot be read.
778
+ */
779
+ export function claudeCodeSession(top) {
780
+ try {
781
+ return compareSessions([top], claudeSpend(0, Infinity, [top]))[0];
782
+ }
783
+ catch {
784
+ return undefined;
785
+ }
786
+ }
787
+ /**
788
+ * A session's requests priced past the day their model's price ended or
789
+ * changed, said as `spend` says it: which price, and the one used instead.
790
+ * Undefined when none (or the transcript cannot be read).
791
+ */
792
+ export function sessionPriceEnded(top) {
793
+ try {
794
+ const items = claudeSpend(0, Infinity, [top]).filter((it) => it.changedOn);
795
+ if (!items.length)
796
+ return undefined;
797
+ const n = items.length;
798
+ 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]))}.`;
799
+ }
800
+ catch {
801
+ return undefined;
802
+ }
803
+ }
804
+ /** Every request of the last `days` days, every tool on this machine, and what could not be read. */
805
+ export function collectSpend(days = 30, opts = {}) {
632
806
  days = Math.min(days, MAX_SPEND_DAYS);
633
807
  const until = opts.now ?? Date.now();
634
808
  const since = until - days * DAY;
635
809
  const home = opts.home ?? homedir();
810
+ const place = opts.by === "repo" || opts.by === "branch";
636
811
  // A subagent's transcript read once for its usage and its timeline (the progress summaries).
637
812
  if (opts.progress !== false)
638
813
  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)];
814
+ // Grouped by where it ran: each transcript read once for its usage and its places.
815
+ if (place)
816
+ prescan([{ paths: claudeUsageFiles(since, opts.claudePaths).map((f) => f.file), extractors: [USAGE_ROWS, CLAUDE_PLACE_ROWS] }]);
817
+ const items = [...claudeSpend(since, until, opts.claudePaths, opts.onProgress, place), ...codexSpend(since, until, home), ...geminiSpend(since, until, home), ...copilotSpend(since, until, home)];
640
818
  const skipped = [];
641
819
  try {
642
820
  items.push(...cursorSpend(since, until));
@@ -645,13 +823,43 @@ export function spendReport(days = 30, opts = {}) {
645
823
  if (e instanceof SqliteUnavailableError)
646
824
  skipped.push({ tool: "cursor", reason: "reading Cursor's history needs SQLite: Node 22.13+ or the sqlite3 command" });
647
825
  }
826
+ try {
827
+ items.push(...opencodeSpend(since, until, home));
828
+ }
829
+ catch (e) {
830
+ // Its JSON files still count; its database needs SQLite.
831
+ items.push(...(e.items ?? []));
832
+ if (e instanceof SqliteUnavailableError)
833
+ skipped.push({ tool: "opencode", reason: "reading OpenCode's opencode.db needs SQLite: Node 22.13+ or the sqlite3 command" });
834
+ }
835
+ items.push(...clineSpend(since, until, home));
836
+ // A request's repository: its git root's or folder's (spendplace.ts), else its project as named here.
837
+ if (place)
838
+ for (const it of items) {
839
+ it.repo = it.root || it.cwd ? repoName((it.root ?? it.cwd), home) : it.project;
840
+ if (opts.by === "repo")
841
+ delete it.branch;
842
+ }
843
+ return { items, days, since, until, skipped };
844
+ }
845
+ /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
846
+ export function spendReport(days = 30, opts = {}) {
847
+ const { items, since, until, skipped, days: d } = collectSpend(days, opts);
848
+ days = d;
648
849
  const report = summarizeSpend(items, days, since, until, skipped);
850
+ // Claude Code's own figure beside ours, on the sessions wholly in the window that recorded one.
851
+ const tops = [...new Set(claudeUsageFiles(since, opts.claudePaths).filter((f) => !f.subagent).map((f) => f.top))];
852
+ const gaps = compareSessions(tops, items, since, until);
853
+ if (gaps.length)
854
+ report.claudeCode = { ccUsd: gaps.reduce((n, g) => n + g.ccUsd, 0), ourUsd: gaps.reduce((n, g) => n + g.ourUsd, 0), sessions: gaps };
649
855
  const progress = opts.progress === false ? undefined : claudeProgressSummaries(since, until, opts.claudePaths, opts.progress);
650
856
  return progress ? { ...report, progressSummaries: progress } : report;
651
857
  }
652
858
  // ---------------------------------------------------------------------------
653
859
  // Rendering
654
860
  // ---------------------------------------------------------------------------
861
+ /** What an iteration type is, in the report's words. */
862
+ 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
863
  export const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n > 0 && n < 0.005 ? "<$0.01" : `$${n.toFixed(2)}`);
656
864
  const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "");
657
865
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
@@ -666,11 +874,13 @@ export function modifiersText(m) {
666
874
  m.longUsd > 0 ? `long-prompt tier +${usd(m.longUsd)}` : "",
667
875
  ].filter(Boolean).join(", ");
668
876
  }
669
- /** The full report, kept within 80 columns. `top`: rows per list. */
877
+ /** AI credits or premium requests: whole above 100, else to two places. */
878
+ const creditsText = (n) => (n >= 100 ? Math.round(n).toLocaleString("en-US") : String(Math.round(n * 100) / 100));
879
+ /** 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
880
  export function renderSpend(r, top = 8) {
671
881
  const lines = [];
672
882
  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.`);
883
+ 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
884
  for (const s of r.skipped)
675
885
  lines.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
676
886
  return lines.join("\n");
@@ -686,7 +896,7 @@ export function renderSpend(r, top = 8) {
686
896
  lines.push("─".repeat(60));
687
897
  for (const t of r.tools) {
688
898
  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);
899
+ 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
900
  const note = notes.length ? ` ${notes.join(", ")}` : "";
691
901
  lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
692
902
  }
@@ -700,14 +910,19 @@ export function renderSpend(r, top = 8) {
700
910
  lines.push(` … and ${more} more`);
701
911
  };
702
912
  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);
913
+ if (r.branches)
914
+ 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);
915
+ else if (r.repos)
916
+ list("By repository", r.repos.slice(0, top).map((p) => ({ name: p.repo, usd: p.usd, tail: toolsOf(p.byTool) })), r.repos.length - top);
917
+ else
918
+ 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
919
  // A model with no list price reads "not priced", not a $0.00 that looks free.
705
920
  const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
706
921
  // One priced by its family's row reads as the estimate it is.
707
922
  const estimatedModels = new Set(r.tools.flatMap((t) => t.estimated?.models ?? []));
708
923
  // One priced past the day its price changed, likewise.
709
924
  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);
925
+ 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
926
  // The last two weeks of the window, a bar each, scaled to the busiest.
712
927
  const recent = r.daily.slice(-14);
713
928
  const peak = Math.max(...recent.map((d) => d.usd), 0);
@@ -725,6 +940,11 @@ export function renderSpend(r, top = 8) {
725
940
  // A compaction's own request is in no row's usage: estimated from the context it read and the summary it wrote.
726
941
  if (r.compactions)
727
942
  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)`);
943
+ if (r.unsettled)
944
+ lines.push(` Of it, ${usd(r.unsettled.usd)} output of ${r.unsettled.replies.toLocaleString("en-US")} subagent ${r.unsettled.replies === 1 ? "reply" : "replies"} whose rows Claude Code never settled (2.1.284-2.1.299), an estimate from ${r.unsettled.replies === 1 ? "its" : "their"} content`);
945
+ // Calls inside a request that its usage totals leave out: the advisor's, an attempt a fallback replaced.
946
+ for (const [type, x] of Object.entries(r.iterations ?? {}))
947
+ 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
948
  const claude = r.tools.find((t) => t.tool === "claude");
729
949
  if (claude?.subagentUsd)
730
950
  lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
@@ -765,10 +985,18 @@ export function renderSpend(r, top = 8) {
765
985
  }
766
986
  if (r.tools.some((t) => t.estimate))
767
987
  notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
988
+ const copilot = r.tools.find((t) => t.tool === "copilot");
989
+ if (copilot) {
990
+ // What Copilot itself counts, beside the tokens at list price: its plan bills credits, not tokens.
991
+ 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);
992
+ notes.push(`Copilot CLI: its tokens at list price${counted.length ? `; Copilot counted ${counted.join(" and ")}` : ""}.`);
993
+ }
768
994
  for (const s of r.skipped)
769
995
  notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
770
996
  if (notes.length)
771
997
  lines.push("", ...notes);
998
+ if (r.claudeCode)
999
+ lines.push("", ...renderComparison(r.claudeCode.sessions));
772
1000
  lines.push("", "As an API key is billed; on a subscription the same tokens come out");
773
1001
  lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
774
1002
  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
+ }