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.
package/dist/pricing.d.ts CHANGED
@@ -22,7 +22,15 @@ export interface ModelPricing {
22
22
  outputPerM: number;
23
23
  /** USD per 1M cached input tokens read (2.5-10% of input, depending on the Claude model). */
24
24
  cacheReadPerM: number;
25
+ /**
26
+ * USD per 1M cache-write tokens, every lifetime alike: only an
27
+ * organization's contracted row has one (orgrates.ts). Without it a write
28
+ * is its TTL's multiple of input.
29
+ */
30
+ cacheWritePerM?: number;
25
31
  }
32
+ /** What a cache write costs per 1M tokens at `mult` times input (its TTL's), or the row's own write rate. */
33
+ export declare function writePerM(p: ModelPricing, mult: number): number;
26
34
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
27
35
  export declare const CACHE_WRITE_5M = 1.25;
28
36
  export declare const CACHE_WRITE_1H = 2;
@@ -160,6 +168,14 @@ export interface RateCard {
160
168
  changedOn?: string;
161
169
  /** Web searches bill per use (Claude). */
162
170
  webSearch?: true;
171
+ /**
172
+ * Priced at the organization's rates (Claude Code's managed `modelPricing`,
173
+ * orgrates.ts): its row for the model, or the list price times its
174
+ * multiplier. Every figure on the card is already scaled by `scale`.
175
+ */
176
+ org?: true;
177
+ /** The organization's multiplier, which also scales the web-search fee. */
178
+ scale?: number;
163
179
  }
164
180
  /** The rate card for one of `model`'s requests at time `at`, with the modifiers its usage records. Undefined for a model with no price. */
165
181
  export declare function rateCard(model: string | undefined, usage?: RecordedUsage | null, at?: number): RateCard | undefined;
@@ -186,6 +202,8 @@ export interface RequestCost extends UsageCost {
186
202
  estimated?: true;
187
203
  /** "YYYY-MM-DD": its row's price changed on this day, before the request. */
188
204
  changedOn?: string;
205
+ /** Priced at the organization's rates (RateCard.org). */
206
+ org?: true;
189
207
  }
190
208
  /**
191
209
  * What one recorded request cost, as billed: its model's row at the time it
package/dist/pricing.js CHANGED
@@ -15,6 +15,11 @@
15
15
  * at a family's price, so a new release still gets a number. A model a
16
16
  * provider prices only per minute, per image or not at all has no row.
17
17
  */
18
+ import { orgApplies, orgRates, orgRowFor } from "./orgrates.js";
19
+ /** What a cache write costs per 1M tokens at `mult` times input (its TTL's), or the row's own write rate. */
20
+ export function writePerM(p, mult) {
21
+ return p.cacheWritePerM ?? mult * p.inputPerM;
22
+ }
18
23
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
19
24
  export const CACHE_WRITE_5M = 1.25;
20
25
  export const CACHE_WRITE_1H = 2;
