context-doctor 0.44.0 → 0.46.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 (62) hide show
  1. package/README.md +5 -2
  2. package/dist/budget.d.ts +14 -1
  3. package/dist/budget.js +50 -28
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +6 -4
  6. package/dist/cacheplan.js +2 -2
  7. package/dist/cachettl.js +8 -5
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +27 -6
  10. package/dist/codexcompact.js +14 -7
  11. package/dist/coldresume.d.ts +6 -0
  12. package/dist/coldresume.js +20 -11
  13. package/dist/compactwindow.js +14 -8
  14. package/dist/doctor.js +26 -2
  15. package/dist/extract.d.ts +2 -2
  16. package/dist/extract.js +14 -3
  17. package/dist/fanout.js +1 -1
  18. package/dist/fix.js +14 -10
  19. package/dist/hook.js +6 -2
  20. package/dist/httpguard.d.ts +9 -1
  21. package/dist/httpguard.js +5 -4
  22. package/dist/lens.js +7 -7
  23. package/dist/limits.d.ts +14 -5
  24. package/dist/limits.js +26 -17
  25. package/dist/mcp.js +62 -62
  26. package/dist/mcpschema.js +5 -3
  27. package/dist/mod/api.d.ts +129 -0
  28. package/dist/mod/api.js +12 -0
  29. package/dist/mod/logic.d.ts +146 -0
  30. package/dist/mod/logic.js +222 -0
  31. package/dist/mod/register.d.ts +58 -0
  32. package/dist/mod/register.js +237 -0
  33. package/dist/modelids.d.ts +23 -0
  34. package/dist/modelids.js +49 -0
  35. package/dist/modmeasure.d.ts +121 -0
  36. package/dist/modmeasure.js +298 -0
  37. package/dist/orgrates.d.ts +75 -0
  38. package/dist/orgrates.js +165 -0
  39. package/dist/overhead.js +11 -8
  40. package/dist/pack.js +95 -22
  41. package/dist/pricing.d.ts +123 -6
  42. package/dist/pricing.js +236 -62
  43. package/dist/proxy.d.ts +12 -1
  44. package/dist/proxy.js +13 -1
  45. package/dist/prune.js +55 -3
  46. package/dist/savings.js +19 -10
  47. package/dist/scan.d.ts +7 -1
  48. package/dist/scan.js +19 -1
  49. package/dist/sessionprice.d.ts +25 -2
  50. package/dist/sessionprice.js +60 -20
  51. package/dist/spend.d.ts +62 -10
  52. package/dist/spend.js +255 -29
  53. package/dist/statusline.d.ts +10 -2
  54. package/dist/statusline.js +18 -9
  55. package/dist/subagentmodel.d.ts +2 -2
  56. package/dist/subagentmodel.js +31 -24
  57. package/dist/subagentpay.d.ts +7 -1
  58. package/dist/subagentpay.js +51 -25
  59. package/dist/subagents.js +15 -10
  60. package/dist/tasks.js +9 -6
  61. package/dist/tooloutput.js +14 -5
  62. package/package.json +1 -1
package/dist/spend.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `context-doctor spend`: one bill across every AI coding tool on this
3
- * machine, at list prices.
3
+ * machine, each request as billed at list rates.
4
4
  *
5
5
  * Each tool keeps its own record of what it sent, and none adds them up:
6
6
  *
@@ -21,7 +21,10 @@
21
21
  * and an upper bound. Replies on Auto ("default") have no list price and
22
22
  * are counted, not priced.
23
23
  *
