context-doctor 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,8 @@ import { basename, join } from "node:path";
29
29
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
30
30
  import { subagentFiles, workflowRunInfo } from "./subagents.js";
31
31
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
32
- import { cacheWriteSplit, formatUsd, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
32
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
33
+ import { priceBasis } from "./orgrates.js";
33
34
  /**
34
35
  * The model `fix` offers the subagents (subagentmodel.ts): the id the price
35
36
  * table knows, which Claude Code's model catalog maps to every provider's
@@ -56,13 +57,30 @@ function blockTokens(content) {
56
57
  }
57
58
  return n;
58
59
  }
59
- /** The price a request is re-priced at for the Sonnet line: Sonnet 5.5 when its own model costs more, else its own. */
60
- const SONNET = pricingFor(SUBAGENT_CANDIDATE);
61
- const atSonnet = (p) => (SONNET.inputPerM < p.inputPerM || (SONNET.inputPerM === p.inputPerM && SONNET.outputPerM < p.outputPerM) ? SONNET : p);
62
- /** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
60
+ const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
61
+ /**
62
+ * A request as billed (requestCost: its tier, fast mode, US-only, its date,
63
+ * web searches) and re-priced for the Sonnet line: at Sonnet 5.5 when that
64
+ * bills it for less, else as billed.
65
+ */
66
+ function billed(model, u, at) {
67
+ const own = requestCost(model, u, at);
68
+ if (!own)
69
+ return undefined;
70
+ const sonnet = requestCost(SUBAGENT_CANDIDATE, u, at);
71
+ const moved = cheaper(sonnet.rates, own.rates);
72
+ return { usd: own.totalUsd, sonnetUsd: moved ? sonnet.totalUsd : own.totalUsd, rates: own.rates, sonnetRates: moved ? sonnet.rates : own.rates };
73
+ }
74
+ /**
75
+ * A subagent's bill (each request as billed, requestCost), steps, startup
76
+ * context, start time, the tool output it read, and the rates its first
77
+ * request billed at.
78
+ */
63
79
  export function scanSubagent(path) {
64
- let costUsd = 0, atSonnetUsd = 0, readTokens = 0, task = "", model;
80
+ let costUsd = 0, atSonnetUsd = 0, readTokens = 0, task = "", model, firstRates;
65
81
  let steps = 0, startup = 0, start = Infinity, writes5m = 0, writes1h = 0;
82
+ // The rates of the last reply, for the output its later rows settle.
83
+ let last;
66
84
  const sighting = replyCounter();
67
85
  const settle = outputSettler();
68
86
  forEachLine(path, (line) => {
@@ -91,10 +109,9 @@ export function scanSubagent(path) {
91
109
  if (seen === "repeat") {
92
110
  // A later row of the same reply: only its final output count is new.
93
111
  const more = settle(e, false);
94
- const price = more ? pricingFor(realModel(e.message.model) ?? model) : undefined;
95
- if (price) {
96
- costUsd += (more * price.outputPerM) / 1e6;
97
- atSonnetUsd += (more * atSonnet(price).outputPerM) / 1e6;
112
+ if (more && last) {
113
+ costUsd += (more * last.rates.outputPerM) / 1e6;
114
+ atSonnetUsd += (more * last.sonnetRates.outputPerM) / 1e6;
98
115
  }
99
116
  return;
100
117
  }
@@ -113,16 +130,18 @@ export function scanSubagent(path) {
113
130
  const w = cacheWriteSplit(u);
114
131
  writes5m += w.fiveMinute;
115
132
  writes1h += w.oneHour;
116
- const price = pricingFor(model);
117
- if (!price)
133
+ const b = billed(model, u, Number.isFinite(at) ? at : undefined);
134
+ last = b;
135
+ if (!b)
118
136
  return;
119
- costUsd += usageCost(u, price).totalUsd;
120
- atSonnetUsd += usageCost(u, atSonnet(price)).totalUsd;
137
+ firstRates ??= b.rates;
138
+ costUsd += b.usd;
139
+ atSonnetUsd += b.sonnetUsd;
121
140
  });
122
- return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h) };
141
+ return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h), ...(firstRates ? { rates: firstRates } : {}) };
123
142
  }
