context-doctor 0.44.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.
Files changed (62) hide show
  1. package/README.md +5 -2
  2. package/dist/budget.d.ts +14 -1
  3. package/dist/budget.js +50 -28
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +6 -4
  6. package/dist/cacheplan.js +2 -2
  7. package/dist/cachettl.js +8 -5
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +27 -6
  10. package/dist/codexcompact.js +14 -7
  11. package/dist/coldresume.d.ts +6 -0
  12. package/dist/coldresume.js +20 -11
  13. package/dist/compactwindow.js +14 -8
  14. package/dist/doctor.js +26 -2
  15. package/dist/extract.d.ts +2 -2
  16. package/dist/extract.js +14 -3
  17. package/dist/fanout.js +1 -1
  18. package/dist/fix.js +14 -10
  19. package/dist/hook.js +6 -2
  20. package/dist/httpguard.d.ts +9 -1
  21. package/dist/httpguard.js +5 -4
  22. package/dist/lens.js +7 -7
  23. package/dist/limits.d.ts +14 -5
  24. package/dist/limits.js +26 -17
  25. package/dist/mcp.js +62 -62
  26. package/dist/mcpschema.js +5 -3
  27. package/dist/mod/api.d.ts +129 -0
  28. package/dist/mod/api.js +12 -0
  29. package/dist/mod/logic.d.ts +146 -0
  30. package/dist/mod/logic.js +222 -0
  31. package/dist/mod/register.d.ts +58 -0
  32. package/dist/mod/register.js +237 -0
  33. package/dist/modelids.d.ts +23 -0
  34. package/dist/modelids.js +49 -0
  35. package/dist/modmeasure.d.ts +121 -0
  36. package/dist/modmeasure.js +298 -0
  37. package/dist/orgrates.d.ts +75 -0
  38. package/dist/orgrates.js +165 -0
  39. package/dist/overhead.js +11 -8
  40. package/dist/pack.js +95 -22
  41. package/dist/pricing.d.ts +123 -6
  42. package/dist/pricing.js +236 -62
  43. package/dist/proxy.d.ts +12 -1
  44. package/dist/proxy.js +13 -1
  45. package/dist/prune.js +55 -3
  46. package/dist/savings.js +19 -10
  47. package/dist/scan.d.ts +7 -1
  48. package/dist/scan.js +19 -1
  49. package/dist/sessionprice.d.ts +25 -2
  50. package/dist/sessionprice.js +60 -20
  51. package/dist/spend.d.ts +62 -10
  52. package/dist/spend.js +255 -29
  53. package/dist/statusline.d.ts +10 -2
  54. package/dist/statusline.js +18 -9
  55. package/dist/subagentmodel.d.ts +2 -2
  56. package/dist/subagentmodel.js +31 -24
  57. package/dist/subagentpay.d.ts +7 -1
  58. package/dist/subagentpay.js +51 -25
  59. package/dist/subagents.js +15 -10
  60. package/dist/tasks.js +9 -6
  61. package/dist/tooloutput.js +14 -5
  62. package/package.json +1 -1
@@ -30,7 +30,7 @@ import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { forEachLine, replyCounter, textOf } from "./session.js";
32
32
  import { pick, rowsOf, slimUsage } from "./scan.js";
33
- import { cacheWriteSplit, pricingFor, formatUsd, writeMultiplier } from "./pricing.js";
33
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier, writePerM } from "./pricing.js";
34
34
  import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
35
35
  import { claudeDir } from "./claudedir.js";
36
36
  /**
@@ -68,7 +68,7 @@ export function isIdleCompactNotice(e) {
68
68
  * reader meets it as a repeat of that reply and skips it.
69
69
  */
