context-doctor 0.48.0 → 0.49.1

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 (77) hide show
  1. package/README.md +16 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +195 -0
  10. package/dist/ccost.js +400 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/install.js +1 -1
  28. package/dist/limits.d.ts +232 -14
  29. package/dist/limits.js +739 -33
  30. package/dist/mcp.js +19 -19
  31. package/dist/mcpdefer.d.ts +47 -0
  32. package/dist/mcpdefer.js +91 -0
  33. package/dist/mod/api.d.ts +72 -2
  34. package/dist/mod/api.js +5 -1
  35. package/dist/mod/logic.d.ts +289 -16
  36. package/dist/mod/logic.js +362 -38
  37. package/dist/mod/register.d.ts +37 -2
  38. package/dist/mod/register.js +290 -9
  39. package/dist/modmeasure.d.ts +6 -4
  40. package/dist/modmeasure.js +8 -4
  41. package/dist/opencode.d.ts +57 -0
  42. package/dist/opencode.js +234 -0
  43. package/dist/orgrates.d.ts +7 -0
  44. package/dist/orgrates.js +19 -0
  45. package/dist/overhead.d.ts +3 -0
  46. package/dist/overhead.js +5 -1
  47. package/dist/pricing.d.ts +59 -2
  48. package/dist/pricing.js +130 -10
  49. package/dist/proxy.d.ts +8 -1
  50. package/dist/proxy.js +13 -1
  51. package/dist/savings.d.ts +5 -1
  52. package/dist/savings.js +11 -5
  53. package/dist/scan.d.ts +3 -1
  54. package/dist/scan.js +8 -1
  55. package/dist/sessionprice.d.ts +5 -0
  56. package/dist/sessionprice.js +5 -1
  57. package/dist/sidecost.d.ts +65 -0
  58. package/dist/sidecost.js +117 -0
  59. package/dist/spend.d.ts +94 -3
  60. package/dist/spend.js +251 -23
  61. package/dist/spendplace.d.ts +40 -0
  62. package/dist/spendplace.js +93 -0
  63. package/dist/spendteam.d.ts +160 -0
  64. package/dist/spendteam.js +286 -0
  65. package/dist/starts.d.ts +106 -0
  66. package/dist/starts.js +406 -0
  67. package/dist/statusline.d.ts +2 -2
  68. package/dist/statusline.js +2 -2
  69. package/dist/subagentmodel.js +9 -7
  70. package/dist/subagentpay.d.ts +31 -2
  71. package/dist/subagentpay.js +232 -68
  72. package/dist/subagents.js +3 -3
  73. package/dist/tasks.js +3 -2
  74. package/dist/tooloutput.js +5 -5
  75. package/dist/usagepane.d.ts +77 -0
  76. package/dist/usagepane.js +287 -0
  77. package/package.json +1 -1
