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.
package/dist/pricing.js CHANGED
@@ -3,9 +3,12 @@
3
3
  *
4
4
  * List rates of each provider's first-party API (standard tier, global
5
5
  * routing, no batch or fast mode), each family with the page it was read
6
- * from and the date. Prices drift, so all cost output is labeled as an
7
- * estimate. One table, one file, easy to update: PRs welcome when prices
8
- * change.
6
+ * from and the date. What a request recorded can bill it differently (fast
7
+ * mode, US-only inference, a long prompt's tier, web searches) and a row's
8
+ * price can end on a known day: requestCost applies all of it, per request,
9
+ * from the row's billing options. Prices drift, so all cost output is
10
+ * labeled as an estimate. One table, one file, easy to update: PRs welcome
11
+ * when prices change.
9
12
  *
10
13
  * A row names one model (a "known" price, see knownPricingFor) unless it is
11
14
  * listed in FALLBACKS: those price ids the table does not know by version,
@@ -59,34 +62,55 @@ function gemini(name) {
59
62
  return new RegExp(`(?<![\\w.-])${escapeRe(name)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`, "i");
60
63
  }
61
64
  /** A row that prices ids the table does not know by name, at a family's price. */
62
- const FALLBACK = true;
65
+ const FALLBACK = { fallback: true };
66
+ /** Claude 4.6 and later. */
67
+ const GEO = { geo: true };
68
+ /**
69
+ * OpenAI's long-context column: a prompt over 272k input tokens bills the
70
+ * whole request at 2x input, cached input and cache writes and 1.5x output.
71
+ * Checked row by row against the page (2026-11-08): every model with a
72
+ * "Long context" price, and only those, is 2x / 1.5x of its short one.
73
+ */
74
+ const OPENAI_LONG = (r) => ({ over: 272_000, rates: rate(r.inputPerM * 2, r.outputPerM * 1.5, r.cacheReadPerM * 2) });
75
+ const openaiLong = (inputPerM, outputPerM, cacheReadPerM) => {
76
+ const r = rate(inputPerM, outputPerM, cacheReadPerM);
77
+ return [r, { long: OPENAI_LONG(r) }];
78
+ };
63
79
  const PRICING = [
64
80
  // Anthropic: platform.claude.com/docs/en/about-claude/pricing ("Model
65
- // pricing"; 5-minute writes 1.25x, 1-hour writes 2x), read 2026-11-06.
81
+ // pricing"; 5-minute writes 1.25x, 1-hour writes 2x), read 2026-11-06,
82
+ // its modifiers read 2026-11-08 (pricing.md):
83
+ // - "Data residency pricing": for Claude 4.6 and later, `inference_geo:
84
+ // "us"` is 1.1x on input, output, cache writes and reads, and on Haiku
85
+ // 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,
87
+ // "across the full context window"; caching multipliers and data
88
+ // residency apply on top (Opus 5.5's reads 0.05x: $0.40).
89
+ // - "Long context pricing": only Haiku 5.5 is priced by prompt length.
66
90
  // Specific Claude versions first: the family rows below are only a
67
91
  // fallback for ids this table does not know yet.
68
- [claude("fable|mythos", 5, 1), rate(10, 50, 0.25)],
69
- [claude("fable|mythos", 5), rate(10, 50, 1)],
70
- [claude("opus", 5, 5), rate(4, 20, 0.2)],
71
- [claude("opus", 5), rate(5, 25, 0.5)],
72
- [claude("opus", 4, 8), rate(5, 25, 0.5)],
73
- [claude("opus", 4, 7), rate(5, 25, 0.5)],
74
- [claude("opus", 4, 6), rate(5, 25, 0.5)],
92
+ [claude("fable|mythos", 5, 1), rate(10, 50, 0.25), GEO],
93
+ [claude("fable|mythos", 5), rate(10, 50, 1), GEO],
94
+ [claude("opus", 5, 5), rate(4, 20, 0.2), { geo: true, fast: rate(8, 40, 0.4) }],
95
+ [claude("opus", 5), rate(5, 25, 0.5), { geo: true, fast: rate(10, 50, 1) }],
96
+ [claude("opus", 4, 8), rate(5, 25, 0.5), { geo: true, fast: rate(10, 50, 1) }],
97
+ [claude("opus", 4, 7), rate(5, 25, 0.5), GEO],
98
+ [claude("opus", 4, 6), rate(5, 25, 0.5), GEO],
75
99
  [claude("opus", 4, 5), rate(5, 25, 0.5)],
76
100
  [claude("opus", 4, 1), rate(15, 75, 1.5)],
77
101
  [claude("opus", 4), rate(15, 75, 1.5)],
78
102
  // Sonnet 5.5's cache hits are 5% of input ($0.10), Sonnet 5's 10%.
79
- [claude("sonnet", 5, 5), rate(2, 10, 0.1)],
80
- [claude("sonnet", 5), rate(2, 10, 0.2)],
81
- // Haiku 5.5's rates hold for prompts up to 100k tokens; a longer prompt
82
- // bills the whole request at $0.50 / $2.50 / $0.05, a tier this per-token
83
- // table does not model.
84
- [claude("haiku", 5, 5), rate(0.1, 0.5, 0.01)],
103
+ [claude("sonnet", 5, 5), rate(2, 10, 0.1), GEO],
104
+ [claude("sonnet", 5), rate(2, 10, 0.2), GEO],
105
+ // Haiku 5.5's rates hold for prompts up to 100,000 tokens; a longer prompt
106
+ // (cache reads and writes count toward it) bills the whole request at
107
+ // $0.50 / $2.50 / $0.05, writes at their multipliers of $0.50.
108
+ [claude("haiku", 5, 5), rate(0.1, 0.5, 0.01), { geo: true, long: { over: 100_000, rates: rate(0.5, 2.5, 0.05) } }],
85
109
  [claude("haiku", 4, 5), rate(1, 5, 0.1)],
86
110
  // Sonnet 4.6, 4.5 and 4 are all $3 / $15 / $0.30, the family row's price;
87
111
  // rows of their own so a spending cap can tell a known version from a
88
112
  // guess (knownPricingFor).
89
- [claude("sonnet", 4, 6), rate(3, 15, 0.3)],
113
+ [claude("sonnet", 4, 6), rate(3, 15, 0.3), GEO],
90
114
  [claude("sonnet", 4, 5), rate(3, 15, 0.3)],
91
115
  [claude("sonnet", 4), rate(3, 15, 0.3)],
92
116
  // Retired Claude 3 models, no longer on the page: their last list price.
@@ -95,42 +119,44 @@ const PRICING = [
95
119
  [/claude-3-haiku/i, rate(0.25, 1.25, 0.03)],
96
120
  [/claude-3-[57]-sonnet/i, rate(3, 15, 0.3)],
97
121
  // Claude Mythos Preview (claude-mythos-preview) has no list price on the
98
- // page; the Fable/Mythos family row prices it as a fallback.
99
- [CLAUDE_FAMILY[0], rate(10, 50, 1), FALLBACK],
100
- [CLAUDE_FAMILY[1], rate(5, 25, 0.5), FALLBACK],
101
- [CLAUDE_FAMILY[2], rate(3, 15, 0.3), FALLBACK],
102
- [CLAUDE_FAMILY[3], rate(1, 5, 0.1), FALLBACK],
122
+ // page; the Fable/Mythos family row prices it as a fallback. A version the
123
+ // table does not know yet is a new one: 4.6 or later, so US-only applies.
124
+ [CLAUDE_FAMILY[0], rate(10, 50, 1), { ...FALLBACK, ...GEO }],
125
+ [CLAUDE_FAMILY[1], rate(5, 25, 0.5), { ...FALLBACK, ...GEO }],
126
+ [CLAUDE_FAMILY[2], rate(3, 15, 0.3), { ...FALLBACK, ...GEO }],
127
+ [CLAUDE_FAMILY[3], rate(1, 5, 0.1), { ...FALLBACK, ...GEO }],
103
128
  // OpenAI: developers.openai.com/api/docs/pricing (Standard, the "Short"
104
- // context column), read 2026-11-06. Prompts over 272k input tokens bill
105
- // the whole request at 2x input and cache rates and 1.5x output on GPT-5.4
106
- // and later (per model page), a tier this table does not model. Cache
107
- // writes are 1.25x input on GPT-5.6 and later (CACHE_WRITE_OPENAI_30M).
108
- // Models with no cached-input price (the -pro ones) read at full input.
109
- [openai("gpt-6-astra"), rate(10, 50, 1)],
129
+ // context column), read 2026-11-06; its "Long context" columns (prompts
130
+ // over 272k input tokens, OPENAI_LONG) read 2026-11-08. Cache writes are
131
+ // 1.25x input on GPT-5.6 and later (CACHE_WRITE_OPENAI_30M). Models with
132
+ // no cached-input price (the -pro ones) read at full input. Not modelled:
133
+ // Fast mode (priority processing; Codex records only its thread's
134
+ // `service_tier`, not each request's) and the 10% regional uplift.
135
+ [openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
110
136
  [openai("gpt-6-astra-law"), rate(10, 50, 1)],
111
- [openai("gpt-6.1-sol"), rate(2, 10, 0.1)],
112
- [openai("gpt-6.1-terra"), rate(1, 5, 0.05)],
113
- [openai("gpt-6-sol"), rate(2, 10, 0.2)],
114
- [openai("gpt-6-luna"), rate(0.1, 0.5, 0.01)],
137
+ [openai("gpt-6.1-sol"), ...openaiLong(2, 10, 0.1)],
138
+ [openai("gpt-6.1-terra"), ...openaiLong(1, 5, 0.05)],
139
+ [openai("gpt-6-sol"), ...openaiLong(2, 10, 0.2)],
140
+ [openai("gpt-6-luna"), ...openaiLong(0.1, 0.5, 0.01)],
115
141
  [openai("gpt-6-cyber"), rate(20, 100, 2)],
116
- [openai("gpt-6-rosalind"), rate(15, 75, 1.5)],
142
+ [openai("gpt-6-rosalind"), ...openaiLong(15, 75, 1.5)],
117
143
  [openai("gpt-rosalind-research"), rate(5, 25, 0.5)],
118
144
  [openai("gpt-rosalind-discovery"), rate(5, 25, 0.5)],
119
- // GPT-5.6 Sol's $4 / $20 is promotional "until November 30, 2026"; the
120
- // page does not say what follows. The gpt-5.6 alias routes to Sol (model
121
- // page, read 2026-11-06).
122
- [openai("gpt-5.6-sol"), rate(4, 20, 0.4)],
123
- [openai("gpt-5.6"), rate(4, 20, 0.4)],
124
- [openai("gpt-5.6-terra"), rate(2, 12, 0.2)],
125
- [openai("gpt-5.6-luna"), rate(0.2, 1.2, 0.02)],
145
+ // GPT-5.6 Sol's $4 / $20 is promotional "until November 30, 2026" (read
146
+ // again 2026-11-08); the page does not say what follows. The gpt-5.6 alias
147
+ // routes to Sol (model page, read 2026-11-06).
148
+ [openai("gpt-5.6-sol"), rate(4, 20, 0.4), { long: OPENAI_LONG(rate(4, 20, 0.4)), changes: "2026-12-01" }],
149
+ [openai("gpt-5.6"), rate(4, 20, 0.4), { long: OPENAI_LONG(rate(4, 20, 0.4)), changes: "2026-12-01" }],
150
+ [openai("gpt-5.6-terra"), ...openaiLong(2, 12, 0.2)],
151
+ [openai("gpt-5.6-luna"), ...openaiLong(0.2, 1.2, 0.02)],
126
152
  [openai("gpt-5.6-cyber"), rate(12.5, 75, 1.25)],
127
- [openai("gpt-5.5"), rate(5, 30, 0.5)],
128
- [openai("gpt-5.5-pro"), rate(30, 180, 30)],
153
+ [openai("gpt-5.5"), ...openaiLong(5, 30, 0.5)],
154
+ [openai("gpt-5.5-pro"), ...openaiLong(30, 180, 30)],
129
155
  [openai("gpt-5.5-cyber"), rate(12.5, 75, 1.25)],
130
- [openai("gpt-5.4"), rate(2.5, 15, 0.25)],
156
+ [openai("gpt-5.4"), ...openaiLong(2.5, 15, 0.25)],
131
157
  [openai("gpt-5.4-mini"), rate(0.75, 4.5, 0.075)],
132
158
  [openai("gpt-5.4-nano"), rate(0.2, 1.25, 0.02)],
133
- [openai("gpt-5.4-pro"), rate(30, 180, 30)],
159
+ [openai("gpt-5.4-pro"), ...openaiLong(30, 180, 30)],
134
160
  [openai("gpt-5.3-codex"), rate(1.75, 14, 0.175)],
135
161
  [openai("gpt-5.2"), rate(1.75, 14, 0.175)],
136
162
  [openai("gpt-5.2-pro"), rate(21, 168, 21)],
@@ -155,20 +181,23 @@ const PRICING = [
155
181
  [/gpt-4-turbo/i, rate(10, 30, 10), FALLBACK],
156
182
  [/o[13](-|$)/i, rate(2, 8, 1), FALLBACK],
157
183
  // Google: ai.google.dev/gemini-api/docs/pricing (paid tier, Standard, text),
158
- // read 2026-11-06.
159
- // Gemini 4 Argon's $2 / $10 / $0.10 hold through 2026-11-30; from
160
- // 2026-12-01 it is $4 / $20 / $0.20.
161
- [gemini("gemini-4-argon"), rate(2, 10, 0.1)],
162
- // 3.6 and 3.8 Flash double from 2027-01-01 ($1.50 / $7.50 / $0.15).
163
- [gemini("gemini-3.8-flash"), rate(0.75, 3.75, 0.075)],
164
- [gemini("gemini-3.6-flash"), rate(0.75, 3.75, 0.075)],
184
+ // read 2026-11-06; the dates and the Pro tiers read again 2026-11-08.
185
+ // Gemini 4 Argon's $2 / $10 / $0.10 hold "through November 30, 2026";
186
+ // "starting December 1, 2026" it is $4 / $20 / $0.20.
187
+ [gemini("gemini-4-argon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
188
+ // 3.6 and 3.8 Flash double "starting January 1, 2027" ($1.50 / $7.50 / $0.15).
189
+ [gemini("gemini-3.8-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
190
+ [gemini("gemini-3.6-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
165
191
  [gemini("gemini-3.5-flash-lite"), rate(0.3, 2.5, 0.03)],
166
192
  [gemini("gemini-3.1-flash-lite"), rate(0.25, 1.5, 0.025)],
167
- // 3.1 Pro and 2.5 Pro bill prompts over 200k at $4 / $18 / $0.40 and
168
- // $2.50 / $15 / $0.25, a tier this table does not model.
169
- [gemini("gemini-3.1-pro"), rate(2, 12, 0.2)],
193
+ // 3.1 Pro and 2.5 Pro bill a prompt over 200k tokens at $4 / $18 / $0.40
194
+ // and $2.50 / $15 / $0.25. From December 1, 2026 every gemini-2.5-pro
195
+ // request is routed to 3.8 Flash and billed at its rates ($0.75 / $3.75 /
196
+ // $0.075 then). gemini-2.5-flash is routed to 3.5 Flash-Lite that day, at
197
+ // the same $0.30 / $2.50 / $0.03: no change to say.
198
+ [gemini("gemini-3.1-pro"), rate(2, 12, 0.2), { long: { over: 200_000, rates: rate(4, 18, 0.4) } }],
170
199
  [gemini("gemini-3-flash"), rate(0.5, 3, 0.05)],
171
- [gemini("gemini-2.5-pro"), rate(1.25, 10, 0.125)],
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) }],
172
201
  [gemini("gemini-2.5-flash"), rate(0.3, 2.5, 0.03)],
173
202
  [gemini("gemini-2.5-flash-lite"), rate(0.1, 0.4, 0.01)],
174
203
  // Fallbacks for Gemini ids not on the page (gemini-3-pro, a new 3.x Flash,
@@ -184,6 +213,7 @@ function row(model) {
184
213
  return undefined;
185
214
  return PRICING.find(([pattern]) => pattern.test(model));
186
215
  }
216
+ /** A model's list row, as the page lists it today (no tier, mode or date applied). */
187
217
  export function pricingFor(model) {
188
218
  return row(model)?.[1];
189
219
  }
@@ -195,7 +225,7 @@ export function pricingFor(model) {
195
225
  */
196
226
  export function knownPricingFor(model) {
197
227
  const r = row(model);
198
- return r && !r[2] ? r[1] : undefined;
228
+ return r && !r[2]?.fallback ? r[1] : undefined;
199
229
  }
200
230
  /** Whether a model id has a price of its own in the table (see knownPricingFor). */
201
231
  export function hasKnownPrice(model) {
@@ -255,9 +285,9 @@ export function writeMultiplier(fiveMinute, oneHour, twelveHour = 0) {
255
285
  return total > 0 ? (fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H) / total : CACHE_WRITE_5M;
256
286
  }
257
287
  /**
258
- * What one recorded request cost: uncached input, cache writes priced by
259
- * TTL, cache reads, output. The one place recorded usage is priced, so every
260
- * report agrees with the others and with the bill.
288
+ * Recorded usage at given rates: uncached input, cache writes priced by
289
+ * TTL, cache reads, output. The rates a request was billed at (its tier,
290
+ * fast mode, US-only, its date) are requestCost's to decide.
261
291
  */
262
292
  export function usageCost(usage, pricing) {
263
293
  const { fiveMinute, oneHour, twelveHour } = cacheWriteSplit(usage);
@@ -269,6 +299,112 @@ export function usageCost(usage, pricing) {
269
299
  const promptUsd = inputUsd + writeUsd + readUsd;
270
300
  return { inputUsd, writeUsd, readUsd, outputUsd, promptUsd, totalUsd: promptUsd + outputUsd };
271
301
  }
302
+ /** US-only inference on Claude 4.6 and later: 1.1x on every token category (Anthropic, "Data residency pricing", read 2026-11-08). */
303
+ export const US_ONLY_MULTIPLIER = 1.1;
304
+ /**
305
+ * Claude's web search tool: $10 per 1,000 searches, on top of its tokens
306
+ * (Anthropic, "Web search tool", read 2026-11-08). A token price, so not
307
+ * under the US-only multiplier. Web fetch has no charge beyond its tokens;
308
+ * code execution bills container time (1,550 free hours a month, then $0.05
309
+ * an hour), which usage does not record per request: not modelled.
310
+ */
311
+ export const WEB_SEARCH_USD = 10 / 1000;
312
+ /** The tokens a request's prompt holds: uncached input, cache reads and cache writes (what a long-prompt tier counts). */
313
+ export function promptTokens(usage) {
314
+ return count(usage?.input_tokens) + count(usage?.cache_read_input_tokens) + count(usage?.cache_creation_input_tokens);
315
+ }
316
+ /** UTC midnight of a "YYYY-MM-DD" day. */
317
+ 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 });
319
+ /** 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
+ export function rateCard(model, usage, at = Date.now()) {
321
+ const r = row(model);
322
+ if (!r)
323
+ return undefined;
324
+ const [, list, b = {}] = r;
325
+ const expired = b.changes !== undefined && at >= dayStart(b.changes);
326
+ const base = expired && b.then ? b.then : list;
327
+ const long = expired && b.then ? undefined : b.long;
328
+ const fast = usage?.speed === "fast" && b.fast ? b.fast : undefined;
329
+ const geo = usage?.inference_geo === "us" && b.geo ? US_ONLY_MULTIPLIER : 1;
330
+ const card = { rates: scaled(fast ?? base, geo), list: base };
331
+ if (long && !fast) {
332
+ card.over = long.over;
333
+ card.longRates = scaled(long.rates, geo);
334
+ }
335
+ if (fast)
336
+ card.fast = true;
337
+ if (geo !== 1)
338
+ card.geo = true;
339
+ if (b.fallback || expired)
340
+ card.estimated = true;
341
+ if (expired)
342
+ card.changedOn = b.changes;
343
+ if (/claude/i.test(model))
344
+ card.webSearch = true;
345
+ return card;
346
+ }
347
+ /** A card's rates for a prompt of `prompt` tokens: its long tier's past `over`. */
348
+ export function ratesAt(card, prompt) {
349
+ return card.over !== undefined && prompt > card.over ? card.longRates : card.rates;
350
+ }
351
+ export const NO_MODIFIERS = Object.freeze({ fastUsd: 0, geoUsd: 0, longUsd: 0, webSearchUsd: 0, webSearches: 0 });
352
+ /**
353
+ * What one recorded request cost, as billed: its model's row at the time it
354
+ * ran, its prompt's tier, fast mode, US-only inference, cache writes by TTL,
355
+ * and per-use tool fees. The one place a request's price is decided, so
356
+ * every report agrees with the others and with the bill. `at`: when it ran.
357
+ * Undefined for a model with no price.
358
+ */
359
+ export function requestCost(model, usage, at = Date.now()) {
360
+ const card = rateCard(model, usage, at);
361
+ if (!card)
362
+ return undefined;
363
+ const prompt = promptTokens(usage);
364
+ const rates = ratesAt(card, prompt);
365
+ const c = usageCost(usage, rates);
366
+ 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 };
368
+ if (card.fast || card.geo || rates !== card.rates || card.over !== undefined) {
369
+ // Each modifier measured from the step before it: list row, its tier, fast mode, US-only.
370
+ const geo = card.geo ? US_ONLY_MULTIPLIER : 1;
371
+ const preGeo = c.totalUsd / geo;
372
+ const list = usageCost(usage, card.list).totalUsd;
373
+ const tiered = card.longRates && prompt > card.over ? usageCost(usage, scaled(card.longRates, 1 / geo)).totalUsd : list;
374
+ m.longUsd = tiered - list;
375
+ m.fastUsd = card.fast ? preGeo - tiered : 0;
376
+ m.geoUsd = c.totalUsd - preGeo;
377
+ }
378
+ return { ...c, totalUsd: c.totalUsd + m.webSearchUsd, rates, modifiers: m, ...(card.estimated ? { estimated: true } : {}), ...(card.changedOn ? { changedOn: card.changedOn } : {}) };
379
+ }
380
+ /** `a` plus `b`, part by part. */
381
+ export function addModifiers(a, b) {
382
+ a.fastUsd += b.fastUsd;
383
+ a.geoUsd += b.geoUsd;
384
+ a.longUsd += b.longUsd;
385
+ a.webSearchUsd += b.webSearchUsd;
386
+ a.webSearches += b.webSearches;
387
+ return a;
388
+ }
389
+ /**
390
+ * When a model's price in the table stops being its list price: the day
391
+ * (YYYY-MM-DD) and, when the page said, the price from then. Undefined for
392
+ * a row with no end date. What `doctor` and the budget say once it has passed.
393
+ */
394
+ export function priceChange(model) {
395
+ const b = row(model)?.[2];
396
+ return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}) } : undefined;
397
+ }
398
+ /** "gemini-4-argon's price changed on 2026-12-01; a newer context-doctor knows the new one": said for each model priced past its row's date. */
399
+ export function priceChangedText(models) {
400
+ const byDay = new Map();
401
+ for (const [m, on] of models) {
402
+ const l = byDay.get(on) ?? byDay.set(on, []).get(on);
403
+ if (!l.includes(m))
404
+ l.push(m);
405
+ }
406
+ return [...byDay].map(([on, ms]) => `${ms.slice(0, 3).join(", ")}${ms.length > 3 ? " and others" : ""}: price changed on ${on}`).join("; ") + "; a newer context-doctor knows the new one";
407
+ }
272
408
  /**
273
409
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
274
410
  * (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`
package/dist/proxy.d.ts CHANGED
@@ -32,6 +32,17 @@ export interface ProxyOptions extends OptimizeOptions {
32
32
  * constant time; a wrong or missing prefix gets 401 and no upstream call.
33
33
  */
34
34
  token?: string;
35
+ /**
36
+ * Host names besides loopback, an IP address and `host` that requests may
37
+ * name in their Host header (comma list; also CONTEXT_DOCTOR_ALLOWED_HOSTS;
38
+ * `*` for any), and origins a browser page may call from besides loopback
39
+ * ones (also CONTEXT_DOCTOR_ALLOWED_ORIGINS). A page that rebinds its own
40
+ * name to 127.0.0.1 is refused, as by the MCP server's --http (httpguard.ts).
41
+ * With a token, Host is not checked: the token is the guard, and a tunnel's
42
+ * name is whatever it is.
43
+ */
44
+ allowedHosts?: string;
45
+ allowedOrigins?: string;
35
46
  /**
36
47
  * Autopilot: instead of the general strategies, run only the cache-aware
37
48
  * stale-tool-output clearing (autoclear.ts), which replays of real sessions
@@ -65,7 +76,7 @@ export interface ProxyOptions extends OptimizeOptions {
65
76
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
66
77
  export declare const DEFAULT_MAX_BODY_BYTES: number;
67
78
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
68
- export declare const PROXY_VERSION = "0.44.0";
79
+ export declare const PROXY_VERSION = "0.45.0";
69
80
  /**
70
81
  * Remove a leading `/t/<token>` from a request path, or return undefined when
71
82
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -21,10 +21,11 @@ import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
21
21
  import { recordLedger } from "./ledger.js";
22
22
  import { minCacheableTokens } from "./cacheplan.js";
23
23
  import { withPromptCacheKey } from "./cachekey.js";
24
+ import { makeGuard, refusal } from "./httpguard.js";
24
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
25
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
26
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
27
- export const PROXY_VERSION = "0.44.0";
28
+ export const PROXY_VERSION = "0.45.0";
28
29
  /** Connection-level headers that must not be forwarded. */
29
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
30
31
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
@@ -245,6 +246,8 @@ export function startProxy(opts = {}) {
245
246
  stats.advice.push(msg);
246
247
  console.error(`[context-doctor] cache advisor: ${msg}`);
247
248
  };
249
+ /** Host and Origin checks: a web page that rebinds its name to this address gets nothing. */
250
+ const guard = makeGuard(opts.host ?? "127.0.0.1", opts.token ? "*" : opts.allowedHosts, opts.allowedOrigins, process.env, { ipLiterals: true });
248
251
  /** Requests still being answered, so a shutdown can let them finish. */
249
252
  let inFlight = 0;
250
253
  const server = http.createServer(async (req, res) => {
@@ -266,6 +269,13 @@ export function startProxy(opts = {}) {
266
269
  res.end(JSON.stringify({ ok: true, service: "context-doctor-proxy", autopilot: Boolean(opts.autopilot), version: PROXY_VERSION }));
267
270
  return;
268
271
  }
272
+ const refused = refusal(guard, req.headers);
273
+ if (refused) {
274
+ res.statusCode = 403;
275
+ res.setHeader("content-type", "application/json");
276
+ res.end(JSON.stringify({ error: `context-doctor proxy: ${refused}` }));
277
+ return;
278
+ }
269
279
  if (opts.token) {
270
280
  const stripped = stripToken(url, opts.token);
271
281
  if (stripped === undefined) {
@@ -718,6 +728,8 @@ export function startProxy(opts = {}) {
718
728
  server.listen(port, host, () => {
719
729
  // Print the token as <token>, never the value: this log is what people paste into bug reports.
720
730
  const prefix = opts.token ? "/t/<token>" : "";
731
+ // The port it got: with --port 0 the system picks one.
732
+ const port = server.address()?.port ?? opts.port ?? 8787;
721
733
  console.error(`context-doctor proxy listening on http://${host}:${port}`);
722
734
  // 127.0.0.1, not localhost: on macOS another program can hold the same
723
735
  // port on :: or ::1 beside this one, and `localhost` may resolve there.
package/dist/prune.js CHANGED
@@ -34,7 +34,7 @@ import { statePath } from "./ledger.js";
34
34
  import { listSessions, isClaudeSession } from "./session.js";
35
35
  import { rowsOf } from "./scan.js";
36
36
  import { subagentFiles } from "./subagents.js";
37
- import { claudeMcpConfigs, countMcpRow, serverUses } from "./mcpschema.js";
37
+ import { claudeMcpConfigs, countMcpRow, serverUses, toolPrefixName } from "./mcpschema.js";
38
38
  import { estimateTokens, formatTokens } from "./tokens.js";
39
39
  import { formatUsd } from "./pricing.js";
40
40
  import { claudeDir, claudeJsonPath } from "./claudedir.js";
@@ -279,10 +279,62 @@ function offFor(cwd, home) {
279
279
  return {
280
280
  off,
281
281
  mcpjsonAllowlist: all ? undefined : allow,
282
- // Approved in so many words: a server nobody said yes to is one Claude Code asks about first.
283
- mcpjsonApproved: (name) => !off.has(`mcp:${name}`) && (all || (allow?.has(name) ?? false)),
282
+ mcpjsonApproved: (name) => mcpjsonApprovedBy(name, cwd, home, read, off),
284
283
  };
285
284
  }
285
+ /**
286
+ * Claude Code's own approval of a project `.mcp.json` server (read from the
287
+ * 2.1.311 binary). Rejected when any settings file lists it in
288
+ * `disabledMcpjsonServers` (or it is toggled off). Otherwise the project's own
289
+ * files, `.claude/settings.json` and `.claude/settings.local.json`, count only
290
+ * once the user trusted the workspace (`hasTrustDialogAccepted` on its
291
+ * project, the repository root or the folder, in ~/.claude.json): both can
292
+ * arrive with a clone, and a repository approving its own servers is the
293
+ * attack the trust dialog stands in front of. Untrusted, only the user's
294
+ * settings approve; trusted, the files merge (a later file's
295
+ * `enableAllProjectMcpServers: false` overrides an earlier `true`). Names
296
+ * compare as Claude Code compares them, in their tool-name spelling.
297
+ */
298
+ function mcpjsonApprovedBy(name, cwd, home, read, off) {
299
+ const same = (n) => typeof n === "string" && toolPrefixName(n) === toolPrefixName(name);
300
+ for (const o of off)
301
+ if (o.startsWith("mcp:") && same(o.slice(4)))
302
+ return false;
303
+ const user = read(join(claudeDir(home), "settings.json"));
304
+ const projects = read(claudeJsonPath(home)).projects;
305
+ const keys = trustKeys(cwd);
306
+ const entry = (k) => (projects && typeof projects === "object" && projects[k] && typeof projects[k] === "object" ? projects[k] : undefined);
307
+ const trusted = keys.some((k) => entry(k)?.hasTrustDialogAccepted === true);
308
+ const legacy = keys.map(entry).find((e) => e && (e.enabledMcpjsonServers !== undefined || e.enableAllProjectMcpServers !== undefined)) ?? {};
309
+ const sources = trusted ? [user, read(join(cwd, ".claude", "settings.json")), legacy, read(localSettingsPath(cwd))] : [user];
310
+ let all = false;
311
+ for (const s of sources)
312
+ if (typeof s.enableAllProjectMcpServers === "boolean")
313
+ all = trusted ? s.enableAllProjectMcpServers : all || s.enableAllProjectMcpServers;
314
+ return all || sources.some((s) => list(s.enabledMcpjsonServers).some(same));
315
+ }
316
+ /**
317
+ * The keys ~/.claude.json may hold this workspace's trust under: the folder
318
+ * and the repository root it is in (Claude Code keys a project by its git
319
+ * root), each as given, resolved and real, with forward slashes too.
320
+ */
321
+ function trustKeys(cwd) {
322
+ const out = new Set();
323
+ const add = (p) => { for (const v of [p, resolve(p), canonical(p)]) {
324
+ out.add(v);
325
+ out.add(v.replace(/\\/g, "/"));
326
+ } };
327
+ add(cwd);
328
+ for (let d = canonical(cwd);; d = dirname(d)) {
329
+ if (existsSync(join(d, ".git"))) {
330
+ add(d);
331
+ break;
332
+ }
333
+ if (dirname(d) === d)
334
+ break;
335
+ }
336
+ return [...out];
337
+ }
286
338
  /**
287
339
  * Whether Claude Code would start this project `.mcp.json` server without
288
340
  * asking: the user approved it (enabledMcpjsonServers, or
package/dist/savings.js CHANGED
@@ -16,7 +16,7 @@ import { AutoClearer } from "./autoclear.js";
16
16
  import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
19
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
20
20
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
21
21
  import { withInvocation } from "./invocation.js";
22
22
  import { sessionsLabel } from "./compactwindow.js";
@@ -134,7 +134,6 @@ function replayExtractor(id, options, makeClearer, replay) {
134
134
  // Each request at its own model: a session that switched from a
135
135
  // $4 to a $10 model was priced at the first one throughout.
136
136
  const pm = realModel(m.model) ?? st.model;
137
- const price = pricingFor(pm);
138
137
  const ttl = cacheWriteSplit(u);
139
138
  st.writes5m += ttl.fiveMinute;
140
139
  st.writes1h += ttl.oneHour;
@@ -142,7 +141,7 @@ function replayExtractor(id, options, makeClearer, replay) {
142
141
  const r = {
143
142
  k: "r", now, cold,
144
143
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
145
- usd: price ? usageCost(u, price).promptUsd : 0,
144
+ usd: requestCost(pm, u, now)?.promptUsd ?? 0,
146
145
  raw: fresh + read + write,
147
146
  };
148
147
  // Only what is set: a record read back from the cache must equal this one.
@@ -150,6 +149,11 @@ function replayExtractor(id, options, makeClearer, replay) {
150
149
  r.uuid = uuid;
151
150
  if (pm !== undefined)
152
151
  r.pm = pm;
152
+ // What bills the arms' requests as this one was (fast mode, US-only).
153
+ if (u.speed === "fast")
154
+ r.f = 1;
155
+ if (u.inference_geo === "us")
156
+ r.g = 1;
153
157
  if (st.base && st.auto) {
154
158
  const b = armRequest(st.base, now, cold), a = armRequest(st.auto, now, cold);
155
159
  Object.assign(r, { b: [b.read, b.write, b.total], a: [a.read, a.write, a.total] });
@@ -191,8 +195,8 @@ function replayExtractor(id, options, makeClearer, replay) {
191
195
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
192
196
  };
193
197
  }
194
- const REPLAY = replayExtractor("replay.2", {}, undefined, true);
195
- const BILL = replayExtractor("bill.2", {}, undefined, false);
198
+ const REPLAY = replayExtractor("replay.3", {}, undefined, true);
199
+ const BILL = replayExtractor("bill.3", {}, undefined, false);
196
200
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
197
201
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
198
202
  /**
@@ -259,9 +263,12 @@ function settleReplay(path, rows, since, runRows, coldRows, replay) {
259
263
  billedUsd += r.usd;
260
264
  billedRaw += r.raw;
261
265
  requests++;
262
- const price = pricingFor(r.pm) ?? UNPRICED;
263
- charge(base, r.b, r.cold, price);
264
- charge(auto, r.a, r.cold, price);
266
+ // Each arm's request at its own tier (Haiku 5.5's 100k): as billed for the
267
+ // 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);
269
+ const cleared = r.b && r.a ? Math.max(0, r.b[2] - r.a[2]) : 0;
270
+ charge(base, r.b, r.cold, card ? ratesAt(card, r.raw) : UNPRICED);
271
+ charge(auto, r.a, r.cold, card ? ratesAt(card, r.raw - cleared) : UNPRICED);
265
272
  }
266
273
  }
267
274
  flush();
package/dist/scan.d.ts CHANGED
@@ -103,4 +103,10 @@ export declare function clearScanMemo(): void;
103
103
  export declare function pruneScanCache(now?: number, force?: boolean): void;
104
104
  /** `o` with only `keys`, those set: what a record keeps of a row. Not an object: as it was. */
105
105
  export declare function pick(o: any, keys: readonly string[]): any;
106
- export declare const slimUsage: (u: unknown) => unknown;
106
+ /**
107
+ * Those fields, and what changes the request's price (requestCost) only
108
+ * when it does: fast mode, US-only inference, web searches. Every request
109
+ * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
110
+ * would grow every record for nothing.
111
+ */
112
+ export declare const slimUsage: (u: any) => unknown;
package/dist/scan.js CHANGED
@@ -501,4 +501,22 @@ export function pick(o, keys) {
501
501
  }
502
502
  /** The usage fields any report reads (cost, cache writes by TTL, reasoning, context edits). */
503
503
  const USAGE_KEYS = ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens", "cache_creation", "output_tokens_details", "context_management"];
504
- export const slimUsage = (u) => pick(u, USAGE_KEYS);
504
+ /**
505
+ * Those fields, and what changes the request's price (requestCost) only
506
+ * when it does: fast mode, US-only inference, web searches. Every request
507
+ * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
508
+ * would grow every record for nothing.
509
+ */
510
+ export const slimUsage = (u) => {
511
+ const out = pick(u, USAGE_KEYS);
512
+ if (!out || typeof out !== "object" || Array.isArray(out))
513
+ return out;
514
+ if (u.speed === "fast")
515
+ out.speed = "fast";
516
+ if (u.inference_geo === "us")
517
+ out.inference_geo = "us";
518
+ const searches = u.server_tool_use?.web_search_requests;
519
+ if (typeof searches === "number" && searches > 0)
520
+ out.server_tool_use = { web_search_requests: searches };
521
+ return out;
522
+ };
@@ -6,7 +6,8 @@
6
6
  * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
7
  * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
8
  * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
- * included (they bill to it), and when it passes $25, $100 and $500 says so
9
+ * included (they bill to it: Claude Code's, and the agents a Codex thread
10
+ * spawned, codexSpawnedRollouts), and when it passes $25, $100 and $500 says so
10
11
  * to the user once: the cost so far, what each message of the main
11
12
  * conversation now costs at the model's cache-read rate (or, after an idle
12
13
  * that expired the cache, the re-write this message pays), and that
@@ -43,7 +44,7 @@ export interface SessionPrice {
43
44
  /** The threshold just passed. */
44
45
  threshold: number;
45
46
  usd: number;
46
- /** Subagents' part of `usd` (the Agent tool's). */
47
+ /** Subagents' part of `usd`: the Agent tool's, or the agents a Codex thread spawned. */
47
48
  subagentUsd: number;
48
49
  /** Workflow agents' part of `usd`. */
49
50
  workflowUsd?: number;