context-doctor 0.43.0 → 0.45.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 (61) hide show
  1. package/README.md +4 -2
  2. package/dist/budget.d.ts +23 -3
  3. package/dist/budget.js +184 -50
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +1 -1
  6. package/dist/cachettl.d.ts +5 -1
  7. package/dist/cachettl.js +16 -29
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +16 -12
  10. package/dist/codexcompact.d.ts +24 -3
  11. package/dist/codexcompact.js +221 -48
  12. package/dist/coldresume.js +16 -8
  13. package/dist/compactwindow.js +14 -9
  14. package/dist/cursor.d.ts +10 -0
  15. package/dist/cursor.js +20 -0
  16. package/dist/doctor.d.ts +9 -0
  17. package/dist/doctor.js +52 -0
  18. package/dist/extract.d.ts +2 -2
  19. package/dist/extract.js +14 -3
  20. package/dist/fanout.js +4 -2
  21. package/dist/fix.d.ts +8 -1
  22. package/dist/fix.js +59 -13
  23. package/dist/hook.js +45 -15
  24. package/dist/httpguard.d.ts +9 -1
  25. package/dist/httpguard.js +5 -4
  26. package/dist/install.js +56 -19
  27. package/dist/lens.js +7 -7
  28. package/dist/limits.d.ts +17 -4
  29. package/dist/limits.js +41 -29
  30. package/dist/mcp.js +63 -63
  31. package/dist/mcpclient.js +19 -19
  32. package/dist/mcpschema.js +10 -12
  33. package/dist/overhead.d.ts +7 -2
  34. package/dist/overhead.js +11 -3
  35. package/dist/pack.js +87 -23
  36. package/dist/pricing.d.ts +125 -6
  37. package/dist/pricing.js +304 -59
  38. package/dist/proxy.d.ts +26 -1
  39. package/dist/proxy.js +45 -5
  40. package/dist/prune.d.ts +8 -0
  41. package/dist/prune.js +73 -10
  42. package/dist/savings.js +17 -9
  43. package/dist/scan.d.ts +7 -1
  44. package/dist/scan.js +19 -1
  45. package/dist/sessionprice.d.ts +9 -2
  46. package/dist/sessionprice.js +95 -36
  47. package/dist/settingsedit.js +3 -2
  48. package/dist/spend.d.ts +75 -10
  49. package/dist/spend.js +279 -37
  50. package/dist/statusline.d.ts +10 -2
  51. package/dist/statusline.js +17 -8
  52. package/dist/subagentmodel.d.ts +2 -2
  53. package/dist/subagentmodel.js +42 -25
  54. package/dist/subagentpay.d.ts +17 -0
  55. package/dist/subagentpay.js +41 -2
  56. package/dist/subagents.d.ts +24 -0
  57. package/dist/subagents.js +93 -27
  58. package/dist/tasks.js +9 -6
  59. package/dist/tooloutput.d.ts +2 -0
  60. package/dist/tooloutput.js +16 -5
  61. package/package.json +1 -1
package/dist/spend.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * Each tool keeps its own record of what it sent, and none adds them up:
6
6
  *
7
7
  * - Claude Code: every reply's `usage` in its transcripts, the main
8
- * conversation and each subagent's (`<session>/subagents/agent-*.jsonl`),
8
+ * conversation, each subagent's (`<session>/subagents/agent-*.jsonl`)
9
+ * and each workflow agent's (`<session>/subagents/workflows/<run>/`),
9
10
  * read as `limits` reads them (claudeFileUsage): each reply once, its
10
11
  * output settled on its last row, a fork's copy of its parent counted once.