@@ -0,0 +1,234 @@
1
+ /**
2
+ * OpenCode's record of what it sent: each assistant message's `tokens`.
3
+ * Checked 2026-11-15 against ccusage's OpenCode loader (rust/adapters/opencode)
4
+ * and its docs. OpenCode keeps its data in `${XDG_DATA_HOME:-~/.local/share}/opencode`
5
+ * (`OPENCODE_DATA_DIR`, a comma list, instead), in one of three places:
6
+ *
7
+ * - `storage/message/<sessionID>/<messageID>.json` (before its SQLite store):
8
+ * `{id, sessionID, role, modelID, providerID, time: {created}, tokens:
9
+ * {input, output, reasoning, cache: {read, write}, total}, path: {cwd, root}}`.
10
+ * - `opencode.db`, table `message`: the same object in `data`.
11
+ * - `opencode.db`, table `session_message` (its v2 store): rows of `type`
12
+ * "assistant" or "compaction" (a compaction is billed apart; only a
13
+ * "completed" one), the model as `model: {id, providerID}`. A forked
14
+ * session starts with a copy of its parent's rows, new ids and the same
15
+ * `seq`; `session_v2.fork_boundary` says up to which (its "through" or
16
+ * "before" a parent message): those copies are not counted again.
17
+ *
18
+ * `tokens.input` is the uncached input; reasoning bills as output, and a
19
+ * `total` above the parts is output too (as ccusage counts it). A message
20
+ * on OpenCode's `claude-agent` provider ran inside Claude Code, whose own
21
+ * transcript `spend` already reads: not counted here. The same message in
22
+ * the JSON files and the database (a store that was migrated) is counted once.
23
+ */
24
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import { join } from "node:path";
27
+ import { queryRows, SqliteUnavailableError } from "./cursor.js";
28
+ /** OpenCode's data folders: $OPENCODE_DATA_DIR's (when `home` is this user's), else <XDG data>/opencode. */
29
+ export function opencodeDataDirs(home = homedir()) {
30
+ const own = home === homedir();
31
+ if (own && process.env.OPENCODE_DATA_DIR)
32
+ return process.env.OPENCODE_DATA_DIR.split(",").map((s) => s.trim()).filter(Boolean);
33
+ return [join(own && process.env.XDG_DATA_HOME ? process.env.XDG_DATA_HOME : join(home, ".local", "share"), "opencode")];
34
+ }
35
+ const num = (v) => {
36
+ const n = typeof v === "string" ? Number(v) : v;
37
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : 0;
38
+ };
39
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
40
+ const parse = (v) => {
41
+ if (typeof v !== "string")
42
+ return v;
43
+ try {
44
+ return JSON.parse(v);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ };
50
+ /** The counts of one message's `tokens`, as billed: reasoning, and a total above the parts, as output. */
51
+ export function opencodeTokens(t) {
52
+ if (!t || typeof t !== "object")
53
+ return undefined;
54
+ const input = num(t.input), read = num(t.cache?.read), write = num(t.cache?.write);
55
+ let output = num(t.output) + num(t.reasoning);
56
+ const missing = num(t.total) - (input + read + write + output);
57
+ if (missing > 0)
58
+ output += missing;
59
+ return input + read + write + output > 0 ? { input, read, write, output } : undefined;
60
+ }
61
+ /** A message object (a JSON file's, or a database row's `data`) as a call; undefined when it is not one. */
62
+ function fromMessage(m, id, session, created) {
63
+ if (!m || typeof m !== "object")
64
+ return undefined;
65
+ if (m.role !== undefined && m.role !== "assistant")
66
+ return undefined;
67
+ const tokens = opencodeTokens(m.tokens);
68
+ if (!tokens)
69
+ return undefined;
70
+ const model = text(m.model?.id) ?? text(m.model?.modelID) ?? text(m.modelID);
71
+ const provider = text(m.model?.providerID) ?? text(m.providerID);
72
+ const ts = num(m.time?.created) || num(created);
73
+ if (!ts)
74
+ return undefined;
75
+ const c = { id, ts, session, ...tokens };
76
+ if (model)
77
+ c.model = model;
78
+ if (provider)
79
+ c.provider = provider;
80
+ if (text(m.path?.cwd))
81
+ c.cwd = m.path.cwd;
82
+ if (text(m.path?.root) && m.path.root !== "/")
83
+ c.root = m.path.root;
84
+ return c;
85
+ }
86
+ /** The JSON files' messages written since `since`. */
87
+ function jsonCalls(dir, since, out, dirs) {
88
+ const sessionsRoot = join(dir, "storage", "session");
89
+ if (existsSync(sessionsRoot)) {
90
+ for (const project of safeList(sessionsRoot))
91
+ for (const f of safeList(join(sessionsRoot, project))) {
92
+ if (!f.endsWith(".json"))
93
+ continue;
94
+ try {
95
+ const s = JSON.parse(readFileSync(join(sessionsRoot, project, f), "utf8"));
96
+ if (text(s?.id) && text(s?.directory))
97
+ dirs.set(s.id, s.directory);
98
+ }
99
+ catch { /* not a session */ }
100
+ }
101
+ }
102
+ const root = join(dir, "storage", "message");
103
+ for (const session of safeList(root)) {
104
+ const folder = join(root, session);
105
+ for (const f of safeList(folder)) {
106
+ if (!f.endsWith(".json"))
107
+ continue;
108
+ const file = join(folder, f);
109
+ try {
110
+ if (statSync(file).mtimeMs < since)
111
+ continue;
112
+ const m = JSON.parse(readFileSync(file, "utf8"));
113
+ const id = text(m?.id) ?? f.slice(0, -5);
114
+ const c = fromMessage(m, id, text(m?.sessionID) ?? session);
115
+ if (c && !out.has(id))
116
+ out.set(id, c);
117
+ }
118
+ catch { /* unreadable: skipped */ }
119
+ }
120
+ }
121
+ }
122
+ function safeList(dir) {
123
+ try {
124
+ return readdirSync(dir);
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ }
130
+ /** A query that may fail on an older schema (no such table or column): undefined. SQLite missing altogether still throws. */
131
+ function tryRows(db, sql) {
132
+ try {
133
+ return queryRows(db, sql);
134
+ }
135
+ catch (e) {
136
+ if (e instanceof SqliteUnavailableError)
137
+ throw e;
138
+ return undefined;
139
+ }
140
+ }
141
+ const rows = (db, sql) => tryRows(db, sql) ?? [];
142
+ /**
143
+ * A WHERE on `time_created` for rows since `since`, a day early, when the
144
+ * column is there and holds milliseconds (its largest value); else none,
145
+ * and the message's own time decides.
146
+ */
147
+ function windowClause(db, table, since) {
148
+ const max = tryRows(db, `SELECT MAX(time_created) AS m FROM ${table}`)?.[0]?.m;
149
+ return typeof max === "number" && max > 1e11 ? ` AND time_created >= ${Math.floor(since) - 86_400_000}` : "";
150
+ }
151
+ /** For each forked v2 session, the last `seq` that is a copy of its parent's history. */
152
+ function forkCutoffs(db) {
153
+ const cut = new Map();
154
+ for (const f of rows(db, "SELECT id, fork_session_id AS parent, fork_boundary AS boundary FROM session_v2 WHERE fork_session_id IS NOT NULL AND fork_boundary IS NOT NULL")) {
155
+ const b = parse(f.boundary);
156
+ const parent = text(f.parent), mid = text(b?.messageID);
157
+ if (!text(f.id) || !parent || !mid || (b.type !== "through" && b.type !== "before"))
158
+ continue;
159
+ const esc = (s) => s.replace(/'/g, "''");
160
+ const at = rows(db, `SELECT seq FROM session_message WHERE session_id = '${esc(parent)}' AND id = '${esc(mid)}' LIMIT 1`)[0]?.seq;
161
+ if (typeof at !== "number")
162
+ continue;
163
+ if (b.type === "through")
164
+ cut.set(f.id, at);
165
+ else {
166
+ const before = rows(db, `SELECT MAX(seq) AS seq FROM session_message WHERE session_id = '${esc(parent)}' AND seq < ${at}`)[0]?.seq;
167
+ if (typeof before === "number")
168
+ cut.set(f.id, before);
169
+ }
170
+ }
171
+ return cut;
172
+ }
173
+ /** The database's messages since `since` (both tables), and each session's folder. */
174
+ function dbCalls(db, since, out, dirs) {
175
+ for (const table of ["session", "session_v2"])
176
+ for (const s of rows(db, `SELECT id, directory FROM ${table}`))
177
+ if (text(s.id) && text(s.directory))
178
+ dirs.set(s.id, s.directory);
179
+ // Only the fields read, projected in SQL: a row's data can be large.
180
+ const fields = "json_extract(data, '$.role') AS role, json_extract(data, '$.modelID') AS modelID, json_extract(data, '$.providerID') AS providerID, json_extract(data, '$.model') AS model, json_extract(data, '$.tokens') AS tokens, json_extract(data, '$.time.created') AS created, json_extract(data, '$.path') AS path";
181
+ for (const r of rows(db, `SELECT id, session_id, ${fields} FROM message WHERE 1${windowClause(db, "message", since)}`)) {
182
+ const c = fromMessage({ role: r.role, modelID: r.modelID, providerID: r.providerID, model: parse(r.model), tokens: parse(r.tokens), time: { created: r.created }, path: parse(r.path) }, String(r.id), String(r.session_id));
183
+ if (c && !out.has(c.id))
184
+ out.set(c.id, c);
185
+ }
186
+ const cut = forkCutoffs(db);
187
+ const win = windowClause(db, "session_message", since);
188
+ const v2sql = (seq) => `SELECT id, session_id, type, time_created${seq ? ", seq" : ""}, json_extract(data, '$.status') AS status, ${fields} FROM session_message WHERE type IN ('assistant', 'compaction')${win}`;
189
+ for (const r of tryRows(db, v2sql(true)) ?? rows(db, v2sql(false))) {
190
+ const session = String(r.session_id);
191
+ const c0 = cut.get(session);
192
+ if (c0 !== undefined && typeof r.seq === "number" && r.seq <= c0)
193
+ continue;
194
+ const compaction = r.type === "compaction";
195
+ if (compaction && r.status !== "completed")
196
+ continue;
197
+ const c = fromMessage({ modelID: r.modelID, providerID: r.providerID, model: parse(r.model), tokens: parse(r.tokens), time: { created: r.created }, path: parse(r.path) }, String(r.id), session, num(r.time_created));
198
+ if (!c || out.has(c.id))
199
+ continue;
200
+ if (compaction)
201
+ c.compaction = true;
202
+ out.set(c.id, c);
203
+ }
204
+ }
205
+ /**
206
+ * Every OpenCode model call between `since` and `until`, each once, less
207
+ * those on the claude-agent provider. `sqlite`: false when an opencode.db
208
+ * was there and this runtime cannot read SQLite.
209
+ */
210
+ export function opencodeCalls(since, until = Infinity, home = homedir()) {
211
+ const out = new Map();
212
+ const dirs = new Map();
213
+ let sqlite = true;
214
+ for (const dir of opencodeDataDirs(home)) {
215
+ if (!existsSync(dir))
216
+ continue;
217
+ const db = join(dir, "opencode.db");
218
+ if (existsSync(db)) {
219
+ try {
220
+ dbCalls(db, since, out, dirs);
221
+ }
222
+ catch (e) {
223
+ if (e instanceof SqliteUnavailableError)
224
+ sqlite = false;
225
+ }
226
+ }
227
+ jsonCalls(dir, since, out, dirs);
228
+ }
229
+ const calls = [...out.values()].filter((c) => c.ts >= since && c.ts <= until && c.provider !== "claude-agent");
230
+ for (const c of calls)
231
+ if (!c.cwd && dirs.has(c.session))
232
+ c.cwd = dirs.get(c.session);
233
+ return { calls: calls.sort((a, b) => a.ts - b.ts), sqlite };
234
+ }
@@ -56,6 +56,13 @@ export declare function readOrgRatesFrom(paths: string[]): OrgRates | undefined;
56
56
  * stat of the managed folder and its drop-in folder, once.
57
57
  */
58
58
  export declare function orgRates(env?: NodeJS.ProcessEnv): OrgRates | undefined;
59
+ /**
60
+ * `fn` with the organization's rates read once: every request a report
61
+ * prices asks for them (rateCard), and reading the two variables that move
62
+ * them is most of that (285 ms of a 1.5 s `subagents` on the author's
63
+ * machine, about 150k requests). Nothing in a report's run changes them.
64
+ */
65
+ export declare function withOrgRatesHeld<T>(fn: () => T): T;
59
66
  /** Forget what orgRates read (tests that rewrite a managed file in place). */
60
67
  export declare function resetOrgRates(): void;
61
68
  /** The row that prices `model`: its exact key first, then its Claude model's. */
package/dist/orgrates.js CHANGED
@@ -119,11 +119,30 @@ let cache;
119
119
  * stat of the managed folder and its drop-in folder, once.
120
120
  */
121
121
  export function orgRates(env = process.env) {
122
+ if (held && env === process.env)
123
+ return held.rates;
122
124
  const k = `${env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS ?? ""}\u0000${env.CLAUDE_CODE_MANAGED_SETTINGS_PATH ?? ""}`;
123
125
  if (cache?.env !== k)
124
126
  cache = { env: k, rates: readOrgRates(env) };
125
127
  return cache.rates;
126
128
  }
129
+ let held;
130
+ /**
131
+ * `fn` with the organization's rates read once: every request a report
132
+ * prices asks for them (rateCard), and reading the two variables that move
133
+ * them is most of that (285 ms of a 1.5 s `subagents` on the author's
134
+ * machine, about 150k requests). Nothing in a report's run changes them.
135
+ */
136
+ export function withOrgRatesHeld(fn) {
137
+ const was = held;
138
+ held = { rates: orgRates() };
139
+ try {
140
+ return fn();
141
+ }
142
+ finally {
143
+ held = was;
144
+ }
145
+ }
127
146
  /** Forget what orgRates read (tests that rewrite a managed file in place). */
128
147
  export function resetOrgRates() {
129
148
  cache = undefined;
@@ -15,6 +15,7 @@
15
15
  * priced per month from the user's own request and cold-start counts.
16
16
  */
17
17
  import { type McpServerConfig, type McpServerSize, type McpUsage } from "./mcpschema.js";
18
+ import { type StartsReport } from "./starts.js";
18
19
  export type Agent = "Claude Code" | "Codex" | "Cursor" | "Gemini CLI";
19
20
  export interface MemoryFile {
20
21
  agent: Agent;
@@ -53,6 +54,8 @@ export interface OverheadReport {
53
54
  files: MemoryFile[];
54
55
  findings: OverheadFinding[];
55
56
  mcp: McpSection;
57
+ /** Each session's and subagent's first request, per entrypoint and subagent type, priced across the period (starts.ts). */
58
+ starts?: StartsReport;
56
59
  }
57
60
  export interface McpSection {
58
61
  configs: McpServerConfig[];
package/dist/overhead.js CHANGED
@@ -28,6 +28,7 @@ import { claudeDir } from "./claudedir.js";
28
28
  import { mcpjsonServerApproved } from "./prune.js";
29
29
  import { REQUEST_ROWS } from "./coldresume.js";
30
30
  import { rowsOf } from "./scan.js";
31
+ import { measureStarts, renderStarts } from "./starts.js";
31
32
  const TTL_MS = 3_600_000;
32
33
  const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
33
34
  function readText(path) {
@@ -421,7 +422,8 @@ export function overheadReport(opts = {}) {
421
422
  // MCP usage comes from Claude Code transcripts only (the tool-name scheme is theirs).
422
423
  const claudePaths = opts.paths?.filter((p) => !isGeminiChat(p) && !/[\\/]\.codex[\\/]/.test(p));
423
424
  const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, claudePaths, tick("mcp")) };
424
- return { cwd, baseline, baselines, files, findings: overheadFindings(files, baselines), mcp };
425
+ const starts = measureStarts({ days: opts.days ?? 30, paths: claudePaths, cwd, home });
426
+ return { cwd, baseline, baselines, files, findings: overheadFindings(files, baselines), mcp, starts };
425
427
  }
426
428
  /**
427
429
  * Launch each configured server and size its tool definitions, then add the
@@ -486,6 +488,8 @@ export function renderOverhead(r, home = homedir()) {
486
488
  ? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} ${priceBasis().replace(/^at /, "")}).`
487
489
  : ""));
488
490
  }
491
+ if (r.starts)
492
+ out.push(...renderStarts(r.starts));
489
493
  out.push(...renderMcp(r));
490
494
  out.push("", "Memory files loaded in this directory", "─".repeat(56));
491
495
  if (r.files.length === 0)
package/dist/pricing.d.ts CHANGED
@@ -48,7 +48,8 @@ export declare const CACHE_WRITE_OPENAI_12H = 2.5;
48
48
  * keeps per request (the budget's, a session's price) were priced by the
49
49
  * table of the context-doctor that read them: under another table (an
50
50
  * upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
51
- * and read again, not carried to the period's end.
51
+ * and read again, not carried to the period's end. So are those priced by
52
+ * rules that changed what a request costs (BILLING_RULES).
52
53
  */
53
54
  export declare function priceTableKey(): string;
54
55
  /** A model's list row, as the page lists it today (no tier, mode or date applied). */
@@ -101,6 +102,8 @@ export interface RecordedUsage {
101
102
  web_fetch_requests?: unknown;
102
103
  code_execution_requests?: unknown;
103
104
  } | null;
105
+ /** The request's inner calls, each with its own tokens (and `model` where it differs): see extraIterations. */
106
+ iterations?: unknown;
104
107
  }
105
108
  export interface UsageCost {
106
109
  /** Uncached input. */
@@ -231,9 +234,63 @@ export declare function addModifiers(a: Modifiers, b: Readonly<Modifiers>): Modi
231
234
  export declare function priceChange(model?: string): {
232
235
  on: string;
233
236
  then?: ModelPricing;
237
+ routes?: string;
234
238
  } | undefined;
235
- /** "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. */
239
+ /** "ended" for a row whose price stops with no price published after it (a promotion), "changed" otherwise: what a report's short label says. */
240
+ export declare function priceEndWord(model?: string): "ended" | "changed";
241
+ /**
242
+ * Said for the models priced past their row's date: which price ended,
243
+ * when, and the price each request was priced at instead, an estimate
244
+ * either way (a scheduled price can be called off, a promotion extended).
245
+ */
236
246
  export declare function priceChangedText(models: Array<[model: string, on: string]>): string;
247
+ /**
248
+ * One iteration of a request's `usage.iterations` that the request's
249
+ * top-level usage does not count: billed on top of it, at its own model's
250
+ * rates (`model`: the iteration's, else the request's).
251
+ */
252
+ export interface ExtraIteration {
253
+ /** "advisor_message", "message" (an attempt a fallback replaced), "fallback_message", "compaction"... */
254
+ type: string;
255
+ model?: string;
256
+ usage: RecordedUsage;
257
+ }
258
+ /**
259
+ * The iterations of a request billed beyond its top-level usage. The API
260
+ * itemizes one request's inner calls in `usage.iterations`, each with its
261
+ * own tokens (and `model` where it differs), and its top-level usage counts
262
+ * only some of them:
263
+ * - the advisor tool: top-level usage is the sum of the executor's
264
+ * iterations ("message"); each `advisor_message` is billed on top, at the
265
+ * advisor model's rates (Anthropic, "Advisor tool", Usage and billing);
266
+ * - server-side fallbacks: top-level usage is the attempt that produced the
267
+ * message, the last; each earlier attempt (the declined model's, its own
268
+ * `model`) is billed on top (refusals and fallback: "usage.iterations is
269
+ * the per-attempt source of truth"). On the author's machine 34 replies
270
+ * carry one: claude-fable-5 declined after reading 294k tokens, and
271
+ * claude-opus-4-8 answered.
272
+ * Which is which is checked on the tokens, never assumed from the types:
273
+ * the iterations other than the advisor's must add up to the top-level
274
+ * prompt (input, cache reads and writes), or the last of them must equal
275
+ * it. A shape that is neither has only its advisor iterations added (never
276
+ * in the top-level, whatever the rest), so nothing is counted twice.
277
+ * Empty for the common request, one iteration that is the request itself.
278
+ */
279
+ export declare function extraIterations(usage: RecordedUsage | undefined | null): ExtraIteration[];
280
+ /**
281
+ * What a request cost with the iterations its top-level usage leaves out
282
+ * (extraIterations), each priced by requestCost at its own model and the
283
+ * request's time: the parts and modifiers added up, `rates` the request's
284
+ * own. `extra` is what those iterations added; absent when none. Undefined
285
+ * when the request's own model has no price.
286
+ */
287
+ export declare function billedCost(model: string | undefined, usage: RecordedUsage | undefined | null, at?: number): (RequestCost & {
288
+ extra?: {
289
+ usd: number;
290
+ iterations: number;
291
+ unpriced: number;
292
+ };
293
+ }) | undefined;
237
294
  /**
238
295
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
239
296
  * (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`
package/dist/pricing.js CHANGED
@@ -144,6 +144,11 @@ const PRICING = [
144
144
  // no cached-input price (the -pro ones) read at full input. Not modelled:
145
145
  // Fast mode (priority processing; Codex records only its thread's
146
146
  // `service_tier`, not each request's) and the 10% regional uplift.
147
+ // GPT-6.2 Astra and Sol, read 2026-11-18. Astra for Law's price is
148
+ // promotional "at least through December 31, 2026": no end date yet.
149
+ [openai("gpt-6.2-astra"), ...openaiLong(8, 40, 0.4)],
150
+ [openai("gpt-6.2-astra-law"), ...openaiLong(8, 40, 0.4)],
151
+ [openai("gpt-6.2-sol"), ...openaiLong(2, 10, 0.1)],
147
152
  [openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
148
153
  // GPT-6 Astra for Law's price is promotional "at least through December
149
154
  // 31, 2026" (read 2026-11-14): no end date to record yet.
@@ -233,16 +238,19 @@ const PRICING = [
233
238
  [/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
234
239
  ];
235
240
  let tableKey;
241
+ /** Bumped when what a request costs changes beyond the table: 2, the iterations its top-level usage leaves out (billedCost); 3, a compaction's context read from the cache however long the idle (compactcost.ts). */
242
+ const BILLING_RULES = 3;
236
243
  /**
237
244
  * A fingerprint of this table and its billing constants. Dollars a ledger
238
245
  * keeps per request (the budget's, a session's price) were priced by the
239
246
  * table of the context-doctor that read them: under another table (an
240
247
  * upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
241
- * and read again, not carried to the period's end.
248
+ * and read again, not carried to the period's end. So are those priced by
249
+ * rules that changed what a request costs (BILLING_RULES).
242
250
  */
243
251
  export function priceTableKey() {
244
252
  tableKey ??= createHash("sha1")
245
- .update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD]))
253
+ .update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD, BILLING_RULES]))
246
254
  .digest("hex")