@@ -79,16 +84,22 @@ const openaiLong = (inputPerM, outputPerM, cacheReadPerM) => {
79
84
  const PRICING = [
80
85
  // Anthropic: platform.claude.com/docs/en/about-claude/pricing ("Model
81
86
  // pricing"; 5-minute writes 1.25x, 1-hour writes 2x), read 2026-11-06,
82
- // its modifiers read 2026-11-08 (pricing.md):
87
+ // its modifiers read 2026-11-08 (pricing.md); read again 2026-11-10: Fable
88
+ // 5.2 and Mythos 5.2 added, every other row and modifier unchanged:
83
89
  // - "Data residency pricing": for Claude 4.6 and later, `inference_geo:
84
90
  // "us"` is 1.1x on input, output, cache writes and reads, and on Haiku
85
91
  // 5.5's over-100k prices too (GEO). Earlier models reject the parameter.
86
- // - "Fast mode pricing": Opus 5.5 $8 / $40, Opus 5 and Opus 4.8 $10 / $50,
92
+ // - "Fast mode pricing": Fable 5.2 and Mythos 5.2 $16 / $80 (read
93
+ // 2026-11-10), Opus 5.5 $8 / $40, Opus 5 and Opus 4.8 $10 / $50,
87
94
  // "across the full context window"; caching multipliers and data
88
95
  // residency apply on top (Opus 5.5's reads 0.05x: $0.40).
89
96
  // - "Long context pricing": only Haiku 5.5 is priced by prompt length.
90
97
  // Specific Claude versions first: the family rows below are only a
91
98
  // fallback for ids this table does not know yet.
99
+ // Fable 5.2 and Mythos 5.2 (read 2026-11-10): $8 / $40, writes $10 (5 min)
100
+ // and $16 (1 h), reads 0.025x ($0.20); fast mode $16 / $80 on the Claude
101
+ // API, reads $0.40 at that multiplier; US-only 1.1x (Claude 4.6 and later).
102
+ [claude("fable|mythos", 5, 2), rate(8, 40, 0.2), { geo: true, fast: rate(16, 80, 0.4) }],
92
103
  [claude("fable|mythos", 5, 1), rate(10, 50, 0.25), GEO],
93
104
  [claude("fable|mythos", 5), rate(10, 50, 1), GEO],
94
105
  [claude("opus", 5, 5), rate(4, 20, 0.2), { geo: true, fast: rate(8, 40, 0.4) }],
@@ -197,7 +208,7 @@ const PRICING = [
197
208
  // the same $0.30 / $2.50 / $0.03: no change to say.
198
209
  [gemini("gemini-3.1-pro"), rate(2, 12, 0.2), { long: { over: 200_000, rates: rate(4, 18, 0.4) } }],
199
210
  [gemini("gemini-3-flash"), rate(0.5, 3, 0.05)],
200
- [gemini("gemini-2.5-pro"), rate(1.25, 10, 0.125), { long: { over: 200_000, rates: rate(2.5, 15, 0.25) }, changes: "2026-12-01", then: rate(0.75, 3.75, 0.075) }],
211
+ [gemini("gemini-2.5-pro"), rate(1.25, 10, 0.125), { long: { over: 200_000, rates: rate(2.5, 15, 0.25) }, changes: "2026-12-01", then: rate(0.75, 3.75, 0.075), routes: "gemini-3.8-flash" }],
201
212
  [gemini("gemini-2.5-flash"), rate(0.3, 2.5, 0.03)],
202
213
  [gemini("gemini-2.5-flash-lite"), rate(0.1, 0.4, 0.01)],
203
214
  // Fallbacks for Gemini ids not on the page (gemini-3-pro, a new 3.x Flash,
@@ -293,7 +304,9 @@ export function usageCost(usage, pricing) {
293
304
  const { fiveMinute, oneHour, twelveHour } = cacheWriteSplit(usage);
294
305
  const perM = (tokens, usd) => (tokens * usd) / 1_000_000;
295
306
  const inputUsd = perM(count(usage?.input_tokens), pricing.inputPerM);
296
- const writeUsd = perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H, pricing.inputPerM);
307
+ const writeUsd = pricing.cacheWritePerM !== undefined
308
+ ? perM(fiveMinute + oneHour + twelveHour, pricing.cacheWritePerM)
309
+ : perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H, pricing.inputPerM);
297
310
  const readUsd = perM(count(usage?.cache_read_input_tokens), pricing.cacheReadPerM);
298
311
  const outputUsd = perM(count(usage?.output_tokens), pricing.outputPerM);
299
312
  const promptUsd = inputUsd + writeUsd + readUsd;
@@ -315,14 +328,30 @@ export function promptTokens(usage) {
315
328
  }
316
329
  /** UTC midnight of a "YYYY-MM-DD" day. */
317
330
  const dayStart = (day) => Date.parse(`${day}T00:00:00Z`);
318
- const scaled = (p, k) => (k === 1 ? p : { inputPerM: p.inputPerM * k, outputPerM: p.outputPerM * k, cacheReadPerM: p.cacheReadPerM * k });
331
+ const scaled = (p, k) => (k === 1 ? p : { inputPerM: p.inputPerM * k, outputPerM: p.outputPerM * k, cacheReadPerM: p.cacheReadPerM * k, ...(p.cacheWritePerM !== undefined ? { cacheWritePerM: p.cacheWritePerM * k } : {}) });
319
332
  /** The rate card for one of `model`'s requests at time `at`, with the modifiers its usage records. Undefined for a model with no price. */
320
333
  export function rateCard(model, usage, at = Date.now()) {
334
+ const org = model ? orgRates() : undefined;
335
+ const own = org && orgRowFor(org, model);
336
+ if (own) {
337
+ // A contracted row is charged as written: no tier, fast mode, US-only or date; then the multiplier.
338
+ const rates = scaled(own, org.multiplier);
339
+ return { rates, list: rates, org: true, ...(org.multiplier !== 1 ? { scale: org.multiplier } : {}), ...(/claude/i.test(model) ? { webSearch: true } : {}) };
340
+ }
321
341
  const r = row(model);
322
342
  if (!r)
323
343
  return undefined;
324
344
  const [, list, b = {}] = r;
345
+ // A request with no time of its own (a row without a timestamp) is priced as of now, the default:
346
+ // past a change that is the newer price, labelled an estimate with its day. NaN compared as never
347
+ // expired, so such a row got an ended price unlabelled in some reports and today's in others.
348
+ if (!Number.isFinite(at))
349
+ at = Date.now();
325
350
  const expired = b.changes !== undefined && at >= dayStart(b.changes);
351
+ // Routed to another model: its card, so a later change of that model's price follows (and is the day said).
352
+ const to = expired && b.routes ? rateCard(b.routes, usage, at) : undefined;
353
+ if (to)
354
+ return { ...to, estimated: true, changedOn: to.changedOn ?? b.changes };
326
355
  const base = expired && b.then ? b.then : list;
327
356
  const long = expired && b.then ? undefined : b.long;
328
357
  const fast = usage?.speed === "fast" && b.fast ? b.fast : undefined;
@@ -342,6 +371,15 @@ export function rateCard(model, usage, at = Date.now()) {
342
371
  card.changedOn = b.changes;
343
372
  if (/claude/i.test(model))
344
373
  card.webSearch = true;
374
+ if (org && orgApplies(org, model)) {
375
+ const k = org.multiplier;
376
+ card.rates = scaled(card.rates, k);
377
+ card.list = scaled(card.list, k);
378
+ if (card.longRates)
379
+ card.longRates = scaled(card.longRates, k);
380
+ card.org = true;
381
+ card.scale = k;
382
+ }
345
383
  return card;
346
384
  }
347
385
  /** A card's rates for a prompt of `prompt` tokens: its long tier's past `over`. */
@@ -364,7 +402,7 @@ export function requestCost(model, usage, at = Date.now()) {
364
402
  const rates = ratesAt(card, prompt);
365
403
  const c = usageCost(usage, rates);
366
404
  const searches = card.webSearch ? count(usage?.server_tool_use?.web_search_requests) : 0;
367
- const m = { ...NO_MODIFIERS, webSearches: searches, webSearchUsd: searches * WEB_SEARCH_USD };
405
+ const m = { ...NO_MODIFIERS, webSearches: searches, webSearchUsd: searches * WEB_SEARCH_USD * (card.scale ?? 1) };
368
406
  if (card.fast || card.geo || rates !== card.rates || card.over !== undefined) {
369
407
  // Each modifier measured from the step before it: list row, its tier, fast mode, US-only.
370
408
  const geo = card.geo ? US_ONLY_MULTIPLIER : 1;
@@ -375,7 +413,7 @@ export function requestCost(model, usage, at = Date.now()) {
375
413
  m.fastUsd = card.fast ? preGeo - tiered : 0;
376
414
  m.geoUsd = c.totalUsd - preGeo;
377
415
  }
378
- return { ...c, totalUsd: c.totalUsd + m.webSearchUsd, rates, modifiers: m, ...(card.estimated ? { estimated: true } : {}), ...(card.changedOn ? { changedOn: card.changedOn } : {}) };
416
+ return { ...c, totalUsd: c.totalUsd + m.webSearchUsd, rates, modifiers: m, ...(card.estimated ? { estimated: true } : {}), ...(card.changedOn ? { changedOn: card.changedOn } : {}), ...(card.org ? { org: true } : {}) };
379
417
  }
380
418
  /** `a` plus `b`, part by part. */
381
419
  export function addModifiers(a, b) {
package/dist/proxy.d.ts CHANGED
@@ -76,7 +76,7 @@ export interface ProxyOptions extends OptimizeOptions {
76
76
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
77
77
  export declare const DEFAULT_MAX_BODY_BYTES: number;
78
78
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
79
- export declare const PROXY_VERSION = "0.45.0";
79
+ export declare const PROXY_VERSION = "0.46.0";
80
80
  /**
81
81
  * Remove a leading `/t/<token>` from a request path, or return undefined when
82
82
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.45.0";
28
+ export const PROXY_VERSION = "0.46.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
package/dist/savings.js CHANGED
@@ -17,6 +17,7 @@ import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
19
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
20
+ import { priceBasis } from "./orgrates.js";
20
21
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
21
22
  import { withInvocation } from "./invocation.js";
22
23
  import { sessionsLabel } from "./compactwindow.js";
@@ -141,7 +142,8 @@ function replayExtractor(id, options, makeClearer, replay) {
141
142
  const r = {
142
143
  k: "r", now, cold,
143
144
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
144
- usd: requestCost(pm, u, now)?.promptUsd ?? 0,
145
+ // No time of its own (now is 0 then): priced as of now, as requestCost prices one.
146
+ usd: requestCost(pm, u, now || undefined)?.promptUsd ?? 0,
145
147
  raw: fresh + read + write,
146
148
  };
147
149
  // Only what is set: a record read back from the cache must equal this one.
@@ -195,8 +197,8 @@ function replayExtractor(id, options, makeClearer, replay) {
195
197
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
196
198
  };
197
199
  }
198
- const REPLAY = replayExtractor("replay.3", {}, undefined, true);
199
- const BILL = replayExtractor("bill.3", {}, undefined, false);
200
+ const REPLAY = replayExtractor("replay.4", {}, undefined, true);
201
+ const BILL = replayExtractor("bill.4", {}, undefined, false);
200
202
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
201
203
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
202
204
  /**
@@ -265,7 +267,7 @@ function settleReplay(path, rows, since, runRows, coldRows, replay) {
265
267
  requests++;
266
268
  // Each arm's request at its own tier (Haiku 5.5's 100k): as billed for the
267
269
  // session as it ran, less what autopilot cleared for the other.
268
- const card = rateCard(r.pm, { ...(r.f ? { speed: "fast" } : {}), ...(r.g ? { inference_geo: "us" } : {}) }, r.now);
270
+ const card = rateCard(r.pm, { ...(r.f ? { speed: "fast" } : {}), ...(r.g ? { inference_geo: "us" } : {}) }, r.now || undefined);
269
271
  const cleared = r.b && r.a ? Math.max(0, r.b[2] - r.a[2]) : 0;
270
272
  charge(base, r.b, r.cold, card ? ratesAt(card, r.raw) : UNPRICED);
271
273
  charge(auto, r.a, r.cold, card ? ratesAt(card, r.raw - cleared) : UNPRICED);
@@ -364,7 +366,7 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
364
366
  // Kept within 80 columns: this is most people's first screen of the tool.
365
367
  lines.push("What context-doctor finds in your Claude Code sessions");
366
368
  // The same count, said the same way, as compact-window's.
367
- lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, at list prices`);
369
+ lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
368
370
  lines.push("─".repeat(60));
369
371
  lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
370
372
  lines.push("");
@@ -428,7 +430,7 @@ export function renderShare(r) {
428
430
  if (r.sessions.length === 0)
429
431
  return "context-doctor found no Claude Code sessions to measure yet.";
430
432
  const lines = [
431
- `My Claude Code input, last ${r.days} days: ${usd(r.billedUsd)} at list price (${r.sessions.length} sessions).`,
433
+ `My Claude Code input, last ${r.days} days: ${usd(r.billedUsd)} ${priceBasis(false)} (${r.sessions.length} sessions).`,
432
434
  ];
433
435
  if (r.coldResumeNetUsd > 0) {
434
436
  lines.push(`Running /compact when I came back to a big session after the cache expired would have saved ${usd(r.coldResumeNetUsd)} (${Math.round((r.coldResumeNetUsd / r.billedUsd) * 100)}%, ${r.coldResumes} times).`);
@@ -74,5 +74,27 @@ export interface SessionPriceInput {
74
74
  * Claims the threshold: a second call for the same one gets undefined.
75
75
  */
76
76
  export declare function sessionPriceDue(input: SessionPriceInput, now?: number, env?: NodeJS.ProcessEnv): SessionPrice | undefined;
77
+ /** What a session has cost so far, subagents included, as the threshold check prices it. */
78
+ export interface SessionTotal {
79
+ app: Tool;
80
+ usd: number;
81
+ subagentUsd: number;
82
+ workflowUsd: number;
83
+ unpriced: number;
84
+ estimatedUsd: number;
85
+ /** Bytes read to bring the entries up to date. */
86
+ read: number;
87
+ /** Keeps the entries, so the next look reads only what was appended. */
88
+ save: () => void;
89
+ }
90
+ /**
91
+ * The session's price so far, from the per-transcript entries the threshold
92
+ * check keeps (shared, so each reads only what the other has not). Claims
93
+ * no threshold: the mod compares it with Claude Code's own cost after each
94
+ * turn (modmeasure.ts).
95
+ */
96
+ export declare function sessionTotal(input: Pick<SessionPriceInput, "sessionId" | "transcript" | "event">, now?: number): SessionTotal;
97
+ /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
98
+ export declare function saveIfWorthIt(t: Pick<SessionTotal, "read" | "save">): void;
77
99
  /** The line for the user (the hook's systemMessage). */
78
100
  export declare function renderSessionPrice(p: SessionPrice): string;
@@ -69,6 +69,8 @@ function base(sessionId) {
69
69
  return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
70
70
  }
71
71
  const ledgerFile = (b) => `${b}.price.json`;
72
+ /** A Codex thread's candidate rollouts and what their first lines named (codexSpawnedRollouts). */
73
+ const headsFile = (b) => `${b}.spawn-heads.json`;
72
74
  /** The price file's format: 2 counts only the session's own rows and may leave a finished subagent's `r` out. */
73
75
  const LEDGER_VERSION = 2;
74
76
  /** A subagent transcript not written for this long is done: its entry keeps no recent replies. */
@@ -128,6 +130,28 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
128
130
  // Everything said: one stat from now on.
129
131
  if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
130
132
  return undefined;
133
+ const { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save } = sessionTotal(input, now);
134
+ const passed = thresholds.filter((t) => usd >= t);
135
+ const top = passed[passed.length - 1];
136
+ if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
137
+ if (read >= SAVE_BYTES)
138
+ save();
139
+ return undefined;
140
+ }
141
+ // Passed two at once (a first look at a long session): said once, for the higher.
142
+ for (const t of passed.slice(0, -1))
143
+ claim(claimFile(b, t));
144
+ save();
145
+ return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
146
+ }
147
+ /**
148
+ * The session's price so far, from the per-transcript entries the threshold
149
+ * check keeps (shared, so each reads only what the other has not). Claims
150
+ * no threshold: the mod compares it with Claude Code's own cost after each
151
+ * turn (modmeasure.ts).
152
+ */
153
+ export function sessionTotal(input, now = Date.now()) {
154
+ const b = base(input.sessionId);
131
155
  const app = appOf(input.transcript, input.event);
132
156
  // Each file and whose it is: the main conversation, a subagent, a workflow agent.
133
157
  const files = [[input.transcript, "main"]];
@@ -136,9 +160,23 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
136
160
  for (const f of subagentFiles(input.transcript))
137
161
  files.push([f.file, f.run ? "workflow" : "sub"]);
138
162
  // A Codex thread's spawned agents: their rollouts name it as their parent (a forked one's copy of its history counts once, by key).
139
- if (app === "codex")
140
- for (const f of codexSpawnedRollouts(input.transcript, now))
163
+ if (app === "codex") {
164
+ // What each rollout's first line named, kept: a prompt reads only the rollouts new since the last.
165
+ const known = { heads: {} };
166
+ try {
167
+ const raw = JSON.parse(readFileSync(headsFile(b), "utf8"));
168
+ if (raw && typeof raw === "object" && !Array.isArray(raw))
169
+ known.heads = raw;
170
+ }
171
+ catch { /* none yet, or damaged: read again */ }
172
+ for (const f of codexSpawnedRollouts(input.transcript, now, undefined, known))
141
173
  files.push([f, "sub"]);
174
+ if (known.changed)
175
+ try {
176
+ writeWhole(headsFile(b), known.heads);
177
+ }
178
+ catch { /* read again next time */ }
179
+ }
142
180
  let saved = {};
143
181
  try {
144
182
  const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
@@ -202,18 +240,12 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
202
240
  }
203
241
  catch { /* read again next time */ }
204
242
  };
205
- const passed = thresholds.filter((t) => usd >= t);
206
- const top = passed[passed.length - 1];
207
- if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
208
- if (read >= SAVE_BYTES)
209
- save();
210
- return undefined;
211
- }
212
- // Passed two at once (a first look at a long session): said once, for the higher.
213
- for (const t of passed.slice(0, -1))
214
- claim(claimFile(b, t));
215
- save();
216
- return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
243
+ return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save };
244
+ }
245
+ /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
246
+ export function saveIfWorthIt(t) {
247
+ if (t.read >= SAVE_BYTES)
248
+ t.save();
217
249
  }
218
250
  /** The main conversation's context now, and what the next message pays for it. */
219
251
  function perMessage(app, input, now) {
package/dist/spend.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `context-doctor spend`: one bill across every AI coding tool on this
3
- * machine, at list prices.
3
+ * machine, each request as billed at list rates.
4
4
  *
5
5
  * Each tool keeps its own record of what it sent, and none adds them up:
6
6
  *
@@ -113,13 +113,22 @@ export declare function codexRolloutMeta(file: string): {
113
113
  * bill to the same work, as a Claude Code subagent's do.
114
114
  */
115
115
  export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
116
+ /** What rollouts' first lines named, by file name: [its thread id, the thread that spawned it]. */
117
+ export interface SpawnHeads {
118
+ heads: Record<string, [id: string, parent?: string]>;
119
+ /** Set when `heads` gained or lost a rollout, so the caller saves it. */
120
+ changed?: boolean;
121
+ }
116
122
  /**
117
123
  * The rollouts of the agents a Codex thread spawned (and theirs), for the
118
124
  * session price: those written since the thread began in its own folder,
119
125
  * the day folders from then to `now` (by local and UTC date) and the
120
- * archive. Only each candidate's first line is read.
126
+ * archive. Only each candidate's first line is read, and with `known` only
127
+ * once: a rollout's first line (its own session_meta) never changes, so
128
+ * what it named is kept there by file name, and a prompt reads only the
129
+ * rollouts written since the last (`known.changed` says when to save it).
121
130
  */
122
- export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string): string[];
131
+ export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string, known?: SpawnHeads): string[];
123
132
  /**
124
133
  * What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
125
134
  * id, time, model and token counts. A message without a time of its own
package/dist/spend.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `context-doctor spend`: one bill across every AI coding tool on this
3
- * machine, at list prices.
3
+ * machine, each request as billed at list rates.
4
4
  *
5
5
  * Each tool keeps its own record of what it sent, and none adds them up:
6
6
  *
@@ -42,6 +42,13 @@ import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, ro
42
42
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
43
43
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
44
44
  import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
45
+ import { orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
46
+ /**
47
+ * What spend's dollars are: each request as it was billed (its tier, fast mode,
48
+ * US-only, web searches) at list rates, or at the organization's rates.
49
+ * "At list prices" was true before those were priced; it no longer is.
50
+ */
51
+ const spendBasis = () => (orgRates() ? priceBasis() : "as billed at list rates");
45
52
  import { pick, rowsOf } from "./scan.js";
46
53
  import { formatTokens } from "./tokens.js";
47
54
  import { withInvocation } from "./invocation.js";
@@ -299,9 +306,12 @@ function headParent(file) {
299
306
  * The rollouts of the agents a Codex thread spawned (and theirs), for the
300
307
  * session price: those written since the thread began in its own folder,
301
308
  * the day folders from then to `now` (by local and UTC date) and the
302
- * archive. Only each candidate's first line is read.
309
+ * archive. Only each candidate's first line is read, and with `known` only
310
+ * once: a rollout's first line (its own session_meta) never changes, so
311
+ * what it named is kept there by file name, and a prompt reads only the
312
+ * rollouts written since the last (`known.changed` says when to save it).
303
313
  */
304
- export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir()) {
314
+ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir(), known) {
305
315
  const id = rolloutId(parent);
306
316
  if (!id)
307
317
  return [];
@@ -324,6 +334,7 @@ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir())
324
334
  dirs.add(join(root, String(y), String(mo).padStart(2, "0"), String(dd).padStart(2, "0")));
325
335
  }