70
70
  export const REQUEST_ROWS = {
71
- id: "requests.1",
71
+ id: "requests.2",
72
72
  init: () => ({ ids: {}, user: false }),
73
73
  line(raw, row, out, st) {
74
74
  let e;
@@ -145,7 +145,7 @@ export function autoCompactsAt(model, home = homedir(), env = process.env) {
145
145
  /** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
146
146
  export const COLD_IDLE_MS = 65 * 60_000;
147
147
  /** Margin past a cache's lifetime before a return counts as cold. */
148
- const COLD_MARGIN_MS = 5 * 60_000;
148
+ export const COLD_MARGIN_MS = 5 * 60_000;
149
149
  const HOUR_MS = 3_600_000;
150
150
  const FIVE_MIN_MS = 5 * 60_000;
151
151
  /**
@@ -173,7 +173,7 @@ function writtenTtlMs(u) {
173
173
  /** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
174
174
  export const COLD_MIN_TOKENS = 150_000;
175
175
  /** What a compacted session restarts from: system prompt and tools plus the summary. */
176
- const AFTER_COMPACT_TOKENS = 45_000;
176
+ export const AFTER_COMPACT_TOKENS = 45_000;
177
177
  /** Output tokens a compaction summary costs, at the model's output price. */
178
178
  const SUMMARY_OUTPUT_TOKENS = 8_000;
179
179
  export function resumeVerdict(input, now = Date.now()) {
@@ -260,7 +260,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
260
260
  if (idle < gate || tokens < minTokens)
261
261
  return undefined;
262
262
  const model = realModel(e.message?.model);
263
- const p = pricingFor(model);
263
+ // As the resuming request bills: fast mode and US-only as the last one recorded, its prompt's tier.
264
+ const card = rateCard(model, u, now);
265
+ const p = card && ratesAt(card, tokens);
264
266
  // The rebuild is written at the TTL this session writes at: Claude
265
267
  // Code's main thread has mostly written the 1-hour cache (2x input,
266
268
  // 97% of the author's main-thread writes), which a flat 1.25x
@@ -271,8 +273,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
271
273
  tokens,
272
274
  model,
273
275
  lastReplyAt,
274
- resumeUsd: p ? (tokens * sessionWriteMultiplier(path) * p.inputPerM) / 1e6 : undefined,
276
+ resumeUsd: p ? (tokens * writePerM(p, sessionWriteMultiplier(path))) / 1e6 : undefined,
275
277
  perMessageUsd: p ? (tokens * p.cacheReadPerM) / 1e6 : undefined,
278
+ ttlMs: ttl ?? HOUR_MS,
276
279
  };
277
280
  }
278
281
  }
@@ -394,7 +397,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
394
397
  writes5m += w.fiveMinute;
395
398
  writes1h += w.oneHour;
396
399
  ttl = writtenTtlMs(u) ?? ttl;
397
- reqs.push({ at, total, price: pricingFor(model), copy: seen === "copy", ttl });
400
+ reqs.push({ at, total, card: rateCard(model, u, at), copy: seen === "copy", ttl });
398
401
  });
399
402
  const mix = writeMultiplier(writes5m, writes1h);
400
403
  const real = reqs.filter((r) => r !== "compact");
@@ -409,8 +412,9 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
409
412
  const gate = (r) => idleMs ?? r.ttl + COLD_MARGIN_MS;
410
413
  if (b.at - a.at <= gate(a) || b.total < minTokens)
411
414
  continue;
412
- if (b.copy || !b.price)
415
+ if (b.copy || !b.card)
413
416
  continue;
417
+ const price = ratesAt(b.card, b.total);
414
418
  const removed = Math.max(0, b.total - AFTER_COMPACT_TOKENS);
415
419
  let saved = 0, n = 0, prev = b;
416
420
  for (const c of reqs.slice(i + 1)) {
@@ -418,14 +422,19 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
418
422
  break;
419
423
  if (c.at - prev.at > gate(prev) && c.total >= minTokens)
420
424
  break;
421
- const p = c.price ?? b.price;
422
- saved += removed * (c.at - prev.at > prev.ttl ? mix * p.inputPerM : p.cacheReadPerM);
425
+ const card = c.card ?? b.card;
426
+ const cold = c.at - prev.at > prev.ttl;
427
+ const per = (p) => (cold ? writePerM(p, mix) : p.cacheReadPerM);
428
+ // A long-prompt tier: the smaller prompt may bill all of it at the lower rates.
429
+ const after = Math.max(0, c.total - removed);
430
+ const hi = ratesAt(card, c.total), lo = ratesAt(card, after);
431
+ saved += hi === lo ? removed * per(hi) : c.total * per(hi) - after * per(lo);
423
432
  prev = c;
424
433
  n++;
425
434
  }
426
435
  // The compaction re-reads the context just rebuilt and writes a summary;
427
436
  // the next request writes the fresh context.
428
- const cost = b.total * b.price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * b.price.outputPerM + mix * AFTER_COMPACT_TOKENS * b.price.inputPerM;
437
+ const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + AFTER_COMPACT_TOKENS * writePerM(ratesAt(b.card, AFTER_COMPACT_TOKENS), mix);
429
438
  events.push({ at: b.at, tokens: b.total, messagesAfter: n, netUsd: (saved - cost) / 1e6 });