11
12
  * - Codex: the `token_count` events of its rollouts (~/.codex/sessions and
@@ -20,7 +21,10 @@
20
21
  * and an upper bound. Replies on Auto ("default") have no list price and
21
22
  * are counted, not priced.
22
23
  *
23
- * 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.
24
28
  * Claude Code, Codex and Gemini CLI are read through the shared scan
25
29
  * (scan.ts), so a second run reads only what was appended since; Cursor's
26
30
  * replies are kept per chat until the chat changes.
@@ -33,33 +37,53 @@
33
37
  import { basename, dirname, join } from "node:path";
34
38
  import { codexDir } from "./codexdir.js";
35
39
  import { homedir } from "node:os";
36
- import { existsSync, statSync } from "node:fs";
40
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
37
41
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
38
42
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
39
- import { cursorUsage, SqliteUnavailableError } from "./cursor.js";
40
- import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
43
+ import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
44
+ import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
41
45
  import { pick, rowsOf } from "./scan.js";
42
46
  import { formatTokens } from "./tokens.js";
43
47
  import { withInvocation } from "./invocation.js";
44
48
  const DAY = 86_400_000;
45
49
  export const TOOLS = ["claude", "codex", "gemini", "cursor"];
46
50
  export const TOOL_NAME = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", cursor: "Cursor" };
47
- /** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
51
+ /**
52
+ * A project folder's name (its path with "-" for separators, as Claude Code
53
+ * names its projects/ folders) less the home folder: "-Users-<you>-" on
54
+ * macOS, "-home-<you>-" (or "-root-") on Linux, "C--Users-<you>-" on Windows.
55
+ * Only macOS's was stripped, so on Linux and Windows every project read
56
+ * "home-kp-app" or "C--Users-kp-app".
57
+ */
58
+ export function projectFromDir(dir) {
59
+ return dir.replace(/^(?:[A-Za-z]-)?-(?:Users|home)-[^-]+-/, "").replace(/^-root-/, "").replace(/^-/, "") || dir;
60
+ }
61
+ /** A project's name as `savings` shows it: the folder's path with "-" for separators, less the home folder. */
48
62
  export function projectName(folder) {
49
- const dir = folder.replace(/[^A-Za-z0-9]/g, "-");
50
- return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
63
+ return projectFromDir(folder.replace(/[^A-Za-z0-9]/g, "-"));
51
64
  }
52
65
  /** A Claude Code transcript's project: its folder under projects/, named as `savings` names it. */
53
66
  function claudeProject(top) {
54
- const dir = basename(dirname(top));
55
- return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
67
+ return projectFromDir(basename(dirname(top)));
68
+ }
69
+ /** Whether a request's modifiers added anything (kept on an item only then). */
70
+ export const anyModifier = (m) => Boolean(m && (m.fastUsd || m.geoUsd || m.longUsd || m.webSearchUsd || m.webSearches));
71
+ /** An estimate's labels, and what the modifiers added, onto an item. */
72
+ function label(item, c) {
73
+ if (c.estimated)
74
+ item.estimated = true;
75
+ if (c.changedOn)
76
+ item.changedOn = c.changedOn;
77
+ if (anyModifier(c.modifiers))
78
+ item.modifiers = c.modifiers;
79
+ return item;
56
80
  }
57
- function priced(base, u) {
58
- const price = pricingFor(base.model);
59
- if (!price)
81
+ /** `priceAs`: the id to price it by, when the model's own name is not one the table knows (Cursor's names for Claude). */
82
+ function priced(base, u, priceAs = base.model) {
83
+ const c = requestCost(priceAs, u, base.ts);
84
+ if (!c)
60
85
  return { ...base, usd: 0, inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0, priced: false };
61
- const c = usageCost(u, price);
62
- return { ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true };
86
+ return label({ ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true }, c);
63
87
  }
64
88
  // ---------------------------------------------------------------------------
65
89
  // Claude Code
@@ -84,17 +108,20 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
84
108
  const project = claudeProject(f.top);
85
109
  const session = basename(f.top, ".jsonl");
86
110
  for (const r of reqs) {
87
- const price = pricingFor(r.model);
88
- // claudeFileUsage priced it (writes by TTL); the split is what the drivers show.
111
+ const price = r.rates;
112
+ // claudeFileUsage priced it (requestCost: writes by TTL, its modifiers); the split is what the drivers show.
89
113
  const inputUsd = price ? (r.input * price.inputPerM) / 1e6 : 0;
90
114
  const readUsd = price ? (r.read * price.cacheReadPerM) / 1e6 : 0;
91
115
  const item = {
92
116
  tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
93
- usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd), priced: Boolean(price),
117
+ 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),
94
118
  };
119
+ label(item, r);
95
120
  if (r.model)
96
121
  item.model = r.model;
97
- if (f.subagent || r.sidechain)
122
+ if (f.run)
123
+ item.workflow = `${session}/${f.run}`;
124
+ else if (f.subagent || r.sidechain)
98
125
  item.subagent = true;
99
126
  if (r.uuid)
100
127
  item.key = r.uuid;
@@ -108,13 +135,26 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
108
135
  // Codex
109
136
  // ---------------------------------------------------------------------------
110
137
  /**
111
- * What `spend` takes from a Codex rollout: its folder, each model change,
112
- * and every token_count event's last request and running total.
138
+ * A spawned Codex agent's rollout names the thread that spawned it in its
139
+ * own (first) session_meta: `parent_thread_id`, also under
140
+ * `source.subagent.thread_spawn` (Codex Desktop 0.146, seen on the author's
141
+ * machine; a forked one starts with a copy of its parent's history, its
142
+ * session_meta rows included, which name no parent of theirs). A thread the
143
+ * user forked names only `forked_from_id`: a session of its own.
144
+ */
145
+ function spawnedBy(p) {
146
+ const parent = p.parent_thread_id ?? p.source?.subagent?.thread_spawn?.parent_thread_id;
147
+ return typeof parent === "string" && parent ? parent : undefined;
148
+ }
149
+ /**
150
+ * What `spend` takes from a Codex rollout: its folder, its own id and the
151
+ * thread that spawned it (the first session_meta), each model change, and
152
+ * every token_count event's last request and running total.
113
153
  */
114
154
  export const CODEX_SPEND_ROWS = {
115
- id: "codex-spend.2",
116
- init: () => null,
117
- line(line, row, out) {
155
+ id: "codex-spend.3",
156
+ init: () => ({}),
157
+ line(line, row, out, st) {
118
158
  if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
119
159
  return;
120
160
  let e;
@@ -127,6 +167,12 @@ export const CODEX_SPEND_ROWS = {
127
167
  const p = e?.payload;
128
168
  if (!p || typeof p !== "object")
129
169
  return;
170
+ if (e.type === "session_meta" && !st.m) {
171
+ st.m = 1;
172
+ const parent = spawnedBy(p);
173
+ if (typeof p.id === "string")
174
+ out.push({ k: "meta", id: p.id, ...(parent ? { parent } : {}) });
175
+ }
130
176
  if (e.type === "session_meta" || e.type === "turn_context") {
131
177
  if (typeof p.cwd === "string")
132
178
  out.push({ k: "cwd", cwd: p.cwd });
@@ -150,6 +196,8 @@ export function codexFileSpend(file, since, until = Infinity) {
150
196
  let model, cwd;
151
197
  let total = -1;
152
198
  for (const r of rowsOf(file, CODEX_SPEND_ROWS)) {
199
+ if (r.k === "meta")
200
+ continue;
153
201
  if (r.k === "cwd") {
154
202
  cwd = cwd ?? r.cwd;
155
203
  continue;
@@ -164,7 +212,7 @@ export function codexFileSpend(file, since, until = Infinity) {
164
212
  continue;
165
213
  total = runTotal;
166
214
  const ts = Date.parse(r.ts);
167
- if (!Number.isFinite(ts) || ts < since || ts > until)
215
+ if (!Number.isFinite(ts) || ts < since || ts > until || isUnbilledModel(model))
168
216
  continue;
169
217
  const u = openAIUsage(r.u);
170
218
  out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { model } : {}), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), ...(r.key ? { key: r.key } : {}) }, u));
@@ -176,18 +224,141 @@ export function codexFiles(since, home = homedir()) {
176
224
  const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
177
225
  return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
178
226
  }
179
- /** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
227
+ /** A Codex rollout's own thread id and the thread that spawned it, when one did (spawnedBy). Throws when it cannot be read. */
228
+ export function codexRolloutMeta(file) {
229
+ const m = rowsOf(file, CODEX_SPEND_ROWS).find((r) => r?.k === "meta");
230
+ return m ? { id: m.id, ...(m.parent ? { parent: m.parent } : {}) } : {};
231
+ }
232
+ /**
233
+ * Every Codex request in the window, once: a forked rollout's copy of its
234
+ * parent's (codexEventKey) counts at the earliest time met. A spawned
235
+ * agent's requests are its session's (the thread at the top of its
236
+ * parents, when its rollout is among the window's), marked `subagent`: they
237
+ * bill to the same work, as a Claude Code subagent's do.
238
+ */
180
239
  export function codexSpend(since, until = Infinity, home = homedir()) {
181
240
  const all = [];
241
+ const files = new Map();
242
+ const byFile = [];
182
243
  for (const f of codexFiles(since, home)) {
183
244
  try {
184
- all.push(...codexFileSpend(f, since, until));
245
+ const items = codexFileSpend(f, since, until);
246
+ const meta = codexRolloutMeta(f);
247
+ if (meta.id && !files.has(meta.id))
248
+ files.set(meta.id, { file: f, ...(meta.parent ? { parent: meta.parent } : {}) });
249
+ byFile.push([f, items]);
185
250
  }
186
251
  catch { /* unreadable: skipped */ }
187
252
  }
253
+ // Each spawned rollout's top known parent: its session.
254
+ const sessionOf = new Map();
255
+ for (const { file, parent } of files.values()) {
256
+ let top;
257
+ for (let p = parent, hops = 0; p && files.has(p) && hops < 32; p = files.get(p).parent, hops++)
258
+ top = p;
259
+ if (top)
260
+ sessionOf.set(file, basename(files.get(top).file, ".jsonl"));
261
+ }
262
+ for (const [f, items] of byFile) {
263
+ const session = sessionOf.get(f);
264
+ for (const it of items)
265
+ all.push(session ? { ...it, session, subagent: true } : it);
266
+ }
188
267
  const seen = new Set();
189
268
  return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
190
269
  }
270
+ /** Rollout names end in the thread's id: rollout-<time>-<id>.jsonl. */
271
+ 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];
272
+ /** The first line's start of a rollout (its own session_meta), as much as `bytes` holds. */
273
+ function rolloutHead(file, bytes = 16 * 1024) {
274
+ const fd = openSync(file, "r");
275
+ try {
276
+ const buf = Buffer.alloc(bytes);
277
+ const n = readSync(fd, buf, 0, bytes, 0);
278
+ const text = buf.subarray(0, n).toString("utf8");
279
+ const nl = text.indexOf("\n");
280
+ return nl >= 0 ? text.slice(0, nl) : text;
281
+ }
282
+ finally {
283
+ closeSync(fd);
284
+ }
285
+ }
286
+ /** The thread a rollout's head says spawned it (spawnedBy), read from its first line without parsing the rest. */
287
+ function headParent(file) {
288
+ const head = rolloutHead(file);
289
+ try {
290
+ const p = JSON.parse(head)?.payload ?? {};
291
+ return { id: typeof p.id === "string" ? p.id : undefined, parent: spawnedBy(p) };
292
+ }
293
+ catch {
294
+ // The line goes on past what was read (its instructions): its first fields are enough.
295
+ return { id: /"id":"([^"]+)"/.exec(head)?.[1], parent: /"parent_thread_id":"([^"]+)"/.exec(head)?.[1] };
296
+ }
297
+ }
298
+ /**
299
+ * The rollouts of the agents a Codex thread spawned (and theirs), for the
300
+ * session price: those written since the thread began in its own folder,
301
+ * the day folders from then to `now` (by local and UTC date) and the
302
+ * archive. Only each candidate's first line is read.
303
+ */
304
+ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir()) {
305
+ const id = rolloutId(parent);
306
+ if (!id)
307
+ return [];
308
+ let born;
309
+ try {
310
+ born = statSync(parent).birthtimeMs || statSync(parent).mtimeMs;
311
+ }
312
+ catch {
313
+ return [];
314
+ }
315
+ const m = /rollout-(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/.exec(basename(parent));
316
+ if (m)
317
+ born = Math.min(born, new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime());
318
+ const root = codexSessionsRoot(home);
319
+ const dirs = new Set([dirname(parent), join(codexDir(home), "archived_sessions")]);
320
+ // A long session's days, a day either side; bounded, so a bad clock is not a walk of years.
321
+ for (let t = Math.max(born, now - 90 * DAY) - DAY; t <= now + DAY; t += 3_600_000) {
322
+ const d = new Date(t);
323
+ for (const [y, mo, dd] of [[d.getFullYear(), d.getMonth() + 1, d.getDate()], [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]])
324
+ dirs.add(join(root, String(y), String(mo).padStart(2, "0"), String(dd).padStart(2, "0")));
325
+ }
326
+ const heads = new Map();
327
+ for (const dir of dirs) {
328
+ let names;
329
+ try {
330
+ names = readdirSync(dir);
331
+ }
332
+ catch {
333
+ continue;
334
+ }
335
+ for (const n of names) {
336
+ const f = join(dir, n);
337
+ if (!n.startsWith("rollout-") || !n.endsWith(".jsonl") || f === parent || heads.has(f))
338
+ continue;
339
+ try {
340
+ if (statSync(f).mtimeMs < born)
341
+ continue;
342
+ heads.set(f, headParent(f));
343
+ }
344
+ catch { /* vanished */ }
345
+ }
346
+ }
347
+ // Children, then theirs.
348
+ const mine = new Set([id]);
349
+ const out = [];
350
+ for (let grew = true; grew;) {
351
+ grew = false;
352
+ for (const [f, h] of heads) {
353
+ if (!h.parent || !mine.has(h.parent) || !h.id || mine.has(h.id))
354
+ continue;
355
+ mine.add(h.id);
356
+ out.push(f);
357
+ grew = true;
358
+ }
359
+ }
360
+ return out.sort((a, b) => basename(a).localeCompare(basename(b)));
361
+ }
191
362
  // ---------------------------------------------------------------------------
192
363
  // Gemini CLI
193
364
  // ---------------------------------------------------------------------------
@@ -255,7 +426,7 @@ export function geminiFileSpend(file, since, until = Infinity) {
255
426
  model = r.model ?? model;
256
427
  // No time anywhere before it: the chat's last write.
257
428
  const ts = Date.parse(r.ts) || (mtime ??= statSync(file).mtimeMs);
258
- if (ts < since || ts > until)
429
+ if (ts < since || ts > until || isUnbilledModel(model))
259
430
  continue;
260
431
  const u = geminiUsage(r.t);
261
432
  if (num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.output_tokens) === 0)
@@ -283,10 +454,12 @@ export function geminiSpend(since, until = Infinity, home = homedir()) {
283
454
  export function cursorSpend(since, until = Infinity) {
284
455
  const out = [];
285
456
  for (const r of cursorUsage(since)) {
286
- if (r.ts > until)
457
+ if (r.ts > until || isUnbilledModel(r.model))
287
458
  continue;
288
- // No cache split: every input token at the uncached rate.
289
- out.push(priced({ tool: "cursor", ts: r.ts, project: r.folder ? projectName(r.folder) : "(no folder)", session: r.composerId, ...(r.model ? { model: r.model } : {}), input: r.input, read: 0, write: 0, output: r.output }, { input_tokens: r.input, output_tokens: r.output }));
459
+ // No cache split: every input token at the uncached rate. Cursor's own
460
+ // names for Claude ("claude-4.6-opus-high-thinking") are priced as the
461
+ // Claude id they stand for, shown as Cursor wrote them.
462
+ out.push(priced({ tool: "cursor", ts: r.ts, project: r.folder ? projectName(r.folder) : "(no folder)", session: r.composerId, ...(r.model ? { model: r.model } : {}), input: r.input, read: 0, write: 0, output: r.output }, { input_tokens: r.input, output_tokens: r.output }, cursorClaudeId(r.model) ?? r.model));
290
463
  }
291
464
  return out;
292
465
  }
@@ -301,6 +474,8 @@ function add(map, key, it) {
301
474
  r.requests++;
302
475
  r.byTool[it.tool] = (r.byTool[it.tool] ?? 0) + it.usd;
303
476
  }
477
+ /** "1 run", "12 runs": workflow runs. */
478
+ const runsText = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "run" : "runs"}`;
304
479
  /** Add up priced requests into the report. */
305
480
  export function summarizeSpend(items, days, since, until, skipped = []) {
306
481
  const tools = new Map();
@@ -308,7 +483,18 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
308
483
  const sessions = new Map();
309
484
  const sessionModels = new Map();
310
485
  const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
486
+ const runs = new Set();
487
+ const mods = { ...NO_MODIFIERS };
488
+ const changed = new Map();
311
489
  for (const it of items) {
490
+ if (it.modifiers)
491
+ addModifiers(mods, it.modifiers);
492
+ if (it.changedOn) {
493
+ const k = `${it.model}\u0000${it.changedOn}`;
494
+ const c = changed.get(k) ?? changed.set(k, { model: it.model ?? "unknown", on: it.changedOn, requests: 0, usd: 0 }).get(k);
495
+ c.requests++;
496
+ c.usd += it.usd;
497
+ }
312
498
  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);
313
499
  t.usd += it.usd;
314
500
  t.requests++;
@@ -316,8 +502,13 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
316
502
  t.tokens.read += it.read;
317
503
  t.tokens.write += it.write;
318
504
  t.tokens.output += it.output;
319
- if (it.subagent && t.subagentUsd !== undefined)
320
- t.subagentUsd += it.usd;
505
+ if (it.subagent)
506
+ t.subagentUsd = (t.subagentUsd ?? 0) + it.usd;
507
+ if (it.workflow) {
508
+ t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
509
+ runs.add(it.workflow);
510
+ t.workflowRuns = runs.size;
511
+ }
321
512
  if (!it.priced) {
322
513
  t.unpriced++;
323
514
  t.unpricedTokens += it.input + it.read + it.write + it.output;
@@ -325,6 +516,14 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
325
516
  if (!t.unpricedModels.includes(m))
326
517
  t.unpricedModels.push(m);
327
518
  }
519
+ else if (it.estimated && !it.changedOn) {
520
+ const e = (t.estimated ??= { requests: 0, usd: 0, models: [] });
521
+ e.requests++;
522
+ e.usd += it.usd;
523
+ const m = it.model ?? "unknown";
524
+ if (!e.models.includes(m))
525
+ e.models.push(m);
526
+ }
328
527
  add(projects, it.project, it);
329
528
  add(models, it.model ?? "unknown", it);
330
529
  add(daily, localDay(it.ts), it);
@@ -354,6 +553,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
354
553
  const day = localDay(d.getTime());
355
554
  days_.push({ day, ...(daily.get(day) ?? { usd: 0, requests: 0, byTool: {} }) });
356
555
  }
556
+ if (mods.webSearchUsd > 0)
557
+ parts.webSearchUsd = mods.webSearchUsd;
357
558
  return {
358
559
  days, since, until,
359
560
  usd: items.reduce((n, it) => n + it.usd, 0),
@@ -363,6 +564,8 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
363
564
  models: [...models].map(([model, r]) => ({ model, ...r })).sort(byUsd),
364
565
  daily: days_,
365
566
  parts,
567
+ ...(anyModifier(mods) ? { modifiers: mods } : {}),
568
+ ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
366
569
  sessions: [...sessions.values()].sort(byUsd),
367
570
  skipped,
368
571
  };
@@ -398,6 +601,15 @@ const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}
398
601
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
399
602
  const shortDay = (day) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(8, 10)}`;
400
603
  const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
604
+ /** "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. */
605
+ export function modifiersText(m) {
606
+ return [
607
+ m.fastUsd > 0 ? `fast mode +${usd(m.fastUsd)}` : "",
608
+ m.geoUsd > 0 ? `US-only +${usd(m.geoUsd)}` : "",
609
+ m.webSearches > 0 ? `web searches ${usd(m.webSearchUsd)} (${m.webSearches.toLocaleString("en-US")})` : "",
610
+ m.longUsd > 0 ? `long-prompt tier +${usd(m.longUsd)}` : "",
611
+ ].filter(Boolean).join(", ");
612
+ }
401
613
  /** The full report, kept within 80 columns. `top`: rows per list. */
402
614
  export function renderSpend(r, top = 8) {
403
615
  const lines = [];
@@ -412,7 +624,7 @@ export function renderSpend(r, top = 8) {
412
624
  lines.push("─".repeat(60));
413
625
  for (const t of r.tools) {
414
626
  const unit = t.tool === "cursor" ? "replies" : "requests";
415
- const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
627
+ const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.workflowUsd ? `workflows ${usd(t.workflowUsd)} (${runsText(t.workflowRuns ?? 0)})` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
416
628
  const note = notes.length ? ` ${notes.join(", ")}` : "";
417
629
  lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
418
630
  }
@@ -429,7 +641,11 @@ export function renderSpend(r, top = 8) {
429
641
  list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
430
642
  // A model with no list price reads "not priced", not a $0.00 that looks free.
431
643
  const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
432
- 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"}` } : {}) })), r.models.length - top);
644
+ // One priced by its family's row reads as the estimate it is.
645
+ const estimatedModels = new Set(r.tools.flatMap((t) => t.estimated?.models ?? []));
646
+ // One priced past the day its price changed, likewise.
647
+ const changedOn = new Map((r.priceChanged ?? []).map((c) => [c.model, c.on]));
648
+ 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);
433
649
  // The last two weeks of the window, a bar each, scaled to the busiest.
434
650
  const recent = r.daily.slice(-14);
435
651
  const peak = Math.max(...recent.map((d) => d.usd), 0);
@@ -437,13 +653,18 @@ export function renderSpend(r, top = 8) {
437
653
  for (const d of recent)
438
654
  lines.push(` ${shortDay(d.day)} ${usd(d.usd).padStart(9)} ${peak > 0 ? "▮".repeat(Math.round((d.usd / peak) * 30)) : ""}`);
439
655
  lines.push("", "Where it goes");
440
- const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
656
+ 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]];
441
657
  const partText = parts.filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${usd(v)} (${share(v, r.usd)})`);
442
658
  for (let i = 0; i < partText.length; i += 2)
443
659
  lines.push(` ${partText.slice(i, i + 2).join(", ")}`);
660
+ // What the requests' own billing added to the list rates, already in the parts above.
661
+ if (r.modifiers)
662
+ lines.push(` Of it, billed above list rates: ${modifiersText(r.modifiers)}`);
444
663
  const claude = r.tools.find((t) => t.tool === "claude");
445
664
  if (claude?.subagentUsd)
446
665
  lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
666
+ if (claude?.workflowUsd)
667
+ lines.push(` Claude Code workflow agents ${usd(claude.workflowUsd)} (${share(claude.workflowUsd, r.usd)}), in ${runsText(claude.workflowRuns ?? 0)}`);
447
668
  lines.push(" Biggest sessions:");
448
669
  for (const s of r.sessions.slice(0, Math.min(top, 5))) {
449
670
  const when = shortDay(localDay(s.last));
@@ -457,6 +678,18 @@ export function renderSpend(r, top = 8) {
457
678
  notes.push(`${t.unpriced.toLocaleString("en-US")} ${t.name} ${t.tool === "cursor" ? "replies" : "requests"} (${formatTokens(t.unpricedTokens)} tokens) not priced:`);
458
679
  notes.push(` ${auto ? "on Auto, which Cursor bills from your plan with no list price" : `no list price for ${t.unpricedModels.slice(0, 3).join(", ")}`}.`);
459
680
  }
681
+ for (const t of r.tools) {
682
+ if (!t.estimated)
683
+ continue;
684
+ const n = t.estimated.requests;
685
+ 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:`);
686
+ notes.push(` no list price of its own for ${t.estimated.models.slice(0, 3).join(", ")}${t.estimated.models.length > 3 ? " and others" : ""}.`);
687
+ }
688
+ if (r.priceChanged) {
689
+ const n = r.priceChanged.reduce((s, c) => s + c.requests, 0);
690
+ 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:`);
691
+ notes.push(` ${priceChangedText(r.priceChanged.map((c) => [c.model, c.on]))}.`);
692
+ }
460
693
  if (r.tools.some((t) => t.estimate))
461
694
  notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
462
695
  for (const s of r.skipped)
@@ -479,11 +712,20 @@ export function renderSpendShare(r) {
479
712
  const claude = r.tools.find((t) => t.tool === "claude");
480
713
  if (claude?.subagentUsd)
481
714
  lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
715
+ if (claude?.workflowUsd)
716
+ lines.push(`Claude Code workflow agents: ${usd(claude.workflowUsd)} of it, in ${runsText(claude.workflowRuns ?? 0)}.`);
482
717
  // Requests on a model with no list price are not in the total: said, so the total is not read as all of it.
483
718
  const unpriced = r.tools.reduce((n, t) => n + t.unpriced, 0);
484
719
  if (unpriced)
485
720
  lines.push(`Not in it: ${unpriced.toLocaleString("en-US")} ${unpriced === 1 ? "request" : "requests"} (${formatTokens(r.tools.reduce((n, t) => n + t.unpricedTokens, 0))} tokens) on models with no list price.`);
486
- const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
721
+ const estimated = r.tools.reduce((n, t) => n + (t.estimated?.usd ?? 0), 0);
722
+ if (r.tools.some((t) => t.estimated))
723
+ lines.push(`Of it, ${usd(estimated)} is on models priced as their family, an estimate.`);
724
+ if (r.priceChanged)
725
+ 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.`);
726
+ if (r.modifiers)
727
+ lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
728
+ 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]];
487
729
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
488
730
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
489
731
  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 } 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,14 +102,18 @@ 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
118
  const extra = tokens !== undefined && price ? (tokens * (price.inputPerM * (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`;
@@ -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;