247
255
  .slice(0, 12);
248
256
  return tableKey;
@@ -459,17 +467,129 @@ export function addModifiers(a, b) {
459
467
  */
460
468
  export function priceChange(model) {
461
469
  const b = row(model)?.[2];
462
- return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}) } : undefined;
470
+ return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}), ...(b.routes ? { routes: b.routes } : {}) } : undefined;
463
471
  }
464
- /** "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. */
472
+ /** "ended" for a row whose price stops with no price published after it (a promotion), "changed" otherwise: what a report's short label says. */
473
+ export function priceEndWord(model) {
474
+ const c = priceChange(model);
475
+ return c && !c.then && !c.routes ? "ended" : "changed";
476
+ }
477
+ /** "$4 in / $20 out per M": a price as the notes quote it. */
478
+ const perMText = (p) => `$${+p.inputPerM.toFixed(4)} in / $${+p.outputPerM.toFixed(4)} out per M`;
479
+ /**
480
+ * What a request priced past its row's date (rateCard's `changedOn`) was
481
+ * priced at, in words: the price the page said would follow, the model it
482
+ * is billed as from then, or, when the page named nothing (gpt-5.6-sol's
483
+ * promotion), the price that ended. Never silent about which.
484
+ */
485
+ function priceUsedText(model, on) {
486
+ const b = row(model)?.[2];
487
+ if (b?.routes && b.changes !== undefined && b.changes < on) {
488
+ // Billed as another model whose own price changed later: that model's change is the one in force.
489
+ return `${model} is billed as ${b.routes} from ${b.changes}; ${priceUsedText(b.routes, on)}`;
490
+ }
491
+ if (b?.routes)
492
+ return `${model}'s price ended on ${on}: from then it is billed as ${b.routes}, priced at ${b.routes}'s rates`;
493
+ if (b?.then)
494
+ return `${model}'s price changed on ${on}: priced at the price the page said would follow (${perMText(b.then)})`;
495
+ const was = pricingFor(model);
496
+ return `${model}'s price ended on ${on} and no later price is published: priced at the one that ended${was ? ` (${perMText(was)})` : ""}`;
497
+ }
498
+ /**
499
+ * Said for the models priced past their row's date: which price ended,
500
+ * when, and the price each request was priced at instead, an estimate
501
+ * either way (a scheduled price can be called off, a promotion extended).
502
+ */
465
503
  export function priceChangedText(models) {
466
- const byDay = new Map();
467
- for (const [m, on] of models) {
468
- const l = byDay.get(on) ?? byDay.set(on, []).get(on);
469
- if (!l.includes(m))
470
- l.push(m);
504
+ const seen = new Map();
505
+ for (const [m, on] of models)
506
+ if (!seen.has(`${m}\u0000${on}`))
507
+ seen.set(`${m}\u0000${on}`, priceUsedText(m, on));
508
+ const parts = [...seen.values()];
509
+ const open = [...seen.keys()].some((k) => { const [m] = k.split("\u0000"); const b = row(m)?.[2]; return !b?.then && !b?.routes; });
510
+ return `${parts.slice(0, 3).join("; ")}${parts.length > 3 ? `; and ${parts.length - 3} more` : ""}; an estimate${open ? "; a newer context-doctor may know the price that followed" : ""}`;
511
+ }
512
+ const promptOf = (u) => count(u?.input_tokens) + count(u?.cache_read_input_tokens) + count(u?.cache_creation_input_tokens);
513
+ /**
514
+ * The iterations of a request billed beyond its top-level usage. The API
515
+ * itemizes one request's inner calls in `usage.iterations`, each with its
516
+ * own tokens (and `model` where it differs), and its top-level usage counts
517
+ * only some of them:
518
+ * - the advisor tool: top-level usage is the sum of the executor's
519
+ * iterations ("message"); each `advisor_message` is billed on top, at the
520
+ * advisor model's rates (Anthropic, "Advisor tool", Usage and billing);
521
+ * - server-side fallbacks: top-level usage is the attempt that produced the
522
+ * message, the last; each earlier attempt (the declined model's, its own
523
+ * `model`) is billed on top (refusals and fallback: "usage.iterations is
524
+ * the per-attempt source of truth"). On the author's machine 34 replies
525
+ * carry one: claude-fable-5 declined after reading 294k tokens, and
526
+ * claude-opus-4-8 answered.
527
+ * Which is which is checked on the tokens, never assumed from the types:
528
+ * the iterations other than the advisor's must add up to the top-level
529
+ * prompt (input, cache reads and writes), or the last of them must equal
530
+ * it. A shape that is neither has only its advisor iterations added (never
531
+ * in the top-level, whatever the rest), so nothing is counted twice.
532
+ * Empty for the common request, one iteration that is the request itself.
533
+ */
534
+ export function extraIterations(usage) {
535
+ const its = usage?.iterations;
536
+ if (!Array.isArray(its) || its.length < 2)
537
+ return [];
538
+ const list = its.filter((t) => !!t && typeof t === "object" && !Array.isArray(t));
539
+ const extra = (t) => ({
540
+ type: typeof t.type === "string" ? t.type : "message",
541
+ ...(typeof t.model === "string" && t.model ? { model: t.model } : {}),
542
+ usage: {
543
+ input_tokens: count(t.input_tokens), cache_read_input_tokens: count(t.cache_read_input_tokens), cache_creation_input_tokens: count(t.cache_creation_input_tokens), output_tokens: count(t.output_tokens),
544
+ ...(t.cache_creation && typeof t.cache_creation === "object" ? { cache_creation: t.cache_creation } : {}),
545
+ // The request's own modifiers: where it ran (US-only) and its speed hold for every call in it.
546
+ ...(usage?.inference_geo === "us" ? { inference_geo: "us" } : {}),
547
+ ...(usage?.speed === "fast" ? { speed: "fast" } : {}),
548
+ },
549
+ });
550
+ const advisor = list.filter((t) => t.type === "advisor_message");
551
+ const rest = list.filter((t) => t.type !== "advisor_message");
552
+ const top = promptOf(usage);
553
+ if (rest.length <= 1 || rest.reduce((n, t) => n + promptOf(t), 0) === top)
554
+ return advisor.map(extra);
555
+ if (promptOf(rest[rest.length - 1]) === top)
556
+ return [...rest.slice(0, -1), ...advisor].map(extra);
557
+ return advisor.map(extra);
558
+ }
559
+ /**
560
+ * What a request cost with the iterations its top-level usage leaves out
561
+ * (extraIterations), each priced by requestCost at its own model and the
562
+ * request's time: the parts and modifiers added up, `rates` the request's
563
+ * own. `extra` is what those iterations added; absent when none. Undefined
564
+ * when the request's own model has no price.
565
+ */
566
+ export function billedCost(model, usage, at = Date.now()) {
567
+ const c = requestCost(model, usage, at);
568
+ const extras = extraIterations(usage);
569
+ if (!c || !extras.length)
570
+ return c;
571
+ const out = { ...c, modifiers: { ...c.modifiers }, extra: { usd: 0, iterations: 0, unpriced: 0 } };
572
+ for (const x of extras) {
573
+ const e = requestCost(x.model ?? model, x.usage, at);
574
+ if (!e) {
575
+ out.extra.unpriced++;
576
+ continue;
577
+ }
578
+ out.inputUsd += e.inputUsd;
579
+ out.writeUsd += e.writeUsd;
580
+ out.readUsd += e.readUsd;
581
+ out.outputUsd += e.outputUsd;
582
+ out.promptUsd += e.promptUsd;
583
+ out.totalUsd += e.totalUsd;
584
+ addModifiers(out.modifiers, e.modifiers);
585
+ out.extra.usd += e.totalUsd;
586
+ out.extra.iterations++;
587
+ if (e.estimated)
588
+ out.estimated = true;
589
+ if (e.changedOn && !out.changedOn)
590
+ out.changedOn = e.changedOn;
471
591
  }
472
- 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";
592
+ return out;
473
593
  }
474
594
  /**
475
595
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
package/dist/proxy.d.ts CHANGED
@@ -72,11 +72,18 @@ export interface ProxyOptions extends OptimizeOptions {
72
72
  * than taking the proxy (and every agent behind it) down.
73
73
  */
74
74
  maxBodyBytes?: number;
75
+ /**
76
+ * Where the plan's rate-limit readings from Anthropic's replies go (the
77
+ * `anthropic-ratelimit-unified-5h-*` / `-7d-*` headers a claude.ai sign-in
78
+ * gets): the limits ledger `context-doctor limits` reads, by default.
79
+ * CONTEXT_DOCTOR_NO_LIMITS_LOG=1 keeps none.
80
+ */
81
+ limitsLogPath?: string;
75
82
  }