430
439
  }
431
440
  return events;
@@ -22,7 +22,8 @@
22
22
  */
23
23
  import { join } from "node:path";
24
24
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
- import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
25
+ import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
26
+ import { priceBasis } from "./orgrates.js";
26
27
  import { realModel } from "./tokens.js";
27
28
  import { backupOnce } from "./install.js";
28
29
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
@@ -40,6 +41,7 @@ const SUMMARY_OUTPUT = 20_000;
40
41
  const TTL_MS = 3_600_000;
41
42
  export const MIN_WINDOW = 100_000;
42
43
  export const MAX_WINDOW = 1_000_000;
44
+ const UNPRICED = { inputPerM: 0, outputPerM: 0, cacheReadPerM: 0 };
43
45
  /**
44
46
  * `writeMult`: what this session pays to write a token to the cache,
45
47
  * relative to input, from the 5-minute and 1-hour writes its usage records.
@@ -81,13 +83,13 @@ function readRequests(path, runRows) {
81
83
  return;
82
84
  // Each request at its own model's price; "<synthetic>" rows carry no usage.
83
85
  model = realModel(e.message.model) ?? model;
84
- const p = pricingFor(model);
85
- if (p)
86
+ const card = rateCard(model, u, at);
87
+ if (card)
86
88
  priced = true;
87
89
  const w = cacheWriteSplit(u);
88
90
  writes5m += w.fiveMinute;
89
91
  writes1h += w.oneHour;
90
- reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy", billedUsd: p ? usageCost(u, p).promptUsd : 0 });
92
+ reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: requestCost(model, u, at)?.promptUsd ?? 0 });
91
93
  });
92
94
  return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
93
95
  }
@@ -133,12 +135,15 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
133
135
  // still shape both arms; only the rest are billed.
134
136
  const counted = r.at >= since && !r.copy;
135
137
  const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
136
- const write = writeMult * r.inPerM;
138
+ // Each prompt, real or simulated, at its own tier's rates.
139
+ const rates = (ctx) => (r.card ? ratesAt(r.card, ctx) : UNPRICED);
137
140
  const cost = (ctx, prev) => {
141
+ const p = rates(ctx);
142
+ const write = writePerM(p, writeMult);
138
143
  if (cold)
139
144
  return write * ctx;
140
145
  const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
141
- return r.readPerM * (ctx - fresh) + write * fresh;
146
+ return p.cacheReadPerM * (ctx - fresh) + write * fresh;
142
147
  };
143
148
  if (counted)
144
149
  base += cost(r.prompt, prevActual);
@@ -151,8 +156,9 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
151
156
  }
152
157
  let simPrev = prevSim;
153
158
  if (ctx >= TRIGGER_SHARE * window) {
159
+ const p = rates(ctx);
154
160
  if (counted) {
155
- sim += r.readPerM * ctx + r.outPerM * SUMMARY_OUTPUT + write * reread;
161
+ sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writePerM(p, writeMult) * reread;
156
162
  extra++;
157
163
  }
158
164
  removed = r.prompt - AFTER_COMPACT - reread;
@@ -280,7 +286,7 @@ export function renderCompactWindows(r, current, limitLines) {
280
286
  const lines = [];
281
287
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
282
288
  // Counted and said exactly as `savings` says it, so the two screens agree.
283
- lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
289
+ lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, ${priceBasis()}`);
284
290
  lines.push("─".repeat(66));
285
291
  lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
286
292
  if (r.sessions === 0) {
package/dist/doctor.js CHANGED
@@ -13,6 +13,7 @@ import { homedir, platform } from "node:os";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { ledgerPath, readLedger } from "./ledger.js";
16
+ import { costCheck } from "./modmeasure.js";
16
17
  import { loadConfig } from "./config.js";
17
18
  import { codexRouting } from "./codexroute.js";
18
19
  import { CURSOR_HOOK_EVENTS } from "./install.js";
@@ -30,7 +31,8 @@ import { codexDir } from "./codexdir.js";
30
31
  import { periodSpend, readBudget } from "./budget.js";
31
32
  import { sessionPriceThresholds } from "./sessionprice.js";
32
33
  import { claudeSpend, codexSpend } from "./spend.js";
33
- import { hasKnownPrice, isUnbilledModel } from "./pricing.js";
34
+ import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
35
+ import { orgRatesLine } from "./orgrates.js";
34
36
  function claudeDesktopConfigPath() {
35
37
  switch (platform()) {
36
38
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -297,10 +299,15 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
297
299
  const label = "Model prices";
298
300
  const since = now - days * 86_400_000;
299
301
  const seen = new Map();
302
+ // A price in the table that changed on a day before some requests (pricing.ts's end dates).
303
+ const changed = new Map();
300
304
  const add = (items) => {
301
305
  for (const i of items)
302
- if (i.model)
306
+ if (i.model) {
303
307
  seen.set(i.model, (seen.get(i.model) ?? 0) + 1);
308
+ if (i.changedOn)
309
+ changed.set(i.model, [i.model, i.changedOn]);
310
+ }
304
311
  };
305
312
  try {
306
313
  add(claudeSpend(since, now));
@@ -313,6 +320,8 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
313
320
  if (seen.size === 0)
314
321
  return undefined;
315
322
  const unknown = [...seen].filter(([m]) => !hasKnownPrice(m) && !isUnbilledModel(m)).sort((a, b) => b[1] - a[1]);
323
+ if (!unknown.length && changed.size)
324
+ return { label, status: "warn", detail: `${priceChangedText([...changed.values()])}: those requests are estimated. npm install -g context-doctor@latest` };
316
325
  if (!unknown.length)
317
326
  return { label, status: "ok", detail: `every model used in the last ${days} days has a list price on file` };
318
327
  const named = unknown.slice(0, 5).map(([m, n]) => `${m} (${n.toLocaleString("en-US")} request${n === 1 ? "" : "s"})`).join(", ") + (unknown.length > 5 ? ` and ${unknown.length - 5} more` : "");
@@ -747,6 +756,15 @@ export async function runDoctor() {
747
756
  /* settings.json unreadable is already reported by the hook check */
