context-doctor 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,10 +30,12 @@
30
30
  */
31
31
  import { closeSync, openSync, readSync, statSync } from "node:fs";
32
32
  import { contextWindowFor, formatTokens } from "./tokens.js";
33
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, pricingFor } from "./pricing.js";
33
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt } from "./pricing.js";
34
34
  import { recordLimits } from "./limits.js";
35
35
  import { recordMiss } from "./missledger.js";
36
36
  import { budgetStatus } from "./budget.js";
37
+ /** The fields of a usage that carry over to the next request's price. */
38
+ const billingOf = (u) => (u && (u.speed === "fast" || u.inference_geo === "us") ? { ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}) } : undefined);
37
39
  /** Newest assistant usage from the END of a transcript, without reading the file. */
38
40
  export function tailUsage(path, tailBytes = 256 * 1024) {
39
41
  try {
@@ -67,8 +69,10 @@ export function tailUsage(path, tailBytes = 256 * 1024) {
67
69
  continue;
68
70
  const read = usage.cache_read_input_tokens ?? 0;
69
71
  const tokens = (usage.input_tokens ?? 0) + read + (usage.cache_creation_input_tokens ?? 0);
70
- if (tokens > 0)
71
- return { tokens, cacheShare: read / tokens, model: entry.message?.model };
72
+ if (tokens > 0) {
73
+ const billing = billingOf(usage);
74
+ return { tokens, cacheShare: read / tokens, model: entry.message?.model, ...(billing ? { billing } : {}) };
75
+ }
72
76
  }
73
77
  }
74
78
  catch {
@@ -98,14 +102,18 @@ const MAX_EXPIRY_AHEAD_S = 2 * 3600;
98
102
  * 2x at an hour) where a warm one would read them (0.1x). The extra is the
99
103
  * price; tokens alone when the model has no price. Undefined when Claude Code
100
104
  * does not say (no `prompt_cache`, caching off, or right after a compaction
101
- * while the cache is cold).
105
+ * while the cache is cold). Priced as the next request bills (requestCost's
106
+ * rate card): `billing` (fast mode, US-only) as the last request recorded,
107
+ * and the tier of a prompt of `prompt` tokens (the re-cached ones when not
108
+ * given).
102
109
  */