76
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
77
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
78
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
79
- export declare const PROXY_VERSION = "0.48.0";
86
+ export declare const PROXY_VERSION = "0.49.1";
80
87
  /**
81
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
82
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.48.0";
28
+ export const PROXY_VERSION = "0.49.1";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
@@ -566,6 +566,18 @@ export function startProxy(opts = {}) {
566
566
  upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
567
567
  }
568
568
  }
569
+ // The plan's windows, as Claude Code reads them from the same headers:
570
+ // into the limits ledger, after the reply is on its way (recordLimits
571
+ // writes only a change, at most once a minute, and never throws).
572
+ if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && (upstream.headers.has("anthropic-ratelimit-unified-7d-utilization") || upstream.headers.has("anthropic-ratelimit-unified-5h-utilization"))) {
573
+ const got = upstream.headers;
574
+ // Loaded on first use: limits.ts reads transcripts and imports this module's version.
575
+ void import("./limits.js").then((m) => {
576
+ const rl = m.rateLimitsFromHeaders((n) => got.get(n));
577
+ if (rl)
578
+ m.recordLimits(rl, Date.now(), opts.limitsLogPath, "proxy");
579
+ }).catch(() => undefined);
580
+ }
569
581
  console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
570
582
  (stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
571
583
  res.statusCode = upstream.status;
package/dist/savings.d.ts CHANGED
@@ -90,7 +90,11 @@ export interface CompactWindowLine {
90
90
  nowPerWeek: number;
91
91
  isCurrent: boolean;
92
92
  }
93
- export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[]): string;
93
+ export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[], keepWarm?: {
94
+ hours: number;
95
+ netUsd: number;
96
+ pingUsd: number;
97
+ }): string;
94
98
  /**
95
99
  * `savings --share`: a few lines people can paste or screenshot. Totals only:
96
100
  * no project names, paths or session ids, so sharing it leaks nothing.