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/budget.js CHANGED
@@ -32,7 +32,7 @@ import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
32
  import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
33
33
  import { subagentFiles } from "./subagents.js";
34
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
35
- import { isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
35
+ import { billedCost, isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
36
36
  import { orgRates, orgRatesLine } from "./orgrates.js";
37
37
  import { anchorOf, rowsOf } from "./scan.js";
38
38
  import { realModel } from "./tokens.js";
@@ -178,8 +178,12 @@ export function periodEnd(period, now = Date.now()) {
178
178
  s.setDate(s.getDate() + (period === "week" ? 7 : 1));
179
179
  return s.getTime();
180
180
  }
181
- /** What a ledger entry counts: 2, each Claude Code compaction's own request too (compactcost.ts). An entry counted otherwise is read again. */
182
- const COUNTED = 2;
181
+ /**
182
+ * What a ledger entry counts: 2, each Claude Code compaction's own request
183
+ * too (compactcost.ts); 3, the iterations a reply's later row settles (`r`'s
184
+ * fifth figure). An entry counted otherwise is read again.
185
+ */
186
+ const COUNTED = 3;
183
187
  /** Replies remembered per transcript, to tell a later row of one from a new reply. */
184
188
  const RECENT_REPLIES = 64;
185
189
  function readState() {
@@ -354,7 +358,7 @@ function readFile(tool, file, since, size) {
354
358
  continue;
355
359
  }
356
360
  const i = at.get(m.id) ?? -1;
357
- last.set(m.id, [m.id, i, out, (i >= 0 ? reqs[i].rates : requestCost(realModel(m.model), m.usage, Date.parse(String(row.timestamp ?? "")))?.rates)?.outputPerM ?? 0]);
361
+ last.set(m.id, [m.id, i, out, (i >= 0 ? reqs[i].rates : requestCost(realModel(m.model), m.usage, Date.parse(String(row.timestamp ?? "")))?.rates)?.outputPerM ?? 0, i >= 0 ? (reqs[i].extra ?? []).reduce((n, x) => n + x.usd, 0) : 0]);
358
362
  if (last.size > RECENT_REPLIES)
359
363
  last.delete(last.keys().next().value);
360
364
  }
@@ -461,12 +465,22 @@ function countLines(e, recent, text, since, own) {
461
465
  e.d[known[1]] += ((out - known[2]) * known[3]) / 1e6;
462
466
  known[2] = out;
463
467
  }
468
+ // And iterations its usage leaves out that it settles on (an advisor's call once it ran): what they add, once.
469
+ if (u.iterations) {
470
+ const extra = billedCost(realModel(m.model), u, Date.parse(String(row.timestamp ?? "")))?.extra?.usd ?? 0;
471
+ if (extra > known[4]) {
472
+ if (known[1] >= 0)
473
+ e.d[known[1]] += extra - known[4];
474
+ known[4] = extra;
475
+ }
476
+ }
464
477
  continue;
465
478
  }
466
479
  const ts = Date.parse(String(row.timestamp ?? ""));
467
480
  const tokens = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].reduce((t, v) => t + (Number(v) > 0 ? Number(v) : 0), 0);
468
481
  const model = realModel(m.model);
469
- const c = requestCost(model, u, ts);
482
+ // As billed: with the iterations its top-level usage leaves out (an advisor's, a declined attempt's).
483
+ const c = billedCost(model, u, ts);
470
484
  let index = -1;
471
485
  // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
472
486
  // A row of another session (`own`): a copy of its history, its spend, not this session's.
@@ -484,7 +498,7 @@ function countLines(e, recent, text, since, own) {
484
498
  e.d.push(c ? c.totalUsd : 0);
485
499
  }
486
500
  if (typeof m.id === "string")
487
- recent.push([m.id, index, out, c?.rates.outputPerM ?? 0]);
501
+ recent.push([m.id, index, out, c?.rates.outputPerM ?? 0, c?.extra?.usd ?? 0]);
488
502
  }
489
503
  }
490
504
  }
@@ -492,7 +506,7 @@ function countLines(e, recent, text, since, own) {
492
506
  export function wellFormed(e) {
493
507
  return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
494
508
  e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
495
- (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4))) &&
509
+ (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 5))) &&
496
510
  (e.z === undefined || (Array.isArray(e.z) && e.z.every((z) => Array.isArray(z) && typeof z[0] === "number" && typeof z[2] === "string")));
497
511
  }
498
512
  /**
package/dist/cache.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * caching at all.
11
11
  */
12
12
  import { readFileSync } from "node:fs";
13
- import { cacheWriteSplit, requestCost } from "./pricing.js";
13
+ import { billedCost, cacheWriteSplit } from "./pricing.js";
14
14
  import { replyCounter } from "./session.js";
