context-doctor 0.42.0 → 0.44.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 (48) hide show
  1. package/README.md +6 -3
  2. package/dist/budget.d.ts +52 -0
  3. package/dist/budget.js +209 -59
  4. package/dist/cachettl.d.ts +5 -1
  5. package/dist/cachettl.js +10 -25
  6. package/dist/cli.js +33 -15
  7. package/dist/codexcompact.d.ts +137 -0
  8. package/dist/codexcompact.js +581 -0
  9. package/dist/compactwindow.js +2 -2
  10. package/dist/cursor.d.ts +10 -0
  11. package/dist/cursor.js +20 -0
  12. package/dist/doctor.d.ts +9 -0
  13. package/dist/doctor.js +55 -0
  14. package/dist/fanout.js +4 -2
  15. package/dist/fix.d.ts +38 -4
  16. package/dist/fix.js +249 -21
  17. package/dist/hook.js +65 -16
  18. package/dist/install.js +56 -19
  19. package/dist/ledger.d.ts +2 -1
  20. package/dist/ledger.js +1 -0
  21. package/dist/limits.d.ts +6 -2
  22. package/dist/limits.js +19 -16
  23. package/dist/mcp.js +63 -63
  24. package/dist/mcpclient.js +19 -19
  25. package/dist/mcpschema.js +5 -9
  26. package/dist/overhead.d.ts +7 -2
  27. package/dist/overhead.js +11 -3
  28. package/dist/pack.js +23 -3
  29. package/dist/pricing.d.ts +25 -5
  30. package/dist/pricing.js +157 -48
  31. package/dist/proxy.d.ts +15 -1
  32. package/dist/proxy.js +33 -5
  33. package/dist/prune.d.ts +8 -0
  34. package/dist/prune.js +20 -9
  35. package/dist/savings.js +2 -1
  36. package/dist/sessionprice.d.ts +77 -0
  37. package/dist/sessionprice.js +267 -0
  38. package/dist/settingsedit.js +3 -2
  39. package/dist/spend.d.ts +25 -3
  40. package/dist/spend.js +67 -19
  41. package/dist/subagentmodel.js +11 -1
  42. package/dist/subagentpay.d.ts +17 -0
  43. package/dist/subagentpay.js +41 -2
  44. package/dist/subagents.d.ts +24 -0
  45. package/dist/subagents.js +82 -17
  46. package/dist/tooloutput.d.ts +120 -0
  47. package/dist/tooloutput.js +357 -0
  48. package/package.json +1 -1