124
143
  function scanParent(path, ids) {
125
- const view = { requests: [], prompts: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
144
+ const view = { requests: [], prompts: [], models: [], billing: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
126
145
  let lastId;
127
146
  forEachLine(path, (line) => {
128
147
  const hits = [...ids].filter((id) => line.includes(id));
@@ -143,15 +162,17 @@ function scanParent(path, ids) {
143
162
  // Placeholder messages Claude Code writes itself ("<synthetic>") are not API requests.
144
163
  if (e?.type === "assistant" && !e.isSidechain && e.message?.usage && e.message.id !== lastId && realModel(e.message.model)) {
145
164
  lastId = e.message.id;
165
+ view.model = realModel(e.message.model) ?? view.model;
146
166
  if (Number.isFinite(at)) {
147
167
  const u = e.message.usage;
148
168
  view.requests.push(at);
149
169
  view.prompts.push((u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0));
170
+ view.billing.push({ speed: u.speed, inference_geo: u.inference_geo });
171
+ view.models.push(view.model);
150
172
  }
151
173
  const w = cacheWriteSplit(e.message.usage);
152
174
  view.writes5m += w.fiveMinute;
153
175
  view.writes1h += w.oneHour;
154
- view.model = realModel(e.message.model) ?? view.model;
155
176
  return;
156
177
  }
157
178
  if (!hits.length || !Number.isFinite(at) || e?.type === "assistant")
@@ -213,7 +234,6 @@ export function subagentPayback(days = 30, paths, onProgress) {
213
234
  });
214
235
  const ids = new Set(metas.flatMap((m) => [m.id, m.meta.toolUseId].filter((x) => Boolean(x))));
215
236
  const view = scanParent(parent, ids);
216
- const price = pricingFor(view.model);
217
237
  // What the parent pays to write a token to its cache, from its own usage.
218
238
  const parentWrite = writeMultiplier(view.writes5m, view.writes1h);
219
239
  for (const m of metas) {
@@ -230,18 +250,24 @@ export function subagentPayback(days = 30, paths, onProgress) {
230
250
  const laterRequests = view.requests.filter((t) => t > from && t < until).length;
231
251
  const carried = Math.max(0, s.readTokens - returnedTokens);
232
252
  // The parent's context when the subagent started: its last request before then.
233
- let parentContextTokens = 0;
234
- for (let i = 0; i < view.requests.length && view.requests[i] <= s.start; i++)
253
+ let parentContextTokens = 0, last = -1;
254
+ for (let i = 0; i < view.requests.length && view.requests[i] <= s.start; i++) {
235
255
  parentContextTokens = view.prompts[i];
236
- const sub = pricingFor(s.model) ?? price;
256
+ last = i;
257
+ }
258
+ // The parent's rates as its next request would have billed them (rateCard: its tier at that context, fast mode and US-only as its last request, the day).
259
+ // The parent as it ran then: a session that moved to another model later (Fable 5.1 to 5.2) is priced on the one it was on.
260
+ const card = rateCard(last >= 0 ? view.models[last] : view.model, last >= 0 ? view.billing[last] : undefined, Number.isFinite(s.start) ? s.start : undefined);
261
+ const price = card && ratesAt(card, parentContextTokens);
262
+ const sub = s.rates ?? price;
237
263
  let inParentUsd = s.costUsd, avoidedUsd = 0;
238
264
  if (price && sub) {
239
265
  // Each side's cache writes at its own TTL mix (subagents write at 5
240
266
  // minutes, the main thread mostly at 1 hour) and reads at its model's rate.
241
- const startupUsd = (s.startup * (s.writeMult * sub.inputPerM + Math.max(0, s.steps - 1) * sub.cacheReadPerM)) / 1e6;
267
+ const startupUsd = (s.startup * (writePerM(sub, s.writeMult) + Math.max(0, s.steps - 1) * sub.cacheReadPerM)) / 1e6;
242
268
  const work = Math.max(0, s.costUsd - startupUsd) * (price.inputPerM / sub.inputPerM);
243
269
  const rideAlong = (parentContextTokens * s.steps * price.cacheReadPerM) / 1e6;
244
- avoidedUsd = (carried * (parentWrite * price.inputPerM + laterRequests * price.cacheReadPerM)) / 1e6;
270
+ avoidedUsd = (carried * (writePerM(price, parentWrite) + laterRequests * price.cacheReadPerM)) / 1e6;
245
271
  inParentUsd = work + rideAlong + avoidedUsd;
246
272
  }
247
273
  out.push({
@@ -271,7 +297,7 @@ export function subagentPayback(days = 30, paths, onProgress) {
271
297
  }
272
298
  /** The workflow agents' lines of `subagents`: what they cost, by run. */
273
299
  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).`];
300
+ const out = ["", `Workflow agents: ${w.agents} in ${w.runs} workflow run${w.runs === 1 ? "" : "s"}, ${formatUsd(w.costUsd)} ${priceBasis(false)} (each run's work handed off whole, so not weighed against the parent).`];
275
301
  if (w.costUsd - w.atSonnetUsd >= 1)
276
302
  out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model): ~${formatUsd(w.atSonnetUsd)}, token counts as recorded: an estimate.`);
277
303
  for (const r of w.byRun.slice(0, top))
@@ -288,7 +314,7 @@ export function renderPayback(r, top = 8) {
288
314
  const cost = all.reduce((s, a) => s + a.costUsd, 0);
289
315
  const inParent = all.reduce((s, a) => s + a.inParentUsd, 0);
290
316
  const paid = all.filter((a) => a.netUsd > 0);
291
- 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))}.`);
317
+ out.push(`Last ${r.days} days: ${all.length} subagents in ${r.sessions} sessions cost ${formatUsd(cost)} ${priceBasis(false)}.`, `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))}.`);
292
318
  const sonnet = all.reduce((s, a) => s + a.atSonnetUsd, 0);
293
319
  if (cost - sonnet >= 1)
294
320
  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.`);
package/dist/subagents.js CHANGED
@@ -17,6 +17,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
17
17
  import { basename, join } from "node:path";
18
18
  import { formatTokens } from "./tokens.js";
19
19
  import { formatUsd, requestCost } from "./pricing.js";
20
+ import { orgRatesLine } from "./orgrates.js";
20
21
  import { forEachLine, outputSettler, replyCounter } from "./session.js";
21
22
  import { realModel } from "./tokens.js";
22
23
  /** Where Claude Code keeps a session's subagents: beside the transcript, under its id. */
@@ -233,6 +234,9 @@ export function renderSubagents(report, parentInputUsd, top = 5, options = {}) {
233
234
  return null;
234
235
  const lines = [];
235
236
  lines.push("Subagents (their own windows, your bill)");
237
+ const org = orgRatesLine();
238
+ if (org)
239
+ lines.push(org);
236
240
  lines.push("─".repeat(56));
237
241
  const cost = report.unpriced === 0 ? formatUsd(report.totalCostUsd) : `${formatUsd(report.totalCostUsd)}+ (${report.unpriced} unpriced)`;
238
242
  lines.push(`${report.agents.length} subagent(s) made ${report.agents.reduce((t, a) => t + a.calls, 0)} API calls: ` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.45.0",
3
+ "version": "0.46.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",