15
15
  import { realModel } from "./tokens.js";
16
16
  export function analyzeCacheUsage(transcriptPath) {
@@ -65,8 +65,8 @@ export function analyzeCacheUsage(transcriptPath) {
65
65
  cacheWrite1hTokens += cacheWriteSplit(usage).oneHour;
66
66
  uncachedTokens += fresh;
67
67
  // Each request at its own model's price: a session can switch models.
68
- // As billed (requestCost): its tier, fast mode, US-only.
69
- const cost = requestCost(model, usage, Date.parse(String(entry.timestamp ?? "")) || undefined);
68
+ // As billed (requestCost): its tier, fast mode, US-only; and the iterations its top-level usage leaves out (billedCost).
69
+ const cost = billedCost(model, usage, Date.parse(String(entry.timestamp ?? "")) || undefined);
70
70
  const pricing = cost?.rates;
71
71
  if (cost && pricing) {
72
72
  priced++;
@@ -36,6 +36,7 @@
36
36
  */
37
37
  import { type Extractor } from "./scan.js";
38
38
  import { type DiagnosedMisses } from "./missledger.js";
39
+ import { type ColdReturnReport } from "./coldreturns.js";
39
40
  export type MissCause = "model switch" | "context edited" | "after an API error" | "over 20 new blocks" | "nothing visible";
40
41
  export interface CacheMiss {
41
42
  path: string;
@@ -124,6 +125,8 @@ export interface CacheMissReport {
124
125
  }>;
125
126
  largest: LateRewrite[];
126
127
  };
128
+ /** Returns after the cache expired, replayed as billed, compacted and kept warm (coldreturns.ts). */
129
+ coldReturns: ColdReturnReport;
127
130
  }
128
131
  /** One Claude Code version's requests (the `version` every transcript line carries). */
129
132
  export interface VersionStats {
@@ -40,6 +40,7 @@ import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.j
40
40
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, requestCost } from "./pricing.js";
41
41
  import { compareVersions } from "./modelswitch.js";
42
42
  import { diagnosedMisses, missLogPath } from "./missledger.js";
43
+ import { coldReturns, renderColdReturns } from "./coldreturns.js";
43
44
  /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
44
45
  function money(n) {
45
46
  if (!(n > 0))
@@ -417,6 +418,7 @@ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath(
417
418
  ...versionReport(versions),
418
419
  diagnosed: diagnosedMisses(since, missLog),
419
420
  late: lateReport(late),
421
+ coldReturns: coldReturns(days, targets),
420
422
  };
421
423
  }
422
424
  /**
@@ -665,6 +667,9 @@ export function renderCacheMisses(r, limitLines) {
665
667
  out.push("", ...late);
666
668
  if (r.diagnosed.misses > 0)
667
669
  out.push("", ...renderDiagnosed(r.diagnosed));
670
+ const cold = renderColdReturns(r.coldReturns);
671
+ if (cold.length)
672
+ out.push("", ...cold);
668
673
  return out.join("\n");
669
674
  }
670
675
  const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of your ${money(r.cacheWriteUsd)} of cache writes)` : "";
@@ -721,5 +726,8 @@ export function renderCacheMisses(r, limitLines) {
721
726
  }
722
727
  }
723
728
  out.push("", "A miss: within the cache lifetime of both requests (5 min, or 1 h when written at", "the 1-hour TTL), no compaction between, previous context over 20k, and the request", "wrote over 60% of that context again. Model switches always miss: each model has", "its own cache. On Claude Code 2.1.251+, `context-doctor install` (or the plugin)", "shows that price before a /model switch.");
729
+ const cold = renderColdReturns(r.coldReturns);
730
+ if (cold.length)
731
+ out.push("", ...cold);
724
732
  return out.join("\n");
725
733
  }
package/dist/cachettl.js CHANGED
@@ -38,7 +38,7 @@ import { join } from "node:path";
38
38
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
39
39
  import { REQUEST_ROWS } from "./coldresume.js";
40
40
  import { rowsOf } from "./scan.js";
41
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
41
+ import { billedCost, CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
42
42
  import { priceBasis } from "./orgrates.js";
43
43
  import { realModel } from "./tokens.js";
44
44
  import { backupOnce } from "./install.js";
@@ -115,7 +115,11 @@ export function replayTtlTranscript(path, acc, since, until = Infinity, sidechai
115
115
  if (!c || !p)
116
116
  acc.unpriced++;
117
117
  else {
118
- acc.billedUsd += c.promptUsd;
118
+ // The iterations its usage leaves out (billedCost): billed, and the same in both arms.
119
+ const extra = (billedCost(model, u, at)?.promptUsd ?? c.promptUsd) - c.promptUsd;
120
+ acc.billedUsd += c.promptUsd + extra;
121
+ acc.at5mUsd += extra;
122
+ acc.at1hUsd += extra;
119
123
  acc.writes += W;
120
124
  acc.writes1h += split.oneHour;
121
125
  const inp = p.inputPerM / 1e6;
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Claude Code's own cost beside ours.
3
+ *
4
+ * Every Claude Code transcript carries `cost-state` rows: Claude Code's
5
+ * running total for the session (`totalCostUSD`, what /cost shows), and per
6
+ * model the tokens and dollars it counted (`modelUsage`). It writes one at
7
+ * points through a session and restores it on resume (one `startTime` per
8
+ * session, the total never falls: all 567 rows of the author's 79 sessions
9
+ * that have one). It counts every request its process made for the session,
10
+ * subagents included, and also what no transcript row records: a
11
+ * compaction's own request (which context-doctor estimates, compactcost.ts),
12
+ * the small requests it makes on its own (titles and the like, on a Haiku),
13
+ * web searches at their fee, and from Claude Code 2.1.325 other mods' own
14
+ * model calls.
15
+ *
16
+ * So it is the check ROADMAP K2 waited on the mod for, read from what is
17
+ * already on disk: per session, its last `cost-state` against our price of
18
+ * the same requests (the session's transcript and its subagents', from the
19
+ * session's start to the last reply before that row). The gap is taken
20
+ * apart, per model, with Claude Code's own token counts:
21
+ * - models it counted that no transcript row has (its side requests);
22
+ * - on the models both count, its tokens beyond ours, at our prices
23
+ * (requests the transcripts keep no usage for: compactions past our
24
+ * estimate of them, retries);
25
+ * - what is left is price: its dollars against ours for its own tokens
26
+ * (its price table, fast mode, a long prompt's tier, contracted rates).
27
+ * The mod's ledger (modmeasure.ts) stays for what it measures live; this is
28
+ * the comparison `spend`, `session` and `doctor` show.
29
+ */
30
+ import type { SpendItem } from "./spend.js";
31
+ /** What one model's line of a `cost-state` holds, as numbers. */
32
+ export interface CcModel {
33
+ usd: number;
34
+ input: number;
35
+ output: number;
36
+ read: number;
37
+ write: number;
38
+ /** The writes by lifetime (`cacheCreationEphemeral1hInputTokens`, `...5m...`): both 0 where Claude Code did not split them (before ~2.1.317). */
39
+ write1h: number;
40
+ write5m: number;
41
+ searches: number;
42
+ }
43
+ /** A `cost-state` row as the usage scan keeps it (scan.ts: numbers and model names only). */
44
+ export interface CostStateRecord {
45
+ type: "cost-state";
46
+ usd: number;
47
+ /** The session's start (ms), restored with the total on resume. */
48
+ start?: number;
49
+ models: Record<string, CcModel>;
50
+ /** Claude Code said some model's cost was unknown to it (`hasUnknownModelCost`). */
51
+ unknown?: true;
52
+ /** The Claude Code version of the replies before it. */
53
+ version?: string;
54
+ }
55
+ /** A `cost-state` row, kept as numbers; undefined when it is not one. */
56
+ export declare function costStateRecord(e: any, version?: string): CostStateRecord | undefined;
57
+ /**
58
+ * A request Claude Code sent, the model declined (a refusal), and Claude
59
+ * Code sent again on another model (`model_refusal_fallback`): billed, and
60
+ * no row records its usage. Kept by the usage scan as its model and time.
61
+ */
62
+ export declare function refusalRecord(e: any): {
63
+ type: "refusal";
64
+ model: string;
65
+ timestamp?: string;
66
+ } | undefined;
67
+ /** A transcript's last `cost-state`, the time of the last reply before it (what it covers), and the declined requests before it, by model. */
68
+ export declare function lastCostState(rows: unknown[]): {
69
+ cs: CostStateRecord;
70
+ to: number;
71
+ first?: number;
72
+ declined: Record<string, number>;
73
+ } | undefined;
74
+ /** One model's two figures in a comparison. */
75
+ export interface ModelGap {
76
+ model: string;
77
+ /** Claude Code's dollars and tokens. */
78
+ ccUsd: number;
79
+ cc: {
80
+ input: number;
81
+ output: number;
82
+ read: number;
83
+ write: number;
84
+ searches: number;
85
+ };
86
+ /** Ours, on the same requests. */
87
+ ourUsd: number;
88
+ ours: {
89
+ input: number;
90
+ output: number;
91
+ read: number;
92
+ write: number;
93
+ requests: number;
94
+ };
95
+ /** Claude Code's tokens at our prices (atOurPrices): an estimate. */
96
+ ccAtOurUsd: number;
97
+ /** Requests on it that it declined and Claude Code sent again on another model (refusalRecord). */
98
+ declined?: number;
99
+ }
100
+ /** One session: Claude Code's figure and ours, and where the gap comes from. */
101
+ export interface SessionGap {
102
+ session: string;
103
+ project?: string;
104
+ /** What both cover: from the session's start to the last reply before Claude Code's last record. */
105
+ from: number;
106
+ to: number;
107
+ ccUsd: number;
108
+ ourUsd: number;
109
+ /** Of ours: the compactions' own requests, which we estimate (no row records their usage). */
110
+ compactionUsd: number;
111
+ compactions: number;
112
+ version?: string;
113
+ unknown?: true;
114
+ models: ModelGap[];
115
+ }
116
+ /** The gap taken apart: each part is Claude Code's figure less ours, so they add up to ccUsd - ourUsd. */
117
+ export interface GapParts {
118
+ /** Models no transcript row has, of requests the model declined and Claude Code sent again elsewhere. */
119
+ declinedUsd: number;
120
+ declined: number;
121
+ declinedModels: string[];
122
+ /** Other models no transcript row has: Claude Code's own side requests (its web searches among them). */
123
+ sideUsd: number;
124
+ sideModels: string[];
125
+ sideSearches: number;
126
+ /** On the models both count: its tokens less ours, priced at ours. */
127
+ tokensUsd: number;
128
+ /** Its dollars against ours on its own tokens: price. */
129
+ priceUsd: number;
130
+ }
131
+ /** The parts of the gap of one or more sessions (see GapParts). */
132
+ export declare function gapParts(sessions: SessionGap[]): GapParts;
133
+ /**
134
+ * The comparison for the sessions among `tops` whose Claude Code record and
135
+ * our requests both fall inside [`since`, `until`]: `items` are spend's
136
+ * Claude Code items (each request once, its session the transcript's name).
137
+ * A session whose last record starts after its first reply (a record that
138
+ * restarted on resume) is compared from where the record starts.
139
+ */
140
+ export declare function compareSessions(tops: string[], items: SpendItem[], since?: number, until?: number): SessionGap[];
141
+ /** One session's figures, from Claude Code's record and our items over the same span. */
142
+ export declare function sessionGap(session: string, cs: CostStateRecord, mine: SpendItem[], from: number, to: number, declined?: Record<string, number>): SessionGap;
143
+ /** The version that counts other mods' model calls in Claude Code's cost (CHANGELOG 2.1.325). */
144
+ export declare const MODS_COUNTED_FROM = "2.1.325";
145
+ /** a >= b, as dotted versions. */
146
+ export declare function versionAtLeast(a: string | undefined, b: string): boolean;
147
+ /** Within this of Claude Code's figure is a match (ROADMAP K2, F1). */
148
+ export declare const CC_GAP_TARGET = 0.02;
149
+ /** What the gap is made of, in words, largest part first: what Claude Code's figure holds more (or less) than ours, and why. */
150
+ export declare function gapText(sessions: SessionGap[]): string[];
151
+ /** `spend`'s lines: Claude Code's figure beside ours on the sessions both cover; none when no session has a record in the window. */
152
+ export declare function renderComparison(sessions: SessionGap[]): string[];
153
+ /** `session`'s lines for one session; none when its transcript has no record. */
154
+ export declare function renderSessionComparison(s: SessionGap | undefined): string[];
155
+ /** `doctor`'s check: how close our price is to Claude Code's own, session by session. Undefined when no session has a record worth comparing. */
156
+ export declare function comparisonCheck(sessions: SessionGap[], days: number): {
157
+ label: string;
158
+ status: "ok" | "warn";
159
+ detail: string;
160
+ } | undefined;
package/dist/ccost.js ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Claude Code's own cost beside ours.
3
+ *
4
+ * Every Claude Code transcript carries `cost-state` rows: Claude Code's
5
+ * running total for the session (`totalCostUSD`, what /cost shows), and per
6
+ * model the tokens and dollars it counted (`modelUsage`). It writes one at
7
+ * points through a session and restores it on resume (one `startTime` per
8
+ * session, the total never falls: all 567 rows of the author's 79 sessions
9
+ * that have one). It counts every request its process made for the session,
10
+ * subagents included, and also what no transcript row records: a
11
+ * compaction's own request (which context-doctor estimates, compactcost.ts),
12
+ * the small requests it makes on its own (titles and the like, on a Haiku),
13
+ * web searches at their fee, and from Claude Code 2.1.325 other mods' own
14
+ * model calls.
15
+ *
16
+ * So it is the check ROADMAP K2 waited on the mod for, read from what is
17
+ * already on disk: per session, its last `cost-state` against our price of
18
+ * the same requests (the session's transcript and its subagents', from the
19
+ * session's start to the last reply before that row). The gap is taken
20
+ * apart, per model, with Claude Code's own token counts:
21
+ * - models it counted that no transcript row has (its side requests);
22
+ * - on the models both count, its tokens beyond ours, at our prices
23
+ * (requests the transcripts keep no usage for: compactions past our
24
+ * estimate of them, retries);
25
+ * - what is left is price: its dollars against ours for its own tokens
26
+ * (its price table, fast mode, a long prompt's tier, contracted rates).
27
+ * The mod's ledger (modmeasure.ts) stays for what it measures live; this is
28
+ * the comparison `spend`, `session` and `doctor` show.
29
+ */
30
+ import { basename } from "node:path";
31
+ import { requestCost } from "./pricing.js";
32
+ import { realModel } from "./tokens.js";
33
+ import { rowsOf } from "./scan.js";
34
+ import { USAGE_ROWS } from "./limits.js";
35
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
36
+ /** A `cost-state` row, kept as numbers; undefined when it is not one. */
37
+ export function costStateRecord(e, version) {
38
+ if (e?.type !== "cost-state" || typeof e.totalCostUSD !== "number" || !Number.isFinite(e.totalCostUSD))
39
+ return undefined;
40
+ const models = {};
41
+ const mu = e.modelUsage && typeof e.modelUsage === "object" && !Array.isArray(e.modelUsage) ? e.modelUsage : {};
42
+ for (const [m, v] of Object.entries(mu).slice(0, 40)) {
43
+ if (!v || typeof v !== "object")
44
+ continue;
45
+ const u = v;
46
+ models[m.slice(0, 100)] = {
47
+ usd: num(u.costUSD), input: num(u.inputTokens), output: num(u.outputTokens), read: num(u.cacheReadInputTokens), write: num(u.cacheCreationInputTokens),
48
+ write1h: num(u.cacheCreationEphemeral1hInputTokens), write5m: num(u.cacheCreationEphemeral5mInputTokens), searches: num(u.webSearchRequests),
49
+ };
50
+ }
51
+ return {
52
+ type: "cost-state", usd: Math.max(0, e.totalCostUSD), ...(num(e.startTime) ? { start: e.startTime } : {}), models,
53
+ ...(e.hasUnknownModelCost === true ? { unknown: true } : {}), ...(version ? { version } : {}),
54
+ };
55
+ }
56
+ /**
57
+ * A request Claude Code sent, the model declined (a refusal), and Claude
58
+ * Code sent again on another model (`model_refusal_fallback`): billed, and
59
+ * no row records its usage. Kept by the usage scan as its model and time.
60
+ */
61
+ export function refusalRecord(e) {
62
+ if (e?.type !== "system" || e.subtype !== "model_refusal_fallback" || typeof e.originalModel !== "string")
63
+ return undefined;
64
+ return { type: "refusal", model: e.originalModel.slice(0, 100), ...(typeof e.timestamp === "string" ? { timestamp: e.timestamp } : {}) };
65
+ }
66
+ /** A transcript's last `cost-state`, the time of the last reply before it (what it covers), and the declined requests before it, by model. */
67
+ export function lastCostState(rows) {
68
+ let cs, to = NaN, last = NaN, first;
69
+ let declined = {}, pending = {};
70
+ for (const r of rows) {
71
+ if (r?.type === "cost-state") {
72
+ cs = r;
73
+ to = last;
74
+ for (const [m, n] of Object.entries(pending))
75
+ declined[m] = (declined[m] ?? 0) + n;
76
+ pending = {};
77
+ continue;
78
+ }
79
+ if (r?.type === "refusal") {
80
+ pending[r.model] = (pending[r.model] ?? 0) + 1;
81
+ continue;
82
+ }
83
+ if (r?.type !== "assistant")
84
+ continue;
85
+ const ts = Date.parse(String(r.timestamp ?? ""));
86
+ if (!Number.isFinite(ts))
87
+ continue;
88
+ last = ts;
89
+ if (first === undefined)
90
+ first = ts;
91
+ }
92
+ return cs && Number.isFinite(to) ? { cs, to, ...(first !== undefined ? { first } : {}), declined } : undefined;
93
+ }
94
+ /** The parts of the gap of one or more sessions (see GapParts). */
95
+ export function gapParts(sessions) {
96
+ const p = { declinedUsd: 0, declined: 0, declinedModels: [], sideUsd: 0, sideModels: [], sideSearches: 0, tokensUsd: 0, priceUsd: 0 };
97
+ const add = (list, m) => { if (!list.includes(m))
98
+ list.push(m); };
99
+ for (const s of sessions) {
100
+ for (const m of s.models) {
101
+ if (m.ours.requests === 0 && m.declined) {
102
+ p.declinedUsd += m.ccUsd;
103
+ p.declined += m.declined;
104
+ add(p.declinedModels, m.model);
105
+ }
106
+ else if (m.ours.requests === 0) {
107
+ p.sideUsd += m.ccUsd;
108
+ p.sideSearches += m.cc.searches;
109
+ if (m.ccUsd > 0)
110
+ add(p.sideModels, m.model);
111
+ }
112
+ else {
113
+ p.tokensUsd += m.ccAtOurUsd - m.ourUsd;
114
+ p.priceUsd += m.ccUsd - m.ccAtOurUsd;
115
+ }
116
+ }
117
+ // What its total holds beyond its models' lines (none seen): kept so the parts add up.
118
+ p.priceUsd += s.ccUsd - s.models.reduce((n, m) => n + m.ccUsd, 0);
119
+ }
120
+ return p;
121
+ }
122
+ /**
123
+ * A model line of Claude Code's priced at ours, as one request at `at`. The
124
+ * tokens are a whole session's, not one prompt, so a long-prompt tier would
125
+ * be misapplied: what it added is taken out. Writes Claude Code did not
126
+ * split by lifetime (all of them before about 2.1.317, and in a session
127
+ * resumed across that version the ones from before it: one of the author's
128
+ * has 3.8M of 10.5M split) are priced at `writePerToken`, what ours cost
129
+ * per token on the same model in the same session (each by its own
130
+ * lifetime), else as 1-hour writes, Claude Code's main thread's.
131
+ */
132
+ function atOurPrices(model, m, at, writePerToken) {
133
+ const w1h = Math.min(m.write, m.write1h), w5m = Math.min(m.write - w1h, m.write5m);
134
+ const rest = m.write - w1h - w5m;
135
+ const asOneHour = writePerToken === undefined ? rest : 0;
136
+ const u = {
137
+ input_tokens: m.input, output_tokens: m.output, cache_read_input_tokens: m.read, cache_creation_input_tokens: w1h + w5m + asOneHour,
138
+ cache_creation: { ephemeral_1h_input_tokens: w1h + asOneHour, ephemeral_5m_input_tokens: w5m },
139
+ server_tool_use: { web_search_requests: m.searches },
140
+ };
141
+ const c = requestCost(realModel(model), u, at);
142
+ if (!c)
143
+ return 0;
144
+ return c.totalUsd - c.modifiers.longUsd + (writePerToken === undefined ? 0 : rest * writePerToken);
145
+ }
146
+ /**
147
+ * The comparison for the sessions among `tops` whose Claude Code record and
148
+ * our requests both fall inside [`since`, `until`]: `items` are spend's
149
+ * Claude Code items (each request once, its session the transcript's name).
150
+ * A session whose last record starts after its first reply (a record that
151
+ * restarted on resume) is compared from where the record starts.
152
+ */
153
+ export function compareSessions(tops, items, since = -Infinity, until = Infinity) {
154
+ const bySession = new Map();
155
+ for (const it of items)
156
+ if (it.tool === "claude")
157
+ (bySession.get(it.session) ?? bySession.set(it.session, []).get(it.session)).push(it);
158
+ const out = [];
159
+ for (const top of tops) {
160
+ let rec;
161
+ try {
162
+ rec = lastCostState(rowsOf(top, USAGE_ROWS));
163
+ }
164
+ catch {
165
+ continue;
166
+ }
167
+ if (!rec)
168
+ continue;
169
+ // From its start, which Claude Code sets a second or so before the first reply; a record that
170
+ // restarted later (a resume that did not restore it) covers only from its own start.
171
+ const start = rec.cs.start !== undefined && rec.first !== undefined && rec.cs.start > rec.first + 60_000 ? rec.cs.start : Math.min(rec.cs.start ?? Infinity, rec.first ?? rec.to);
172
+ if (start < since || rec.to > until)
173
+ continue;
174
+ const session = basename(top, ".jsonl");
175
+ const mine = (bySession.get(session) ?? []).filter((it) => it.ts >= start - 1000 && it.ts <= rec.to);
176
+ out.push(sessionGap(session, rec.cs, mine, start, rec.to, rec.declined));
177
+ }
178
+ return out.sort((a, b) => b.ccUsd - a.ccUsd);
179
+ }
180
+ /** One session's figures, from Claude Code's record and our items over the same span. */
181
+ export function sessionGap(session, cs, mine, from, to, declined = {}) {
182
+ const models = new Map();
183
+ const line = (model) => models.get(model) ?? models.set(model, { model, ccUsd: 0, cc: { input: 0, output: 0, read: 0, write: 0, searches: 0 }, ourUsd: 0, ours: { input: 0, output: 0, read: 0, write: 0, requests: 0 }, ccAtOurUsd: 0 }).get(model);
184
+ let compactionUsd = 0, compactions = 0;
185
+ const writeUsd = new Map();
186
+ for (const it of mine) {
187
+ const g = line(it.model ?? "unknown");
188
+ g.ourUsd += it.usd;
189
+ g.ours.input += it.input;
190
+ g.ours.output += it.output;
191
+ g.ours.read += it.read;
192
+ g.ours.write += it.write;
193
+ g.ours.requests++;
194
+ writeUsd.set(g.model, (writeUsd.get(g.model) ?? 0) + it.writeUsd);
195
+ if (it.compaction) {
196
+ compactionUsd += it.usd;
197
+ compactions++;
198
+ }
199
+ }
200
+ for (const [model, m] of Object.entries(cs.models)) {
201
+ const g = line(realModel(model) ?? model);
202
+ g.ccUsd += m.usd;
203
+ g.cc.input += m.input;
204
+ g.cc.output += m.output;
205
+ g.cc.read += m.read;
206
+ g.cc.write += m.write;
207
+ g.cc.searches += m.searches;
208
+ g.ccAtOurUsd += atOurPrices(model, m, to, g.ours.write > 0 ? writeUsd.get(g.model) / g.ours.write : undefined);
209
+ }
210
+ for (const [model, n] of Object.entries(declined)) {
211
+ const g = models.get(realModel(model) ?? model);
212
+ if (g)
213
+ g.declined = (g.declined ?? 0) + n;
214
+ }
215
+ return {
216
+ session, ...(mine[0]?.project ? { project: mine[0].project } : {}), from, to, ccUsd: cs.usd, ourUsd: mine.reduce((n, it) => n + it.usd, 0), compactionUsd, compactions,
217
+ ...(cs.version ? { version: cs.version } : {}), ...(cs.unknown ? { unknown: true } : {}),
218
+ models: [...models.values()].sort((a, b) => b.ccUsd - a.ccUsd),
219
+ };
220
+ }
221
+ /** The version that counts other mods' model calls in Claude Code's cost (CHANGELOG 2.1.325). */
222
+ export const MODS_COUNTED_FROM = "2.1.325";
223
+ /** a >= b, as dotted versions. */
224
+ export function versionAtLeast(a, b) {
225
+ if (!a)
226
+ return false;
227
+ const x = a.split(/[.-]/).map((n) => parseInt(n, 10) || 0), y = b.split(".").map((n) => parseInt(n, 10) || 0);
228
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
229
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
230
+ return (x[i] ?? 0) > (y[i] ?? 0);
231
+ return true;
232
+ }
233
+ const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
234
+ const pct = (x) => `${x >= 0 ? "+" : ""}${(x * 100).toFixed(1)}%`;
235
+ const more = (n) => `${usd(Math.abs(n))} ${n >= 0 ? "more" : "less"}`;
236
+ const list = (ms) => `${ms.slice(0, 2).join(", ")}${ms.length > 2 ? " and others" : ""}`;
237
+ /** Within this of Claude Code's figure is a match (ROADMAP K2, F1). */
238
+ export const CC_GAP_TARGET = 0.02;
239
+ /** Below this, Claude Code's figure for a session is too small for a percentage to mean anything. */
240
+ const MIN_COMPARE_USD = 0.5;
241
+ /** What the gap is made of, in words, largest part first: what Claude Code's figure holds more (or less) than ours, and why. */
242
+ export function gapText(sessions) {
243
+ const p = gapParts(sessions);
244
+ const comp = sessions.reduce((n, s) => n + s.compactionUsd, 0), nComp = sessions.reduce((n, s) => n + s.compactions, 0);
245
+ const parts = [];
246
+ if (Math.abs(p.declinedUsd) >= 0.005)
247
+ parts.push([p.declinedUsd, `Claude Code counts ${more(p.declinedUsd)} on ${list(p.declinedModels)}, requests it declined (${p.declined} refusal${p.declined === 1 ? "" : "s"} recorded) and Claude Code sent again on another model: no row records their usage`]);
248
+ if (Math.abs(p.sideUsd) >= 0.005)
249
+ parts.push([p.sideUsd, `Claude Code counts ${more(p.sideUsd)} on ${list(p.sideModels)}, its own side requests${p.sideSearches ? ` (${p.sideSearches} web search${p.sideSearches === 1 ? "" : "es"} among them)` : ""}: no transcript row records them`]);
250
+ // Ours holds the compactions' own requests as estimates (no row records their usage): what its tokens say of them.
251
+ const compText = nComp ? `${nComp} compaction${nComp === 1 ? "'s" : "s'"} own request${nComp === 1 ? "" : "s"}, which we estimate at ${usd(comp)}` : "";
252
+ if (Math.abs(p.tokensUsd) >= 0.005) {
253
+ parts.push([p.tokensUsd, p.tokensUsd > 0
254
+ ? `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: requests no row records the usage of${compText ? `, beyond our ${compText}` : ""}`
255
+ : `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: ${compText ? `our ${compText}, are above what it counted` : "requests we count that it does not"}`]);
256
+ }
257
+ if (Math.abs(p.priceUsd) >= 0.005)
258
+ parts.push([p.priceUsd, `Its prices come to ${more(p.priceUsd)} than ours on its own tokens (its price table, fast mode, a long prompt's tier, contracted rates)`]);
259
+ const lines = parts.sort((a, b) => Math.abs(b[0]) - Math.abs(a[0])).map(([, t]) => t);
260
+ if (sessions.some((s) => versionAtLeast(s.version, MODS_COUNTED_FROM)))
261
+ lines.push(`From Claude Code ${MODS_COUNTED_FROM} its figure also counts other mods' own model calls, in the parts above`);
262
+ if (sessions.some((s) => s.unknown))
263
+ lines.push("Claude Code said it had no price for some model: its figure leaves that model out");
264
+ return lines;
265
+ }
266
+ /** `spend`'s lines: Claude Code's figure beside ours on the sessions both cover; none when no session has a record in the window. */
267
+ export function renderComparison(sessions) {
268
+ if (!sessions.length)
269
+ return [];
270
+ const cc = sessions.reduce((n, s) => n + s.ccUsd, 0), ours = sessions.reduce((n, s) => n + s.ourUsd, 0);
271
+ const n = sessions.length;
272
+ const worth = sessions.filter((s) => s.ccUsd >= MIN_COMPARE_USD);
273
+ const within = worth.filter((s) => Math.abs(s.ourUsd - s.ccUsd) <= CC_GAP_TARGET * s.ccUsd).length;
274
+ const lines = [
275
+ `Claude Code's own figure (its cost-state), ${n} session${n === 1 ? "" : "s"} wholly in the window: ${usd(cc)}; ours ${usd(ours)}${cc > 0 ? ` (${pct((ours - cc) / cc)})` : ""}`,
276
+ ...(worth.length ? [` ${within} of the ${worth.length} over ${usd(MIN_COMPARE_USD)} within ${CC_GAP_TARGET * 100}% of it (context-doctor session <file> shows one)`] : []),
277
+ ];
278
+ for (const t of gapText(sessions))
279
+ lines.push(` ${t}`);
280
+ return lines;
281
+ }
282
+ /** `session`'s lines for one session; none when its transcript has no record. */
283
+ export function renderSessionComparison(s) {
284
+ if (!s)
285
+ return [];
286
+ const lines = [`Claude Code's own figure for this session: ${usd(s.ccUsd)}; ours ${usd(s.ourUsd)}${s.ccUsd > 0 ? ` (${pct((s.ourUsd - s.ccUsd) / s.ccUsd)})` : ""}, to ${new Date(s.to).toISOString().slice(0, 16).replace("T", " ")} UTC (its last record)`];
287
+ for (const t of gapText([s]))
288
+ lines.push(` ${t}`);
289
+ return lines;
290
+ }
291
+ /** `doctor`'s check: how close our price is to Claude Code's own, session by session. Undefined when no session has a record worth comparing. */
292
+ export function comparisonCheck(sessions, days) {
293
+ const worth = sessions.filter((s) => s.ccUsd >= MIN_COMPARE_USD);
294
+ if (!worth.length)
295
+ return undefined;
296
+ const label = "Our price vs Claude Code's own";
297
+ const cc = worth.reduce((n, s) => n + s.ccUsd, 0), ours = worth.reduce((n, s) => n + s.ourUsd, 0);
298
+ const gap = (ours - cc) / cc;
299
+ const within = worth.filter((s) => Math.abs((s.ourUsd - s.ccUsd) / s.ccUsd) <= CC_GAP_TARGET).length;
300
+ const head = `${usd(ours)} against Claude Code's ${usd(cc)} (${pct(gap)}) on ${worth.length} session${worth.length === 1 ? "" : "s"} of the last ${days} days (its cost-state records); ${within} within ${CC_GAP_TARGET * 100}%`;
301
+ if (Math.abs(gap) <= CC_GAP_TARGET)
302
+ return { label, status: "ok", detail: head };
303
+ return { label, status: "warn", detail: `${head}. The gap: ${gapText(worth).join("; ")}` };
304
+ }