@@ -0,0 +1,77 @@
1
+ /**
2
+ * A session's own price, said once while it runs.
3
+ *
4
+ * The budget counts a day across tools; one session can cost $2,000 on its
5
+ * own without anyone noticing that each message now re-reads ~470k tokens
6
+ * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
+ * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
+ * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
+ * included (they bill to it), and when it passes $25, $100 and $500 says so
10
+ * to the user once: the cost so far, what each message of the main
11
+ * conversation now costs at the model's cache-read rate (or, after an idle
12
+ * that expired the cache, the re-write this message pays), and that
13
+ * /compact or a handoff to a new session cuts it.
14
+ *
15
+ * To the user, not the model: compacting or moving to a new session is the
16
+ * person's decision about their money, and only they can run /compact. The
17
+ * cold-resume offer measured how a model-delivered offer fares (acted on 1
18
+ * time in 33 before it got a line of its own), and a note in the model's
19
+ * context costs every later request and can pull it off the task. The
20
+ * heavy-context note already asks the model to offer a compaction.
21
+ *
22
+ * Fast and quiet. The cost is the budget ledger's per-transcript entry
23
+ * (budget.ts refreshEntry), with the period starting at 0: a prompt reads
24
+ * only what was appended since the last read. The entries are kept beside
25
+ * the hook's per-session state, but written only once enough was read to be
26
+ * worth keeping (SAVE_BYTES) or a threshold was said, so a session below
27
+ * the first threshold costs a read of its last turns and writes nothing.
28
+ * Each threshold is claimed by creating a file that must not exist yet
29
+ * (`wx`), which exactly one of several hooks running at once can do. Once
30
+ * the top threshold is said, the check is one stat.
31
+ *
32
+ * Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
33
+ * off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
34
+ */
35
+ import { type Tool } from "./spend.js";
36
+ import { type ResumeVerdict } from "./coldresume.js";
37
+ /** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
38
+ export declare const SESSION_PRICE_THRESHOLDS: number[];
39
+ /** The thresholds in force, ascending; none when switched off. */
40
+ export declare function sessionPriceThresholds(env?: NodeJS.ProcessEnv): number[];
41
+ export interface SessionPrice {
42
+ app: Tool;
43
+ /** The threshold just passed. */
44
+ threshold: number;
45
+ usd: number;
46
+ /** Subagents' part of `usd` (the Agent tool's). */
47
+ subagentUsd: number;
48
+ /** Workflow agents' part of `usd`. */
49
+ workflowUsd?: number;
50
+ /** Requests on a model with no list price, not in `usd`. */
51
+ unpriced?: number;
52
+ /** The part of `usd` priced at its model's family's row (an estimate). */
53
+ estimatedUsd?: number;
54
+ /** The main conversation's context at its last request, and its model. */
55
+ tokens?: number;
56
+ model?: string;
57
+ /** What the next message pays to re-read that context from the cache. */
58
+ readUsd?: number;
59
+ /** The cache expired while idle: what this message pays to write it again. */
60
+ coldUsd?: number;
61
+ }
62
+ export interface SessionPriceInput {
63
+ sessionId: string;
64
+ transcript: string;
65
+ event?: string;
66
+ model?: string;
67
+ /** Claude Code's SessionStart verdict on a resumed cache, from the hook's state (read only when a threshold is due). */
68
+ rv?: () => ResumeVerdict | undefined;
69
+ }
70
+ /**
71
+ * The threshold this prompt is the first to pass, with what to say about
72
+ * it, or undefined (below the first, said already, or anything unreadable).
73
+ * Claims the threshold: a second call for the same one gets undefined.
74
+ */
75
+ export declare function sessionPriceDue(input: SessionPriceInput, now?: number, env?: NodeJS.ProcessEnv): SessionPrice | undefined;
76
+ /** The line for the user (the hook's systemMessage). */
77
+ export declare function renderSessionPrice(p: SessionPrice): string;
@@ -0,0 +1,267 @@
1
+ /**
2
+ * A session's own price, said once while it runs.
3
+ *
4
+ * The budget counts a day across tools; one session can cost $2,000 on its
5
+ * own without anyone noticing that each message now re-reads ~470k tokens
6
+ * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
+ * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
+ * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
+ * included (they bill to it), and when it passes $25, $100 and $500 says so
10
+ * to the user once: the cost so far, what each message of the main
11
+ * conversation now costs at the model's cache-read rate (or, after an idle
12
+ * that expired the cache, the re-write this message pays), and that
13
+ * /compact or a handoff to a new session cuts it.
14
+ *
15
+ * To the user, not the model: compacting or moving to a new session is the
16
+ * person's decision about their money, and only they can run /compact. The
17
+ * cold-resume offer measured how a model-delivered offer fares (acted on 1
18
+ * time in 33 before it got a line of its own), and a note in the model's
19
+ * context costs every later request and can pull it off the task. The
20
+ * heavy-context note already asks the model to offer a compaction.
21
+ *
22
+ * Fast and quiet. The cost is the budget ledger's per-transcript entry
23
+ * (budget.ts refreshEntry), with the period starting at 0: a prompt reads
24
+ * only what was appended since the last read. The entries are kept beside
25
+ * the hook's per-session state, but written only once enough was read to be
26
+ * worth keeping (SAVE_BYTES) or a threshold was said, so a session below
27
+ * the first threshold costs a read of its last turns and writes nothing.
28
+ * Each threshold is claimed by creating a file that must not exist yet
29
+ * (`wx`), which exactly one of several hooks running at once can do. Once
30
+ * the top threshold is said, the check is one stat.
31
+ *
32
+ * Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
33
+ * off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
34
+ */
35
+ import { mkdirSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";
36
+ import { createHash } from "node:crypto";
37
+ import { basename, dirname, join } from "node:path";
38
+ import { statePath } from "./ledger.js";
39
+ import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
40
+ import { codexFileSpend, geminiFileSpend } from "./spend.js";
41
+ import { isGeminiChat } from "./gemini.js";
42
+ import { subagentFiles } from "./subagents.js";
43
+ import { tailUsage } from "./statusline.js";
44
+ import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
45
+ import { formatUsd, pricingFor } from "./pricing.js";
46
+ import { formatTokens } from "./tokens.js";
47
+ /** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
48
+ export const SESSION_PRICE_THRESHOLDS = [25, 100, 500];
49
+ /**
50
+ * The entries are written once a prompt has read this much: below it, the
51
+ * next prompt reading the same bytes again costs a few milliseconds, less
52
+ * than a write.
53
+ */
54
+ const SAVE_BYTES = 512 * 1024;
55
+ /** The thresholds in force, ascending; none when switched off. */
56
+ export function sessionPriceThresholds(env = process.env) {
57
+ if (env.CONTEXT_DOCTOR_NO_SESSION_PRICE === "1")
58
+ return [];
59
+ const raw = env.CONTEXT_DOCTOR_SESSION_PRICE?.trim();
60
+ if (!raw)
61
+ return SESSION_PRICE_THRESHOLDS;
62
+ const set = raw.split(/[\s,]+/).map((v) => Number(v.replace(/^\$/, ""))).filter((v) => Number.isFinite(v) && v > 0);
63
+ // A value that is not a list of dollars is not a reason to go quiet: the defaults.
64
+ return set.length ? [...new Set(set)].sort((a, b) => a - b) : SESSION_PRICE_THRESHOLDS;
65
+ }
66
+ /** This session's files beside the hook's own state: one hash per session, as hook.ts and fanout.ts name them. */
67
+ function base(sessionId) {
68
+ return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
69
+ }
70
+ const ledgerFile = (b) => `${b}.price.json`;
71
+ /** The price file's format: 2 counts only the session's own rows and may leave a finished subagent's `r` out. */
72
+ const LEDGER_VERSION = 2;
73
+ /** A subagent transcript not written for this long is done: its entry keeps no recent replies. */
74
+ const FINISHED_MS = 60 * 60_000;
75
+ const claimFile = (b, usd) => `${b}.price-${usd}`;
76
+ const DAY = 86_400_000;
77
+ /**
78
+ * Whether a threshold was said: its marker is there. The marker of a
79
+ * session still in use is touched once a day, so the hook's pruning (the
80
+ * sessions touched least recently go, hook.ts) does not take it while the
81
+ * session goes on, and the threshold is not said twice.
82
+ */
83
+ function said(path, now) {
84
+ try {
85
+ if (now - statSync(path).mtimeMs > DAY)
86
+ try {
87
+ utimesSync(path, new Date(now), new Date(now));
88
+ }
89
+ catch { /* read-only: said all the same */ }
90
+ return true;
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ /** True for exactly one caller per path: the file is created only if it is not there. */
97
+ function claim(path) {
98
+ for (let attempt = 0; attempt < 2; attempt++) {
99
+ try {
100
+ writeFileSync(path, "", { flag: "wx", mode: 0o600 });
101
+ return true;
102
+ }
103
+ catch (e) {
104
+ if (e.code !== "ENOENT" || attempt)
105
+ return false;
106
+ mkdirSync(dirname(path), { recursive: true });
107
+ }
108
+ }
109
+ return false;
110
+ }
111
+ /** The app a transcript belongs to. */
112
+ function appOf(transcript, event) {
113
+ if (event === "BeforeAgent" || isGeminiChat(transcript))
114
+ return "gemini";
115
+ return /^rollout-.*\.jsonl$/.test(basename(transcript)) ? "codex" : "claude";
116
+ }
117
+ /**
118
+ * The threshold this prompt is the first to pass, with what to say about
119
+ * it, or undefined (below the first, said already, or anything unreadable).
120
+ * Claims the threshold: a second call for the same one gets undefined.
121
+ */
122
+ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
123
+ const thresholds = sessionPriceThresholds(env);
124
+ if (!thresholds.length)
125
+ return undefined;
126
+ const b = base(input.sessionId);
127
+ // Everything said: one stat from now on.
128
+ if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
129
+ return undefined;
130
+ const app = appOf(input.transcript, input.event);
131
+ // Each file and whose it is: the main conversation, a subagent, a workflow agent.
132
+ const files = [[input.transcript, "main"]];
133
+ // Subagents and workflow agents bill to the session that started them.
134
+ if (app === "claude")
135
+ for (const f of subagentFiles(input.transcript))
136
+ files.push([f.file, f.run ? "workflow" : "sub"]);
137
+ let saved = {};
138
+ try {
139
+ const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
140
+ // Version 2 counts only this session's own rows: an older file counted a resumed session's copy of the old one.
141
+ if (raw?.v === LEDGER_VERSION && raw.f && typeof raw.f === "object")
142
+ saved = raw.f;
143
+ }
144
+ catch { /* none yet, or damaged: read again */ }
145
+ // A Claude Code session's own rows carry its id (the transcript's name); a resumed or forked session's copy of the old one's keep the old id.
146
+ const own = app === "claude" ? basename(input.transcript, ".jsonl") : undefined;
147
+ const kept = {};
148
+ let read = 0;
149
+ for (const [file] of files) {
150
+ const prev = saved[file];
151
+ const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true, own);
152
+ if (!r)
153
+ continue;
154
+ kept[file] = r.e;
155
+ // Only a Claude Code entry saves a read: Codex's and Gemini's are read whole on a change (through the scan's cache).
156
+ if (app === "claude")
157
+ read += Math.max(0, r.read);
158
+ }
159
+ // Each reply once: a fork's copy shares its key with the reply it copied.
160
+ const seen = new Set();
161
+ let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
162
+ for (const [file, whose] of files) {
163
+ const e = kept[file];
164
+ if (!e)
165
+ continue;
166
+ const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
167
+ e.k.forEach((key, i) => {
168
+ if (key) {
169
+ if (seen.has(key))
170
+ return;
171
+ seen.add(key);
172
+ }
173
+ usd += e.d[i];
174
+ if (whose === "sub")
175
+ subagentUsd += e.d[i];
176
+ if (whose === "workflow")
177
+ workflowUsd += e.d[i];
178
+ if (x.has(i))
179
+ unpriced++;
180
+ if (y.has(i))
181
+ estimatedUsd += e.d[i];
182
+ });
183
+ }
184
+ const save = () => {
185
+ // A subagent done writing (nothing for FINISHED_MS) keeps no list of its last replies: with
186
+ // hundreds of agents the list was most of the file, read on every prompt. Should it grow
187
+ // after all, it is read again whole (readAppended will not resume without the list).
188
+ const out = {};
189
+ for (const [file, whose] of files) {
190
+ const e = kept[file];
191
+ if (!e)
192
+ continue;
193
+ out[file] = whose !== "main" && e.r && now - e.m > FINISHED_MS ? (({ r: _r, ...rest }) => rest)(e) : e;
194
+ }
195
+ try {
196
+ writeWhole(ledgerFile(b), { v: LEDGER_VERSION, f: out });
197
+ }
198
+ catch { /* read again next time */ }
199
+ };
200
+ const passed = thresholds.filter((t) => usd >= t);
201
+ const top = passed[passed.length - 1];
202
+ if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
203
+ if (read >= SAVE_BYTES)
204
+ save();
205
+ return undefined;
206
+ }
207
+ // Passed two at once (a first look at a long session): said once, for the higher.
208
+ for (const t of passed.slice(0, -1))
209
+ claim(claimFile(b, t));
210
+ save();
211
+ return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
212
+ }
213
+ /** The main conversation's context now, and what the next message pays for it. */
214
+ function perMessage(app, input, now) {
215
+ try {
216
+ if (app !== "claude") {
217
+ // Codex and Gemini CLI: the last request's prompt, at the cached rate.
218
+ const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
219
+ const last = items[items.length - 1];
220
+ const model = last?.model ?? input.model;
221
+ const p = pricingFor(model);
222
+ if (!last || !p)
223
+ return {};
224
+ const tokens = last.input + last.read + last.write;
225
+ return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
226
+ }
227
+ // Undefined right after a compaction: the new size is not known yet.
228
+ const live = tailUsage(input.transcript);
229
+ if (!live)
230
+ return {};
231
+ const model = live.model ?? input.model;
232
+ const p = pricingFor(model);
233
+ // Claude Code compacts this very prompt itself: the figure is about to be wrong.
234
+ if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
235
+ return {};
236
+ const cold = withResumeVerdict(detectColdResume(input.transcript, now, undefined, 0), input.rv?.(), now);
237
+ return { tokens: live.tokens, model, readUsd: (live.tokens * p.cacheReadPerM) / 1e6, ...(cold?.resumeUsd !== undefined ? { coldUsd: cold.resumeUsd } : {}) };
238
+ }
239
+ catch {
240
+ return {};
241
+ }
242
+ }
243
+ /** "$112", "$1,240", "$25.40": a session's cost as the line shows it. */
244
+ const dollars = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
245
+ /** The line for the user (the hook's systemMessage). */
246
+ export function renderSessionPrice(p) {
247
+ // What the figure holds, briefly: its subagents and workflow agents, a part priced by family, and what it leaves out.
248
+ const agents = [
249
+ p.subagentUsd >= 0.005 ? `${dollars(p.subagentUsd)} of it subagents` : "",
250
+ (p.workflowUsd ?? 0) >= 0.005 ? `${dollars(p.workflowUsd)}${p.subagentUsd >= 0.005 ? "" : " of it"} workflow agents` : "",
251
+ ].filter(Boolean).join(", ");
252
+ const parts = [
253
+ agents,
254
+ (p.estimatedUsd ?? 0) >= 0.005 ? `~${dollars(p.estimatedUsd)} priced as its model's family, an estimate` : "",
255
+ p.unpriced ? `${p.unpriced.toLocaleString("en-US")} request${p.unpriced === 1 ? "" : "s"} with no list price not counted` : "",
256
+ ].filter(Boolean);
257
+ const subs = parts.length ? ` (${parts.join("; ")})` : "";
258
+ const head = `context-doctor: this session has cost ${dollars(p.usd)} so far${subs}`;
259
+ if (p.tokens === undefined || p.readUsd === undefined)
260
+ return `${head}.`;
261
+ const compact = p.app === "gemini" ? "/compress" : "/compact";
262
+ const ctx = `~${formatTokens(p.tokens)} tokens`;
263
+ const each = p.coldUsd !== undefined
264
+ ? `the cache expired while it was idle, so this message re-writes its ${ctx} (~${formatUsd(p.coldUsd)}), and each one after re-reads them (~${formatUsd(p.readUsd)})`
265
+ : `each message now re-reads ${ctx} (~${formatUsd(p.readUsd)})`;
266
+ return `${head}; ${each}. ${compact}, or a handoff to a new session, cuts that.`;
267
+ }
@@ -234,7 +234,8 @@ export function setJsonPath(text, path, value) {
234
234
  const root = skipWs(text, text.startsWith("") ? 1 : 0);
235
235
  const edit = (t, objStart, keys) => {
236
236
  const o = scanObject(t, objStart);
237
- const idx = o.members.findIndex((m) => m.key === keys[0]);
237
+ // A key written twice: the last one, the one JSON.parse (and Claude Code) reads.
238
+ const idx = o.members.map((m) => m.key).lastIndexOf(keys[0]);
238
239
  const m = idx >= 0 ? o.members[idx] : undefined;
239
240
  if (keys.length > 1) {
240
241
  if (m) {
@@ -304,7 +305,7 @@ function scanArray(t, start) {
304
305
  function arrayAt(t, path) {
305
306
  let at = skipWs(t, t.startsWith("") ? 1 : 0);
306
307
  for (const k of path) {
307
- const m = t[at] === "{" ? scanObject(t, at).members.find((x) => x.key === k) : undefined;
308
+ const m = t[at] === "{" ? scanObject(t, at).members.filter((x) => x.key === k).pop() : undefined;
308
309
  if (!m)
309
310
  throw new SettingsError(`"${path.join(".")}" is not in the settings file. Nothing was changed.`);
310
311
  at = m.valueStart;
package/dist/spend.d.ts 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
@@ -53,12 +54,24 @@ export interface SpendItem {
53
54
  readUsd: number;
54
55
  outputUsd: number;
55
56
  priced: boolean;
56
- /** Claude Code: run by a subagent. */
57
+ /** Priced by its family's row, not one of its own (a new release, an id the table does not list): an estimate. */
58
+ estimated?: boolean;
59
+ /** Claude Code: run by a subagent (the Agent tool's). */
57
60
  subagent?: boolean;
61
+ /** Claude Code: run by a workflow agent: its run, "<session>/<run>". */
62
+ workflow?: string;
58
63
  /** Claude Code: the reply's row uuid, which a fork's copy shares. Codex: the event's codexEventKey, which a forked rollout's copy shares. */
59
64
  key?: string;
60
65
  }
61
- /** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
66
+ /**
67
+ * A project folder's name (its path with "-" for separators, as Claude Code
68
+ * names its projects/ folders) less the home folder: "-Users-<you>-" on
69
+ * macOS, "-home-<you>-" (or "-root-") on Linux, "C--Users-<you>-" on Windows.
70
+ * Only macOS's was stripped, so on Linux and Windows every project read
71
+ * "home-kp-app" or "C--Users-kp-app".
72
+ */
73
+ export declare function projectFromDir(dir: string): string;
74
+ /** A project's name as `savings` shows it: the folder's path with "-" for separators, less the home folder. */
62
75
  export declare function projectName(folder: string): string;
63
76
  /**
64
77
  * Claude Code's requests between `since` and `until`, main threads and
@@ -102,12 +115,21 @@ export interface ToolSpend {
102
115
  };
103
116
  /** Claude Code: what its subagents cost, inside `usd`. */
104
117
  subagentUsd?: number;
118
+ /** Claude Code: what its workflow agents cost, inside `usd`, and in how many workflow runs. */
119
+ workflowUsd?: number;
120
+ workflowRuns?: number;
105
121
  /** Cursor: priced without a cache split, an upper bound. */
106
122
  estimate?: boolean;
107
123
  /** Requests whose model has no list price, counted but not in `usd`. */
108
124
  unpriced: number;
109
125
  unpricedTokens: number;
110
126
  unpricedModels: string[];
127
+ /** Requests on a model the table prices only by its family (SpendItem.estimated): in `usd`, an estimate. */
128
+ estimated?: {
129
+ requests: number;
130
+ usd: number;
131
+ models: string[];
132
+ };
111
133
  }
112
134
  export interface SpendRow {
113
135
  usd: number;
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
@@ -36,30 +37,39 @@ import { homedir } from "node:os";
36
37
  import { existsSync, statSync } from "node:fs";
37
38
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
38
39
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
39
- import { cursorUsage, SqliteUnavailableError } from "./cursor.js";
40
- import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
40
+ import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
41
+ import { hasKnownPrice, isUnbilledModel, openAIUsage, pricingFor, usageCost } from "./pricing.js";
41
42
  import { pick, rowsOf } from "./scan.js";
42
43
  import { formatTokens } from "./tokens.js";
43
44
  import { withInvocation } from "./invocation.js";
44
45
  const DAY = 86_400_000;
45
46
  export const TOOLS = ["claude", "codex", "gemini", "cursor"];
46
47
  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>-". */
48
+ /**
49
+ * A project folder's name (its path with "-" for separators, as Claude Code
50
+ * names its projects/ folders) less the home folder: "-Users-<you>-" on
51
+ * macOS, "-home-<you>-" (or "-root-") on Linux, "C--Users-<you>-" on Windows.
52
+ * Only macOS's was stripped, so on Linux and Windows every project read
53
+ * "home-kp-app" or "C--Users-kp-app".
54
+ */
55
+ export function projectFromDir(dir) {
56
+ return dir.replace(/^(?:[A-Za-z]-)?-(?:Users|home)-[^-]+-/, "").replace(/^-root-/, "").replace(/^-/, "") || dir;
57
+ }
58
+ /** A project's name as `savings` shows it: the folder's path with "-" for separators, less the home folder. */
48
59
  export function projectName(folder) {
49
- const dir = folder.replace(/[^A-Za-z0-9]/g, "-");
50
- return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
60
+ return projectFromDir(folder.replace(/[^A-Za-z0-9]/g, "-"));
51
61
  }
52
62
  /** A Claude Code transcript's project: its folder under projects/, named as `savings` names it. */
53
63
  function claudeProject(top) {
54
- const dir = basename(dirname(top));
55
- return dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir;
64
+ return projectFromDir(basename(dirname(top)));
56
65
  }
57
- function priced(base, u) {
58
- const price = pricingFor(base.model);
66
+ /** `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
+ function priced(base, u, priceAs = base.model) {
68
+ const price = pricingFor(priceAs);
59
69
  if (!price)
60
70
  return { ...base, usd: 0, inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0, priced: false };
61
71
  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 };
72
+ return { ...base, usd: c.totalUsd, inputUsd: c.inputUsd, writeUsd: c.writeUsd, readUsd: c.readUsd, outputUsd: c.outputUsd, priced: true, ...(hasKnownPrice(priceAs) ? {} : { estimated: true }) };
63
73
  }
64
74
  // ---------------------------------------------------------------------------
65
75
  // Claude Code
@@ -92,9 +102,13 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
92
102
  tool: "claude", ts: r.ts, project, session, input: r.input, read: r.read, write: r.write, output: r.output,
93
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),
94
104
  };
105
+ if (price && !hasKnownPrice(r.model))
106
+ item.estimated = true;
95
107
  if (r.model)
96
108
  item.model = r.model;
97
- if (f.subagent || r.sidechain)
109
+ if (f.run)
110
+ item.workflow = `${session}/${f.run}`;
111
+ else if (f.subagent || r.sidechain)
98
112
  item.subagent = true;
99
113
  if (r.uuid)
100
114
  item.key = r.uuid;
@@ -164,7 +178,7 @@ export function codexFileSpend(file, since, until = Infinity) {
164
178
  continue;
165
179
  total = runTotal;
166
180
  const ts = Date.parse(r.ts);
167
- if (!Number.isFinite(ts) || ts < since || ts > until)
181
+ if (!Number.isFinite(ts) || ts < since || ts > until || isUnbilledModel(model))
168
182
  continue;
169
183
  const u = openAIUsage(r.u);
170
184
  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));
@@ -255,7 +269,7 @@ export function geminiFileSpend(file, since, until = Infinity) {
255
269
  model = r.model ?? model;
256
270
  // No time anywhere before it: the chat's last write.
257
271
  const ts = Date.parse(r.ts) || (mtime ??= statSync(file).mtimeMs);
258
- if (ts < since || ts > until)
272
+ if (ts < since || ts > until || isUnbilledModel(model))
259
273
  continue;
260
274
  const u = geminiUsage(r.t);
261
275
  if (num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.output_tokens) === 0)
@@ -283,10 +297,12 @@ export function geminiSpend(since, until = Infinity, home = homedir()) {
283
297
  export function cursorSpend(since, until = Infinity) {
284
298
  const out = [];
285
299
  for (const r of cursorUsage(since)) {
286
- if (r.ts > until)
300
+ if (r.ts > until || isUnbilledModel(r.model))
287
301
  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 }));
302
+ // No cache split: every input token at the uncached rate. Cursor's own
303
+ // names for Claude ("claude-4.6-opus-high-thinking") are priced as the
304
+ // Claude id they stand for, shown as Cursor wrote them.
305
+ 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
306
  }
291
307
  return out;
292
308
  }
@@ -301,6 +317,8 @@ function add(map, key, it) {
301
317
  r.requests++;
302
318
  r.byTool[it.tool] = (r.byTool[it.tool] ?? 0) + it.usd;
303
319
  }
320
+ /** "1 run", "12 runs": workflow runs. */
321
+ const runsText = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "run" : "runs"}`;
304
322
  /** Add up priced requests into the report. */
305
323
  export function summarizeSpend(items, days, since, until, skipped = []) {
306
324
  const tools = new Map();
@@ -308,6 +326,7 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
308
326
  const sessions = new Map();
309
327
  const sessionModels = new Map();
310
328
  const parts = { inputUsd: 0, writeUsd: 0, readUsd: 0, outputUsd: 0 };
329
+ const runs = new Set();
311
330
  for (const it of items) {
312
331
  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
332
  t.usd += it.usd;
@@ -318,6 +337,11 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
318
337
  t.tokens.output += it.output;
319
338
  if (it.subagent && t.subagentUsd !== undefined)
320
339
  t.subagentUsd += it.usd;
340
+ if (it.workflow) {
341
+ t.workflowUsd = (t.workflowUsd ?? 0) + it.usd;
342
+ runs.add(it.workflow);
343
+ t.workflowRuns = runs.size;
344
+ }
321
345
  if (!it.priced) {
322
346
  t.unpriced++;
323
347
  t.unpricedTokens += it.input + it.read + it.write + it.output;
@@ -325,6 +349,14 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
325
349
  if (!t.unpricedModels.includes(m))
326
350
  t.unpricedModels.push(m);
327
351
  }
352
+ else if (it.estimated) {
353
+ const e = (t.estimated ??= { requests: 0, usd: 0, models: [] });
354
+ e.requests++;
355
+ e.usd += it.usd;
356
+ const m = it.model ?? "unknown";
357
+ if (!e.models.includes(m))
358
+ e.models.push(m);
359
+ }
328
360
  add(projects, it.project, it);
329
361
  add(models, it.model ?? "unknown", it);
330
362
  add(daily, localDay(it.ts), it);
@@ -412,7 +444,7 @@ export function renderSpend(r, top = 8) {
412
444
  lines.push("─".repeat(60));
413
445
  for (const t of r.tools) {
414
446
  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);
447
+ 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
448
  const note = notes.length ? ` ${notes.join(", ")}` : "";
417
449
  lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
418
450
  }
@@ -429,7 +461,9 @@ export function renderSpend(r, top = 8) {
429
461
  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
462
  // A model with no list price reads "not priced", not a $0.00 that looks free.
431
463
  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);
464
+ // One priced by its family's row reads as the estimate it is.
465
+ 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);
433
467
  // The last two weeks of the window, a bar each, scaled to the busiest.
434
468
  const recent = r.daily.slice(-14);
435
469
  const peak = Math.max(...recent.map((d) => d.usd), 0);
@@ -444,6 +478,8 @@ export function renderSpend(r, top = 8) {
444
478
  const claude = r.tools.find((t) => t.tool === "claude");
445
479
  if (claude?.subagentUsd)
446
480
  lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
481
+ if (claude?.workflowUsd)
482
+ lines.push(` Claude Code workflow agents ${usd(claude.workflowUsd)} (${share(claude.workflowUsd, r.usd)}), in ${runsText(claude.workflowRuns ?? 0)}`);
447
483
  lines.push(" Biggest sessions:");
448
484
  for (const s of r.sessions.slice(0, Math.min(top, 5))) {
449
485
  const when = shortDay(localDay(s.last));
@@ -457,6 +493,13 @@ export function renderSpend(r, top = 8) {
457
493
  notes.push(`${t.unpriced.toLocaleString("en-US")} ${t.name} ${t.tool === "cursor" ? "replies" : "requests"} (${formatTokens(t.unpricedTokens)} tokens) not priced:`);
458
494
  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
495
  }
496
+ for (const t of r.tools) {
497
+ if (!t.estimated)
498
+ continue;
499
+ const n = t.estimated.requests;
500
+ 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
+ notes.push(` no list price of its own for ${t.estimated.models.slice(0, 3).join(", ")}${t.estimated.models.length > 3 ? " and others" : ""}.`);
502
+ }
460
503
  if (r.tools.some((t) => t.estimate))
461
504
  notes.push("Cursor records no cache split: its input is priced uncached, an upper bound.");
462
505
  for (const s of r.skipped)
@@ -479,10 +522,15 @@ export function renderSpendShare(r) {
479
522
  const claude = r.tools.find((t) => t.tool === "claude");
480
523
  if (claude?.subagentUsd)
481
524
  lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
525
+ if (claude?.workflowUsd)
526
+ lines.push(`Claude Code workflow agents: ${usd(claude.workflowUsd)} of it, in ${runsText(claude.workflowRuns ?? 0)}.`);
482
527
  // 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
528
  const unpriced = r.tools.reduce((n, t) => n + t.unpriced, 0);
484
529
  if (unpriced)
485
530
  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.`);
531
+ const estimated = r.tools.reduce((n, t) => n + (t.estimated?.usd ?? 0), 0);
532
+ if (r.tools.some((t) => t.estimated))
533
+ lines.push(`Of it, ${usd(estimated)} is on models priced as their family, an estimate.`);
486
534
  const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
487
535
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
488
536
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];