context-doctor 0.43.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.
Files changed (61) hide show
  1. package/README.md +4 -2
  2. package/dist/budget.d.ts +23 -3
  3. package/dist/budget.js +184 -50
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +1 -1
  6. package/dist/cachettl.d.ts +5 -1
  7. package/dist/cachettl.js +16 -29
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +16 -12
  10. package/dist/codexcompact.d.ts +24 -3
  11. package/dist/codexcompact.js +221 -48
  12. package/dist/coldresume.js +16 -8
  13. package/dist/compactwindow.js +14 -9
  14. package/dist/cursor.d.ts +10 -0
  15. package/dist/cursor.js +20 -0
  16. package/dist/doctor.d.ts +9 -0
  17. package/dist/doctor.js +52 -0
  18. package/dist/extract.d.ts +2 -2
  19. package/dist/extract.js +14 -3
  20. package/dist/fanout.js +4 -2
  21. package/dist/fix.d.ts +8 -1
  22. package/dist/fix.js +59 -13
  23. package/dist/hook.js +45 -15
  24. package/dist/httpguard.d.ts +9 -1
  25. package/dist/httpguard.js +5 -4
  26. package/dist/install.js +56 -19
  27. package/dist/lens.js +7 -7
  28. package/dist/limits.d.ts +17 -4
  29. package/dist/limits.js +41 -29
  30. package/dist/mcp.js +63 -63
  31. package/dist/mcpclient.js +19 -19
  32. package/dist/mcpschema.js +10 -12
  33. package/dist/overhead.d.ts +7 -2
  34. package/dist/overhead.js +11 -3
  35. package/dist/pack.js +87 -23
  36. package/dist/pricing.d.ts +125 -6
  37. package/dist/pricing.js +304 -59
  38. package/dist/proxy.d.ts +26 -1
  39. package/dist/proxy.js +45 -5
  40. package/dist/prune.d.ts +8 -0
  41. package/dist/prune.js +73 -10
  42. package/dist/savings.js +17 -9
  43. package/dist/scan.d.ts +7 -1
  44. package/dist/scan.js +19 -1
  45. package/dist/sessionprice.d.ts +9 -2
  46. package/dist/sessionprice.js +95 -36
  47. package/dist/settingsedit.js +3 -2
  48. package/dist/spend.d.ts +75 -10
  49. package/dist/spend.js +279 -37
  50. package/dist/statusline.d.ts +10 -2
  51. package/dist/statusline.js +17 -8
  52. package/dist/subagentmodel.d.ts +2 -2
  53. package/dist/subagentmodel.js +42 -25
  54. package/dist/subagentpay.d.ts +17 -0
  55. package/dist/subagentpay.js +41 -2
  56. package/dist/subagents.d.ts +24 -0
  57. package/dist/subagents.js +93 -27
  58. package/dist/tasks.js +9 -6
  59. package/dist/tooloutput.d.ts +2 -0
  60. package/dist/tooloutput.js +16 -5
  61. package/package.json +1 -1
package/dist/pricing.js CHANGED
@@ -1,11 +1,19 @@
1
1
  /**
2
2
  * Per-model pricing for cost estimation, USD per million tokens.
3
3
  *
4
- * Anthropic prices are first-party API list rates, checked against
5
- * Anthropic's price list in October 2026. OpenAI/Google figures are
6
- * approximate public list prices and drift over time — all cost output is
4
+ * List rates of each provider's first-party API (standard tier, global
5
+ * routing, no batch or fast mode), each family with the page it was read
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
7
10
  * labeled as an estimate. One table, one file, easy to update: PRs welcome
8
11
  * when prices change.
12
+ *
13
+ * A row names one model (a "known" price, see knownPricingFor) unless it is
14
+ * listed in FALLBACKS: those price ids the table does not know by version,
15
+ * at a family's price, so a new release still gets a number. A model a
16
+ * provider prices only per minute, per image or not at all has no row.
9
17
  */
10
18
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
11
19
  export const CACHE_WRITE_5M = 1.25;
@@ -34,64 +42,202 @@ function claude(families, major, minor) {
34
42
  }
35
43
  /** The Claude family fallbacks: a price for ids the table does not know by version yet. */
36
44
  const CLAUDE_FAMILY = [/claude.*fable|claude.*mythos/i, /claude.*opus/i, /claude.*sonnet/i, /claude.*haiku/i];