326
336
  const heads = new Map();
337
+ const kept = {};
327
338
  for (const dir of dirs) {
328
339
  let names;
329
340
  try {
@@ -336,14 +347,32 @@ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir())
336
347
  const f = join(dir, n);
337
348
  if (!n.startsWith("rollout-") || !n.endsWith(".jsonl") || f === parent || heads.has(f))
338
349
  continue;
350
+ const k = known?.heads[n];
351
+ if (Array.isArray(k) && typeof k[0] === "string") {
352
+ heads.set(f, { id: k[0], ...(typeof k[1] === "string" ? { parent: k[1] } : {}) });
353
+ kept[n] = k;
354
+ continue;
355
+ }
339
356
  try {
340
357
  if (statSync(f).mtimeMs < born)
341
358
  continue;
342
- heads.set(f, headParent(f));
359
+ const h = headParent(f);
360
+ heads.set(f, h);
361
+ // Kept only once its id is there: a rollout caught before its first line was written is read again.
362
+ if (known && h.id) {
363
+ kept[n] = h.parent ? [h.id, h.parent] : [h.id];
364
+ known.changed = true;
365
+ }
343
366
  }
344
367
  catch { /* vanished */ }
345
368
  }
346
369
  }
370
+ if (known) {
371
+ // A rollout gone from every folder looked in is forgotten.
372
+ if (Object.keys(known.heads).some((n) => !(n in kept)))
373
+ known.changed = true;
374
+ known.heads = kept;
375
+ }
347
376
  // Children, then theirs.
