context-doctor 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,12 +28,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
28
28
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
29
29
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
30
30
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
31
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.45.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.46.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
32
 
33
33
  ## What it does
34
34
 
35
35
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
36
- - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
36
+ - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, as billed at list rates ([spend and budget](./docs/spend.md)).
37
37
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
38
38
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
39
39
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
@@ -181,6 +181,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
181
181
 
182
182
  ## What's new
183
183
 
184
+ - **0.46 Fable 5.2, the Desktop app, and an audit**: Claude Fable 5.2 is priced (0.45 read it 1.5x too high); managed `modelPricing` is honoured; a check catches new models without a price. The plugin's new mod brings limit readings, Claude Code's own cost, a cache-expiry band with **Compact first**, and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app and VS Code ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
184
185
  - **0.45 Price what is billed, and a security pass**: fast mode, US-only inference, Haiku 5.5's long-prompt rates, web searches and OpenAI's and Gemini's long-prompt tiers are priced per request in every report, and prices that end on a known day say so. A security pass fixed a cloned repository approving its own MCP servers for `overhead --mcp`, a PDF's name running as a command through `pack` on macOS, the agents' API-key configs being packed, and the proxy answering a DNS-rebinding page ([details](./ROADMAP.md#shipped-in-0450-price-what-is-billed-and-a-security-pass-on-044)).
185
186
  - **0.44 Workflow agents on the bill, current prices, and an audit**: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542. `spend`, the budget, a session's price, `subagents` and `fix` now count them, and `spend` equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed `overhead --mcp` launching a cloned repository's unapproved MCP servers, `pack_context` returning the agents' sign-in files, and more ([details](./ROADMAP.md#shipped-in-0440-workflow-agents-on-the-bill-current-prices-and-an-audit-of-043)).
186
187
  - **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
@@ -207,6 +208,7 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
207
208
  - [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
208
209
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
209
210
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
211
+ - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, the cache band with Compact first, and `/context-doctor-fix`
210
212
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
211
213
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
212
214
  - [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
package/dist/budget.d.ts CHANGED
@@ -72,7 +72,9 @@ export declare function periodEnd(period: Period, now?: number): number;
72
72
  * lists those priced only by their model's family (an estimate), the same
73
73
  * way; `z` those priced past the day their model's price changed (index,
74
74
  * model, the day). `d` is requestCost's: each request's tier, fast mode,
75
- * US-only and web searches, and the output price in `r` is its own.
75
+ * US-only and web searches, and the output price in `r` is its own. `p`
76
+ * fingerprints the organization's rates `d` was priced at (orgrates.ts;
77
+ * absent at list prices): an entry priced under other rates is read again.
76
78
  */
77
79
  export interface FileEntry {
78
80
  t: Tool;
@@ -87,6 +89,7 @@ export interface FileEntry {
87
89
  x?: Array<[number, string]>;
88
90
  y?: Array<[number, string]>;
89
91
  z?: Array<[number, string, string]>;
92
+ p?: string;
90
93
  }
91
94
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
92
95
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
package/dist/budget.js CHANGED
@@ -33,6 +33,7 @@ import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS,
33
33
  import { subagentFiles } from "./subagents.js";
34
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
35
35
  import { isUnbilledModel, priceChangedText, requestCost } from "./pricing.js";
36
+ import { orgRates, orgRatesLine } from "./orgrates.js";
36
37
  import { anchorOf, rowsOf } from "./scan.js";
37
38
  import { realModel } from "./tokens.js";
38
39
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
@@ -450,7 +451,8 @@ function countLines(e, recent, text, since, own) {
450
451
  // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
451
452
  // A row of another session (`own`): a copy of its history, its spend, not this session's.
452
453
  const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
453
- if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
454
+ // A row with no time of its own fits no period, but it is in the session's price (since 0), at today's rates (requestCost).
455
+ if ((Number.isFinite(ts) ? ts >= since : since <= 0) && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
454
456
  index = e.k.length;
455
457
  if (!c)
456
458
  (e.x ??= []).push([index, model ?? "unknown"]);
@@ -493,8 +495,9 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
493
495
  catch {
494
496
  return undefined;
495
497
  }
496
- // An entry not in the shape this version writes (edited, or another version's) is read again.
497
- const e = wellFormed(prev) ? prev : undefined;
498
+ // An entry not in the shape this version writes (edited, or another version's), or priced at other rates, is read again.
499
+ const org = orgRates()?.key;
500
+ const e = wellFormed(prev) && prev.p === org ? prev : undefined;
498
501
  if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
499
502
  return { e, read: -1 };
500
503
  try {
@@ -514,11 +517,11 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
514
517
  finally {
515
518
  closeSync(fd);
516
519
  }
517
- const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
520
+ const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [], ...(org ? { p: org } : {}) };
518
521
  if (readAppended(blank, file, since, own))
519
522
  return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
520
523
  }
521
- return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
524
+ return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size), ...(org ? { p: org } : {}) }, read: s.size };
522
525
  }