45
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46
+ /**
47
+ * One OpenAI model by its exact name, bare, with a snapshot date
48
+ * (gpt-5.5-2026-04-23) or behind a provider prefix (openai/gpt-5.5):
49
+ * "gpt-5.5" never matches gpt-5.5-pro or gpt-5.5-cyber, "gpt-5" never
50
+ * gpt-5.4, "o3" never o3-pro.
51
+ */
52
+ function openai(name) {
53
+ return new RegExp(`(?<![\\w.-])${escapeRe(name)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`, "i");
54
+ }
55
+ /**
56
+ * One Gemini text model, with any suffix Google adds to the same model
57
+ * (-preview, -001, -preview-05-20, -customtools), but not the image, audio,
58
+ * live and TTS models that share its name and are priced per image or
59
+ * minute, nor its -lite sibling.
60
+ */
61
+ function gemini(name) {
62
+ return new RegExp(`(?<![\\w.-])${escapeRe(name)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`, "i");
63
+ }
64
+ /** A row that prices ids the table does not know by name, at a family's price. */
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
+ };
37
79
  const PRICING = [
80
+ // Anthropic: platform.claude.com/docs/en/about-claude/pricing ("Model
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.
38
90
  // Specific Claude versions first: the family rows below are only a
39
91
  // fallback for ids this table does not know yet.
40
- [claude("fable|mythos", 5, 1), rate(10, 50, 0.25)],
41
- [claude("fable|mythos", 5), rate(10, 50, 1)],
42
- [claude("opus", 5, 5), rate(4, 20, 0.2)],
43
- [claude("opus", 5), rate(5, 25, 0.5)],
44
- [claude("opus", 4, 8), rate(5, 25, 0.5)],
45
- [claude("opus", 4, 7), rate(5, 25, 0.5)],
46
- [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],
47
99
  [claude("opus", 4, 5), rate(5, 25, 0.5)],
48
100
  [claude("opus", 4, 1), rate(15, 75, 1.5)],
49
101
  [claude("opus", 4), rate(15, 75, 1.5)],
50
- [/claude-3-opus/i, rate(15, 75, 1.5)],
51
- [claude("sonnet", 5, 5), rate(2, 10, 0.2)],
52
- [claude("sonnet", 5), rate(2, 10, 0.2)],
53
- // Haiku 5.5's rates hold for prompts up to 100k tokens; longer prompts
54
- // bill higher, a tier this per-token table does not model.
55
- [claude("haiku", 5, 5), rate(0.1, 0.5, 0.01)],
102
+ // Sonnet 5.5's cache hits are 5% of input ($0.10), Sonnet 5's 10%.
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) } }],
56
109
  [claude("haiku", 4, 5), rate(1, 5, 0.1)],
57
- [/claude-3-5-haiku/i, rate(0.8, 4, 0.08)],
58
- [/claude-3-haiku/i, rate(0.25, 1.25, 0.03)],
59
- // Sonnet 4.6, 4.5, 4 and the 3.x Sonnets are all $3 / $15 / $0.30, the
60
- // family row's price; rows of their own so a spending cap can tell a known
61
- // version from a guess (exactClaudePricingFor).
62
- [claude("sonnet", 4, 6), rate(3, 15, 0.3)],
110
+ // Sonnet 4.6, 4.5 and 4 are all $3 / $15 / $0.30, the family row's price;
111
+ // rows of their own so a spending cap can tell a known version from a
112
+ // guess (knownPricingFor).
113
+ [claude("sonnet", 4, 6), rate(3, 15, 0.3), GEO],
63
114
  [claude("sonnet", 4, 5), rate(3, 15, 0.3)],
64
115
  [claude("sonnet", 4), rate(3, 15, 0.3)],
116
+ // Retired Claude 3 models, no longer on the page: their last list price.
117
+ [/claude-3-opus/i, rate(15, 75, 1.5)],
118
+ [/claude-3-5-haiku/i, rate(0.8, 4, 0.08)],
119
+ [/claude-3-haiku/i, rate(0.25, 1.25, 0.03)],
65
120
  [/claude-3-[57]-sonnet/i, rate(3, 15, 0.3)],
