context-doctor 0.43.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.
@@ -43,8 +43,14 @@ export interface SessionPrice {
43
43
  /** The threshold just passed. */
44
44
  threshold: number;
45
45
  usd: number;
46
- /** Subagents' part of `usd`. */
46
+ /** Subagents' part of `usd` (the Agent tool's). */
47
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;
48
54
  /** The main conversation's context at its last request, and its model. */
49
55
  tokens?: number;
50
56
  model?: string;
@@ -32,14 +32,14 @@
32
32
  * Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
33
33
  * off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
34
34
  */
35
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
35
+ import { mkdirSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";
36
36
  import { createHash } from "node:crypto";
37
37
  import { basename, dirname, join } from "node:path";
38
38
  import { statePath } from "./ledger.js";
39
39
  import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
40
40
  import { codexFileSpend, geminiFileSpend } from "./spend.js";
41
41
  import { isGeminiChat } from "./gemini.js";
42
- import { subagentDir } from "./subagents.js";
42
+ import { subagentFiles } from "./subagents.js";
43
43
  import { tailUsage } from "./statusline.js";
44
44
  import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
45
45
  import { formatUsd, pricingFor } from "./pricing.js";
@@ -68,7 +68,31 @@ function base(sessionId) {
68
68
  return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
69
69
  }
70
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;
71
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
+ }
72
96
  /** True for exactly one caller per path: the file is created only if it is not there. */
73
97
  function claim(path) {
74
98
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -101,32 +125,30 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
101
125
  return undefined;
102
126
  const b = base(input.sessionId);
103
127
  // Everything said: one stat from now on.
104
- if (existsSync(claimFile(b, thresholds[thresholds.length - 1])))
128
+ if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
105
129
  return undefined;
106
130
  const app = appOf(input.transcript, input.event);
107
- const files = [[input.transcript, false]];
108
- if (app === "claude") {
109
- // Subagents bill to the session that started them.
110
- const dir = subagentDir(input.transcript);
111
- try {
112
- for (const f of readdirSync(dir))
113
- if (f.endsWith(".jsonl"))
114
- files.push([join(dir, f), true]);
115
- }
116
- catch { /* no subagents */ }
117
- }
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"]);
118
137
  let saved = {};
119
138
  try {
120
- const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"))?.f;
121
- if (raw && typeof raw === "object")
122
- saved = raw;
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;
123
143
  }
124
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;
125
147
  const kept = {};
126
148
  let read = 0;
127
149
  for (const [file] of files) {
128
150
  const prev = saved[file];
129
- const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true);
151
+ const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true, own);
130
152
  if (!r)
131
153
  continue;
132
154
  kept[file] = r.e;
@@ -136,11 +158,12 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
136
158
  }
137
159
  // Each reply once: a fork's copy shares its key with the reply it copied.
138
160
  const seen = new Set();
139
- let usd = 0, subagentUsd = 0;
140
- for (const [file, sub] of files) {
161
+ let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
162
+ for (const [file, whose] of files) {
141
163
  const e = kept[file];
142
164
  if (!e)
143
165
  continue;
166
+ const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
144
167
  e.k.forEach((key, i) => {
145
168
  if (key) {
146
169
  if (seen.has(key))
@@ -148,17 +171,35 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
148
171
  seen.add(key);
149
172
  }
150
173
  usd += e.d[i];
151
- if (sub)
174
+ if (whose === "sub")
152
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];
153
182
  });
154
183
  }
155
- const save = () => { try {
156
- writeWhole(ledgerFile(b), { f: kept });
157
- }
158
- catch { /* read again next time */ } };
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
+ };
159
200
  const passed = thresholds.filter((t) => usd >= t);
160
201
  const top = passed[passed.length - 1];
161
- if (top === undefined || existsSync(claimFile(b, top)) || !claim(claimFile(b, top))) {
202
+ if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
162
203
  if (read >= SAVE_BYTES)
163
204
  save();
164
205
  return undefined;
@@ -167,7 +208,7 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
167
208
  for (const t of passed.slice(0, -1))
168
209
  claim(claimFile(b, t));
169
210
  save();
170
- return { app, threshold: top, usd, subagentUsd, ...perMessage(app, input, now) };
211
+ return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
171
212
  }
172
213
  /** The main conversation's context now, and what the next message pays for it. */