348
377
  const mine = new Set([id]);
349
378
  const out = [];
@@ -620,7 +649,10 @@ export function renderSpend(r, top = 8) {
620
649
  return lines.join("\n");
621
650
  }
622
651
  lines.push("What your AI coding cost, across every tool here");
623
- lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices`);
652
+ lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}`);
653
+ const org = orgRatesLine();
654
+ if (org)
655
+ lines.push(org);
624
656
  lines.push("─".repeat(60));
625
657
  for (const t of r.tools) {
626
658
  const unit = t.tool === "cursor" ? "replies" : "requests";
@@ -696,7 +728,7 @@ export function renderSpend(r, top = 8) {
696
728
  notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
697
729
  if (notes.length)
698
730
  lines.push("", ...notes);
699
- lines.push("", "List prices, as an API key bills; on a subscription the same tokens come out");
731
+ lines.push("", "As an API key is billed; on a subscription the same tokens come out");
700
732
  lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
701
733
  return withInvocation(lines.map((l) => l.trimEnd()).join("\n"));
702
734
  }
@@ -708,7 +740,7 @@ export function renderSpendShare(r) {
708
740
  if (r.requests === 0)
709
741
  return "context-doctor found no AI coding usage to measure yet.";
710
742
  const tools = r.tools.map((t) => `${t.name} ${t.estimate ? "~" : ""}${usd(t.usd)}${t.estimate ? " (estimate)" : ""}`).join(", ");
711
- const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, at list prices: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
743
+ const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
712
744
  const claude = r.tools.find((t) => t.tool === "claude");
713
745
  if (claude?.subagentUsd)
714
746
  lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
@@ -30,7 +30,7 @@
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, rateCard, ratesAt } from "./pricing.js";
33
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt, writePerM } from "./pricing.js";
34
34
  import { recordLimits } from "./limits.js";
