context-doctor 0.40.0 → 0.41.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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The subagents' model: what they cost as billed, and what the same requests
3
+ * would cost on a cheaper model, per agent type. The `subagent-model` lever
4
+ * of `fix`.
5
+ *
6
+ * Claude Code reads `CLAUDE_CODE_SUBAGENT_MODEL` ("inherit" by default: a
7
+ * subagent runs on the main conversation's model). Read from the 2.1.309
8
+ * binary (the function that picks a subagent's model), highest first:
9
+ * 1. the Agent call's own `model` parameter;
10
+ * 2. the agent definition's `model` (an agent file's frontmatter; the
11
+ * built-ins: Explore, Plan and fork say "inherit", claude-code-guide
12
+ * "haiku", statusline-setup "sonnet"; general-purpose and claude name
13
+ * none);
14
+ * 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is "inherit" or "default";
15
+ * 4. the main conversation's model.
16
+ * So the variable moves only the agents whose definition names no model
17
+ * (general-purpose, claude, agents of your own without `model:`).
18
+ * CLAUDE_CODE_SUBAGENT_MODEL_FORCE makes it win over 1 and 2 as well (forks
19
+ * still inherit). 2.1.62 read the variable too, ahead of everything. Claude
20
+ * Code applies every settings file's `env` block to its own process at
21
+ * start, so the variable can live in ~/.claude/settings.json.
22
+ *
23
+ * The replay prices each subagent request twice: as billed (its recorded
24
+ * usage at its model's list price, cache writes at each TTL's multiplier,
25
+ * output as settled on the reply's last row), and at the candidate model,
26
+ * for the requests the variable would move that ran on a pricier model.
27
+ * The token counts stay as they were: an estimate, since another model
28
+ * tokenizes differently and may take more or fewer steps for the same task.
29
+ * Requests on a model no pricier than the candidate stay as billed.
30
+ */
31
+ import { type Extractor } from "./scan.js";
32
+ import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
33
+ export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
34
+ /** The environment variable the lever writes. */
35
+ export declare const SUBAGENT_MODEL_ENV = "CLAUDE_CODE_SUBAGENT_MODEL";
36
+ export declare const SUBAGENT_MODEL_FORCE_ENV = "CLAUDE_CODE_SUBAGENT_MODEL_FORCE";
37
+ /**
38
+ * One record per reply: its usage, time and model when first met; a top-up
39
+ * of its output count when a later row of the same reply carries more
40
+ * (subagent replies are written as they stream; output is final only on the
41
+ * last row); the working folder once, to find the project's agent files.
42
+ */
43
+ export declare const SUBAGENT_ROWS: Extractor<{
44
+ out: Record<string, number>;
45
+ cwd: boolean;
46
+ }>;
47
+ /** An agent's definition as far as the model goes: undefined when it names none. */
48
+ export interface AgentDefinition {
49
+ model?: string;
50
+ where: string;
51
+ }
52
+ /** How a type's model is chosen: whether CLAUDE_CODE_SUBAGENT_MODEL moves it, and why not. */
53
+ export declare function variableMoves(type: string, defs: Map<string, AgentDefinition>, force?: boolean): {
54
+ moves: boolean;
55
+ why?: string;
56
+ };
57
+ export interface TypeReplay {
58
+ type: string;
59
+ agents: number;
60
+ requests: number;
61
+ billedUsd: number;
62
+ /** The same requests with the ones the variable moves at the candidate model. */
63
+ atCandidateUsd: number;
64
+ /** Every request of this type at Haiku 5.5's base rates (a floor: see over100k). */
65
+ atHaikuUsd: number;
66
+ /** Requests whose prompt was over 100k tokens, which Haiku 5.5 bills at a higher rate not priced here. */
67
+ over100k: number;
68
+ moves: boolean;
69
+ why?: string;
70
+ readOnly: boolean;
71
+ }
72
+ export interface SubagentModelReplay {
73
+ candidate: string;
74
+ agents: number;
75
+ requests: number;
76
+ billedUsd: number;
77
+ atCandidateUsd: number;
78
+ /** billed - at candidate. */
79
+ savedUsd: number;
80
+ /** The moved requests' bill by the model they ran on: what "saved since" compares against. */
81
+ movedFrom: Record<string, number>;
82
+ /** Requests on models with no price (left out of the dollars). */
83
+ unpriced: number;
84
+ byType: TypeReplay[];
85
+ }
86
+ export interface SubagentModelOptions {
87
+ since: number;
88
+ until?: number;
89
+ /** Subagent transcripts (default: those written since `since`). */
90
+ paths?: string[];
91
+ candidate?: string;
92
+ /** CLAUDE_CODE_SUBAGENT_MODEL_FORCE is on: the variable moves every type but forks. */
93
+ force?: boolean;
94
+ /** Agent definitions (default: ~/.claude/agents, then each subagent's project's .claude/agents). */
95
+ definitions?: Map<string, AgentDefinition>;
96
+ home?: string;
97
+ /** Price every moved request at this mix of models (shares adding to 1) instead of the candidate: "saved since". */
98
+ baseline?: Record<string, number>;
99
+ }
100
+ /** The agent type Claude Code recorded beside a subagent's transcript ("unknown" for an older one without it). */
101
+ export declare function agentTypeOf(transcript: string): string;
102
+ /**
103
+ * Replay every subagent request in [since, until): as billed, and with the
104
+ * requests CLAUDE_CODE_SUBAGENT_MODEL would move at the candidate model.
105
+ * With `baseline`, the other arm prices the moved requests at the mix of
106
+ * models they ran on before the change (prices are linear in each rate, so
107
+ * a request at the blended rates costs the blend of its costs).
108
+ */
109
+ export declare function replaySubagentModels(opts: SubagentModelOptions): SubagentModelReplay;
110
+ /** The models the moved requests ran on, for people: the one or two that carry 10%+ of the bill ("Fable 5.1 or Opus 5.5"). */
111
+ export declare function movedFromNames(movedFrom: Record<string, number>): string | undefined;
112
+ /** Each model's share of a bill by model (what a fix record keeps as the baseline). */
113
+ export declare function shares(byModel: Record<string, number>): Record<string, number>;
114
+ /** A model id for people: "claude-opus-5-5" as "Opus 5.5". */
115
+ export declare function modelName(model: string | undefined): string;
116
+ /** The per-type lines under the lever in `fix`. */
117
+ export declare function renderSubagentTypes(r: SubagentModelReplay): string[];
118
+ /**
119
+ * What the change saved since `since`: the moved types' requests priced at
120
+ * the model they ran on before it, against as billed (an estimate, the same
121
+ * token counts either way).
122
+ */
123
+ export declare function subagentModelSavedSince(since: number, before: Record<string, number> | undefined, paths?: string[]): {
124
+ usd: number;
125
+ requests: number;
126
+ };
@@ -0,0 +1,320 @@
1
+ /**
2
+ * The subagents' model: what they cost as billed, and what the same requests
3
+ * would cost on a cheaper model, per agent type. The `subagent-model` lever
4
+ * of `fix`.
5
+ *
6
+ * Claude Code reads `CLAUDE_CODE_SUBAGENT_MODEL` ("inherit" by default: a
7
+ * subagent runs on the main conversation's model). Read from the 2.1.309
8
+ * binary (the function that picks a subagent's model), highest first:
9
+ * 1. the Agent call's own `model` parameter;
10
+ * 2. the agent definition's `model` (an agent file's frontmatter; the
11
+ * built-ins: Explore, Plan and fork say "inherit", claude-code-guide
12
+ * "haiku", statusline-setup "sonnet"; general-purpose and claude name
13
+ * none);
14
+ * 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is "inherit" or "default";
15
+ * 4. the main conversation's model.
16
+ * So the variable moves only the agents whose definition names no model
17
+ * (general-purpose, claude, agents of your own without `model:`).
18
+ * CLAUDE_CODE_SUBAGENT_MODEL_FORCE makes it win over 1 and 2 as well (forks
19
+ * still inherit). 2.1.62 read the variable too, ahead of everything. Claude
20
+ * Code applies every settings file's `env` block to its own process at
21
+ * start, so the variable can live in ~/.claude/settings.json.
22
+ *
23
+ * The replay prices each subagent request twice: as billed (its recorded
24
+ * usage at its model's list price, cache writes at each TTL's multiplier,
25
+ * output as settled on the reply's last row), and at the candidate model,
26
+ * for the requests the variable would move that ran on a pricier model.
27
+ * The token counts stay as they were: an estimate, since another model
28
+ * tokenizes differently and may take more or fewer steps for the same task.
29
+ * Requests on a model no pricier than the candidate stay as billed.
30
+ */
31
+ import { readdirSync, readFileSync } from "node:fs";
32
+ import { homedir } from "node:os";
33
+ import { basename, join } from "node:path";
34
+ import { pick, rowsOf, slimUsage } from "./scan.js";
35
+ import { pricingFor, usageCost } from "./pricing.js";
36
+ import { realModel } from "./tokens.js";
37
+ import { claudeDir } from "./claudedir.js";
38
+ import { subagentTranscripts } from "./cachettl.js";
39
+ import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
40
+ export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
41
+ /** The environment variable the lever writes. */
42
+ export const SUBAGENT_MODEL_ENV = "CLAUDE_CODE_SUBAGENT_MODEL";
43
+ export const SUBAGENT_MODEL_FORCE_ENV = "CLAUDE_CODE_SUBAGENT_MODEL_FORCE";
44
+ const HAIKU = "claude-haiku-5-5";
45
+ /** Haiku 5.5's per-token rates hold for prompts up to this size; longer prompts bill higher. */
46
+ const HAIKU_TIER = 100_000;
47
+ /** The model each built-in agent's definition names (2.1.309); undefined: none, so the variable applies. */
48
+ const BUILT_IN = {
49
+ "general-purpose": undefined,
50
+ claude: undefined,
51
+ Explore: "inherit",
52
+ Plan: "inherit",
53
+ fork: "inherit",
54
+ "claude-code-guide": "haiku",
55
+ "statusline-setup": "sonnet",
56
+ };
57
+ /** Types that only read (no Edit or Write): the ones a smaller model is most often enough for. */
58
+ const READ_ONLY = new Set(["Explore", "Plan"]);
59
+ /**
60
+ * One record per reply: its usage, time and model when first met; a top-up
61
+ * of its output count when a later row of the same reply carries more
62
+ * (subagent replies are written as they stream; output is final only on the
63
+ * last row); the working folder once, to find the project's agent files.
64
+ */
65
+ export const SUBAGENT_ROWS = {
66
+ id: "subagent-requests.1",
67
+ init: () => ({ out: {}, cwd: false }),
68
+ line(raw, row, out, st) {
69
+ const usage = raw.includes('"usage"');
70
+ if (!usage && (st.cwd || !raw.includes('"cwd"')))
71
+ return;
72
+ let e;
73
+ try {
74
+ e = row();
75
+ }
76
+ catch {
77
+ return;
78
+ }
79
+ if (!e || typeof e !== "object")
80
+ return;
81
+ if (!st.cwd && typeof e.cwd === "string") {
82
+ st.cwd = true;
83
+ out.push({ t: "c", cwd: e.cwd });
84
+ }
85
+ const m = e.message;
86
+ if (e.type !== "assistant" || !m || typeof m !== "object" || !m.usage)
87
+ return;
88
+ const o = Number(m.usage.output_tokens);
89
+ const output = Number.isFinite(o) && o > 0 ? o : 0;
90
+ const id = typeof m.id === "string" ? m.id : undefined;
91
+ if (id && st.out[id] !== undefined) {
92
+ if (output > st.out[id]) {
93
+ out.push({ t: "o", id, more: output - st.out[id] });
94
+ st.out[id] = output;
95
+ }
96
+ return;
97
+ }
98
+ if (id)
99
+ st.out[id] = output;
100
+ out.push({ t: "r", ...pick(e, ["uuid", "timestamp"]), id, model: m.model, usage: slimUsage(m.usage) });
101
+ },
102
+ };
103
+ /** `name:` and `model:` from the frontmatter of the agent files in `dir`. */
104
+ function definitionsIn(dir, into) {
105
+ let files;
106
+ try {
107
+ files = readdirSync(dir).filter((f) => f.endsWith(".md"));
108
+ }
109
+ catch {
110
+ return;
111
+ }
112
+ for (const f of files) {
113
+ let text;
114
+ try {
115
+ text = readFileSync(join(dir, f), "utf8");
116
+ }
117
+ catch {
118
+ continue;
119
+ }
120
+ const fm = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
121
+ if (fm === undefined)
122
+ continue;
123
+ const field = (k) => new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(fm)?.[1].trim().replace(/^["']|["']$/g, "") || undefined;
124
+ const name = field("name") ?? basename(f, ".md");
125
+ if (!into.has(name))
126
+ into.set(name, { model: field("model"), where: join(dir, f) });
127
+ }
128
+ }
129
+ /** How a type's model is chosen: whether CLAUDE_CODE_SUBAGENT_MODEL moves it, and why not. */
130
+ export function variableMoves(type, defs, force = false) {
131
+ if (type === "fork")
132
+ return { moves: false, why: "a fork runs on the main conversation's model" };
133
+ if (force)
134
+ return { moves: true };
135
+ if (type in BUILT_IN && !defs.has(type)) {
136
+ const m = BUILT_IN[type];
137
+ return m === undefined ? { moves: true } : { moves: false, why: m === "inherit" ? "built in, on the main conversation's model" : `built in, on ${m}` };
138
+ }
139
+ const d = defs.get(type);
140
+ if (!d)
141
+ return { moves: false, why: "its agent file was not found here" };
142
+ if (!d.model)
143
+ return { moves: true };
144
+ return { moves: false, why: `its file says model: ${d.model}` };
145
+ }
146
+ /** The agent type Claude Code recorded beside a subagent's transcript ("unknown" for an older one without it). */
147
+ export function agentTypeOf(transcript) {
148
+ try {
149
+ const meta = JSON.parse(readFileSync(transcript.replace(/\.jsonl$/, ".meta.json"), "utf8"));
150
+ if (typeof meta?.agentType === "string" && meta.agentType)
151
+ return meta.agentType;
152
+ }
153
+ catch {
154
+ /* older Claude Code: no meta */
155
+ }
156
+ return "unknown";
157
+ }
158
+ const tokens = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
159
+ const promptTokens = (u) => tokens(u?.input_tokens) + tokens(u?.cache_read_input_tokens) + tokens(u?.cache_creation_input_tokens);
160
+ /** The rates of a mix of models (shares adding to 1); undefined when none has a price. */
161
+ function blend(mix) {
162
+ const parts = Object.entries(mix).map(([m, w]) => [pricingFor(m), w]).filter((x) => !!x[0] && x[1] > 0);
163
+ const total = parts.reduce((s, [, w]) => s + w, 0);
164
+ if (!(total > 0))
165
+ return undefined;
166
+ const rate = (k) => parts.reduce((s, [p, w]) => s + (p[k] * w) / total, 0);
167
+ return { inputPerM: rate("inputPerM"), outputPerM: rate("outputPerM"), cacheReadPerM: rate("cacheReadPerM") };
168
+ }
169
+ const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
170
+ /**
171
+ * Replay every subagent request in [since, until): as billed, and with the
172
+ * requests CLAUDE_CODE_SUBAGENT_MODEL would move at the candidate model.
173
+ * With `baseline`, the other arm prices the moved requests at the mix of
174
+ * models they ran on before the change (prices are linear in each rate, so
175
+ * a request at the blended rates costs the blend of its costs).
176
+ */
177
+ export function replaySubagentModels(opts) {
178
+ const candidate = opts.candidate ?? SUBAGENT_CANDIDATE;
179
+ const cand = pricingFor(candidate);
180
+ const haiku = pricingFor(HAIKU);
181
+ const base = opts.baseline ? blend(opts.baseline) : undefined;
182
+ const until = opts.until ?? Infinity;
183
+ const paths = opts.paths ?? subagentTranscripts(opts.since, opts.home ?? homedir());
184
+ const defs = opts.definitions ?? new Map();
185
+ if (!opts.definitions)
186
+ definitionsIn(join(claudeDir(opts.home), "agents"), defs);
187
+ const types = new Map();
188
+ const movedBy = new Map();
189
+ const seen = new Set();
190
+ let unpriced = 0;
191
+ for (const p of paths) {
192
+ let rows;
193
+ try {
194
+ rows = rowsOf(p, SUBAGENT_ROWS);
195
+ }
196
+ catch {
197
+ continue;
198
+ }
199
+ const cwd = rows.find((r) => r?.t === "c")?.cwd;
200
+ // A project's own agents, looked up the first time a subagent of that project is met.
201
+ if (typeof cwd === "string" && !opts.definitions)
202
+ definitionsIn(join(cwd, ".claude", "agents"), defs);
203
+ const type = agentTypeOf(p);
204
+ const how = variableMoves(type, defs, opts.force);
205
+ const t = types.get(type) ?? types.set(type, { type, agents: 0, requests: 0, billedUsd: 0, atCandidateUsd: 0, atHaikuUsd: 0, over100k: 0, moves: how.moves, why: how.why, readOnly: READ_ONLY.has(type) }).get(type);
206
+ // Per reply of this file: the prices its output top-ups are charged at.
207
+ const priced = new Map();
208
+ let counted = false;
209
+ for (const r of rows) {
210
+ if (r?.t === "o") {
211
+ const q = priced.get(r.id);
212
+ if (!q)
213
+ continue;
214
+ t.billedUsd += (r.more * q.billed.outputPerM) / 1e6;
215
+ t.atCandidateUsd += (r.more * q.other.outputPerM) / 1e6;
216
+ t.atHaikuUsd += (r.more * haiku.outputPerM) / 1e6;
217
+ continue;
218
+ }
219
+ if (r?.t !== "r")
220
+ continue;
221
+ const model = realModel(r.model);
222
+ if (!model)
223
+ continue;
224
+ const at = Date.parse(String(r.timestamp ?? ""));
225
+ if (!Number.isFinite(at) || at < opts.since || at >= until)
226
+ continue;
227
+ // The same reply in another subagent file (a copied or resumed transcript): billed once.
228
+ if (r.id) {
229
+ if (seen.has(r.id))
230
+ continue;
231
+ seen.add(r.id);
232
+ }
233
+ const price = pricingFor(model);
234
+ if (!price) {
235
+ unpriced++;
236
+ continue;
237
+ }
238
+ const u = r.usage;
239
+ const billed = usageCost(u, price).totalUsd;
240
+ const target = base ?? cand;
241
+ const move = how.moves && (base ? true : cheaper(cand, price));
242
+ const other = move ? target : price;
243
+ t.requests++;
244
+ counted = true;
245
+ t.billedUsd += billed;
246
+ t.atCandidateUsd += move ? usageCost(u, other).totalUsd : billed;
247
+ t.atHaikuUsd += usageCost(u, haiku).totalUsd;
248
+ if (promptTokens(u) > HAIKU_TIER)
249
+ t.over100k++;
250
+ if (move)
251
+ movedBy.set(model, (movedBy.get(model) ?? 0) + billed);
252
+ if (r.id)
253
+ priced.set(r.id, { billed: price, other });
254
+ }
255
+ if (counted)
256
+ t.agents++;
257
+ }
258
+ const byType = [...types.values()].filter((t) => t.requests > 0).sort((a, b) => b.billedUsd - a.billedUsd);
259
+ const sum = (k) => byType.reduce((s, t) => s + t[k], 0);
260
+ const movedFrom = Object.fromEntries([...movedBy.entries()].sort((a, b) => b[1] - a[1]));
261
+ return { candidate, agents: sum("agents"), requests: sum("requests"), billedUsd: sum("billedUsd"), atCandidateUsd: sum("atCandidateUsd"), savedUsd: sum("billedUsd") - sum("atCandidateUsd"), movedFrom, unpriced, byType };
262
+ }
263
+ /** The models the moved requests ran on, for people: the one or two that carry 10%+ of the bill ("Fable 5.1 or Opus 5.5"). */
264
+ export function movedFromNames(movedFrom) {
265
+ const all = Object.entries(movedFrom);
266
+ const total = all.reduce((s, [, v]) => s + v, 0);
267
+ const names = [...new Set(all.filter(([, v]) => v >= 0.1 * total).slice(0, 2).map(([m]) => modelName(m)))];
268
+ return names.length ? names.join(" or ") : undefined;
269
+ }
270
+ /** Each model's share of a bill by model (what a fix record keeps as the baseline). */
271
+ export function shares(byModel) {
272
+ const total = Object.values(byModel).reduce((s, v) => s + v, 0);
273
+ return total > 0 ? Object.fromEntries(Object.entries(byModel).map(([m, v]) => [m, v / total])) : {};
274
+ }
275
+ /** A model id for people: "claude-opus-5-5" as "Opus 5.5". */
276
+ export function modelName(model) {
277
+ const m = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(model ?? "");
278
+ if (!m)
279
+ return model ?? "their model";
280
+ return `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}`;
281
+ }
282
+ const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
283
+ /** The per-type lines under the lever in `fix`. */
284
+ export function renderSubagentTypes(r) {
285
+ const name = r.candidate === SUBAGENT_CANDIDATE ? SUBAGENT_CANDIDATE_NAME : modelName(r.candidate);
286
+ const col = `at ${name}`;
287
+ const out = [`${"by type".padEnd(20)}${"runs".padStart(6)}${"as billed".padStart(11)}${col.padStart(col.length + 3)}`];
288
+ for (const t of r.byType) {
289
+ const head = `${t.type.slice(0, 19).padEnd(20)}${String(t.agents).padStart(6)}${usd(t.billedUsd).padStart(11)}`;
290
+ out.push(head + (t.moves ? usd(t.atCandidateUsd).padStart(col.length + 3) : ` unchanged: ${t.why}`));
291
+ }
292
+ const ro = r.byType.filter((t) => t.readOnly);
293
+ if (ro.length) {
294
+ const billed = ro.reduce((s, t) => s + t.billedUsd, 0);
295
+ const haiku = ro.reduce((s, t) => s + t.atHaikuUsd, 0);
296
+ const over = ro.reduce((s, t) => s + t.over100k, 0);
297
+ const reqs = ro.reduce((s, t) => s + t.requests, 0);
298
+ const what = `Read-only work (${ro.map((t) => t.type).join(", ")}, ${usd(billed)}) at Haiku 5.5`;
299
+ // Haiku 5.5's rates hold to 100k-token prompts; above that it bills a tier the price table does not hold.
300
+ if (over === 0)
301
+ out.push(`${what}: ~${usd(haiku)}.`);
302
+ else if (over <= 0.1 * reqs)
303
+ out.push(`${what}: over ~${usd(haiku)} (${over} of ${reqs} requests had prompts over 100k tokens, which Haiku bills higher).`);
304
+ else
305
+ out.push(`${what}: not priced, ${over} of ${reqs} requests had prompts over 100k tokens, where Haiku bills a higher rate.`);
306
+ out.push("Only an agent of your own runs there (`model: haiku` in its file); the built-ins keep the main conversation's model.");
307
+ }
308
+ return out;
309
+ }
310
+ /**
311
+ * What the change saved since `since`: the moved types' requests priced at
312
+ * the model they ran on before it, against as billed (an estimate, the same
313
+ * token counts either way).
314
+ */
315
+ export function subagentModelSavedSince(since, before, paths) {
316
+ if (!before || !blend(before))
317
+ return { usd: 0, requests: 0 };
318
+ const r = replaySubagentModels({ since, paths, baseline: before });
319
+ return { usd: r.atCandidateUsd - r.billedUsd, requests: r.byType.filter((t) => t.moves).reduce((s, t) => s + t.requests, 0) };
320
+ }
@@ -24,11 +24,21 @@
24
24
  * window for a hard task) and what the parent would have spent on its own tool
25
25
  * calls, so "did not pay" means "did not pay in context", not "was a mistake".
26
26
  */
27
+ /**
28
+ * The model `fix` offers the subagents (subagentmodel.ts): the id the price
29
+ * table knows, which Claude Code's model catalog maps to every provider's
30
+ * id. Kept here: the every-prompt hook loads this file, and should not load
31
+ * the replay's.
32
+ */
33
+ export declare const SUBAGENT_CANDIDATE = "claude-sonnet-5-5";
34
+ export declare const SUBAGENT_CANDIDATE_NAME = "Sonnet 5.5";
27
35
  export interface SubagentPayback {
28
36
  id: string;
29
37
  type: string;
30
38
  task: string;
31
39
  costUsd: number;
40
+ /** The same requests at Sonnet 5.5 where they ran on a pricier model, token counts as recorded (an estimate). */
41
+ atSonnetUsd: number;
32
42
  /** What the same work would have cost in the parent. */
33
43
  inParentUsd: number;
34
44
  steps: number;
@@ -48,6 +58,7 @@ export interface PaybackReport {
48
58
  /** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
49
59
  export declare function scanSubagent(path: string): {
50
60
  costUsd: number;
61
+ atSonnetUsd: number;
51
62
  readTokens: number;
52
63
  task: string;
53
64
  steps: number;
@@ -29,6 +29,14 @@ import { basename, join } from "node:path";
29
29
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
30
30
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
31
31
  import { cacheWriteSplit, formatUsd, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
32
+ /**
33
+ * The model `fix` offers the subagents (subagentmodel.ts): the id the price
34
+ * table knows, which Claude Code's model catalog maps to every provider's
35
+ * id. Kept here: the every-prompt hook loads this file, and should not load
36
+ * the replay's.
37
+ */
38
+ export const SUBAGENT_CANDIDATE = "claude-sonnet-5-5";
39
+ export const SUBAGENT_CANDIDATE_NAME = "Sonnet 5.5";
32
40
  const CLAUDE = "claude-opus-5";
33
41
  const IMAGE_TOKENS = 1600;
34
42
  function blockTokens(content) {
@@ -47,9 +55,12 @@ function blockTokens(content) {
47
55
  }
48
56
  return n;
49
57
  }
58
+ /** The price a request is re-priced at for the Sonnet line: Sonnet 5.5 when its own model costs more, else its own. */
59
+ const SONNET = pricingFor(SUBAGENT_CANDIDATE);
60
+ const atSonnet = (p) => (SONNET.inputPerM < p.inputPerM || (SONNET.inputPerM === p.inputPerM && SONNET.outputPerM < p.outputPerM) ? SONNET : p);
50
61
  /** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
51
62
  export function scanSubagent(path) {
52
- let costUsd = 0, readTokens = 0, task = "", model;
63
+ let costUsd = 0, atSonnetUsd = 0, readTokens = 0, task = "", model;
53
64
  let steps = 0, startup = 0, start = Infinity, writes5m = 0, writes1h = 0;
54
65
  const sighting = replyCounter();
55
66
  const settle = outputSettler();
@@ -80,8 +91,10 @@ export function scanSubagent(path) {
80
91
  // A later row of the same reply: only its final output count is new.
81
92
  const more = settle(e, false);
82
93
  const price = more ? pricingFor(realModel(e.message.model) ?? model) : undefined;
83
- if (price)
94
+ if (price) {
84
95
  costUsd += (more * price.outputPerM) / 1e6;
96
+ atSonnetUsd += (more * atSonnet(price).outputPerM) / 1e6;
97
+ }
85
98
  return;
86
99
  }
87
100
  if (seen !== "new")
@@ -103,8 +116,9 @@ export function scanSubagent(path) {
103
116
  if (!price)
104
117
  return;
105
118
  costUsd += usageCost(u, price).totalUsd;
119
+ atSonnetUsd += usageCost(u, atSonnet(price)).totalUsd;
106
120
  });
107
- return { costUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h) };
121
+ return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h) };
108
122
  }
109
123
  function scanParent(path, ids) {
110
124
  const view = { requests: [], prompts: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
@@ -213,6 +227,7 @@ export function subagentPayback(days = 30, paths, onProgress) {
213
227
  type: m.meta.agentType ?? "unknown",
214
228
  task: m.meta.description ?? s.task,
215
229
  costUsd: s.costUsd,
230
+ atSonnetUsd: s.atSonnetUsd,
216
231
  inParentUsd,
217
232
  steps: s.steps,
218
233
  parentContextTokens,
@@ -236,7 +251,11 @@ export function renderPayback(r, top = 8) {
236
251
  const cost = all.reduce((s, a) => s + a.costUsd, 0);
237
252
  const inParent = all.reduce((s, a) => s + a.inParentUsd, 0);
238
253
  const paid = all.filter((a) => a.netUsd > 0);
239
- out.push(`Last ${r.days} days: ${all.length} subagents in ${r.sessions} sessions cost ${formatUsd(cost)} at list price.`, `The same work done in the parent would have cost ~${formatUsd(inParent)}: ${paid.length} of ${all.length} were cheaper as subagents, net ${inParent - cost >= 0 ? "+" : "−"}${formatUsd(Math.abs(inParent - cost))}.`, "");
254
+ out.push(`Last ${r.days} days: ${all.length} subagents in ${r.sessions} sessions cost ${formatUsd(cost)} at list price.`, `The same work done in the parent would have cost ~${formatUsd(inParent)}: ${paid.length} of ${all.length} were cheaper as subagents, net ${inParent - cost >= 0 ? "+" : "−"}${formatUsd(Math.abs(inParent - cost))}.`);
255
+ const sonnet = all.reduce((s, a) => s + a.atSonnetUsd, 0);
256
+ if (cost - sonnet >= 1)
257
+ out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model) the same requests come to ~${formatUsd(sonnet)}, token counts as recorded: an estimate. context-doctor fix says which of them a setting moves.`);
258
+ out.push("");
240
259
  const byType = new Map();
241
260
  for (const a of all) {
242
261
  const t = byType.get(a.type) ?? { n: 0, cost: 0, net: 0, paid: 0 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",