24
- * Priced at pricing.ts's list prices (usageCost), as every report here is.
24
+ * Priced at pricing.ts's list prices with what each request recorded that
25
+ * changes its bill (requestCost: fast mode, US-only inference, a long
26
+ * prompt's tier, web searches, a price past its end date), as every report
27
+ * here is; the report says what the modifiers added.
25
28
  * Claude Code, Codex and Gemini CLI are read through the shared scan
26
29
  * (scan.ts), so a second run reads only what was appended since; Cursor's
27
30
  * replies are kept per chat until the chat changes.
@@ -34,11 +37,18 @@
34
37
  import { basename, dirname, join } from "node:path";
35
38
  import { codexDir } from "./codexdir.js";
36
39
  import { homedir } from "node:os";
37
- import { existsSync, statSync } from "node:fs";
40
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
38
41
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
39
42
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
40
43
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
41
- import { hasKnownPrice, isUnbilledModel, openAIUsage, pricingFor, usageCost } from "./pricing.js";
44
+ import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
45
+ import { orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
46
+ /**
47
+ * What spend's dollars are: each request as it was billed (its tier, fast mode,
48
+ * US-only, web searches) at list rates, or at the organization's rates.
49
+ * "At list prices" was true before those were priced; it no longer is.
50
+ */
51
+ const spendBasis = () => (orgRates() ? priceBasis() : "as billed at list rates");
42
52
  import { pick, rowsOf } from "./scan.js";
43
53
  import { formatTokens } from "./tokens.js";
44
54
  import { withInvocation } from "./invocation.js";
@@ -63,13 +73,24 @@ export function projectName(folder) {
63
73
  function claudeProject(top) {
64
74
  return projectFromDir(basename(dirname(top)));
65
75
  }
76
+ /** Whether a request's modifiers added anything (kept on an item only then). */
77
+ export const anyModifier = (m) => Boolean(m && (m.fastUsd || m.geoUsd || m.longUsd || m.webSearchUsd || m.webSearches));
78
+ /** An estimate's labels, and what the modifiers added, onto an item. */
79
+ function label(item, c) {
80
+ if (c.estimated)
81
+ item.estimated = true;
82
+ if (c.changedOn)
83
+ item.changedOn = c.changedOn;
84
+ if (anyModifier(c.modifiers))
85
+ item.modifiers = c.modifiers;
86
+ return item;
87
+ }
66
88
  /** `priceAs`: the id to price it by, when the model's own name is not one the table knows (Cursor's names for Claude). */
67
89
  function priced(base, u, priceAs = base.model) {
68
- const price = pricingFor(priceAs);
69
- if (!price)
90
+ const c = requestCost(priceAs, u, base.ts);
91
+ if (!c)
70
92
  return { ...base, usd: 0, inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0, priced: false };
71
- const c = usageCost(u, price);
72
- return { ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true, ...(hasKnownPrice(priceAs) ? {} : { estimated: true }) };
93
+ return label({ ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true }, c);
73
94
  }
74
95
  // ---------------------------------------------------------------------------
75
96
  // Claude Code
@@ -94,16 +115,15 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
94
115
  const project = claudeProject(f.top);
95
116
  const session = basename(f.top, ".jsonl");
96
117
  for (const r of reqs) {
97
- const price = pricingFor(r.model);
98
- // claudeFileUsage priced it (writes by TTL); the split is what the drivers show.
118
+ const price = r.rates;
119
+ // claudeFileUsage priced it (requestCost: writes by TTL, its modifiers); the split is what the drivers show.
99
120
  const inputUsd = price ? (r.input * price.inputPerM) / 1e6 : 0;
100
121
  const readUsd = price ? (r.read * price.cacheReadPerM) / 1e6 : 0;
101
122
  const item = {
102
123
  tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
103
- usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd), priced: Boolean(price),
124
+ 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),
104
125
  };
105
- if (price && !hasKnownPrice(r.model))
106
- item.estimated = true;
126
+ label(item, r);
107
127
  if (r.model)
108
128
  item.model = r.model;
109
129
  if (f.run)
@@ -122,13 +142,26 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
122
142
  // Codex
123
143
  // ---------------------------------------------------------------------------
124
144
  /**
125
- * What `spend` takes from a Codex rollout: its folder, each model change,
126
- * and every token_count event's last request and running total.
145
+ * A spawned Codex agent's rollout names the thread that spawned it in its
146
+ * own (first) session_meta: `parent_thread_id`, also under
147
+ * `source.subagent.thread_spawn` (Codex Desktop 0.146, seen on the author's
148
+ * machine; a forked one starts with a copy of its parent's history, its
149
+ * session_meta rows included, which name no parent of theirs). A thread the
150
+ * user forked names only `forked_from_id`: a session of its own.
151
+ */
152
+ function spawnedBy(p) {
153
+ const parent = p.parent_thread_id ?? p.source?.subagent?.thread_spawn?.parent_thread_id;
154
+ return typeof parent === "string" && parent ? parent : undefined;
155
+ }
156
+ /**
157
+ * What `spend` takes from a Codex rollout: its folder, its own id and the
158
+ * thread that spawned it (the first session_meta), each model change, and
159
+ * every token_count event's last request and running total.
127
160
  */
128
161
  export const CODEX_SPEND_ROWS = {
129
- id: "codex-spend.2",
130
- init: () => null,
131
- line(line, row, out) {
162
+ id: "codex-spend.3",
163
+ init: () => ({}),
164
+ line(line, row, out, st) {
132
165
  if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
133
166
  return;
134
167
  let e;
@@ -141,6 +174,12 @@ export const CODEX_SPEND_ROWS = {
141
174
  const p = e?.payload;
142
175
  if (!p || typeof p !== "object")
143
176
  return;
177
+ if (e.type === "session_meta" && !st.m) {
178
+ st.m = 1;
179
+ const parent = spawnedBy(p);
180
+ if (typeof p.id === "string")
181
+ out.push({ k: "meta", id: p.id, ...(parent ? { parent } : {}) });
182
+ }
144
183
  if (e.type === "session_meta" || e.type === "turn_context") {
145
184
  if (typeof p.cwd === "string")
146
185
  out.push({ k: "cwd", cwd: p.cwd });
@@ -164,6 +203,8 @@ export function codexFileSpend(file, since, until = Infinity) {
164
203
  let model, cwd;
165
204
  let total = -1;
166
205
  for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
206
+ if (r.k === "meta")
207
+ continue;
167
208
  if (r.k === "cwd") {
168
209
  cwd = cwd ?? r.cwd;
169
210
  continue;
@@ -190,18 +231,163 @@ export function codexFiles(since, home = homedir()) {
190
231
  const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
191
232
  return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
192
233
  }
193
- /** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
234
+ /** A Codex rollout's own thread id and the thread that spawned it, when one did (spawnedBy). Throws when it cannot be read. */
235
+ export function codexRolloutMeta(file) {
236
+ const m = rowsOf(file, CODEX_SPEND_ROWS).find((r) => r?.k === "meta");
237
+ return m ? { id: m.id, ...(m.parent ? { parent: m.parent } : {}) } : {};
238
+ }
239
+ /**
240
+ * Every Codex request in the window, once: a forked rollout's copy of its
241
+ * parent's (codexEventKey) counts at the earliest time met. A spawned
242
+ * agent's requests are its session's (the thread at the top of its
243
+ * parents, when its rollout is among the window's), marked `subagent`: they
244
+ * bill to the same work, as a Claude Code subagent's do.
245
+ */
194
246
  export function codexSpend(since, until = Infinity, home = homedir()) {
195
247
  const all = [];
248
+ const files = new Map();
249
+ const byFile = [];
196
250
  for (const f of codexFiles(since, home)) {
197
251
  try {
198
- all.push(...codexFileSpend(f, since, until));
252
+ const items = codexFileSpend(f, since, until);
253
+ const meta = codexRolloutMeta(f);
254
+ if (meta.id && !files.has(meta.id))
255
+ files.set(meta.id, { file: f, ...(meta.parent ? { parent: meta.parent } : {}) });
256
+ byFile.push([f, items]);
199
257
  }
200
258
  catch { /* unreadable: skipped */ }
201
259
  }
260
+ // Each spawned rollout's top known parent: its session.
261
+ const sessionOf = new Map();
262
+ for (const { file, parent } of files.values()) {
263
+ let top;
264
+ for (let p = parent, hops = 0; p && files.has(p) && hops < 32; p = files.get(p).parent, hops++)
265
+ top = p;
266
+ if (top)
267
+ sessionOf.set(file, basename(files.get(top).file, ".jsonl"));
268
+ }
269
+ for (const [f, items] of byFile) {
270
+ const session = sessionOf.get(f);
271
+ for (const it of items)
272
+ all.push(session ? { ...it, session, subagent: true } : it);
273
+ }
202
274
  const seen = new Set();
203
275
  return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
204
276
  }
277
+ /** Rollout names end in the thread's id: rollout-<time>-<id>.jsonl. */
278
+ const rolloutId = (file) => /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(basename(file))?.[1];
279
+ /** The first line's start of a rollout (its own session_meta), as much as `bytes` holds. */
280
+ function rolloutHead(file, bytes = 16 * 1024) {
281
+ const fd = openSync(file, "r");
282
+ try {
283
+ const buf = Buffer.alloc(bytes);
284
+ const n = readSync(fd, buf, 0, bytes, 0);
285
+ const text = buf.subarray(0, n).toString("utf8");
286
+ const nl = text.indexOf("\n");
287
+ return nl >= 0 ? text.slice(0, nl) : text;
288
+ }
289
+ finally {
290
+ closeSync(fd);
291
+ }
292
+ }
293
+ /** The thread a rollout's head says spawned it (spawnedBy), read from its first line without parsing the rest. */
294
+ function headParent(file) {
295
+ const head = rolloutHead(file);
296
+ try {
297
+ const p = JSON.parse(head)?.payload ?? {};
298
+ return { id: typeof p.id === "string" ? p.id : undefined, parent: spawnedBy(p) };
299
+ }
300
+ catch {
301
+ // The line goes on past what was read (its instructions): its first fields are enough.
302
+ return { id: /"id":"([^"]+)"/.exec(head)?.[1], parent: /"parent_thread_id":"([^"]+)"/.exec(head)?.[1] };
303
+ }
304
+ }
305
+ /**
306
+ * The rollouts of the agents a Codex thread spawned (and theirs), for the
307
+ * session price: those written since the thread began in its own folder,
308
+ * the day folders from then to `now` (by local and UTC date) and the
309
+ * archive. Only each candidate's first line is read, and with `known` only
310
+ * once: a rollout's first line (its own session_meta) never changes, so
311
+ * what it named is kept there by file name, and a prompt reads only the
312
+ * rollouts written since the last (`known.changed` says when to save it).
313
+ */
314
+ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir(), known) {
315
+ const id = rolloutId(parent);
316
+ if (!id)
317
+ return [];
318
+ let born;
319
+ try {
320
+ born = statSync(parent).birthtimeMs || statSync(parent).mtimeMs;
321
+ }
322
+ catch {
323
+ return [];
324
+ }
325
+ const m = /rollout-(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/.exec(basename(parent));
326
+ if (m)
327
+ born = Math.min(born, new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime());
328
+ const root = codexSessionsRoot(home);
329
+ const dirs = new Set([dirname(parent), join(codexDir(home), "archived_sessions")]);
330
+ // A long session's days, a day either side; bounded, so a bad clock is not a walk of years.
331
+ for (let t = Math.max(born, now - 90 * DAY) - DAY; t <= now + DAY; t += 3_600_000) {
332
+ const d = new Date(t);
333
+ for (const [y, mo, dd] of [[d.getFullYear(), d.getMonth() + 1, d.getDate()], [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]])
334
+ dirs.add(join(root, String(y), String(mo).padStart(2, "0"), String(dd).padStart(2, "0")));
335
+ }
336
+ const heads = new Map();
337
+ const kept = {};
338
+ for (const dir of dirs) {
339
+ let names;
340
+ try {
341
+ names = readdirSync(dir);
342
+ }
343
+ catch {
344
+ continue;
345
+ }
346
+ for (const n of names) {
347
+ const f = join(dir, n);
348
+ if (!n.startsWith("rollout-") || !n.endsWith(".jsonl") || f === parent || heads.has(f))
349
+ continue;
350
+ const k = known?.heads[n];
351
+ if (Array.isArray(k) && typeof k[0] === "string") {
352
+ heads.set(f, { id: k[0], ...(typeof k[1] === "string" ? { parent: k[1] } : {}) });
353
+ kept[n] = k;
354
+ continue;
355
+ }
356
+ try {
357
+ if (statSync(f).mtimeMs < born)
358
+ continue;
359
+ const h = headParent(f);
360
+ heads.set(f, h);
361
+ // Kept only once its id is there: a rollout caught before its first line was written is read again.
362
+ if (known && h.id) {
363
+ kept[n] = h.parent ? [h.id, h.parent] : [h.id];
364
+ known.changed = true;
365
+ }
366
+ }
367
+ catch { /* vanished */ }
368
+ }
369
+ }
370
+ if (known) {
371
+ // A rollout gone from every folder looked in is forgotten.
372
+ if (Object.keys(known.heads).some((n) => !(n in kept)))
373
+ known.changed = true;
374
+ known.heads = kept;
375
+ }
376
+ // Children, then theirs.
377
+ const mine = new Set([id]);
378
+ const out = [];
379
+ for (let grew = true; grew;) {
380
+ grew = false;
381
+ for (const [f, h] of heads) {
382
+ if (!h.parent || !mine.has(h.parent) || !h.id || mine.has(h.id))
383
+ continue;
384
+ mine.add(h.id);
385
+ out.push(f);
386
+ grew = true;
387
+ }
388
+ }
389
+ return out.sort((a, b) => basename(a).localeCompare(basename(b)));
390
+ }
205
391
  // ---------------------------------------------------------------------------
206
392
  // Gemini CLI
207
393
  // ---------------------------------------------------------------------------
@@ -327,7 +513,17 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
327
513
  const sessionModels = new Map();
328
514
  const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
329
515
  const runs = new Set();
516
+ const mods = { ...NO_MODIFIERS };
517
+ const changed = new Map();
330
518
  for (const it of items) {
519
+ if (it.modifiers)
520
+ addModifiers(mods, it.modifiers);
521
+ if (it.changedOn) {
522
+ const k = `${it.model}\u0000${it.changedOn}`;
523
+ const c = changed.get(k) ?? changed.set(k, { model: it.model ?? "unknown", on: it.changedOn, requests: 0, usd: 0 }).get(k);
524
+ c.requests++;
525
+ c.usd += it.usd;
526
+ }
331
527
  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);
332
528
  t.usd += it.usd;
333
529
  t.requests++;
@@ -335,8 +531,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
335
531
  t.tokens.read += it.read;
336
532
  t.tokens.write += it.write;
337
533
  t.tokens.output += it.output;
338
- if (it.subagent && t.subagentUsd !== undefined)
339
- t.subagentUsd += it.usd;
534
+ if (it.subagent)
535
+ t.subagentUsd = (t.subagentUsd ?? 0) + it.usd;
340
536
  if (it.workflow) {
341
537
  t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
342
538
  runs.add(it.workflow);
@@ -349,7 +545,7 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
349
545
  if (!t.unpricedModels.includes(m))
350
546
  t.unpricedModels.push(m);
351
547
  }
352
- else if (it.estimated) {
548
+ else if (it.estimated && !it.changedOn) {
353
549
  const e = (t.estimated ??= { requests: 0, usd: 0, models: [] });
354
550
  e.requests++;
355
551
  e.usd += it.usd;
@@ -386,6 +582,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
386
582
  const day = localDay(d.getTime());
387
583
  days_.push({ day, ...(daily.get(day) ?? { usd: 0, requests: 0, byTool: {} }) });
388
584
  }
585
+ if (mods.webSearchUsd > 0)
586
+ parts.webSearchUsd = mods.webSearchUsd;
389
587
  return {
390
588
  days, since, until,
391
589
  usd: items.reduce((n, it) => n + it.usd, 0),
@@ -395,6 +593,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
395
593
  models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
396
594
  daily: days_,
397
595
  parts,
596
+ ...(anyModifier(mods) ? { modifiers: mods } : {}),
597
+ ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
398
598
  sessions: [...sessions.values()].sort(byUsd),
399
599
  skipped,
400
600
  };
@@ -430,6 +630,15 @@ const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}
430
630
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
431
631
  const shortDay = (day) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(8, 10)}`;
432
632
  const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
633
+ /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
634
+ export function modifiersText(m) {
635
+ return [
636
+ m.fastUsd > 0 ? `fast mode +${usd(m.fastUsd)}` : "",
637
+ m.geoUsd > 0 ? `US-only +${usd(m.geoUsd)}` : "",
638
+ m.webSearches > 0 ? `web searches ${usd(m.webSearchUsd)} (${m.webSearches.toLocaleString("en-US")})` : "",
639
+ m.longUsd > 0 ? `long-prompt tier +${usd(m.longUsd)}` : "",
640
+ ].filter(Boolean).join(", ");
641
+ }
433
642
  /** The full report, kept within 80 columns. `top`: rows per list. */
434
643
  export function renderSpend(r, top = 8) {
435
644
  const lines = [];
@@ -440,7 +649,10 @@ export function renderSpend(r, top = 8) {
440
649
  return lines.join("\n");
441
650
  }
442
651
  lines.push("What your AI coding cost, across every tool here");
443
- lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices`);
652
+ lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}`);
653
+ const org = orgRatesLine();
654
+ if (org)
655
+ lines.push(org);
444
656
  lines.push("─".repeat(60));
445
657
  for (const t of r.tools) {
446
658
  const unit = t.tool === "cursor" ? "replies" : "requests";
@@ -463,7 +675,9 @@ export function renderSpend(r, top = 8) {
463
675
  const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
464
676
  // One priced by its family's row reads as the estimate it is.
465
677
  const estimatedModels = new Set(r.tools.flatMap((t) => t.estimated?.models ?? []));
466
- 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" } : {}) })), r.models.length - top);
678
+ // One priced past the day its price changed, likewise.
679
+ const changedOn = new Map((r.priceChanged ?? []).map((c) => [c.model, c.on]));
680
+ 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);
467
681
  // The last two weeks of the window, a bar each, scaled to the busiest.
468
682
  const recent = r.daily.slice(-14);
469
683
  const peak = Math.max(...recent.map((d) => d.usd), 0);
@@ -471,10 +685,13 @@ export function renderSpend(r, top = 8) {
471
685
  for (const d of recent)
472
686
  lines.push(` ${shortDay(d.day)} ${usd(d.usd).padStart(9)} ${peak > 0 ? "▮".repeat(Math.round((d.usd / peak) * 30)) : ""}`);
473
687
  lines.push("", "Where it goes");
474
- const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
688
+ const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
475
689
  const partText = parts.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${usd(v)} (${share(v, r.usd)})`);
476
690
  for (let i = 0; i < partText.length; i += 2)
477
691
  lines.push(` ${partText.slice(i, i + 2).join(", ")}`);
692
+ // What the requests' own billing added to the list rates, already in the parts above.
693
+ if (r.modifiers)
694
+ lines.push(` Of it, billed above list rates: ${modifiersText(r.modifiers)}`);
478
695
  const claude = r.tools.find((t) => t.tool === "claude");
479
696
  if (claude?.subagentUsd)
480
697
  lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
@@ -500,13 +717,18 @@ export function renderSpend(r, top = 8) {
500
717
  notes.push(`${n.toLocaleString("en-US")} ${t.name} ${t.tool === "cursor" ? (n === 1 ? "reply" : "replies") : n === 1 ? "request" : "requests"} (${usd(t.estimated.usd)}) priced as ${n === 1 ? "its" : "their"} model's family, an estimate:`);
501
718
  notes.push(` no list price of its own for ${t.estimated.models.slice(0, 3).join(", ")}${t.estimated.models.length > 3 ? " and others" : ""}.`);
502
719
  }
720
+ if (r.priceChanged) {
721
+ const n = r.priceChanged.reduce((s, c) => s + c.requests, 0);
722
+ notes.push(`${n.toLocaleString("en-US")} ${n === 1 ? "request" : "requests"} (${usd(r.priceChanged.reduce((s, c) => s + c.usd, 0))}) priced past the day ${n === 1 ? "its" : "their"} model's price changed, an estimate:`);
723
+ notes.push(` ${priceChangedText(r.priceChanged.map((c) => [c.model, c.on]))}.`);
724
+ }
503
725
  if (r.tools.some((t) => t.estimate))
504
726
  notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
505
727
  for (const s of r.skipped)
506
728
  notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
507
729
  if (notes.length)
508
730
  lines.push("", ...notes);
509
- lines.push("", "List prices, as an API key bills; on a subscription the same tokens come out");
731
+ lines.push("", "As an API key is billed; on a subscription the same tokens come out");
510
732
  lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
511
733
  return withInvocation(lines.map((l) => l.trimEnd()).join("\n"));
512
734
  }
@@ -518,7 +740,7 @@ export function renderSpendShare(r) {
518
740
  if (r.requests === 0)
519
741
  return "context-doctor found no AI coding usage to measure yet.";
520
742
  const tools = r.tools.map((t) => `${t.name} ${t.estimate ? "~" : ""}${usd(t.usd)}${t.estimate ? " (estimate)" : ""}`).join(", ");
521
- const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
743
+ const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
522
744
  const claude = r.tools.find((t) => t.tool === "claude");
523
745
  if (claude?.subagentUsd)
524
746
  lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
@@ -531,7 +753,11 @@ export function renderSpendShare(r) {
531
753
  const estimated = r.tools.reduce((n, t) => n + (t.estimated?.usd ?? 0), 0);
532
754
  if (r.tools.some((t) => t.estimated))
533
755
  lines.push(`Of it, ${usd(estimated)} is on models priced as their family, an estimate.`);
534
- const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
756
+ if (r.priceChanged)
757
+ lines.push(`Of it, ${usd(r.priceChanged.reduce((s, c) => s + c.usd, 0))} is on models priced past the day their price changed, an estimate.`);
758
+ if (r.modifiers)
759
+ lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
760
+ const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
535
761
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
536
762
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
537
763
  if (r.models[0] && r.usd > 0)
@@ -28,6 +28,7 @@
28
28
  * prints nothing at all, because a status line that shows an error is worse
29
29
  * than one that shows nothing.
30
30
  */
31
+ import { type RecordedUsage } from "./pricing.js";
31
32
  /** The parts of Claude Code's status payload this reads. All optional. */
32
33
  interface StatusInput {
33
34
  session_id?: string;
@@ -52,6 +53,8 @@ interface StatusInput {
52
53
  input_tokens?: number;
53
54
  cache_read_input_tokens?: number;
54
55
  cache_creation_input_tokens?: number;
56
+ speed?: string;
57
+ inference_geo?: string;
55
58
  } | null;
56
59
  };
57
60
  }
@@ -74,6 +77,8 @@ interface LiveUsage {
74
77
  tokens: number;
75
78
  cacheShare?: number;
76
79
  model?: string;
80
+ /** What the last request recorded that changes its price (fast mode, US-only): the next one is billed alike. */
81
+ billing?: Pick<RecordedUsage, "speed" | "inference_geo">;
77
82
  }
78
83
  /** Newest assistant usage from the END of a transcript, without reading the file. */
79
84
  export declare function tailUsage(path: string, tailBytes?: number): LiveUsage | undefined;
@@ -83,9 +88,12 @@ export declare function tailUsage(path: string, tailBytes?: number): LiveUsage |
83
88
  * 2x at an hour) where a warm one would read them (0.1x). The extra is the
84
89
  * price; tokens alone when the model has no price. Undefined when Claude Code
85
90
  * does not say (no `prompt_cache`, caching off, or right after a compaction
86
- * while the cache is cold).
91
+ * while the cache is cold). Priced as the next request bills (requestCost's
92
+ * rate card): `billing` (fast mode, US-only) as the last request recorded,
93
+ * and the tier of a prompt of `prompt` tokens (the re-cached ones when not
94
+ * given).
87
95
  */
88
- export declare function cacheClock(pc: PromptCache | null | undefined, model: string | undefined, nowMs?: number): string | undefined;
96
+ export declare function cacheClock(pc: PromptCache | null | undefined, model: string | undefined, nowMs?: number, billing?: LiveUsage["billing"], prompt?: number): string | undefined;
89
97
  /**
90
98
  * Build the status line, or null when there is nothing trustworthy to show.
91
99
  * `budget`: the spend budget's part ("$12/$50 today"), when one is set.
@@ -30,10 +30,12 @@
30
30
  */
31
31
  import { closeSync, openSync, readSync, statSync } from "node:fs";
32
32
  import { contextWindowFor, formatTokens } from "./tokens.js";
33
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, pricingFor } from "./pricing.js";
33
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt, writePerM } from "./pricing.js";
34
34
  import { recordLimits } from "./limits.js";
35
35
  import { recordMiss } from "./missledger.js";
36
36
  import { budgetStatus } from "./budget.js";
37
+ /** The fields of a usage that carry over to the next request's price. */
38
+ const billingOf = (u) => (u && (u.speed === "fast" || u.inference_geo === "us") ? { ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}) } : undefined);
37
39
  /** Newest assistant usage from the END of a transcript, without reading the file. */