35
35
  import { recordMiss } from "./missledger.js";
36
36
  import { budgetStatus } from "./budget.js";
@@ -115,7 +115,7 @@ export function cacheClock(pc, model, nowMs = Date.now(), billing, prompt) {
115
115
  const card = rateCard(model, billing, nowMs);
116
116
  const price = card && ratesAt(card, prompt ?? tokens ?? 0);
117
117
  const oneHour = pc.ttl === "1h";
118
- const extra = tokens !== undefined && price ? (tokens * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
118
+ const extra = tokens !== undefined && price ? (tokens * (writePerM(price, oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
119
119
  const cost = tokens === undefined ? undefined : extra !== undefined && extra > 0 ? `+${formatUsd(extra)}` : `${formatTokens(tokens)} re-write`;
120
120
  // Epoch seconds within two hours of now: milliseconds, 1e300 and the like
121
121
  // would print a nonsense time ("NaN:NaN"), so they count as no expiry.
@@ -24,6 +24,7 @@
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
+ import { type ModelPricing } from "./pricing.js";
27
28
  /**
28
29
  * The model `fix` offers the subagents (subagentmodel.ts): the id the price
29
30
  * table knows, which Claude Code's model catalog maps to every provider's
@@ -72,7 +73,11 @@ export interface PaybackReport {
72
73
  }>;
73
74
  };
74
75
  }
75
- /** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
76
+ /**
77
+ * A subagent's bill (each request as billed, requestCost), steps, startup
78
+ * context, start time, the tool output it read, and the rates its first
79
+ * request billed at.
80
+ */
76
81
  export declare function scanSubagent(path: string): {
77
82
  costUsd: number;
78
83
  atSonnetUsd: number;
@@ -83,6 +88,7 @@ export declare function scanSubagent(path: string): {
83
88
  start: number;
84
89
  model?: string;
85
90
  writeMult: number;
91
+ rates?: ModelPricing;
86
92
  };
87
93
  export declare function subagentPayback(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): PaybackReport;
88
94
  export declare function renderPayback(r: PaybackReport, top?: number): string;