66
- [CLAUDE_FAMILY[0], rate(10, 50, 1)],
67
- [CLAUDE_FAMILY[1], rate(5, 25, 0.5)],
68
- [CLAUDE_FAMILY[2], rate(3, 15, 0.3)],
69
- [CLAUDE_FAMILY[3], rate(1, 5, 0.1)],
70
- [/gpt-5.*(mini|nano)/i, { inputPerM: 0.25, outputPerM: 2, cacheReadPerM: 0.025 }],
71
- [/gpt-5/i, { inputPerM: 1.25, outputPerM: 10, cacheReadPerM: 0.125 }],
72
- [/gpt-4o-mini/i, { inputPerM: 0.15, outputPerM: 0.6, cacheReadPerM: 0.075 }],
73
- [/gpt-4o|gpt-4\.1/i, { inputPerM: 2.5, outputPerM: 10, cacheReadPerM: 1.25 }],
74
- [/gpt-4-turbo/i, { inputPerM: 10, outputPerM: 30, cacheReadPerM: 10 }],
75
- [/o[13](-|$)/i, { inputPerM: 2, outputPerM: 8, cacheReadPerM: 1 }],
76
- // Gemini 3, paid tier (ai.google.dev/gemini-api/docs/pricing, Oct 2026). 3.6/3.8 Flash
77
- // double from 2027-01-01; 3.1 Pro bills prompts over 200k at $4/$18/$0.40, a tier
78
- // this per-token table does not model.
79
- [/gemini-3[.\d]*-flash-lite/i, rate(0.3, 2.5, 0.03)],
80
- [/gemini-3\.1-flash-lite/i, rate(0.25, 1.5, 0.025)],
81
- [/gemini-3-flash/i, rate(0.5, 3, 0.05)],
82
- [/gemini-3[.\d]*-flash/i, rate(0.75, 3.75, 0.075)],
83
- [/gemini-3[.\d]*-pro/i, rate(2, 12, 0.2)],
84
- [/gemini.*flash/i, { inputPerM: 0.1, outputPerM: 0.4, cacheReadPerM: 0.025 }],
85
- [/gemini.*pro/i, { inputPerM: 1.25, outputPerM: 5, cacheReadPerM: 0.31 }],
121
+ // Claude Mythos Preview (claude-mythos-preview) has no list price on the
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 }],
128
+ // OpenAI: developers.openai.com/api/docs/pricing (Standard, the "Short"
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)],
136
+ [openai("gpt-6-astra-law"), rate(10, 50, 1)],
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)],
141
+ [openai("gpt-6-cyber"), rate(20, 100, 2)],
142
+ [openai("gpt-6-rosalind"), ...openaiLong(15, 75, 1.5)],
143
+ [openai("gpt-rosalind-research"), rate(5, 25, 0.5)],
144
+ [openai("gpt-rosalind-discovery"), rate(5, 25, 0.5)],
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)],
152
+ [openai("gpt-5.6-cyber"), rate(12.5, 75, 1.25)],
153
+ [openai("gpt-5.5"), ...openaiLong(5, 30, 0.5)],
154
+ [openai("gpt-5.5-pro"), ...openaiLong(30, 180, 30)],
155
+ [openai("gpt-5.5-cyber"), rate(12.5, 75, 1.25)],
156
+ [openai("gpt-5.4"), ...openaiLong(2.5, 15, 0.25)],
157
+ [openai("gpt-5.4-mini"), rate(0.75, 4.5, 0.075)],
158
+ [openai("gpt-5.4-nano"), rate(0.2, 1.25, 0.02)],
159
+ [openai("gpt-5.4-pro"), ...openaiLong(30, 180, 30)],
160
+ [openai("gpt-5.3-codex"), rate(1.75, 14, 0.175)],
161
+ [openai("gpt-5.2"), rate(1.75, 14, 0.175)],
162
+ [openai("gpt-5.2-pro"), rate(21, 168, 21)],
163
+ [openai("gpt-5.1"), rate(1.25, 10, 0.125)],
164
+ [openai("gpt-5"), rate(1.25, 10, 0.125)],
165
+ [openai("gpt-5-mini"), rate(0.25, 2, 0.025)],
166
+ [openai("gpt-5-nano"), rate(0.05, 0.4, 0.005)],
167
+ [openai("gpt-5-pro"), rate(15, 120, 15)],
168
+ [openai("gpt-4.1"), rate(2, 8, 0.5)],
169
+ [openai("gpt-4.1-mini"), rate(0.4, 1.6, 0.1)],
170
+ [openai("gpt-4o"), rate(2.5, 10, 1.25)],
171
+ [openai("gpt-4o-mini"), rate(0.15, 0.6, 0.075)],
172
+ [openai("o3"), rate(2, 8, 0.5)],
173
+ [openai("o3-pro"), rate(20, 80, 20)],
174
+ [openai("chat-latest"), rate(5, 30, 0.5)],
175
+ // Fallbacks for OpenAI ids not on the page (gpt-5-codex, gpt-5.1-codex-max,
176
+ // gpt-4.1-nano, gpt-4-turbo, o1, o3-mini...): older approximate prices.
177
+ [/gpt-5.*(mini|nano)/i, rate(0.25, 2, 0.025), FALLBACK],
178
+ [/gpt-5/i, rate(1.25, 10, 0.125), FALLBACK],
179
+ [/gpt-4o-mini/i, rate(0.15, 0.6, 0.075), FALLBACK],
180
+ [/gpt-4o|gpt-4\.1/i, rate(2.5, 10, 1.25), FALLBACK],
181
+ [/gpt-4-turbo/i, rate(10, 30, 10), FALLBACK],
182
+ [/o[13](-|$)/i, rate(2, 8, 1), FALLBACK],
183
+ // Google: ai.google.dev/gemini-api/docs/pricing (paid tier, Standard, text),
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) }],
191
+ [gemini("gemini-3.5-flash-lite"), rate(0.3, 2.5, 0.03)],
192
+ [gemini("gemini-3.1-flash-lite"), rate(0.25, 1.5, 0.025)],
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) } }],
199
+ [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) }],
201
+ [gemini("gemini-2.5-flash"), rate(0.3, 2.5, 0.03)],
202
+ [gemini("gemini-2.5-flash-lite"), rate(0.1, 0.4, 0.01)],
203
+ // Fallbacks for Gemini ids not on the page (gemini-3-pro, a new 3.x Flash,
204
+ // 2.0 Flash...).
205
+ [/gemini-3[.\d]*-flash-lite/i, rate(0.3, 2.5, 0.03), FALLBACK],
206
+ [/gemini-3[.\d]*-flash/i, rate(0.75, 3.75, 0.075), FALLBACK],
207
+ [/gemini-3[.\d]*-pro/i, rate(2, 12, 0.2), FALLBACK],
208
+ [/gemini.*flash/i, rate(0.1, 0.4, 0.025), FALLBACK],
209
+ [/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
86
210
  ];