103
- export function cacheClock(pc, model, nowMs = Date.now()) {
110
+ export function cacheClock(pc, model, nowMs = Date.now(), billing, prompt) {
104
111
  if (!pc || pc.caching_observed === false)
105
112
  return undefined;
106
113
  const r = pc.recache_tokens_if_cold;
107
114
  const tokens = typeof r === "number" && Number.isFinite(r) && r > 0 && r <= MAX_RECACHE_TOKENS ? r : undefined;
108
- const price = pricingFor(model);
115
+ const card = rateCard(model, billing, nowMs);
116
+ const price = card && ratesAt(card, prompt ?? tokens ?? 0);
109
117
  const oneHour = pc.ttl === "1h";
110
118
  const extra = tokens !== undefined && price ? (tokens * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
111
119
  const cost = tokens === undefined ? undefined : extra !== undefined && extra > 0 ? `+${formatUsd(extra)}` : `${formatTokens(tokens)} re-write`;
@@ -140,7 +148,8 @@ export function renderStatusLine(input, nowMs = Date.now(), budget) {
140
148
  const fromPayload = cu ? (cu.input_tokens ?? 0) + (cu.cache_read_input_tokens ?? 0) + (cu.cache_creation_input_tokens ?? 0) : 0;
141
149
  if (cu && fromPayload > 0) {
142
150
  const read = cu.cache_read_input_tokens;
143
- live = { tokens: fromPayload, cacheShare: read !== undefined ? read / fromPayload : undefined, model: input.model?.id };
151
+ const billing = billingOf(cu);
152
+ live = { tokens: fromPayload, cacheShare: read !== undefined ? read / fromPayload : undefined, model: input.model?.id, ...(billing ? { billing } : {}) };
144
153
  }
145
154
  else if (input.transcript_path) {
146
155
  live = tailUsage(input.transcript_path);
@@ -160,7 +169,7 @@ export function renderStatusLine(input, nowMs = Date.now(), budget) {
160
169
  if (live.cacheShare !== undefined)
161
170
  parts.push(`cache ${Math.round(live.cacheShare * 100)}%`);
162
171
  }
163
- const warmth = cacheClock(input.prompt_cache, input.model?.id ?? live?.model, nowMs);
172
+ const warmth = cacheClock(input.prompt_cache, input.model?.id ?? live?.model, nowMs, live?.billing, live?.tokens);
164
173
  if (warmth)
165
174
  parts.push(warmth);
166
175
  // The session's cost is true whatever the context is; show it on its own.
@@ -69,9 +69,9 @@ export interface TypeReplay {
69
69
  billedUsd: number;
70
70
  /** The same requests with the ones the variable moves at the candidate model. */
71
71
  atCandidateUsd: number;
72
- /** Every request of this type at Haiku 5.5's base rates (a floor: see over100k). */
72
+ /** Every request of this type at Haiku 5.5, a prompt over 100k at its higher rates. */
73
73
  atHaikuUsd: number;
74
- /** Requests whose prompt was over 100k tokens, which Haiku 5.5 bills at a higher rate not priced here. */
74
+ /** Requests whose prompt was over 100k tokens, which Haiku 5.5 bills at its higher rates (in atHaikuUsd). */
75
75
  over100k: number;
76
76
  moves: boolean;
77
77
  why?: string;
@@ -34,7 +34,7 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "n
34
34
  import { homedir } from "node:os";
35
35
  import { dirname, join, resolve } from "node:path";
36
36
  import { pick, rowsOf, slimUsage } from "./scan.js";
37
- import { pricingFor, usageCost } from "./pricing.js";
37
+ import { pricingFor, rateCard, ratesAt, requestCost, usageCost, WEB_SEARCH_USD } from "./pricing.js";
38
38
  import { realModel } from "./tokens.js";
39
39
  import { claudeDir } from "./claudedir.js";
40
40
  import { subagentTranscripts } from "./cachettl.js";
@@ -72,7 +72,7 @@ const READ_ONLY = new Set(["Explore", "Plan"]);
72
72
  * last row); the working folder once, to find the project's agent files.
73
73
  */
74
74
  export const SUBAGENT_ROWS = {
75
- id: "subagent-requests.1",
75
+ id: "subagent-requests.2",
76
76
  init: () => ({ out: {}, cwd: false }),
77
77
  line(raw, row, out, st) {
78
78
  const usage = raw.includes('"usage"');
@@ -238,15 +238,25 @@ export function agentTypeOf(transcript) {
238
238
  }
239
239
  const tokens = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
240
240
  const promptTokens = (u) => tokens(u?.input_tokens) + tokens(u?.cache_read_input_tokens) + tokens(u?.cache_creation_input_tokens);
241
- /** The rates of a mix of models (shares adding to 1); undefined when none has a price. */
242
- function blend(mix) {
243
- const parts = Object.entries(mix).map(([m, w]) => [pricingFor(m), w]).filter((x) => !!x[0] && x[1] > 0);
241
+ /**
242
+ * The rates of a mix of models (shares adding to 1), each as it would bill
243
+ * `u` (its tier, US-only: rateCard) when given; undefined when none has a price.
244
+ */
245
+ function blend(mix, u, at) {
246
+ const rates = (m) => { const c = rateCard(m, u, at); return c && ratesAt(c, promptTokens(u ?? {})); };
247
+ const parts = Object.entries(mix).map(([m, w]) => [rates(m), w]).filter((x) => !!x[0] && x[1] > 0);
244
248
  const total = parts.reduce((s, [, w]) => s + w, 0);
245
249
  if (!(total > 0))
246
250
  return undefined;
247
251
  const rate = (k) => parts.reduce((s, [p, w]) => s + (p[k] * w) / total, 0);
248
252
  return { inputPerM: rate("inputPerM"), outputPerM: rate("outputPerM"), cacheReadPerM: rate("cacheReadPerM") };
249
253
  }
254
+ /** A request at the baseline mix (prices are linear in each rate: the blend of its costs), web searches as any Claude model bills them. */
255
+ function atBaseline(base, u, at, mix) {
256
+ const rates = (mix && blend(mix, u, at)) || base;
257
+ const searches = Number(u?.server_tool_use?.web_search_requests) > 0 ? Number(u.server_tool_use.web_search_requests) : 0;
258
+ return { totalUsd: usageCost(u, rates).totalUsd + searches * WEB_SEARCH_USD, rates };
259
+ }
250
260
  const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
251
261
  /**
252
262
  * Replay every subagent request in [since, until): as billed, and with the
@@ -258,7 +268,6 @@ const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputP
258
268
  export function replaySubagentModels(opts) {
259
269
  const candidate = opts.candidate ?? SUBAGENT_CANDIDATE;
260
270
  const cand = pricingFor(candidate);
261
- const haiku = pricingFor(HAIKU);
262
271
  const base = opts.baseline ? blend(opts.baseline) : undefined;
263
272
  const until = opts.until ?? Infinity;
264
273
  const home = opts.home ?? homedir();
@@ -304,9 +313,9 @@ export function replaySubagentModels(opts) {
304
313
  continue;
305
314
  t.billedUsd += (r.more * q.billed.outputPerM) / 1e6;
306
315
  t.atCandidateUsd += (r.more * q.other.outputPerM) / 1e6;
307
- t.atHaikuUsd += (r.more * haiku.outputPerM) / 1e6;
316
+ t.atHaikuUsd += (r.more * q.haiku.outputPerM) / 1e6;
308
317
  if (how.moves)
309
- add(beforeBy, q.model, (r.more * cand.outputPerM) / 1e6);
318
+ add(beforeBy, q.model, (r.more * q.cand.outputPerM) / 1e6);
310
319
  continue;
311
320
  }
312
321
  if (r?.t !== "r")
@@ -324,28 +333,31 @@ export function replaySubagentModels(opts) {
324
333
  seen.add(r.id);
325
334
  }
326
335
  const price = pricingFor(model);
327
- if (!price) {
336
+ const u = r.usage;
337
+ // Each arm as that model would bill these tokens (requestCost): its tier (Haiku 5.5 over 100k), US-only, web searches.
338
+ const asBilled = requestCost(model, u, at);
339
+ if (!price || !asBilled) {
328
340
  unpriced++;
329
341
  continue;
330
342
  }
331
- const u = r.usage;
332
- const billed = usageCost(u, price).totalUsd;
333
- const target = base ?? cand;
343
+ const atCand = requestCost(candidate, u, at);
344
+ const atHaiku = requestCost(HAIKU, u, at);
345
+ const billed = asBilled.totalUsd;
334
346
  const move = how.moves && (base ? true : cheaper(cand, price));
335
- const other = move ? target : price;
347
+ const other = move ? base ? atBaseline(base, u, at, opts.baseline) : atCand : asBilled;
336
348
  t.requests++;
337
349
  counted = true;
338
350
  t.billedUsd += billed;
339
- t.atCandidateUsd += move ? usageCost(u, other).totalUsd : billed;
340
- t.atHaikuUsd += usageCost(u, haiku).totalUsd;
351
+ t.atCandidateUsd += move ? other.totalUsd : billed;
352
+ t.atHaikuUsd += atHaiku.totalUsd;
341
353
  if (promptTokens(u) > HAIKU_TIER)
342
354
  t.over100k++;
343
355
  if (move)
344
356
  add(movedBy, model, billed);
345
357
  if (how.moves)
346
- add(beforeBy, model, usageCost(u, cand).totalUsd);
358
+ add(beforeBy, model, atCand.totalUsd);
347
359
  if (r.id)
348
- priced.set(r.id, { billed: price, other, model });
360
+ priced.set(r.id, { billed: asBilled.rates, other: other.rates, haiku: atHaiku.rates, cand: atCand.rates, model });
349
361
  }
350
362
  if (counted)
351
363
  t.agents++;
@@ -394,13 +406,8 @@ export function renderSubagentTypes(r) {
394
406
  const over = ro.reduce((s, t) => s + t.over100k, 0);
395
407
  const reqs = ro.reduce((s, t) => s + t.requests, 0);
396
408
  const what = `Read-only work (${ro.map((t) => t.type).join(", ")}, ${usd(billed)}) at Haiku 5.5`;
397
- // Haiku 5.5's rates hold to 100k-token prompts; above that it bills a tier the price table does not hold.
398
- if (over === 0)
399
- out.push(`${what}: ~${usd(haiku)}.`);
400
- else if (over <= 0.1 * reqs)
401
- out.push(`${what}: over ~${usd(haiku)} (${over} of ${reqs} requests had prompts over 100k tokens, which Haiku bills higher).`);
402
- else
403
- out.push(`${what}: not priced, ${over} of ${reqs} requests had prompts over 100k tokens, where Haiku bills a higher rate.`);
409
+ // Haiku 5.5's rates hold to 100k-token prompts; a longer one bills all of it at 5x, priced in.
410
+ out.push(`${what}: ~${usd(haiku)}${over ? ` (${over} of ${reqs} requests had prompts over 100k tokens, at Haiku's higher rates for those)` : ""}.`);
404
411
  out.push("Only an agent of your own runs there (`model: haiku` in its file); the built-ins keep the main conversation's model.");
405
412
  }
406
413
  return out;
package/dist/subagents.js CHANGED
@@ -16,7 +16,7 @@
16
16
  import { readdirSync, readFileSync, statSync } from "node:fs";
17
17
  import { basename, join } from "node:path";
18
18
  import { formatTokens } from "./tokens.js";
19
- import { formatUsd, pricingFor, usageCost } from "./pricing.js";
19
+ import { formatUsd, requestCost } from "./pricing.js";
20
20
  import { forEachLine, outputSettler, replyCounter } from "./session.js";
21
21
  import { realModel } from "./tokens.js";
22
22
  /** Where Claude Code keeps a session's subagents: beside the transcript, under its id. */
@@ -107,6 +107,8 @@ function summarize(path) {
107
107
  let last;
108
108
  let cost = 0;
109
109
  let priced = true;
110
+ // The last reply's rates: its later rows settle its output at them.
111
+ let rates;
110
112
  // One reply is written as several rows with the same usage; counting rows
111
113
  // doubled the calls and the bill (a real session: 6156 calls / $769 per
112
114
  // row against 3228 / $387 per reply).
@@ -148,7 +150,7 @@ function summarize(path) {
148
150
  if (seen === "repeat") {
149
151
  // A later row of the same reply: only its final output count is new.
150
152
  const more = settle(e, false);
151
- const p = more ? pricingFor(s.model) : undefined;
153
+ const p = more ? rates : undefined;
152
154
  s.outputTokens += more;
153
155
  if (p)
154
156
  cost += (more * p.outputPerM) / 1_000_000;
@@ -163,15 +165,14 @@ function summarize(path) {
163
165
  s.inputBilledTokens += input + read + write;
164
166
  s.cacheReadTokens += read;
165
167
  s.outputTokens += out;
166
- const p = pricingFor(s.model);
167
- if (p) {
168
- // Subagents write at the 5-minute TTL (1.25x), the main thread mostly
169
- // at 1 hour (2x); the usage records which.
170
- cost += usageCost(u, p).totalUsd;
171
- }
172
- else {
168
+ // Subagents write at the 5-minute TTL (1.25x), the main thread mostly
169
+ // at 1 hour (2x); the usage records which. As billed: requestCost.
170
+ const c = requestCost(s.model, u, Number.isFinite(at) ? at : undefined);
171
+ rates = c?.rates;
172
+ if (c)
173
+ cost += c.totalUsd;
174
+ else
173
175
  priced = false;
174
- }
175
176
  }
176
177
  });
177
178
  if (first !== undefined && last !== undefined)
package/dist/tasks.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { realModel } from "./tokens.js";
22
22
  import { basename } from "node:path";
23
23
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
24
- import { formatUsd, pricingFor, usageCost } from "./pricing.js";
24
+ import { formatUsd, requestCost } from "./pricing.js";
25
25
  /**
26
26
  * One session's bill, priced as the prompt cache bills it, from the usage the
27
27
  * transcript records. `since` counts only requests and commits from then on,
@@ -32,6 +32,8 @@ import { formatUsd, pricingFor, usageCost } from "./pricing.js";
32
32
  export function sessionCost(path, since = 0, counted = { rows: new Set(), commits: new Set() }) {
33
33
  let cwd, model;
34
34
  let start = Infinity, end = 0, usd = 0, requests = 0, commits = 0;
35
+ // The last counted reply's rates (requestCost's): its later rows settle its output at them.
36
+ let rates;
35
37
  const commitCalls = new Map();
36
38
  const sighting = replyCounter(counted.rows);
37
39
  const settle = outputSettler();
@@ -81,7 +83,7 @@ export function sessionCost(path, since = 0, counted = { rows: new Set(), commit
81
83
  if (seen === "repeat") {
82
84
  // A later row of a counted reply: only its final output count is new.
83
85
  const more = settle(e, false);
84
- const price = more ? pricingFor(realModel(e.message.model) ?? model) : undefined;
86
+ const price = more ? rates : undefined;
85
87
  if (price)
86
88
  usd += (more * price.outputPerM) / 1e6;
87
89
  return;
@@ -94,11 +96,12 @@ export function sessionCost(path, since = 0, counted = { rows: new Set(), commit
94
96
  end = Math.max(end, at);
95
97
  }
96
98
  model = realModel(e.message.model) ?? model;
97
- // Each request at its own model's price: one session can switch models.
98
- const price = pricingFor(model);
99
- if (!price)
99
+ // Each request at its own model's price, as billed: one session can switch models.
100
+ const c = requestCost(model, e.message.usage, Number.isFinite(at) ? at : undefined);
101
+ if (!c)
100
102
  return;
101
- usd += usageCost(e.message.usage, price).totalUsd;
103
+ rates = c.rates;
104
+ usd += c.totalUsd;
102
105
  settle(e, true);
103
106
  requests++;
104
107
  });
@@ -38,7 +38,7 @@
38
38
  */
39
39
  import { listSessions, isClaudeSession, replyCounter } from "./session.js";
40
40
  import { pick, rowsOf, slimUsage } from "./scan.js";
41
- import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
41
+ import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
42
42
  import { isCodeLike, realModel, tokensForLength } from "./tokens.js";
43
43
  import { subagentTranscripts } from "./cachettl.js";
44
44
  /** The settings key the lever writes. */
@@ -90,7 +90,7 @@ function resultText(content) {
90
90
  return s;
91
91
  }
92
92
  export const TOOL_OUTPUT_ROWS = {
93
- id: "tool-output.1",
93
+ id: "tool-output.2",
94
94
  init: () => ({ ids: {}, calls: {} }),
95
95
  line(raw, row, out, st) {
96
96
  if (!raw.includes('"usage"') && !raw.includes('"tool_use"') && !raw.includes('"tool_result"') && !raw.includes("compact_boundary"))
@@ -209,14 +209,17 @@ function timeline(path, since, until, runRows) {
209
209
  for (const x of unsized[th].splice(0))
210
210
  x.model = m;
211
211
  }
212
- const price = pricingFor(m);
212
+ const card = rateCard(m, u, at);
213
+ const price = card && ratesAt(card, prompt);
214
+ const below = card?.over !== undefined && prompt > card.over ? card.rates : undefined;
213
215
  out.push({
214
216
  k: "r", prompt,
215
217
  readPerM: price?.cacheReadPerM ?? 0,
216
218
  writePerM: (price?.inputPerM ?? 0) * writeMult,
217
219
  cold: num(u.cache_creation_input_tokens) > COLD_SHARE * prompt,
218
220
  counted: !!price && seen === "new" && at >= since && at < until,
219
- billedUsd: price ? usageCost(u, price).promptUsd : 0,
221
+ billedUsd: requestCost(m, u, at)?.promptUsd ?? 0,
222
+ ...(below && price ? { over: card.over, lower: below.inputPerM / price.inputPerM } : {}),
220
223
  });
221
224
  }
222
225
  return threads;
@@ -266,6 +269,7 @@ function walk(lines, move, kind) {
266
269
  // Never more than the request held.
267
270
  const held = live.reduce((n, x) => n + x.e, 0);
268
271
  const scale = held > s.prompt ? s.prompt / held : 1;
272
+ let here = 0;
269
273
  for (const x of live) {
270
274
  if (x.fresh && s.counted) {
271
275
  moved++;
@@ -274,10 +278,15 @@ function walk(lines, move, kind) {
274
278
  if (s.counted) {
275
279
  const t = x.e * scale;
276
280
  tokens += t;
277
- savedUsd += (t * (x.fresh || s.cold ? s.writePerM : s.readPerM)) / 1e6;
281
+ const usd = (t * (x.fresh || s.cold ? s.writePerM : s.readPerM)) / 1e6;
282
+ savedUsd += usd;
283
+ here += usd;
278
284
  }
279
285
  x.fresh = false;
280
286
  }
287
+ // Under its tier's threshold now: the rest of its prompt bills at the lower rates too.
288
+ if (s.counted && s.over !== undefined && s.lower !== undefined && s.prompt - held * scale <= s.over)
289
+ savedUsd += Math.max(0, s.billedUsd - here) * (1 - s.lower);
281
290
  }
282
291
  }
283
292
  return { moved, results, tokens, savedUsd, openUsd };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.44.0",
3
+ "version": "0.45.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",