38
40
  export function tailUsage(path, tailBytes = 256 * 1024) {
39
41
  try {
@@ -67,8 +69,10 @@ export function tailUsage(path, tailBytes = 256 * 1024) {
67
69
  continue;
68
70
  const read = usage.cache_read_input_tokens ?? 0;
69
71
  const tokens = (usage.input_tokens ?? 0) + read + (usage.cache_creation_input_tokens ?? 0);
70
- if (tokens > 0)
71
- return { tokens, cacheShare: read / tokens, model: entry.message?.model };
72
+ if (tokens > 0) {
73
+ const billing = billingOf(usage);
74
+ return { tokens, cacheShare: read / tokens, model: entry.message?.model, ...(billing ? { billing } : {}) };
75
+ }
72
76
  }
73
77
  }
74
78
  catch {
@@ -98,16 +102,20 @@ const MAX_EXPIRY_AHEAD_S = 2 * 3600;
98
102
  * 2x at an hour) where a warm one would read them (0.1x). The extra is the
99
103
  * price; tokens alone when the model has no price. Undefined when Claude Code
100
104
  * does not say (no `prompt_cache`, caching off, or right after a compaction
101
- * while the cache is cold).
105
+ * while the cache is cold). Priced as the next request bills (requestCost's
106
+ * rate card): `billing` (fast mode, US-only) as the last request recorded,
107
+ * and the tier of a prompt of `prompt` tokens (the re-cached ones when not
108
+ * given).
102
109
  */