523
526
  catch {
524
527
  return undefined;
@@ -686,6 +689,9 @@ export function renderBudgetStatus(b, s, hookInstalled) {
686
689
  `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
687
690
  `${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
688
691
  ];
692
+ const org = orgRatesLine();
693
+ if (org)
694
+ lines.push(org);
689
695
  if (s.unpriced)
690
696
  lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
691
697
  if (s.estimated) {
@@ -37,7 +37,7 @@
37
37
  import { listSessions, isClaudeSession } from "./session.js";
38
38
  import { rowsOf, slimUsage } from "./scan.js";
39
39
  import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
40
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
40
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, requestCost } from "./pricing.js";
41
41
  import { compareVersions } from "./modelswitch.js";
42
42
  import { diagnosedMisses, missLogPath } from "./missledger.js";
43
43
  /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
@@ -209,10 +209,12 @@ runRows, onLate = () => { }) {
209
209
  if (prev && at - prev.at >= prev.ttl)
210
210
  colds++;
211
211
  if (at >= since) {
212
- const price = pricingFor(model);
212
+ // As billed (requestCost): fast mode, US-only, the prompt's tier, its day's price, each TTL at its own rate.
213
+ const cost = requestCost(model, u, at);
214
+ const price = cost?.rates;
213
215
  const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
214
216
  const w5m = u.cache_creation ? Math.min(write - w1h, num(u.cache_creation?.ephemeral_5m_input_tokens)) : write - w1h;
215
- onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
217
+ onRequest(cost?.writeUsd ?? 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
216
218
  if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
217
219
  const isMiss = write > MISS_SHARE * prev.total;
218
220
  let miss;
package/dist/cacheplan.js CHANGED
@@ -42,8 +42,8 @@ const MAX_BREAKPOINTS = 4;
42
42
  * on some models and called cacheable prompts too small on others.
43
43
  */
44
44
  const CACHE_MINIMUMS = {
45
- "opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512,
46
- "mythos 5.0": 512, "mythos 5.1": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
45
+ "opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512, "fable 5.2": 512,
46
+ "mythos 5.0": 512, "mythos 5.1": 512, "mythos 5.2": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
47
47
  "opus 4.8": 1024, "sonnet 5.0": 1024, "sonnet 4.6": 1024, "sonnet 4.5": 1024,
48
48
  "opus 4.1": 1024, "opus 4.0": 1024, "sonnet 4.0": 1024,
49
49
  "opus 4.7": 2048, "haiku 3.5": 2048, "mythos preview": 2048,
package/dist/cachettl.js CHANGED
@@ -39,6 +39,7 @@ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
39
39
  import { REQUEST_ROWS } from "./coldresume.js";
40
40
  import { rowsOf } from "./scan.js";
41
41
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
42
+ import { priceBasis } from "./orgrates.js";
42
43
  import { realModel } from "./tokens.js";
43
44
  import { backupOnce } from "./install.js";
44
45
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
@@ -311,7 +312,7 @@ function block(label, r, set, kind) {
311
312
  export function renderCacheTtl(r, current, installs = [], command = (s) => `context-doctor ${s}`) {
312
313
  const out = [];
313
314
  out.push("Prompt cache lifetime: 5 minutes or 1 hour (Claude Code's own setting)");
314
- out.push(`Last ${r.days} days, at list prices; the same content is sent either way`);
315
+ out.push(`Last ${r.days} days, ${priceBasis()}; the same content is sent either way`);
315
316
  out.push("─".repeat(66));
316
317
  out.push(...block("Main conversation", r.main, current.main, "main"));
317
318
  out.push("");
package/dist/cli.js CHANGED
@@ -41,6 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
41
41
  import { renderDiff } from "./diff.js";
42
42
  import { renderExperiment, runExperiment } from "./experiment.js";
43
43
  import { runStatusLine } from "./statusline.js";
44
+ import { runMod } from "./modmeasure.js";
44
45
  import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
45
46
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
46
47
  import { runWatch } from "./watch.js";
@@ -156,8 +157,8 @@ Measure:
156
157
  One bill across every tool here: Claude Code (with
157
158
  its subagents), Codex, Gemini CLI and Cursor (an
158
159
  estimate: no cache split), by project, model and
159
- day, and what drives it, at list prices. --share:
160
- totals only, to paste
160
+ day, and what drives it, as billed at list rates.
161
+ --share: totals only, to paste
161
162
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
162
163
  still warm: priced, by model and context size, with
163
164
  the cause where the transcript shows one
@@ -261,6 +262,9 @@ Internal (Claude Code and MCP clients run these for you):
261
262
  context-doctor statusline Claude Code status bar line: live context size, cache
262
263
  share, cost (wired by \`install --statusline\`; reads
263
264
  the status JSON on stdin)
265
+ context-doctor mod measure|event Run by the plugin's mod after each turn (Desktop, VS Code,
266
+ terminal): limit readings, Claude Code's cost beside
267
+ ours, the band's figures (JSON on stdin and stdout)
264
268
  context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
265
269
  that launch \`npx -y context-doctor mcp\`
266
270
 
@@ -495,7 +499,7 @@ const COMMANDS = [
495
499
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
496
500
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
497
501
  "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "cache-ttl", "fix", "limits", "subagents", "tasks",
498
- "spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
502
+ "spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "mod", "help", "version",
499
503
  ];
500
504
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
501
505
  function strategyArg(v) {
@@ -796,6 +800,16 @@ async function main() {
796
800
  void runStatusLine();
797
801
  return;
798
802
  }
803
+ if (args.command === "mod") {
804
+ if (args.file !== "measure" && args.file !== "event")
805
+ usageError(`Usage: context-doctor mod measure|event (the plugin's mod runs these, with JSON on stdin); got "${args.file ?? ""}".`);
806
+ if (process.stdin.isTTY) {
807
+ console.log("context-doctor mod is run by the plugin's mod in Claude Code with JSON on stdin; there is nothing for it to do in a terminal.");
808
+ return;
809
+ }
810
+ await runMod(args.file);
811
+ return;
812
+ }
799
813
  if (args.command === "ab") {
800
814
  process.exitCode = await abCommand({
801
815
  levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
@@ -77,8 +77,12 @@ export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
77
77
  export declare function autoCompactsAt(model: string | undefined, home?: string, env?: NodeJS.ProcessEnv): number | undefined;
78
78
  /** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
79
79
  export declare const COLD_IDLE_MS: number;
80
+ /** Margin past a cache's lifetime before a return counts as cold. */
81
+ export declare const COLD_MARGIN_MS: number;
80
82
  /** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
81
83
  export declare const COLD_MIN_TOKENS = 150000;
84
+ /** What a compacted session restarts from: system prompt and tools plus the summary. */
85
+ export declare const AFTER_COMPACT_TOKENS = 45000;
82
86
  export interface ColdResume {
83
87
  idleMs: number;
84
88
  /** Context size at the last request, from the API's own usage. */
@@ -92,6 +96,8 @@ export interface ColdResume {
92
96
  perMessageUsd?: number;
93
97
  /** `resumeUsd` is Claude Code's own estimate (SessionStart), which honours a managed modelPricing. */
94
98
  claudeCodePriced?: boolean;
99
+ /** How long the cache the last reply left behind lives, as the gate counted it. */
100
+ ttlMs?: number;
95
101
  }
96
102
  /**
97
103
  * What Claude Code's SessionStart hook says on a resume (2.1.29x):
@@ -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, formatUsd, rateCard, ratesAt, 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
  /**
@@ -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()) {
@@ -273,8 +273,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
273
273
  tokens,
274
274
  model,
275
275
  lastReplyAt,
276
- resumeUsd: p ? (tokens * sessionWriteMultiplier(path) * p.inputPerM) / 1e6 : undefined,
276
+ resumeUsd: p ? (tokens * writePerM(p, sessionWriteMultiplier(path))) / 1e6 : undefined,
277
277
  perMessageUsd: p ? (tokens * p.cacheReadPerM) / 1e6 : undefined,
278
+ ttlMs: ttl ?? HOUR_MS,
278
279
  };
279
280
  }
280
281
  }
@@ -423,7 +424,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
423
424
  break;
424
425
  const card = c.card ?? b.card;
425
426
  const cold = c.at - prev.at > prev.ttl;
426
- const per = (p) => (cold ? mix * p.inputPerM : p.cacheReadPerM);
427
+ const per = (p) => (cold ? writePerM(p, mix) : p.cacheReadPerM);
427
428
  // A long-prompt tier: the smaller prompt may bill all of it at the lower rates.
428
429
  const after = Math.max(0, c.total - removed);
429
430
  const hi = ratesAt(card, c.total), lo = ratesAt(card, after);
@@ -433,7 +434,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
433
434
  }
434
435
  // The compaction re-reads the context just rebuilt and writes a summary;
435
436
  // the next request writes the fresh context.
436
- const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + mix * AFTER_COMPACT_TOKENS * ratesAt(b.card, AFTER_COMPACT_TOKENS).inputPerM;
437
+ const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + AFTER_COMPACT_TOKENS * writePerM(ratesAt(b.card, AFTER_COMPACT_TOKENS), mix);
437
438
  events.push({ at: b.at, tokens: b.total, messagesAfter: n, netUsd: (saved - cost) / 1e6 });
438
439
  }
439
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, rateCard, ratesAt, requestCost, 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";
@@ -138,7 +139,7 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
138
139
  const rates = (ctx) => (r.card ? ratesAt(r.card, ctx) : UNPRICED);
139
140
  const cost = (ctx, prev) => {
140
141
  const p = rates(ctx);
141
- const write = writeMult * p.inputPerM;
142
+ const write = writePerM(p, writeMult);
142
143
  if (cold)
143
144
  return write * ctx;
144
145
  const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
@@ -157,7 +158,7 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
157
158
  if (ctx >= TRIGGER_SHARE * window) {
158
159
  const p = rates(ctx);
159
160
  if (counted) {
160
- sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writeMult * p.inputPerM * reread;
161
+ sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writePerM(p, writeMult) * reread;
161
162
  extra++;
162
163
  }
163
164
  removed = r.prompt - AFTER_COMPACT - reread;
@@ -285,7 +286,7 @@ export function renderCompactWindows(r, current, limitLines) {
285
286
  const lines = [];
286
287
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
287
288
  // Counted and said exactly as `savings` says it, so the two screens agree.
288
- 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()}`);
289
290
  lines.push("─".repeat(66));
290
291
  lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
291
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";
@@ -31,6 +32,7 @@ import { periodSpend, readBudget } from "./budget.js";
31
32
  import { sessionPriceThresholds } from "./sessionprice.js";
32
33
  import { claudeSpend, codexSpend } from "./spend.js";
33
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");
@@ -754,6 +756,15 @@ export async function runDoctor() {
754
756
  /* settings.json unreadable is already reported by the hook check */
755
757
  }
756
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
+ }
757
768
  // Skill
758
769
  const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
759
770
  checks.push(existsSync(skillPath)
@@ -827,6 +838,12 @@ export async function runDoctor() {
827
838
  if (c)
828
839
  checks.push(c);
829
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
+ }
830
847
  checks.push(await checkMcpHandshake());
831
848
  // Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
832
849
  // dead proxy or a settings file pointing elsewhere is a real problem.
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