748
757
  }
749
758
  }
759
+ // The plugin's mod: our session price against Claude Code's own cost, where it measured any.
760
+ try {
761
+ const c = costCheck();
762
+ if (c)
763
+ checks.push(c);
764
+ }
765
+ catch {
766
+ /* an unreadable ledger is no finding */
767
+ }
750
768
  // Skill
751
769
  const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
752
770
  checks.push(existsSync(skillPath)
@@ -820,6 +838,12 @@ export async function runDoctor() {
820
838
  if (c)
821
839
  checks.push(c);
822
840
  }
841
+ // Contracted rates in managed settings: every report prices Claude at them, as Claude Code does.
842
+ {
843
+ const org = orgRatesLine();
844
+ if (org)
845
+ checks.push({ label: "Prices", status: "ok", detail: org });
846
+ }
823
847
  checks.push(await checkMcpHandshake());
824
848
  // Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
825
849
  // dead proxy or a settings file pointing elsewhere is a real problem.
package/dist/extract.d.ts CHANGED
@@ -22,7 +22,7 @@ export declare const EXTRACTABLE: Set<string>;
22
22
  /** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
23
23
  export declare const TEXTUTIL_ARGS: string[];
24
24
  /** The document's text, or the reason it could not be read. */
25
- export declare function extractText(path: string): {
25
+ export declare function extractText(name: string): {
26
26
  text: string;
27
27
  } | {
28
28
  error: string;
@@ -42,7 +42,7 @@ export declare const monotonicNow: () => number;
42
42
  * `end` on the same clock: a deadline on the wall clock, converted per
43
43
  * document, let a clock jump between two documents cut the later ones short.
44
44
  */
45
- export declare function extractTextAsync(path: string, end?: number): Promise<{
45
+ export declare function extractTextAsync(name: string, end?: number): Promise<{
46
46
  text: string;
47
47
  } | {
48
48
  error: string;
package/dist/extract.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { execFile, spawnSync } from "node:child_process";
22
22
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
23
23
  import { tmpdir } from "node:os";
24
- import { dirname, extname, join } from "node:path";
24
+ import { dirname, extname, join, resolve } from "node:path";
25
25
  export const EXTRACTABLE = new Set([".pdf", ".docx", ".doc", ".rtf", ".odt", ".pptx"]);
26
26
  const RUN = { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024 };
27
27
  function run(cmd, args) {
@@ -72,8 +72,18 @@ function xmlToText(xml) {
72
72
  .replace(/\n{3,}/g, "\n\n")
73
73
  .trim();
74
74
  }
75
+ /**
76
+ * The document's path as a converter's argument: absolute, so a file named
77
+ * like an option is never read as one. `pack .` met
78
+ * `-eObjC.import("stdlib");$.system("…");var x={};x.pdf` as that very
79
+ * string, and osascript ran it as a second script statement.
80
+ */
81
+ function argPath(path) {
82
+ return resolve(path);
83
+ }
75
84
  /** The document's text, or the reason it could not be read. */
76
- export function extractText(path) {
85
+ export function extractText(name) {
86
+ const path = argPath(name);
77
87
  const ext = extname(path).toLowerCase();
78
88
  const mac = process.platform === "darwin";
79
89
  let text;
@@ -173,7 +183,8 @@ function runAsync(cmd, args, end) {
173
183
  * `end` on the same clock: a deadline on the wall clock, converted per
174
184
  * document, let a clock jump between two documents cut the later ones short.
175
185
  */
176
- export async function extractTextAsync(path, end = monotonicNow() + EXTRACT_BUDGET_MS) {
186
+ export async function extractTextAsync(name, end = monotonicNow() + EXTRACT_BUDGET_MS) {
187
+ const path = argPath(name);
177
188
  const ext = extname(path).toLowerCase();
178
189
  const mac = process.platform === "darwin";
179
190
  let text;
package/dist/fanout.js CHANGED
@@ -150,7 +150,7 @@ const ALIAS = {
150
150
  sonnet: { family: /sonnet/i, fallback: "claude-sonnet-5-5" },
151
151
  opus: { family: /opus/i, fallback: "claude-opus-5-5" },
152
152
  haiku: { family: /haiku/i, fallback: "claude-haiku-5-5" },
153
- fable: { family: /fable|mythos/i, fallback: "claude-fable-5-1" },
153
+ fable: { family: /fable|mythos/i, fallback: "claude-fable-5-2" },
154
154
  };
155
155
  function aliasModel(alias, costs) {
156
156
  const a = ALIAS[alias.toLowerCase()];
package/dist/fix.js CHANGED
@@ -37,7 +37,8 @@ import { existsSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
37
37
  import { homedir } from "node:os";
38
38
  import { dirname, join } from "node:path";
39
39
  import { forEachLine, listSessions, isClaudeSession } from "./session.js";
40
- import { pricingFor } from "./pricing.js";
40
+ import { rateCard, ratesAt } from "./pricing.js";
41
+ import { priceBasis } from "./orgrates.js";
41
42
  import { contextWindowFor, realModel } from "./tokens.js";
42
43
  import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl } from "./cachettl.js";
43
44
  import { compareVersions, describeInstalls } from "./modelswitch.js";
@@ -674,26 +675,29 @@ export function compactWindowSavingsSince(since, previousWindow, paths) {
674
675
  return;
675
676
  lastId = typeof msg.id === "string" ? msg.id : undefined;
676
677
  const model = realModel(msg.model);
677
- const price = pricingFor(model);
678
678
  const u = msg.usage;
679
+ // As the replays price (requestCost's rates): each prompt at its own tier, so the request a
680
+ // compaction avoided and the one it made can bill at different rates (Haiku 5.5 over 100k).
681
+ const card = rateCard(model, u, Number.isFinite(at) ? at : undefined);
679
682
  const total = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
680
683
  if (pendingPre !== undefined) {
681
684
  const oldTrigger = 0.97 * (previousWindow ?? contextWindowFor(model) ?? 200_000);
682
685
  // Only a compaction the old window would not have made yet.
683
- if (pendingPre < 0.9 * oldTrigger && price) {
686
+ if (pendingPre < 0.9 * oldTrigger && card) {
684
687
  episode = { pre: pendingPre, post: total, trigger: oldTrigger, open: true };
685
688
  compactions++;
686
- usd -= (pendingPre * price.cacheReadPerM + 20_000 * price.outputPerM) / 1e6;
689
+ const p = ratesAt(card, pendingPre);
690
+ usd -= (pendingPre * p.cacheReadPerM + 20_000 * p.outputPerM) / 1e6;
687
691
  }
688
692
  pendingPre = undefined;
689
693
  return;
690
694
  }
691
- if (episode?.open && price && episode.post !== undefined) {
695
+ if (episode?.open && card && episode.post !== undefined) {
692
696
  const cf = episode.pre + Math.max(0, total - episode.post);
693
697
  if (cf >= episode.trigger)
694
698
  episode.open = false;
695
699
  else
696
- usd += ((cf - total) * price.cacheReadPerM) / 1e6;
700
+ usd += (cf * ratesAt(card, cf).cacheReadPerM - total * ratesAt(card, total).cacheReadPerM) / 1e6;
697
701
  }
698
702
  });
699
703
  }
@@ -785,11 +789,11 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
785
789
  out.push("context-doctor fix: what to change, ranked by what it saves you");
786
790
  // Codex's input named beside Claude Code's when there is some; alone on a machine with only Codex.
787
791
  if (codexBilledUsd > 0 && billedUsd > 0)
788
- out.push(`Last ${days} days of your sessions: Claude Code ${money(billedUsd)} of input, Codex ${money(codexBilledUsd)}, at list prices`);
792
+ out.push(`Last ${days} days of your sessions: Claude Code ${money(billedUsd)} of input, Codex ${money(codexBilledUsd)}, ${priceBasis()}`);
789
793
  else if (codexBilledUsd > 0)
790
- out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input at list prices`);
794
+ out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input ${priceBasis()}`);
791
795
  else
792
- out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
796
+ out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input ${priceBasis()}`);
793
797
  out.push("─".repeat(66));
794
798
  const avail = fixes.filter((f) => f.state === "available");
795
799
  // No input billed: there is no history to measure, which is not "all applied".
@@ -845,7 +849,7 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
845
849
  if (avail.length) {
846
850
  out.push(`Apply: ${command("fix")} in a terminal asks about each one; or ${command(`fix --apply ${avail.map((f) => f.id).join(",")}`)}`);
847
851
  }
848
- out.push(`Undo everything fix applied: ${command("fix undo")}. Dollars at list price; on a subscription the same tokens come out of your usage limit.`);
852
+ out.push(`Undo everything fix applied: ${command("fix undo")}. Dollars ${priceBasis(false)}; on a subscription the same tokens come out of your usage limit.`);
849
853
  return out.join("\n");
850
854
  }
851
855
  /** What `fix` says on a machine with no Claude Code sessions in the period: savings' wording, and what to do. */
package/dist/hook.js CHANGED
@@ -22,7 +22,7 @@ import { parseSessionFile } from "./session.js";
22
22
  import { formatTokens, CHARS_PER_TOKEN, LARGEST_WINDOW } from "./tokens.js";
23
23
  import { ensureProxyUp } from "./autopilot.js";
24
24
  import { autoCompactsAt, detectColdResume, renderColdResume, renderColdResumeNotice, resumeVerdict, sessionWriteMultiplier, withResumeVerdict } from "./coldresume.js";
25
- import { formatUsd, pricingFor } from "./pricing.js";
25
+ import { formatUsd, rateCard, ratesAt } from "./pricing.js";
26
26
  import { checkBudget, loadConfig } from "./config.js";
27
27
  import { modelSwitchMessage } from "./modelswitch.js";
28
28
  import { compactFacts, compactInstructions } from "./precompact.js";
@@ -30,6 +30,7 @@ import { fanoutHook, subagentCosts } from "./fanout.js";
30
30
  import { claudeDir } from "./claudedir.js";
31
31
  import { budgetVerdict } from "./budget.js";
32
32
  import { renderSessionPrice, sessionPriceDue } from "./sessionprice.js";
33
+ import { tailUsage } from "./statusline.js";
33
34
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
34
35
  const DEFAULT_WARN_TOKENS = 80_000;
35
36
  /**
@@ -438,7 +439,10 @@ export async function runHook(app) {
438
439
  // from the transcript's tail: Claude Code's main thread has mostly
439
440
  // written the 1-hour cache, at 2x input, where a flat 1.25x quoted the
440
441
  // cold message 37% low (5-minute writes stay at 1.25x).
441
- const pricing = pricingFor(model);
442
+ // At the rates the next request bills, as the session price's line says them (rateCard): fast mode
443
+ // and US-only as the last reply recorded, the tier of a prompt this size, today's price.
444
+ const card = rateCard(model, cursor ? undefined : tailUsage(transcriptPath)?.billing);
445
+ const pricing = card && ratesAt(card, liveTokens);
442
446
  const cachedUsd = pricing ? (liveTokens * pricing.cacheReadPerM) / 1e6 : undefined;
443
447
  const coldUsd = pricing ? (liveTokens * pricing.inputPerM * sessionWriteMultiplier(transcriptPath)) / 1e6 : undefined;
444
448
  // Cursor's agent transcript records tool calls but not their output, and
@@ -31,6 +31,12 @@ export interface HttpGuard {
31
31
  /** Host names (lowercase, no port, no brackets) accepted in Host; "*" accepts any. */
32
32
  hosts: Set<string> | "*";
33
33
  origins: Set<string>;
34
+ /**
35
+ * Accept any IP address in Host too (the proxy): DNS rebinding needs a
36
+ * host name the attacker controls, and a client of a proxy published from
37
+ * a container may call it by its address.
38
+ */
39
+ ipLiterals?: boolean;
34
40
  }
35
41
  /** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
36
42
  export declare function hostName(hostHeader: string): string;
@@ -39,7 +45,9 @@ export declare function hostName(hostHeader: string): string;
39
45
  * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
40
46
  * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
41
47
  */
42
- export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv): HttpGuard;
48
+ export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv, opts?: {
49
+ ipLiterals?: boolean;
50
+ }): HttpGuard;
43
51
  /** Why this request may not reach /mcp, or undefined when it may. */
44
52
  export declare function refusal(guard: HttpGuard, headers: IncomingMessage["headers"]): string | undefined;
45
53
  /**
package/dist/httpguard.js CHANGED
@@ -20,6 +20,7 @@
20
20
  * then handed to the transport, so no request can make the server buffer
21
21
  * an unbounded body.
22
22
  */
23
+ import { isIP } from "node:net";
23
24
  export const HTTP_LIMITS = { bodyBytes: 10 * 1024 * 1024, bodyMs: 30_000 };
24
25
  /** Origins a browser may call from without being listed: ChatGPT's. */
25
26
  export const DEFAULT_ALLOWED_ORIGINS = ["https://chatgpt.com", "https://chat.openai.com"];
@@ -41,17 +42,17 @@ export function hostName(hostHeader) {
41
42
  * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
42
43
  * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
43
44
  */
44
- export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env) {
45
+ export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env, opts = {}) {
45
46
  const extra = [...list(allowedHosts), ...list(env.CONTEXT_DOCTOR_ALLOWED_HOSTS)];
46
47
  const origins = new Set([...DEFAULT_ALLOWED_ORIGINS, ...list(allowedOrigins), ...list(env.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map((o) => o.toLowerCase().replace(/\/+$/, "")));
47
48
  if (extra.includes("*"))
48
- return { hosts: "*", origins };
49
+ return { hosts: "*", origins, ipLiterals: opts.ipLiterals };
49
50
  const bind = hostName(bindHost);
50
51
  const hosts = new Set([...LOOPBACK_HOSTS, ...extra.map(hostName)]);
51
52
  // A specific bind address or name is one the server answers to; a wildcard is not a name.
52
53
  if (bind && bind !== "0.0.0.0" && bind !== "::")
53
54
  hosts.add(bind);
54
- return { hosts, origins };
55
+ return { hosts, origins, ipLiterals: opts.ipLiterals };
55
56
  }
56
57
  /** Why this request may not reach /mcp, or undefined when it may. */
57
58
  export function refusal(guard, headers) {
@@ -59,7 +60,7 @@ export function refusal(guard, headers) {
59
60
  const host = hostName(String(headers.host ?? ""));
60
61
  if (!host)
61
62
  return "the request has no Host header";
62
- if (!guard.hosts.has(host)) {
63
+ if (!guard.hosts.has(host) && !(guard.ipLiterals && isIP(host))) {
63
64
  return `Host "${host}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${host}`;
64
65
  }
65
66
  }
package/dist/lens.js CHANGED
@@ -17,7 +17,7 @@
17
17
  import { createHash } from "node:crypto";
18
18
  import { forEachLine, listSessions, replyCounter, isClaudeSession } from "./session.js";
19
19
  import { rowsOf, slimUsage } from "./scan.js";
20
- import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
20
+ import { openAIUsage, requestCost } from "./pricing.js";
21
21
  import { formatTokens, realModel } from "./tokens.js";
22
22
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
23
23
  class Acc {
@@ -25,11 +25,11 @@ class Acc {
25
25
  polls = new Map();
26
26
  pollContext = 0;
27
27
  sessions = 0;
28
- request(model, u, reasoning) {
28
+ request(model, u, reasoning, at) {
29
29
  const name = model ?? "unknown";
30
30
  const m = this.models.get(name) ?? { model: name, requests: 0, outputTokens: 0, reasoningTokens: 0, outputUsd: 0, totalUsd: 0 };
31
- const price = pricingFor(model);
32
- const cost = price ? usageCost(u, price) : undefined;
31
+ // As billed (requestCost): fast mode, US-only, a long prompt's tier, web searches.
32
+ const cost = requestCost(model, u, Number.isFinite(at) ? at : undefined);
33
33
  m.requests++;
34
34
  m.outputTokens += num(u.output_tokens);
35
35
  m.reasoningTokens += Math.min(num(u.output_tokens), reasoning);
@@ -61,7 +61,7 @@ const callKey = (name, input) => `${name}\u0000${typeof input === "string" ? inp
61
61
  /** A call's identity, as a hash: equal calls stay equal, and the cache keeps no command or input. */
62
62
  const callId = (key) => createHash("sha1").update(key).digest("base64");
63
63
  export const LENS_ROWS = {
64
- id: "lens.1",
64
+ id: "lens.2",
65
65
  init: () => null,
66
66
  line(line, row, out) {
67
67
  const prompt = line.includes('"type":"user"') && !line.includes('"tool_result"');
@@ -118,7 +118,7 @@ function scanClaude(path, acc, since, runRows) {
118
118
  const seen = sighting({ message: { id }, uuid: r.uuid });
119
119
  if (seen === "new" && inPeriod) {
120
120
  const u = r.u;
121
- const usd = acc.request(r.model, u, num(u.output_tokens_details?.thinking_tokens));
121
+ const usd = acc.request(r.model, u, num(u.output_tokens_details?.thinking_tokens), at);
122
122
  if (id)
123
123
  costOf.set(id, { usd, context: num(r.u.input_tokens) + num(r.u.cache_read_input_tokens) + num(r.u.cache_creation_input_tokens) });
124
124
  }
@@ -176,7 +176,7 @@ function scanCodex(path, acc, since) {
176
176
  return;
177
177
  }
178
178
  const u = openAIUsage(last);
179
- const usd = acc.request(model, u, num(last.reasoning_output_tokens));
179
+ const usd = acc.request(model, u, num(last.reasoning_output_tokens), at);
180
180
  pending.forEach((name, i) => acc.poll(name, i === 0 ? usd : 0, i === 0 ? num(last.input_tokens) : 0));
181
181
  pending = [];
182
182
  }
package/dist/limits.d.ts CHANGED
@@ -26,6 +26,7 @@
26
26
  * instead of printing a number.
27
27
  */
28
28
  import { type Extractor } from "./scan.js";
29
+ import { type ModelPricing, type Modifiers } from "./pricing.js";
29
30
  /** Claude Code's two windows, as its status line input names them. */
30
31
  export declare const CLAUDE_WINDOWS: readonly ["five_hour", "seven_day"];
31
32
  /** One reading of one window: how much of it was used at `ts`. */
@@ -116,14 +117,22 @@ export interface ClaudeRequest extends UsagePoint {
116
117
  sidechain?: boolean;
117
118
  /** The prompt's part of `usd` (input, cache writes, cache reads): what `savings` bills. */
118
119
  promptUsd: number;
120
+ /** The rates it billed at (requestCost: its tier, fast mode, US-only, its date); absent when unpriced. */
121
+ rates?: ModelPricing;
122
+ /** What fast mode, US-only, a long prompt's tier and web searches added to its list price, inside `usd`. */
123
+ modifiers: Modifiers;
124
+ /** Priced by family, or past the day its row's price changed: an estimate. */
125
+ estimated?: boolean;
126
+ /** Its row's price changed on this day, before the request. */
127
+ changedOn?: string;
119
128
  }
120
129
  /**
121
130
  * The requests of one Claude Code transcript between `since` and `until`,
122
- * each reply once, its output settled on its last row. `runRows` is shared
123
- * by every file of one report, so a fork's copy of its parent's replies is
124
- * counted once, in the file met first (replyCounter). Replies on
125
- * `<synthetic>` (isUnbilledModel) are left out. Throws when the transcript
126
- * cannot be read.
131
+ * each reply once, its output settled on its last row (billed at the
132
+ * reply's own rates, requestCost's). `runRows` is shared by every file of
133
+ * one report, so a fork's copy of its parent's replies is counted once, in
134
+ * the file met first (replyCounter). Replies on `<synthetic>`
135
+ * (isUnbilledModel) are left out. Throws when the transcript cannot be read.
127
136
  */
128
137
  export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
129
138
  /**