87
- export function pricingFor(model) {
211
+ function row(model) {
88
212
  if (!model)
89
213
  return undefined;
90
- for (const [pattern, pricing] of PRICING) {
91
- if (pattern.test(model))
92
- return pricing;
93
- }
94
- return undefined;
214
+ return PRICING.find(([pattern]) => pattern.test(model));
215
+ }
216
+ /** A model's list row, as the page lists it today (no tier, mode or date applied). */
217
+ export function pricingFor(model) {
218
+ return row(model)?.[1];
219
+ }
220
+ /**
221
+ * A model's price from a row for that model, not a family fallback: undefined
222
+ * for an id the table only knows by family (a new release, a typo like
223
+ * claude-opus-9, gpt-5-codex) and for one it does not know at all. What a
224
+ * report needs to say which models it priced by guess or not at all.
225
+ */
226
+ export function knownPricingFor(model) {
227
+ const r = row(model);
228
+ return r && !r[2]?.fallback ? r[1] : undefined;
229
+ }
230
+ /** Whether a model id has a price of its own in the table (see knownPricingFor). */
231
+ export function hasKnownPrice(model) {
232
+ return knownPricingFor(model) !== undefined;
233
+ }
234
+ /**
235
+ * Ids that are never billed, so never "unpriced": Claude Code writes
236
+ * `<synthetic>` on replies it makes itself (an error, an interruption)
237
+ * without calling the API.
238
+ */
239
+ export function isUnbilledModel(model) {
240
+ return model === "<synthetic>";
95
241
  }
96
242
  /**
97
243
  * A Claude model's price from a row for its own version, not a family
@@ -100,14 +246,7 @@ export function pricingFor(model) {
100
246
  * claude-opus-9) gets undefined.
101
247
  */
102
248
  export function exactClaudePricingFor(model) {
103
- if (!model || !/claude/i.test(model))
104
- return undefined;
105
- for (const [pattern, pricing] of PRICING) {
106
- if (!pattern.test(model))
107
- continue;
108
- return CLAUDE_FAMILY.includes(pattern) ? undefined : pricing;
109
- }
110
- return undefined;
249
+ return model && /claude/i.test(model) ? knownPricingFor(model) : undefined;
111
250
  }
112
251
  export function inputCostUsd(tokens, pricing) {
113
252
  return (tokens / 1_000_000) * pricing.inputPerM;
@@ -146,9 +285,9 @@ export function writeMultiplier(fiveMinute, oneHour, twelveHour = 0) {
146
285
  return total > 0 ? (fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H) / total : CACHE_WRITE_5M;
147
286
  }
148
287
  /**
149
- * What one recorded request cost: uncached input, cache writes priced by
150
- * TTL, cache reads, output. The one place recorded usage is priced, so every
151
- * 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.
152
291
  */
153
292
  export function usageCost(usage, pricing) {
154
293
  const { fiveMinute, oneHour, twelveHour } = cacheWriteSplit(usage);
@@ -160,6 +299,112 @@ export function usageCost(usage, pricing) {
160
299
  const promptUsd = inputUsd + writeUsd + readUsd;
161
300
  return { inputUsd, writeUsd, readUsd, outputUsd, promptUsd, totalUsd: promptUsd + outputUsd };
162
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
+ }
163
408
  /**
164
409
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
165
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.43.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
@@ -90,6 +101,20 @@ export declare function stripToken(url: string, token: string): string | undefin
90
101
  */
91
102
  export declare function upstreamFor(url: string, opts: ProxyOptions, headers?: http.IncomingHttpHeaders): string;
92
103
  export declare function isGeminiRequest(url: string, headers?: http.IncomingHttpHeaders): boolean;
104
+ /**
105
+ * A request path as the log may show it. Gemini's REST API takes its key in
106
+ * the query (`?key=AIza…`), and the log is a file on disk (autopilot's
107
+ * service writes it beside settings.json): a key there outlives the request.
108
+ */
109
+ export declare function logUrl(url: string): string;
110
+ /**
111
+ * What to say when the proxy listens beyond this machine with no token:
112
+ * anyone who can reach the address can relay through it (with their own
113
+ * keys) and read /stats. Inside a container that is the point (`--host
114
+ * 0.0.0.0` with the port published to the host only), so it is said, not
115
+ * refused. Undefined on a loopback address or with a token.
116
+ */
117
+ export declare function exposureWarning(host: string, token?: string): string | undefined;
93
118
  /** The model a Gemini request names in its path (…/models/<model>:generateContent). */
94
119
  export declare function geminiModelFromUrl(url: string): string | undefined;
95
120
  export interface ProxyStats {
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.43.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"]);
@@ -84,6 +85,30 @@ export function isGeminiRequest(url, headers = {}) {
84
85
  /^\/(upload\/)?v1(beta|alpha)\d*\//.test(url) ||
85
86
  /^\/v1\/[^?]*:(generateContent|streamGenerateContent|countTokens|embedContent|batchEmbedContents)/.test(url));
86
87
  }
88
+ /**
89
+ * A request path as the log may show it. Gemini's REST API takes its key in
90
+ * the query (`?key=AIza…`), and the log is a file on disk (autopilot's
91
+ * service writes it beside settings.json): a key there outlives the request.
92
+ */
93
+ export function logUrl(url) {
94
+ return url.replace(/([?&](?:key|api[_-]?key|access_token|token)=)[^&#\s]*/gi, "$1…");
95
+ }
96
+ /**
97
+ * What to say when the proxy listens beyond this machine with no token:
98
+ * anyone who can reach the address can relay through it (with their own
99
+ * keys) and read /stats. Inside a container that is the point (`--host
100
+ * 0.0.0.0` with the port published to the host only), so it is said, not
101
+ * refused. Undefined on a loopback address or with a token.
102
+ */
103
+ export function exposureWarning(host, token) {
104
+ if (token)
105
+ return undefined;
106
+ const h = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
107
+ if (h === "localhost" || h === "::1" || /^127\.\d+\.\d+\.\d+$/.test(h) || /^::ffff:127\./.test(h))
108
+ return undefined;
109
+ return (` WARNING: listening on ${host}, beyond this machine, with no token: anyone who can reach it can send requests through it and read /stats.\n` +
110
+ ` Add --token <secret> (or CONTEXT_DOCTOR_PROXY_TOKEN) unless only you can reach this address (a container whose port is published to localhost).`);
111
+ }
87
112
  /** The model a Gemini request names in its path (…/models/<model>:generateContent). */
88
113
  export function geminiModelFromUrl(url) {
89
114
  return /\/models\/([^/:?]+):/.exec(url)?.[1];
@@ -221,6 +246,8 @@ export function startProxy(opts = {}) {
221
246
  stats.advice.push(msg);
222
247
  console.error(`[context-doctor] cache advisor: ${msg}`);
223
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 });
224
251
  /** Requests still being answered, so a shutdown can let them finish. */
225
252
  let inFlight = 0;
226
253
  const server = http.createServer(async (req, res) => {
@@ -242,6 +269,13 @@ export function startProxy(opts = {}) {
242
269
  res.end(JSON.stringify({ ok: true, service: "context-doctor-proxy", autopilot: Boolean(opts.autopilot), version: PROXY_VERSION }));
243
270
  return;
244
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
+ }
245
279
  if (opts.token) {
246
280
  const stripped = stripToken(url, opts.token);
247
281
  if (stripped === undefined) {
@@ -532,7 +566,7 @@ export function startProxy(opts = {}) {
532
566
  upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
533
567
  }
534
568
  }
535
- console.error(`[context-doctor] ${req.method} ${url} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
569
+ console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
536
570
  (stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
537
571
  res.statusCode = upstream.status;
538
572
  // setHeader per value kept only the last of a repeated header: two
@@ -589,11 +623,12 @@ export function startProxy(opts = {}) {
589
623
  }
590
624
  catch (e) {
591
625
  if (upstreamAbort.signal.aborted) {
592
- console.error(`[context-doctor] ${req.method} ${url}: client went away; upstream request cancelled`);
626
+ console.error(`[context-doctor] ${req.method} ${logUrl(url)}: client went away; upstream request cancelled`);
593
627
  res.destroy();
594
628
  return;
595
629
  }
596
- console.error(`[context-doctor] error on ${url}: ${e.message}`);
630
+ // fetch's own message can carry the whole upstream URL, query included.
631
+ console.error(`[context-doctor] error on ${logUrl(url)}: ${logUrl(e.message)}`);
597
632
  if (res.headersSent) {
598
633
  // Upstream failed mid-body. Status and part of the body are already
599
634
  // with the client; appending a JSON error and ending cleanly made a
@@ -604,7 +639,7 @@ export function startProxy(opts = {}) {
604
639
  }
605
640
  res.statusCode = 502;
606
641
  res.setHeader("content-type", "application/json");
607
- res.end(JSON.stringify({ error: `context-doctor proxy: ${e.message}` }));
642
+ res.end(JSON.stringify({ error: `context-doctor proxy: ${logUrl(e.message)}` }));
608
643
  }
609
644
  });
610
645
  // Savings live in memory, so a restart would erase the record the dashboard
@@ -693,6 +728,8 @@ export function startProxy(opts = {}) {
693
728
  server.listen(port, host, () => {
694
729
  // Print the token as <token>, never the value: this log is what people paste into bug reports.
695
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;
696
733
  console.error(`context-doctor proxy listening on http://${host}:${port}`);
697
734
  // 127.0.0.1, not localhost: on macOS another program can hold the same
698
735
  // port on :: or ::1 beside this one, and `localhost` may resolve there.
@@ -703,6 +740,9 @@ export function startProxy(opts = {}) {
703
740
  ? ` Autopilot: stale re-runnable tool output is cleared only when the prompt cache is cold; savings are logged here.`
704
741
  : ` Every request's context is optimized in flight; savings are logged here.`);
705
742
  console.error(` Cumulative savings: http://127.0.0.1:${port}${prefix}/stats`);
743
+ const exposed = exposureWarning(host, opts.token);
744
+ if (exposed)
745
+ console.error(exposed);
706
746
  if (opts.token) {
707
747
  console.error(` Token required: every path except /health must start with /t/<token>/.`);
708
748
  console.error(` Cursor with your own OpenAI key: expose this port on HTTPS (a tunnel), then Settings > Models > OpenAI API Key >`);
package/dist/prune.d.ts CHANGED
@@ -85,6 +85,14 @@ export interface PrunePlan {
85
85
  }
86
86
  /** The project's own settings file, where prune writes. */
87
87
  export declare function localSettingsPath(cwd: string): string;
88
+ /**
89
+ * Whether Claude Code would start this project `.mcp.json` server without
90
+ * asking: the user approved it (enabledMcpjsonServers, or
91
+ * enableAllProjectMcpServers, in a settings file or ~/.claude.json) and has
92
+ * not switched it off. A `.mcp.json` arrives with a clone, so its commands
93
+ * are a stranger's until then: `overhead --mcp` launches only approved ones.
94
+ */
95
+ export declare function mcpjsonServerApproved(name: string, cwd?: string, home?: string): boolean;
88
96
  export declare function planPrune(days?: number, opts?: {
89
97
  home?: string;
90
98
  usage?: Map<string, ProjectUse>;