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/ccost.js ADDED
@@ -0,0 +1,400 @@
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
+ import { subagentFiles } from "./subagents.js";
36
+ import { SUGGESTION_PROMPT_TOKENS, suggestionCost } from "./sidecost.js";
37
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
38
+ /** A `cost-state` row, kept as numbers; undefined when it is not one. */
39
+ export function costStateRecord(e, version) {
40
+ if (e?.type !== "cost-state" || typeof e.totalCostUSD !== "number" || !Number.isFinite(e.totalCostUSD))
41
+ return undefined;
42
+ const models = {};
43
+ const mu = e.modelUsage && typeof e.modelUsage === "object" && !Array.isArray(e.modelUsage) ? e.modelUsage : {};
44
+ for (const [m, v] of Object.entries(mu).slice(0, 40)) {
45
+ if (!v || typeof v !== "object")
46
+ continue;
47
+ const u = v;
48
+ models[m.slice(0, 100)] = {
49
+ usd: num(u.costUSD), input: num(u.inputTokens), output: num(u.outputTokens), read: num(u.cacheReadInputTokens), write: num(u.cacheCreationInputTokens),
50
+ write1h: num(u.cacheCreationEphemeral1hInputTokens), write5m: num(u.cacheCreationEphemeral5mInputTokens), searches: num(u.webSearchRequests),
51
+ };
52
+ }
53
+ return {
54
+ type: "cost-state", usd: Math.max(0, e.totalCostUSD), ...(num(e.startTime) ? { start: e.startTime } : {}), models,
55
+ ...(e.hasUnknownModelCost === true ? { unknown: true } : {}), ...(version ? { version } : {}),
56
+ };
57
+ }
58
+ /**
59
+ * A request Claude Code sent, the model declined (a refusal), and Claude
60
+ * Code sent again on another model (`model_refusal_fallback`): billed, and
61
+ * no row records its usage. Kept by the usage scan as its model and time.
62
+ */
63
+ export function refusalRecord(e) {
64
+ if (e?.type !== "system" || e.subtype !== "model_refusal_fallback" || typeof e.originalModel !== "string")
65
+ return undefined;
66
+ return { type: "refusal", model: e.originalModel.slice(0, 100), ...(typeof e.timestamp === "string" ? { timestamp: e.timestamp } : {}) };
67
+ }
68
+ /** 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. */
69
+ export function lastCostState(rows) {
70
+ let cs, to = NaN, last = NaN, first;
71
+ let declined = {}, pending = {};
72
+ for (const r of rows) {
73
+ if (r?.type === "cost-state") {
74
+ cs = r;
75
+ to = last;
76
+ for (const [m, n] of Object.entries(pending))
77
+ declined[m] = (declined[m] ?? 0) + n;
78
+ pending = {};
79
+ continue;
80
+ }
81
+ if (r?.type === "refusal") {
82
+ pending[r.model] = (pending[r.model] ?? 0) + 1;
83
+ continue;
84
+ }
85
+ if (r?.type !== "assistant")
86
+ continue;
87
+ const ts = Date.parse(String(r.timestamp ?? ""));
88
+ if (!Number.isFinite(ts))
89
+ continue;
90
+ last = ts;
91
+ if (first === undefined)
92
+ first = ts;
93
+ }
94
+ return cs && Number.isFinite(to) ? { cs, to, ...(first !== undefined ? { first } : {}), declined } : undefined;
95
+ }
96
+ /** The parts of the gap of one or more sessions (see GapParts). */
97
+ export function gapParts(sessions) {
98
+ const p = { declinedUsd: 0, declined: 0, declinedModels: [], sideUsd: 0, sideModels: [], sideSearches: 0, tokensUsd: 0, priceUsd: 0 };
99
+ const add = (list, m) => { if (!list.includes(m))
100
+ list.push(m); };
101
+ for (const s of sessions) {
102
+ for (const m of s.models) {
103
+ if (m.ours.requests === 0 && m.declined) {
104
+ p.declinedUsd += m.ccUsd;
105
+ p.declined += m.declined;
106
+ add(p.declinedModels, m.model);
107
+ }
108
+ else if (m.ours.requests === 0) {
109
+ p.sideUsd += m.ccUsd;
110
+ p.sideSearches += m.cc.searches;
111
+ if (m.ccUsd > 0)
112
+ add(p.sideModels, m.model);
113
+ }
114
+ else {
115
+ p.tokensUsd += m.ccAtOurUsd - m.ourUsd;
116
+ p.priceUsd += m.ccUsd - m.ccAtOurUsd;
117
+ }
118
+ }
119
+ // What its total holds beyond its models' lines (none seen): kept so the parts add up.
120
+ p.priceUsd += s.ccUsd - s.models.reduce((n, m) => n + m.ccUsd, 0);
121
+ }
122
+ return p;
123
+ }
124
+ /**
125
+ * A model line of Claude Code's priced at ours, as one request at `at`. The
126
+ * tokens are a whole session's, not one prompt, so a long-prompt tier would
127
+ * be misapplied: what it added is taken out. Writes Claude Code did not
128
+ * split by lifetime (all of them before about 2.1.317, and in a session
129
+ * resumed across that version the ones from before it: one of the author's
130
+ * has 3.8M of 10.5M split) are priced at `writePerToken`, what ours cost
131
+ * per token on the same model in the same session (each by its own
132
+ * lifetime), else as 1-hour writes, Claude Code's main thread's.
133
+ */
134
+ function atOurPrices(model, m, at, writePerToken) {
135
+ const w1h = Math.min(m.write, m.write1h), w5m = Math.min(m.write - w1h, m.write5m);
136
+ const rest = m.write - w1h - w5m;
137
+ const asOneHour = writePerToken === undefined ? rest : 0;
138
+ const u = {
139
+ input_tokens: m.input, output_tokens: m.output, cache_read_input_tokens: m.read, cache_creation_input_tokens: w1h + w5m + asOneHour,
140
+ cache_creation: { ephemeral_1h_input_tokens: w1h + asOneHour, ephemeral_5m_input_tokens: w5m },
141
+ server_tool_use: { web_search_requests: m.searches },
142
+ };
143
+ const c = requestCost(realModel(model), u, at);
144
+ if (!c)
145
+ return 0;
146
+ return c.totalUsd - c.modifiers.longUsd + (writePerToken === undefined ? 0 : rest * writePerToken);
147
+ }
148
+ /** The turns of a main transcript's rows that ended where Claude Code may send a prompt suggestion, within [`from`, `to`], and their price (sidecost.ts). */
149
+ export function turnEnds(rows, from, to) {
150
+ let n = 0, usd = 0;
151
+ for (const r of rows) {
152
+ const ts = Date.parse(String(r?.timestamp ?? ""));
153
+ if (!(ts >= from && ts <= to))
154
+ continue;
155
+ const c = suggestionCost(r);
156
+ if (c) {
157
+ n++;
158
+ usd += c.cost.totalUsd;
159
+ }
160
+ }
161
+ return { n, usd };
162
+ }
163
+ /** A connection error that means the request never reached the API (not billed). */
164
+ const UNSENT = /^(ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH)$/;
165
+ /** A request no reply answers, sent again unchanged this long after or later: it hung. */
166
+ export const HUNG_MS = 60_000;
167
+ /**
168
+ * Requests that hung: Claude Code sent one (an `api-request` row, 2.1.308+),
169
+ * no reply answers it, and Claude Code sent it again unchanged (a row whose
170
+ * `base` is it, with no new messages) a minute or more later, with no error
171
+ * between saying it never left the machine. On the author's machine they
172
+ * come in runs while the network is down or the machine sleeps (a subagent
173
+ * sent the same 380k-token prompt every ~16 minutes through a night), and
174
+ * the two stretches between Claude Code's cost-state records that hold most
175
+ * of them hold most of the gap: Claude Code bills a request the API had
176
+ * begun, and no row records its usage. Which ones the API had begun is in
177
+ * no file, so they are counted, not priced. Within [`from`, `to`].
178
+ */
179
+ export function stalledRetries(files, from, to) {
180
+ let n = 0;
181
+ for (const f of files) {
182
+ let rows;
183
+ try {
184
+ rows = rowsOf(f, USAGE_ROWS);
185
+ }
186
+ catch {
187
+ continue;
188
+ }
189
+ const answered = new Set();
190
+ for (const r of rows)
191
+ if (r?.type === "assistant" && typeof r.requestRef === "string")
192
+ answered.add(r.requestRef);
193
+ let pending;
194
+ for (const r of rows) {
195
+ if (r?.type === "system" && r.subtype === "api_error") {
196
+ if (pending && UNSENT.test(String(r.code ?? "")))
197
+ pending.unsent = true;
198
+ continue;
199
+ }
200
+ if (r?.type !== "api-request")
201
+ continue;
202
+ const at = Date.parse(String(r.timestamp ?? ""));
203
+ if (pending && r.base === pending.id && r.t === 0 && !pending.unsent && at - pending.at >= HUNG_MS && pending.at >= from && pending.at <= to)
204
+ n++;
205
+ pending = typeof r.id === "string" && !answered.has(r.id) && Number.isFinite(at) ? { id: r.id, at, unsent: false } : undefined;
206
+ }
207
+ }
208
+ return n;
209
+ }
210
+ /**
211
+ * The comparison for the sessions among `tops` whose Claude Code record and
212
+ * our requests both fall inside [`since`, `until`]: `items` are spend's
213
+ * Claude Code items (each request once, its session the transcript's name).
214
+ * A session whose last record starts after its first reply (a record that
215
+ * restarted on resume) is compared from where the record starts.
216
+ */
217
+ export function compareSessions(tops, items, since = -Infinity, until = Infinity) {
218
+ const bySession = new Map();
219
+ for (const it of items)
220
+ if (it.tool === "claude")
221
+ (bySession.get(it.session) ?? bySession.set(it.session, []).get(it.session)).push(it);
222
+ const out = [];
223
+ for (const top of tops) {
224
+ let rec;
225
+ try {
226
+ rec = lastCostState(rowsOf(top, USAGE_ROWS));
227
+ }
228
+ catch {
229
+ continue;
230
+ }
231
+ if (!rec)
232
+ continue;
233
+ // From its start, which Claude Code sets a second or so before the first reply; a record that
234
+ // restarted later (a resume that did not restore it) covers only from its own start.
235
+ 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);
236
+ if (start < since || rec.to > until)
237
+ continue;
238
+ const session = basename(top, ".jsonl");
239
+ const mine = (bySession.get(session) ?? []).filter((it) => it.ts >= start - 1000 && it.ts <= rec.to);
240
+ const g = sessionGap(session, rec.cs, mine, start, rec.to, rec.declined);
241
+ const stalled = stalledRetries([top, ...subagentFiles(top).map((f) => f.file)], start - 1000, rec.to);
242
+ if (stalled)
243
+ g.stalled = stalled;
244
+ const ends = turnEnds(rowsOf(top, USAGE_ROWS), start - 1000, rec.to);
245
+ if (ends.n)
246
+ g.turnEnds = ends;
247
+ out.push(g);
248
+ }
249
+ return out.sort((a, b) => b.ccUsd - a.ccUsd);
250
+ }
251
+ /** One session's figures, from Claude Code's record and our items over the same span. */
252
+ export function sessionGap(session, cs, mine, from, to, declined = {}) {
253
+ const models = new Map();
254
+ 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);
255
+ let compactionUsd = 0, compactions = 0, unsettledUsd = 0, unsettled = 0;
256
+ const writeUsd = new Map();
257
+ for (const it of mine) {
258
+ const g = line(it.model ?? "unknown");
259
+ g.ourUsd += it.usd;
260
+ g.ours.input += it.input;
261
+ g.ours.output += it.output;
262
+ g.ours.read += it.read;
263
+ g.ours.write += it.write;
264
+ g.ours.requests++;
265
+ writeUsd.set(g.model, (writeUsd.get(g.model) ?? 0) + it.writeUsd);
266
+ if (it.compaction) {
267
+ compactionUsd += it.usd;
268
+ compactions++;
269
+ }
270
+ if (it.unsettled && it.output > 0) {
271
+ unsettledUsd += (it.outputUsd * it.unsettled) / it.output;
272
+ unsettled++;
273
+ }
274
+ }
275
+ for (const [model, m] of Object.entries(cs.models)) {
276
+ const g = line(realModel(model) ?? model);
277
+ g.ccUsd += m.usd;
278
+ g.cc.input += m.input;
279
+ g.cc.output += m.output;
280
+ g.cc.read += m.read;
281
+ g.cc.write += m.write;
282
+ g.cc.searches += m.searches;
283
+ g.ccAtOurUsd += atOurPrices(model, m, to, g.ours.write > 0 ? writeUsd.get(g.model) / g.ours.write : undefined);
284
+ }
285
+ for (const [model, n] of Object.entries(declined)) {
286
+ const g = models.get(realModel(model) ?? model);
287
+ if (g)
288
+ g.declined = (g.declined ?? 0) + n;
289
+ }
290
+ return {
291
+ session, ...(mine[0]?.project ? { project: mine[0].project } : {}), from, to, ccUsd: cs.usd, ourUsd: mine.reduce((n, it) => n + it.usd, 0), compactionUsd, compactions,
292
+ ...(unsettled ? { unsettledUsd, unsettled } : {}),
293
+ ...(cs.version ? { version: cs.version } : {}), ...(cs.unknown ? { unknown: true } : {}),
294
+ models: [...models.values()].sort((a, b) => b.ccUsd - a.ccUsd),
295
+ };
296
+ }
297
+ /** The version that counts other mods' model calls in Claude Code's cost (CHANGELOG 2.1.325). */
298
+ export const MODS_COUNTED_FROM = "2.1.325";
299
+ /** a >= b, as dotted versions. */
300
+ export function versionAtLeast(a, b) {
301
+ if (!a)
302
+ return false;
303
+ const x = a.split(/[.-]/).map((n) => parseInt(n, 10) || 0), y = b.split(".").map((n) => parseInt(n, 10) || 0);
304
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
305
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
306
+ return (x[i] ?? 0) > (y[i] ?? 0);
307
+ return true;
308
+ }
309
+ const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
310
+ const pct = (x) => `${x >= 0 ? "+" : ""}${(x * 100).toFixed(1)}%`;
311
+ const more = (n) => `${usd(Math.abs(n))} ${n >= 0 ? "more" : "less"}`;
312
+ const list = (ms) => `${ms.slice(0, 2).join(", ")}${ms.length > 2 ? " and others" : ""}`;
313
+ /** Within this of Claude Code's figure is a match (ROADMAP K2, F1). */
314
+ export const CC_GAP_TARGET = 0.02;
315
+ /** Below this, Claude Code's figure for a session is too small for a percentage to mean anything. */
316
+ const MIN_COMPARE_USD = 0.5;
317
+ /** What the gap is made of, in words, largest part first: what Claude Code's figure holds more (or less) than ours, and why. */
318
+ export function gapText(sessions) {
319
+ const p = gapParts(sessions);
320
+ const comp = sessions.reduce((n, s) => n + s.compactionUsd, 0), nComp = sessions.reduce((n, s) => n + s.compactions, 0);
321
+ const parts = [];
322
+ if (Math.abs(p.declinedUsd) >= 0.005)
323
+ 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`]);
324
+ if (Math.abs(p.sideUsd) >= 0.005)
325
+ 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`]);
326
+ // Ours holds the compactions' own requests as estimates (no row records their usage): what its tokens say of them.
327
+ // Claude Code's prompt suggestions: as many as its input beyond ours on the session's models has room for (each adds its
328
+ // ~506-token instruction), priced as the turn ends they may follow are on average (sidecost.ts). An estimate of a part of the gap.
329
+ let nSug = 0, sug = 0;
330
+ for (const s of sessions) {
331
+ const ends = s.turnEnds;
332
+ if (!ends?.n)
333
+ continue;
334
+ const room = Math.round(s.models.filter((m) => m.ours.requests > 0).reduce((t, m) => t + Math.max(0, m.cc.input - m.ours.input), 0) / SUGGESTION_PROMPT_TOKENS);
335
+ const k = Math.min(ends.n, room);
336
+ nSug += k;
337
+ sug += (ends.usd * k) / ends.n;
338
+ }
339
+ const nUns = sessions.reduce((n, s) => n + (s.unsettled ?? 0), 0), uns = sessions.reduce((n, s) => n + (s.unsettledUsd ?? 0), 0);
340
+ const stalled = sessions.reduce((n, s) => n + (s.stalled ?? 0), 0);
341
+ const ests = [
342
+ nComp ? `${nComp} compaction${nComp === 1 ? "'s" : "s'"} own request${nComp === 1 ? "" : "s"} (${usd(comp)})` : "",
343
+ nUns ? `the output of ${nUns.toLocaleString("en-US")} subagent repl${nUns === 1 ? "y" : "ies"} whose rows never settled it (${usd(uns)})` : "",
344
+ ].filter(Boolean);
345
+ const compText = ests.length ? `${ests.length > 1 ? `${ests.slice(0, -1).join(", ")} and ${ests[ests.length - 1]}` : ests[0]}, which we estimate` : "";
346
+ const sugText = nSug ? `; about ${nSug.toLocaleString("en-US")} of them Claude Code's prompt suggestions (the line it suggests after a turn, reading the conversation from the cache; counted by the ${SUGGESTION_PROMPT_TOKENS} input tokens each adds), about ${usd(sug)}` : "";
347
+ const hung = stalled ? `; ${stalled.toLocaleString("en-US")} request${stalled === 1 ? "" : "s"} hung and ${stalled === 1 ? "was" : "were"} sent again (no reply, retried a minute or more later, most while the network was down): Claude Code bills those the API had begun, and no file says which` : "";
348
+ if (Math.abs(p.tokensUsd) >= 0.005) {
349
+ parts.push([p.tokensUsd, p.tokensUsd > 0
350
+ ? `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}` : ""}${sugText}${hung}`
351
+ : `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"}`]);
352
+ }
353
+ if (Math.abs(p.priceUsd) >= 0.005)
354
+ 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)`]);
355
+ const lines = parts.sort((a, b) => Math.abs(b[0]) - Math.abs(a[0])).map(([, t]) => t);
356
+ if (sessions.some((s) => versionAtLeast(s.version, MODS_COUNTED_FROM)))
357
+ lines.push(`From Claude Code ${MODS_COUNTED_FROM} its figure also counts other mods' own model calls, in the parts above`);
358
+ if (sessions.some((s) => s.unknown))
359
+ lines.push("Claude Code said it had no price for some model: its figure leaves that model out");
360
+ return lines;
361
+ }
362
+ /** `spend`'s lines: Claude Code's figure beside ours on the sessions both cover; none when no session has a record in the window. */
363
+ export function renderComparison(sessions) {
364
+ if (!sessions.length)
365
+ return [];
366
+ const cc = sessions.reduce((n, s) => n + s.ccUsd, 0), ours = sessions.reduce((n, s) => n + s.ourUsd, 0);
367
+ const n = sessions.length;
368
+ const worth = sessions.filter((s) => s.ccUsd >= MIN_COMPARE_USD);
369
+ const within = worth.filter((s) => Math.abs(s.ourUsd - s.ccUsd) <= CC_GAP_TARGET * s.ccUsd).length;
370
+ const lines = [
371
+ `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)})` : ""}`,
372
+ ...(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)`] : []),
373
+ ];
374
+ for (const t of gapText(sessions))
375
+ lines.push(` ${t}`);
376
+ return lines;
377
+ }
378
+ /** `session`'s lines for one session; none when its transcript has no record. */
379
+ export function renderSessionComparison(s) {
380
+ if (!s)
381
+ return [];
382
+ 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)`];
383
+ for (const t of gapText([s]))
384
+ lines.push(` ${t}`);
385
+ return lines;
386
+ }
387
+ /** `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. */
388
+ export function comparisonCheck(sessions, days) {
389
+ const worth = sessions.filter((s) => s.ccUsd >= MIN_COMPARE_USD);
390
+ if (!worth.length)
391
+ return undefined;
392
+ const label = "Our price vs Claude Code's own";
393
+ const cc = worth.reduce((n, s) => n + s.ccUsd, 0), ours = worth.reduce((n, s) => n + s.ourUsd, 0);
394
+ const gap = (ours - cc) / cc;
395
+ const within = worth.filter((s) => Math.abs((s.ourUsd - s.ccUsd) / s.ccUsd) <= CC_GAP_TARGET).length;
396
+ 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}%`;
397
+ if (Math.abs(gap) <= CC_GAP_TARGET)
398
+ return { label, status: "ok", detail: head };
399
+ return { label, status: "warn", detail: `${head}. The gap: ${gapText(worth).join("; ")}` };
400
+ }