173
214
  function perMessage(app, input, now) {
@@ -203,7 +244,17 @@ function perMessage(app, input, now) {
203
244
  const dollars = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
204
245
  /** The line for the user (the hook's systemMessage). */
205
246
  export function renderSessionPrice(p) {
206
- const subs = p.subagentUsd >= 0.005 ? ` (${dollars(p.subagentUsd)} of it subagents)` : "";
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("; ")})` : "";
207
258
  const head = `context-doctor: this session has cost ${dollars(p.usd)} so far${subs}`;
208
259
  if (p.tokens === undefined || p.readUsd === undefined)
209
260
  return `${head}.`;
@@ -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];
@@ -38,6 +38,7 @@ import { pricingFor, usageCost } from "./pricing.js";
38
38
  import { realModel } from "./tokens.js";
39
39
  import { claudeDir } from "./claudedir.js";
40
40
  import { subagentTranscripts } from "./cachettl.js";
41
+ import { workflowRunOf } from "./subagents.js";
41
42
  import { managedDir } from "./effective.js";
42
43
  import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
43
44
  export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
@@ -56,6 +57,11 @@ const BUILT_IN = {
56
57
  fork: "inherit",
57
58
  "claude-code-guide": "haiku",
58
59
  "statusline-setup": "sonnet",
60
+ // A workflow agent (subagents/workflows/<run>/): read from the 2.1.317 binary, its model is the
61
+ // script's agent() `model`, then CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL, then this lever's
62
+ // CLAUDE_CODE_SUBAGENT_MODEL, then the main conversation's. Scripts seldom name one (none of the
63
+ // author's 9 runs did), so the variable moves them.
64
+ "workflow-subagent": undefined,
59
65
  };
60
66
  /** Types that only read (no Edit or Write): the ones a smaller model is most often enough for. */
61
67
  const READ_ONLY = new Set(["Explore", "Plan"]);
@@ -227,7 +233,8 @@ export function agentTypeOf(transcript) {
227
233
  catch {
228
234
  /* older Claude Code: no meta */
229
235
  }
230
- return "unknown";
236
+ // A workflow agent's folder says what it is when its meta file is missing.
237
+ return workflowRunOf(transcript) ? "workflow-subagent" : "unknown";
231
238
  }
232
239
  const tokens = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
233
240
  const promptTokens = (u) => tokens(u?.input_tokens) + tokens(u?.cache_read_input_tokens) + tokens(u?.cache_creation_input_tokens);
@@ -377,6 +384,9 @@ export function renderSubagentTypes(r) {
377
384
  const head = `${t.type.slice(0, 19).padEnd(20)}${String(t.agents).padStart(6)}${usd(t.billedUsd).padStart(11)}`;
378
385
  out.push(head + (t.moves ? usd(t.atCandidateUsd).padStart(col.length + 3) : ` unchanged: ${t.why}`));
379
386
  }
387
+ // Workflow agents follow this variable too; Claude Code has one of their own, which this lever does not set.
388
+ if (r.byType.some((t) => t.type === "workflow-subagent"))
389
+ out.push("Workflow agents move with it unless the workflow's script names a model. For them alone: CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL (it also overrides a model the script names).");
380
390
  const ro = r.byType.filter((t) => t.readOnly);
381
391
  if (ro.length) {
382
392
  const billed = ro.reduce((s, t) => s + t.billedUsd, 0);
@@ -54,6 +54,23 @@ export interface PaybackReport {
54
54
  days: number;
55
55
  sessions: number;
56
56
  subagents: SubagentPayback[];
57
+ /**
58
+ * Workflow agents (subagents/workflows/<run>/): their bill, by run. Not
59
+ * weighed against the parent: a workflow is work the parent hands off
60
+ * whole, not a read it would otherwise do itself.
61
+ */
62
+ workflows?: {
63
+ runs: number;
64
+ agents: number;
65
+ costUsd: number;
66
+ atSonnetUsd: number;
67
+ byRun: Array<{
68
+ name: string;
69
+ agents: number;
70
+ costUsd: number;
71
+ start: number;
72
+ }>;
73
+ };
57
74
  }
58
75
  /** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
59
76
  export declare function scanSubagent(path: string): {
@@ -27,6 +27,7 @@
27
27
  import { existsSync, readdirSync, readFileSync } from "node:fs";
28
28
  import { basename, join } from "node:path";
29
29
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
30
+ import { subagentFiles, workflowRunInfo } from "./subagents.js";
30
31
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
31
32
  import { cacheWriteSplit, formatUsd, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
32
33
  /**
@@ -171,8 +172,29 @@ export function subagentPayback(days = 30, paths, onProgress) {
171
172
  const sessions = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
172
173
  const out = [];
173
174
  let withSubagents = 0;
175
+ const runs = new Map();
174
176
  for (const [index, parent] of sessions.entries()) {
175
177
  onProgress?.(index, sessions.length);
178
+ for (const f of subagentFiles(parent)) {
179
+ if (!f.run)
180
+ continue;
181
+ let w;
182
+ try {
183
+ w = scanSubagent(f.file);
184
+ }
185
+ catch {
186
+ continue;
187
+ }
188
+ // Each by its own start, as the Agent tool's below.
189
+ if (!(w.steps > 0) || (Number.isFinite(w.start) && w.start < since))
190
+ continue;
191
+ const key = `${parent}\u0000${f.run}`;
192
+ const r = runs.get(key) ?? runs.set(key, { name: workflowRunInfo(parent, f.run).name ?? f.run, agents: 0, costUsd: 0, atSonnetUsd: 0, start: w.start }).get(key);
193
+ r.agents++;
194
+ r.costUsd += w.costUsd;
195
+ r.atSonnetUsd += w.atSonnetUsd;
196
+ r.start = Math.min(r.start, w.start);
197
+ }
176
198
  const dir = join(parent.replace(/\.jsonl$/, ""), "subagents");
177
199
  if (!existsSync(dir))
178
200
  continue;
@@ -241,13 +263,28 @@ export function subagentPayback(days = 30, paths, onProgress) {
241
263
  if (out.length > before)
242
264
  withSubagents++;
243
265
  }
244
- return { days, sessions: withSubagents, subagents: out };
266
+ const byRun = [...runs.values()].sort((a, b) => b.costUsd - a.costUsd);
267
+ const workflows = byRun.length
268
+ ? { runs: byRun.length, agents: byRun.reduce((n, r) => n + r.agents, 0), costUsd: byRun.reduce((n, r) => n + r.costUsd, 0), atSonnetUsd: byRun.reduce((n, r) => n + r.atSonnetUsd, 0), byRun: byRun.map(({ atSonnetUsd: _s, ...r }) => r) }
269
+ : undefined;
270
+ return { days, sessions: withSubagents, subagents: out, ...(workflows ? { workflows } : {}) };
271
+ }
272
+ /** The workflow agents' lines of `subagents`: what they cost, by run. */
273
+ function renderWorkflows(w, top) {
274
+ const out = ["", `Workflow agents: ${w.agents} in ${w.runs} workflow run${w.runs === 1 ? "" : "s"}, ${formatUsd(w.costUsd)} at list price (each run's work handed off whole, so not weighed against the parent).`];
275
+ if (w.costUsd - w.atSonnetUsd >= 1)
276
+ out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model): ~${formatUsd(w.atSonnetUsd)}, token counts as recorded: an estimate.`);
277
+ for (const r of w.byRun.slice(0, top))
278
+ out.push(` ${formatUsd(r.costUsd).padStart(9)} ${String(r.agents).padStart(3)} agents ${r.name.slice(0, 60)}`);
279
+ if (w.byRun.length > top)
280
+ out.push(` … and ${w.byRun.length - top} more`);
281
+ return out;
245
282
  }
246
283
  export function renderPayback(r, top = 8) {
247
284
  const out = ["DO SUBAGENTS PAY FOR THEMSELVES?", "═".repeat(56)];
248
285
  const all = r.subagents;
249
286
  if (!all.length)
250
- return [...out, `No subagents in the last ${r.days} days.`].join("\n");
287
+ return [...out, `No subagents in the last ${r.days} days.`, ...(r.workflows ? renderWorkflows(r.workflows, top) : [])].join("\n");
251
288
  const cost = all.reduce((s, a) => s + a.costUsd, 0);
252
289
  const inParent = all.reduce((s, a) => s + a.inParentUsd, 0);
253
290
  const paid = all.filter((a) => a.netUsd > 0);
@@ -277,5 +314,7 @@ export function renderPayback(r, top = 8) {
277
314
  out.push(` −${formatUsd(-a.netUsd).padEnd(8)} ${String(a.steps).padStart(3)} steps, parent at ~${formatTokens(a.parentContextTokens)}, read ~${formatTokens(a.readTokens)} ${a.task}`);
278
315
  }
279
316
  out.push("", "Counts context only: a subagent can still be worth it for parallel time or a clean window on a hard task.", "Subagents pay most when the parent is already large (every step there re-reads it) and least for short tasks from a small parent.");
317
+ if (r.workflows)
318
+ out.push(...renderWorkflows(r.workflows, top));
280
319
  return out.join("\n");
281
320
  }