103
- export function cacheClock(pc, model, nowMs = Date.now()) {
110
+ export function cacheClock(pc, model, nowMs = Date.now(), billing, prompt) {
104
111
  if (!pc || pc.caching_observed === false)
105
112
  return undefined;
106
113
  const r = pc.recache_tokens_if_cold;
107
114
  const tokens = typeof r === "number" && Number.isFinite(r) && r > 0 && r <= MAX_RECACHE_TOKENS ? r : undefined;
108
- const price = pricingFor(model);
115
+ const card = rateCard(model, billing, nowMs);
116
+ const price = card && ratesAt(card, prompt ?? tokens ?? 0);
109
117
  const oneHour = pc.ttl === "1h";
110
- const extra = tokens !== undefined && price ? (tokens * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
118
+ const extra = tokens !== undefined && price ? (tokens * (writePerM(price, oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
111
119
  const cost = tokens === undefined ? undefined : extra !== undefined && extra > 0 ? `+${formatUsd(extra)}` : `${formatTokens(tokens)} re-write`;
112
120
  // Epoch seconds within two hours of now: milliseconds, 1e300 and the like
113
121
  // would print a nonsense time ("NaN:NaN"), so they count as no expiry.
@@ -140,7 +148,8 @@ export function renderStatusLine(input, nowMs = Date.now(), budget) {
140
148
  const fromPayload = cu ? (cu.input_tokens ?? 0) + (cu.cache_read_input_tokens ?? 0) + (cu.cache_creation_input_tokens ?? 0) : 0;
141
149
  if (cu && fromPayload > 0) {
142
150
  const read = cu.cache_read_input_tokens;
143
- live = { tokens: fromPayload, cacheShare: read !== undefined ? read / fromPayload : undefined, model: input.model?.id };
151
+ const billing = billingOf(cu);
152
+ live = { tokens: fromPayload, cacheShare: read !== undefined ? read / fromPayload : undefined, model: input.model?.id, ...(billing ? { billing } : {}) };
144
153
  }
145
154
  else if (input.transcript_path) {
146
155
  live = tailUsage(input.transcript_path);
@@ -160,7 +169,7 @@ export function renderStatusLine(input, nowMs = Date.now(), budget) {
160
169
  if (live.cacheShare !== undefined)
161
170
  parts.push(`cache ${Math.round(live.cacheShare * 100)}%`);
162
171
  }
163
- const warmth = cacheClock(input.prompt_cache, input.model?.id ?? live?.model, nowMs);
172
+ const warmth = cacheClock(input.prompt_cache, input.model?.id ?? live?.model, nowMs, live?.billing, live?.tokens);
164
173
  if (warmth)
165
174
  parts.push(warmth);
166
175
  // The session's cost is true whatever the context is; show it on its own.
@@ -69,9 +69,9 @@ export interface TypeReplay {
69
69
  billedUsd: number;
70
70
  /** The same requests with the ones the variable moves at the candidate model. */
71
71
  atCandidateUsd: number;
72
- /** Every request of this type at Haiku 5.5's base rates (a floor: see over100k). */
72
+ /** Every request of this type at Haiku 5.5, a prompt over 100k at its higher rates. */
73
73
  atHaikuUsd: number;
74
- /** Requests whose prompt was over 100k tokens, which Haiku 5.5 bills at a higher rate not priced here. */
74
+ /** Requests whose prompt was over 100k tokens, which Haiku 5.5 bills at its higher rates (in atHaikuUsd). */
75
75
  over100k: number;
76
76
  moves: boolean;
77
77
  why?: string;