context-doctor 0.49.0 → 0.50.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 (50) hide show
  1. package/README.md +16 -14
  2. package/dist/appwindow.d.ts +69 -0
  3. package/dist/appwindow.js +147 -0
  4. package/dist/ccost.d.ts +35 -0
  5. package/dist/ccost.js +105 -5
  6. package/dist/claudedir.d.ts +15 -0
  7. package/dist/claudedir.js +19 -1
  8. package/dist/cli.js +59 -23
  9. package/dist/clihelp.d.ts +5 -1
  10. package/dist/clihelp.js +9 -1
  11. package/dist/codexstatusline.d.ts +176 -0
  12. package/dist/codexstatusline.js +353 -0
  13. package/dist/compactwindow.d.ts +14 -2
  14. package/dist/compactwindow.js +30 -5
  15. package/dist/credits.d.ts +130 -0
  16. package/dist/credits.js +265 -0
  17. package/dist/doctor.d.ts +6 -0
  18. package/dist/doctor.js +15 -1
  19. package/dist/fanout.d.ts +2 -0
  20. package/dist/fanout.js +12 -2
  21. package/dist/fix.d.ts +37 -1
  22. package/dist/fix.js +67 -9
  23. package/dist/install.js +1 -1
  24. package/dist/limits.d.ts +56 -2
  25. package/dist/limits.js +181 -14
  26. package/dist/mcp.d.ts +1 -0
  27. package/dist/mcp.js +106 -100
  28. package/dist/mod/api.d.ts +27 -1
  29. package/dist/mod/api.js +2 -1
  30. package/dist/mod/logic.d.ts +47 -16
  31. package/dist/mod/logic.js +68 -39
  32. package/dist/mod/register.d.ts +6 -0
  33. package/dist/mod/register.js +34 -6
  34. package/dist/modelids.js +2 -2
  35. package/dist/orgrates.d.ts +4 -2
  36. package/dist/orgrates.js +21 -3
  37. package/dist/overhead.js +2 -1
  38. package/dist/pricing.js +12 -0
  39. package/dist/progresssummaries.d.ts +20 -1
  40. package/dist/progresssummaries.js +33 -3
  41. package/dist/proxy.d.ts +1 -1
  42. package/dist/proxy.js +9 -4
  43. package/dist/savings.js +3 -1
  44. package/dist/sidecost.d.ts +65 -0
  45. package/dist/sidecost.js +117 -0
  46. package/dist/spend.d.ts +36 -1
  47. package/dist/spend.js +49 -5
  48. package/dist/starts.d.ts +27 -1
  49. package/dist/starts.js +81 -18
  50. package/package.json +1 -1
@@ -35,6 +35,18 @@
35
35
  * the notes. So both are priced: the notes as the low figure, the whole
36
36
  * context as the high one.
37
37
  *
38
+ * From 2.1.328 (its CHANGELOG: "written by the default small fast model
39
+ * from short notes ... using far fewer tokens", terminal sessions on the
40
+ * Anthropic API; 2.1.327 moved Bedrock, Vertex and Foundry to notes on the
41
+ * agent's own model) there is one way: the notes, on the small fast model.
42
+ * The 2.1.329 binary agrees: the writer is ANTHROPIC_SMALL_FAST_MODEL's
43
+ * default, the catalog's Haiku (`claude-haiku-5-5` on the Anthropic API),
44
+ * and the notes are cut to 2,000 - 500 tokens less the label lines, by its
45
+ * own count of about 3 characters a token, under a ~100-token system prompt
46
+ * and a ~250-token instruction: NOTES_TOKENS stays the ceiling. So a
47
+ * subagent whose transcript says `version` 2.1.328 or later is priced once,
48
+ * at Haiku 5.5's rates (low and high the same); an older one as before.
49
+ *
38
50
  * Estimated per subagent from what its transcript does record: the time of
39
51
  * each message (the ticks and whether the transcript changed), each reply's
40
52
  * prompt size and model (the context a fork would read, the rates). Each
@@ -57,6 +69,11 @@ export const PROGRESS_SUMMARIES_SINCE = "2.1.318";
57
69
  export const SUMMARY_TICK_MS = 30_000;
58
70
  /** A short summary's prompt: notes capped at 2,000 - 500 tokens, plus its system prompt and instruction. */
59
71
  export const NOTES_TOKENS = 1_850;
72
+ /** The first Claude Code that writes every summary from notes on the small fast model (its CHANGELOG). */
73
+ export const SMALL_NOTES_SINCE = "2.1.328";
74
+ /** The small fast model those run on: the 2.1.329 catalog's Haiku on the Anthropic API. */
75
+ export const SMALL_FAST_MODEL = "claude-haiku-5-5";
76
+ export const SMALL_FAST_MODEL_NAME = "Haiku 5.5";
60
77
  /** A fork summary's own instruction, after the agent's context. */
61
78
  export const FORK_PROMPT_TOKENS = 150;
62
79
  /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
@@ -147,7 +164,7 @@ export function eligibility(meta, entrypoint, opts = {}) {
147
164
  * it has 3+ messages and more than at the last summary. Only ticks in
148
165
  * [since, until] are counted.
149
166
  */
150
- export function simulateAgent(recs, since = -Infinity, until = Infinity) {
167
+ export function simulateAgent(recs, since = -Infinity, until = Infinity, smallNotes = false) {
151
168
  const msgs = recs.filter((r) => r.t === "m").map((r) => r.ts).sort((a, b) => a - b);
152
169
  const replies = recs.filter((r) => r.t === "r").sort((a, b) => a.ts - b.ts);
153
170
  const out = { calls: 0, notesUsd: 0, forkUsd: 0 };
@@ -177,6 +194,16 @@ export function simulateAgent(recs, since = -Infinity, until = Infinity) {
177
194
  const read = cur ? cur.p : 0;
178
195
  const fresh = (next ? Math.max(0, next.p - read) : 0) + FORK_PROMPT_TOKENS;
179
196
  const b = { ...(ref.speed ? { speed: ref.speed } : {}), ...(ref.geo ? { inference_geo: ref.geo } : {}) };
197
+ if (smallNotes) {
198
+ // 2.1.328+: the notes on the small fast model, the one way it sends them (the agent's fast mode is not the writer's).
199
+ const small = requestCost(SMALL_FAST_MODEL, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...(ref.geo ? { inference_geo: ref.geo } : {}) }, at);
200
+ if (!small)
201
+ continue;
202
+ out.calls++;
203
+ out.forkUsd += small.totalUsd;
204
+ out.notesUsd += small.totalUsd;
205
+ continue;
206
+ }
180
207
  const fork = requestCost(model, { input_tokens: fresh, cache_read_input_tokens: read, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
181
208
  const notes = requestCost(model, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
182
209
  if (!fork || !notes)
@@ -189,7 +216,7 @@ export function simulateAgent(recs, since = -Infinity, until = Infinity) {
189
216
  }
190
217
  /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
191
218
  export function estimateProgressSummaries(files, opts = {}) {
192
- const r = { agents: 0, summarized: 0, calls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
219
+ const r = { agents: 0, summarized: 0, calls: 0, smallCalls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
193
220
  const hosts = new Set();
194
221
  for (const file of files) {
195
222
  let recs;
@@ -217,11 +244,14 @@ export function estimateProgressSummaries(files, opts = {}) {
217
244
  if (first > until)
218
245
  why = "off";
219
246
  else {
220
- const s = simulateAgent(recs, opts.since, until);
247
+ const small = !!head?.version && compareVersions(head.version, SMALL_NOTES_SINCE) >= 0;
248
+ const s = simulateAgent(recs, opts.since, until, small);
221
249
  // One that ran under 30 s, or outside the window, sent none.
222
250
  if (s.calls)
223
251
  r.summarized++;
224
252
  r.calls += s.calls;
253
+ if (small)
254
+ r.smallCalls += s.calls;
225
255
  r.notesUsd += s.notesUsd;
226
256
  r.forkUsd += s.forkUsd;
227
257
  continue;
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.49.0";
86
+ export declare const PROXY_VERSION = "0.50.0";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,9 +25,11 @@ 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.49.0";
28
+ export const PROXY_VERSION = "0.50.0";
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
+ /** A reply carrying any of these has something for the limits ledger: a plan window, or the usage-credits state. */
32
+ const LIMIT_HEADERS = ["7d-utilization", "5h-utilization", "overage-status", "overage-in-use"].map((h) => `anthropic-ratelimit-unified-${h}`);
31
33
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
32
34
  /**
33
35
  * Remove a leading `/t/<token>` from a request path, or return undefined when
@@ -566,16 +568,19 @@ export function startProxy(opts = {}) {
566
568
  upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
567
569
  }
568
570
  }
569
- // The plan's windows, as Claude Code reads them from the same headers:
571
+ // The plan's windows, as Claude Code reads them from the same headers,
572
+ // and whether usage credits are paying past them (the overage headers):
570
573
  // 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"))) {
574
+ // and recordOverage write only a change, at most once a minute, and
575
+ // never throw).
576
+ if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && LIMIT_HEADERS.some((h) => upstream.headers.has(h))) {
573
577
  const got = upstream.headers;
574
578
  // Loaded on first use: limits.ts reads transcripts and imports this module's version.
575
579
  void import("./limits.js").then((m) => {
576
580
  const rl = m.rateLimitsFromHeaders((n) => got.get(n));
577
581
  if (rl)
578
582
  m.recordLimits(rl, Date.now(), opts.limitsLogPath, "proxy");
583
+ m.recordOverage(m.overageFromHeaders((n) => got.get(n)), Date.now(), opts.limitsLogPath, "proxy");
579
584
  }).catch(() => undefined);
580
585
  }
581
586
  console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
package/dist/savings.js CHANGED
@@ -369,7 +369,9 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
369
369
  // The same count, said the same way, as compact-window's.
370
370
  lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
371
371
  lines.push("─".repeat(60));
372
- lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
372
+ lines.push(`Input in your main conversations ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
373
+ // spend's total is larger: it adds output and the subagents. Said here, so the two do not look like they disagree.
374
+ lines.push(" Not in it: output and subagents (context-doctor spend has the whole bill).");
373
375
  lines.push("");
374
376
  lines.push(`1. Compact when you come back ${usd(Math.max(0, r.coldResumeNetUsd)).padStart(9)}${pct(Math.max(0, r.coldResumeNetUsd))}`);
375
377
  lines.push(` ${r.coldResumes} return${r.coldResumes === 1 ? "" : "s"} to a session over 150k tokens after the prompt cache`);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { type RecordedUsage } from "./pricing.js";
39
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
40
+ export declare const SUGGESTION_PROMPT_TOKENS = 506;
41
+ /** A suggestion's output (measured: 12-17). */
42
+ export declare const SUGGESTION_OUTPUT_TOKENS = 15;
43
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
44
+ export declare const SUGGESTION_MAX_LAST_TOKENS = 10000;
45
+ /**
46
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
47
+ * Code was billed for it; undefined when the row ends no main-thread turn or
48
+ * Claude Code would have skipped it.
49
+ */
50
+ export declare function suggestionUsage(e: any): RecordedUsage | undefined;
51
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
52
+ export declare function suggestionCost(e: any): {
53
+ usage: RecordedUsage;
54
+ cost: import("./pricing.js").RequestCost;
55
+ } | undefined;
56
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
57
+ export declare const UNSETTLED_FROM = "2.1.284";
58
+ export declare const UNSETTLED_UNTIL = "2.1.299";
59
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
60
+ export declare function unsettledVersion(v: unknown): boolean;
61
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
62
+ export declare const OUTPUT_PER_CHAR = 0.4;
63
+ export declare const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
64
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
65
+ export declare function contentOutputTokens(content: unknown): number;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { isUnbilledModel, requestCost } from "./pricing.js";
39
+ import { realModel } from "./tokens.js";
40
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
41
+ export const SUGGESTION_PROMPT_TOKENS = 506;
42
+ /** A suggestion's output (measured: 12-17). */
43
+ export const SUGGESTION_OUTPUT_TOKENS = 15;
44
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
45
+ export const SUGGESTION_MAX_LAST_TOKENS = 10_000;
46
+ const n = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
47
+ /**
48
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
49
+ * Code was billed for it; undefined when the row ends no main-thread turn or
50
+ * Claude Code would have skipped it.
51
+ */
52
+ export function suggestionUsage(e) {
53
+ const m = e?.message;
54
+ if (e?.type !== "assistant" || e.isSidechain === true || m?.stop_reason !== "end_turn" || !m.usage || isUnbilledModel(m.model))
55
+ return undefined;
56
+ if (typeof e.entrypoint === "string" && e.entrypoint.startsWith("sdk"))
57
+ return undefined;
58
+ const u = m.usage;
59
+ const input = n(u.input_tokens), read = n(u.cache_read_input_tokens), write = n(u.cache_creation_input_tokens), output = n(u.output_tokens);
60
+ if (input + output + write > SUGGESTION_MAX_LAST_TOKENS || input + read + write === 0)
61
+ return undefined;
62
+ // Its reply written at the lifetime the turn's own writes used (the main thread's: an hour, unless they were all 5-minute).
63
+ const fiveMin = n(u.cache_creation?.ephemeral_5m_input_tokens) > 0 && n(u.cache_creation?.ephemeral_1h_input_tokens) === 0;
64
+ return {
65
+ input_tokens: SUGGESTION_PROMPT_TOKENS, cache_read_input_tokens: input + read + write, cache_creation_input_tokens: output,
66
+ cache_creation: fiveMin ? { ephemeral_5m_input_tokens: output, ephemeral_1h_input_tokens: 0 } : { ephemeral_1h_input_tokens: output, ephemeral_5m_input_tokens: 0 },
67
+ output_tokens: SUGGESTION_OUTPUT_TOKENS,
68
+ ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}),
69
+ };
70
+ }
71
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
72
+ export function suggestionCost(e) {
73
+ const u = suggestionUsage(e);
74
+ if (!u)
75
+ return undefined;
76
+ const c = requestCost(realModel(e.message.model), u, Date.parse(String(e.timestamp ?? "")));
77
+ return c ? { usage: u, cost: c } : undefined;
78
+ }
79
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
80
+ export const UNSETTLED_FROM = "2.1.284";
81
+ export const UNSETTLED_UNTIL = "2.1.299";
82
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
83
+ export function unsettledVersion(v) {
84
+ if (typeof v !== "string")
85
+ return false;
86
+ const x = v.split(/[.-]/).map((n) => parseInt(n, 10) || 0);
87
+ const cmp = (b) => {
88
+ const y = b.split(".").map(Number);
89
+ for (let i = 0; i < 3; i++)
90
+ if ((x[i] ?? 0) !== y[i])
91
+ return (x[i] ?? 0) - y[i];
92
+ return 0;
93
+ };
94
+ return cmp(UNSETTLED_FROM) >= 0 && cmp(UNSETTLED_UNTIL) <= 0;
95
+ }
96
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
97
+ export const OUTPUT_PER_CHAR = 0.4;
98
+ export const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
99
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
100
+ export function contentOutputTokens(content) {
101
+ if (!Array.isArray(content))
102
+ return 0;
103
+ let chars = 0, sig = 0;
104
+ for (const c of content) {
105
+ if (!c || typeof c !== "object")
106
+ continue;
107
+ if (c.type === "text" && typeof c.text === "string")
108
+ chars += c.text.length;
109
+ else if (c.type === "tool_use")
110
+ chars += JSON.stringify(c.input ?? {}).length + String(c.name ?? "").length;
111
+ else if (c.type === "thinking") {
112
+ chars += typeof c.thinking === "string" ? c.thinking.length : 0;
113
+ sig += typeof c.signature === "string" ? c.signature.length : 0;
114
+ }
115
+ }
116
+ return Math.round(chars * OUTPUT_PER_CHAR + sig * OUTPUT_PER_SIGNATURE_CHAR);
117
+ }
package/dist/spend.d.ts CHANGED
@@ -32,7 +32,8 @@
32
32
  * Not in the total: Claude Code's subagent progress summaries, side requests
33
33
  * no transcript records (progresssummaries.ts). They are estimated per
34
34
  * background subagent and shown beside the total as a range, the two ways
35
- * Anthropic may serve them (short notes, or the whole context).
35
+ * Anthropic may serve them (short notes, or the whole context); a subagent
36
+ * on Claude Code 2.1.328+ once, as notes on the small fast model.
36
37
  *
37
38
  * `savings` bills a narrower slice of the same Claude Code requests: the main
38
39
  * conversation's input (cache writes and reads included, output not), in
@@ -42,6 +43,7 @@
42
43
  import { type ProgressOptions } from "./progresssummaries.js";
43
44
  import { type Modifiers } from "./pricing.js";
44
45
  import { type SessionGap } from "./ccost.js";
46
+ import type { ExtraUsage } from "./claudedir.js";
45
47
  /**
46
48
  * What spend's dollars are: each request as it was billed (its tier, fast mode,
47
49
  * US-only, web searches) at list rates, or at the organization's rates.
@@ -85,6 +87,8 @@ export interface SpendItem {
85
87
  key?: string;
86
88
  /** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
87
89
  compaction?: boolean;
90
+ /** Claude Code: output tokens estimated from the reply's content, inside `output` and `usd`, where its rows never settled it (sidecost.ts). */
91
+ unsettled?: number;
88
92
  /** Copilot CLI: the AI credits it used (one is $0.01), as Copilot recorded them; not in `usd`. */
89
93
  credits?: number;
90
94
  /** Copilot CLI: the premium requests it counted (its multiplier); not in `usd`. */
@@ -269,6 +273,12 @@ export interface SpendReport {
269
273
  requests: number;
270
274
  usd: number;
271
275
  };
276
+ /** Claude Code subagent replies whose rows never settled their output (2.1.284-2.1.299): the output estimated from their content, inside `usd`; absent when none. */
277
+ unsettled?: {
278
+ replies: number;
279
+ tokens: number;
280
+ usd: number;
281
+ };
272
282
  /** Claude Code: iterations billed beyond their request's top-level usage (the advisor's calls, attempts a fallback replaced), by type: inside `usd`; absent when none. */
273
283
  iterations?: Record<string, {
274
284
  calls: number;
@@ -287,12 +297,14 @@ export interface SpendReport {
287
297
  /**
288
298
  * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
289
299
  * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
300
+ * `smallCalls`: of `calls`, those on Claude Code 2.1.328+, notes on the small fast model in both figures (absent when none).
290
301
  * `set`: CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set there, since when unknown: not estimated.
291
302
  * Absent when no subagent got any.
292
303
  */
293
304
  progressSummaries?: {
294
305
  agents: number;
295
306
  calls: number;
307
+ smallCalls?: number;
296
308
  notesUsd: number;
297
309
  forkUsd: number;
298
310
  } | {
@@ -308,6 +320,20 @@ export interface SpendReport {
308
320
  first: number;
309
321
  last: number;
310
322
  }>;
323
+ /**
324
+ * Claude Code past the plan's limit, paid from usage credits (credits.ts):
325
+ * its dollars and requests (`fromHeaders` as the API's replies said,
326
+ * `inferred` from a window at 100%), `claudeUsd` all of Claude Code's,
327
+ * `since` when the first such limit ran out. Inside `usd`; absent when none.
328
+ */
329
+ credits?: {
330
+ usd: number;
331
+ requests: number;
332
+ claudeUsd: number;
333
+ fromHeaders: number;
334
+ inferred: number;
335
+ since: number;
336
+ };
311
337
  /** A tool that could not be read (Cursor without SQLite), and why. */
312
338
  skipped: Array<{
313
339
  tool: Tool;
@@ -333,6 +359,10 @@ export interface SpendOptions {
333
359
  progress?: false | (Pick<ProgressOptions, "forkGateOff" | "offSince"> & {
334
360
  set?: string;
335
361
  });
362
+ /** The limits ledger to read for requests past the plan's limit (tests); default ~/.claude's. */
363
+ limitsLogPath?: string;
364
+ /** `~/.claude.json`'s extra-usage word (tests); null: none. Default read from `home`. */
365
+ extraUsage?: ExtraUsage | null;
336
366
  }
337
367
  /**
338
368
  * The longest window: ten years, older than any history these tools keep.
@@ -365,6 +395,11 @@ export declare function spendReport(days?: number, opts?: SpendOptions): SpendRe
365
395
  export declare const usd: (n: number) => string;
366
396
  /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
367
397
  export declare function modifiersText(m: Modifiers): string;
398
+ /**
399
+ * Claude Code's dollars split at the plan's limit: what ran past it on usage
400
+ * credits, and the rest, inside the plan.
401
+ */
402
+ export declare function creditsSplitLines(c: NonNullable<SpendReport["credits"]>, now: number): string[];
368
403
  /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
369
404
  export declare function renderSpend(r: SpendReport, top?: number): string;
370
405
  /**
package/dist/spend.js CHANGED
@@ -32,7 +32,8 @@
32
32
  * Not in the total: Claude Code's subagent progress summaries, side requests
33
33
  * no transcript records (progresssummaries.ts). They are estimated per
34
34
  * background subagent and shown beside the total as a range, the two ways
35
- * Anthropic may serve them (short notes, or the whole context).
35
+ * Anthropic may serve them (short notes, or the whole context); a subagent
36
+ * on Claude Code 2.1.328+ once, as notes on the small fast model.
36
37
  *
37
38
  * `savings` bills a narrower slice of the same Claude Code requests: the main
38
39
  * conversation's input (cache writes and reads included, output not), in
@@ -44,7 +45,7 @@ import { codexDir } from "./codexdir.js";
44
45
  import { homedir } from "node:os";
45
46
  import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
46
47
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
47
- import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV } from "./progresssummaries.js";
48
+ import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV, SMALL_FAST_MODEL_NAME as SMALL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
48
49
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
49
50
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
50
51
  import { copilotCalls } from "./copilotusage.js";
@@ -54,6 +55,7 @@ import { clineCalls } from "./cline.js";
54
55
  import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, priceEndWord, requestCost } from "./pricing.js";
55
56
  import { managedSourcesLine, orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
56
57
  import { compareSessions, renderComparison } from "./ccost.js";
58
+ import { AT_LIST_PRICES, creditsInputs, creditsOf, nothingPast, whenText } from "./credits.js";
57
59
  /**
58
60
  * What spend's dollars are: each request as it was billed (its tier, fast mode,
59
61
  * US-only, web searches) at list rates, or at the organization's rates.
@@ -156,6 +158,8 @@ export function claudeSpend(since, until = Infinity, tops, onProgress, place = f
156
158
  label(item, { estimated: r.estimated, changedOn: r.changedOn, modifiers: extra.reduce((m, x) => minus(m, x.modifiers), { ...r.modifiers }) });
157
159
  if (r.compaction)
158
160
  item.compaction = true;
161
+ if (r.unsettled)
162
+ item.unsettled = r.unsettled;
159
163
  if (r.model)
160
164
  item.model = r.model;
161
165
  if (f.run)
@@ -633,12 +637,18 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
633
637
  const mods = { ...NO_MODIFIERS };
634
638
  const changed = new Map();
635
639
  const compactions = { requests: 0, usd: 0 };
640
+ const unsettled = { replies: 0, tokens: 0, usd: 0 };
636
641
  const iterations = {};
637
642
  for (const it of items) {
638
643
  if (it.compaction) {
639
644
  compactions.requests++;
640
645
  compactions.usd += it.usd;
641
646
  }
647
+ if (it.unsettled) {
648
+ unsettled.replies++;
649
+ unsettled.tokens += it.unsettled;
650
+ unsettled.usd += it.output > 0 ? (it.outputUsd * it.unsettled) / it.output : 0;
651
+ }
642
652
  if (it.iteration) {
643
653
  const x = (iterations[it.iteration] ??= { calls: 0, usd: 0, models: [] });
644
654
  x.calls++;
@@ -743,6 +753,7 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
743
753
  ...(anyModifier(mods) ? { modifiers: mods } : {}),
744
754
  ...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
745
755
  ...(compactions.requests ? { compactions } : {}),
756
+ ...(unsettled.replies ? { unsettled } : {}),
746
757
  ...(Object.keys(iterations).length ? { iterations } : {}),
747
758
  sessions: [...sessions.values()].sort(byUsd),
748
759
  skipped,
@@ -754,7 +765,7 @@ function claudeProgressSummaries(since, until, tops, o) {
754
765
  return { set: o.set };
755
766
  const files = claudeUsageFiles(since, tops).filter((f) => f.subagent && !f.run).map((f) => f.file);
756
767
  const e = estimateProgressSummaries(files, { since, until, forkGateOff: o?.forkGateOff, offSince: o?.offSince });
757
- return e.calls ? { agents: e.summarized, calls: e.calls, notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
768
+ return e.calls ? { agents: e.summarized, calls: e.calls, ...(e.smallCalls ? { smallCalls: e.smallCalls } : {}), notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
758
769
  }
759
770
  /**
760
771
  * The longest window: ten years, older than any history these tools keep.
@@ -843,6 +854,14 @@ export function spendReport(days = 30, opts = {}) {
843
854
  const gaps = compareSessions(tops, items, since, until);
844
855
  if (gaps.length)
845
856
  report.claudeCode = { ccUsd: gaps.reduce((n, g) => n + g.ccUsd, 0), ourUsd: gaps.reduce((n, g) => n + g.ourUsd, 0), sessions: gaps };
857
+ // Claude Code past the plan's limit: only when the limits ledger says a limit ran out or credits were in use.
858
+ const inp = creditsInputs(since, { now: until, logPath: opts.limitsLogPath, extraUsage: opts.extraUsage, home: opts.home });
859
+ if (!nothingPast(inp)) {
860
+ const claude = items.filter((it) => it.tool === "claude" && it.ts >= since && it.ts <= until);
861
+ const c = creditsOf(claude, inp);
862
+ if (c.requests)
863
+ report.credits = { usd: c.usd, requests: c.requests, claudeUsd: claude.reduce((n, it) => n + it.usd, 0), fromHeaders: c.fromHeaders, inferred: c.inferred, since: c.episodes[0].ranOutAt };
864
+ }
846
865
  const progress = opts.progress === false ? undefined : claudeProgressSummaries(since, until, opts.claudePaths, opts.progress);
847
866
  return progress ? { ...report, progressSummaries: progress } : report;
848
867
  }
@@ -867,6 +886,21 @@ export function modifiersText(m) {
867
886
  }
868
887
  /** AI credits or premium requests: whole above 100, else to two places. */
869
888
  const creditsText = (n) => (n >= 100 ? Math.round(n).toLocaleString("en-US") : String(Math.round(n * 100) / 100));
889
+ /**
890
+ * Claude Code's dollars split at the plan's limit: what ran past it on usage
891
+ * credits, and the rest, inside the plan.
892
+ */
893
+ export function creditsSplitLines(c, now) {
894
+ const n = `${c.requests.toLocaleString("en-US")} ${c.requests === 1 ? "request" : "requests"}`;
895
+ const how = !c.inferred ? "paid from usage credits" : !c.fromHeaders ? "likely paid from usage credits (inferred from 100% readings)" : `paid from usage credits (${c.inferred.toLocaleString("en-US")} inferred from 100% readings)`;
896
+ return [
897
+ "",
898
+ `Past your plan's limit since ${whenText(c.since, now).replace(/^(at|on) /, "")}: ${usd(c.usd)} of Claude Code's ${usd(c.claudeUsd)},`,
899
+ ` ${n}, ${how},`,
900
+ ` ${orgRates() ? "at your rates above (an estimate)" : AT_LIST_PRICES}. The other ${usd(Math.max(0, c.claudeUsd - c.usd))} was inside the plan.`,
901
+ " `context-doctor limits` says when each limit ran out.",
902
+ ];
903
+ }
870
904
  /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
871
905
  export function renderSpend(r, top = 8) {
872
906
  const lines = [];
@@ -893,6 +927,8 @@ export function renderSpend(r, top = 8) {
893
927
  }
894
928
  if (r.tools.length > 1)
895
929
  lines.push(`${"Total".padEnd(14)}${usd(r.usd).padStart(11)}`);
930
+ if (r.credits)
931
+ lines.push(...creditsSplitLines(r.credits, r.until));
896
932
  const list = (title, rows, more) => {
897
933
  lines.push("", title);
898
934
  for (const x of rows)
@@ -931,6 +967,8 @@ export function renderSpend(r, top = 8) {
931
967
  // A compaction's own request is in no row's usage: estimated from the context it read and the summary it wrote.
932
968
  if (r.compactions)
933
969
  lines.push(` Of it, ${r.compactions.requests.toLocaleString("en-US")} Claude Code ${r.compactions.requests === 1 ? "compaction's own request" : "compactions' own requests"} ${usd(r.compactions.usd)}, an estimate (no row records their usage)`);
970
+ if (r.unsettled)
971
+ lines.push(` Of it, ${usd(r.unsettled.usd)} output of ${r.unsettled.replies.toLocaleString("en-US")} subagent ${r.unsettled.replies === 1 ? "reply" : "replies"} whose rows Claude Code never settled (2.1.284-2.1.299), an estimate from ${r.unsettled.replies === 1 ? "its" : "their"} content`);
934
972
  // Calls inside a request that its usage totals leave out: the advisor's, an attempt a fallback replaced.
935
973
  for (const [type, x] of Object.entries(r.iterations ?? {}))
936
974
  lines.push(` Of it, ${x.calls.toLocaleString("en-US")} ${ITERATION_NAME[type]?.[x.calls === 1 ? 0 : 1] ?? `"${type}" iterations`} ${usd(x.usd)} (${x.models.slice(0, 2).join(", ")}), beyond their requests' usage totals`);
@@ -941,7 +979,13 @@ export function renderSpend(r, top = 8) {
941
979
  const ps = r.progressSummaries;
942
980
  if (ps && "calls" in ps) {
943
981
  lines.push(` Not in it: ~${ps.calls.toLocaleString("en-US")} subagent progress summaries (${ps.agents} background ${ps.agents === 1 ? "agent" : "agents"}), an estimate:`);
944
- lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
982
+ if (ps.smallCalls === ps.calls)
983
+ lines.push(` ${usd(ps.notesUsd)}, short notes on ${SMALL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+); in no transcript`);
984
+ else {
985
+ lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
986
+ if (ps.smallCalls)
987
+ lines.push(` (${ps.smallCalls.toLocaleString("en-US")} of them on Claude Code ${SMALL_NOTES_SINCE}+: notes on ${SMALL_NAME} either way)`);
988
+ }
945
989
  }
946
990
  else if (ps)
947
991
  lines.push(` Subagent progress summaries: not estimated, ${PROGRESS_SUMMARIES_ENV} is set in ${ps.set}`);
@@ -1017,7 +1061,7 @@ export function renderSpendShare(r) {
1017
1061
  lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
1018
1062
  const ps = r.progressSummaries;
1019
1063
  if (ps && "calls" in ps)
1020
- lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${usd(ps.notesUsd)}-${usd(ps.forkUsd)}, an estimate.`);
1064
+ lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${ps.smallCalls === ps.calls ? usd(ps.notesUsd) : `${usd(ps.notesUsd)}-${usd(ps.forkUsd)}`}, an estimate.`);
1021
1065
  const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
1022
1066
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
1023
1067
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
package/dist/starts.d.ts CHANGED
@@ -33,6 +33,14 @@ export declare const START_ROWS: Extractor<{
33
33
  u?: 1;
34
34
  r?: 1;
35
35
  }>;
36
+ /**
37
+ * The MCP servers a transcript called a tool of, by name only: which starts
38
+ * needed a server whose tools could have waited behind tool search (fix's
39
+ * desktop-tools-defer prices only the starts that never called it).
40
+ */
41
+ export declare const CALL_ROWS: Extractor<{
42
+ seen: string[];
43
+ }>;
36
44
  /** An entrypoint as people call it. */
37
45
  export declare function entrypointName(e: string | undefined): string;
38
46
  /** The MCP server a tool name belongs to (`mcp__<server>__<tool>`), or undefined for a built-in. */
@@ -46,6 +54,12 @@ export interface StartServer {
46
54
  tokens: number;
47
55
  /** In the user's own MCP config (~/.claude.json, the folder's .mcp.json): `alwaysLoad: false` there defers it. */
48
56
  configured?: "user" | "project" | ".mcp.json";
57
+ /** Of `starts`, the ones whose session or subagent called one of its tools. */
58
+ calledStarts: number;
59
+ /** Its definitions' part of the starts that never called it, each start at its own rates: what keeping it behind tool search would have saved there. */
60
+ unusedUsd: number;
61
+ /** The same in the starts that did call it: with `unusedUsd`, its definitions' whole part of its starts, counted alike. */
62
+ calledUsd: number;
49
63
  }
50
64
  export interface StartGroup {
51
65
  kind: "session" | "subagent";
@@ -102,5 +116,17 @@ export declare function deferrableConfigured(r: StartsReport): Array<{
102
116
  tokens: number;
103
117
  usd: number;
104
118
  }>;
119
+ /** Every server whose tools went whole into some start, across the groups: its share of each group's deferrable part, as `overhead` lists it. */
120
+ export declare function startServers(r: StartsReport): Array<StartServer & {
121
+ usd: number;
122
+ }>;
123
+ /**
124
+ * The Desktop app's own servers (Claude_Browser, ccd_session, visualize,
125
+ * terminal) whose tools went whole into some start, and no config file of the
126
+ * user's holds: fix's desktop-tools-defer, which context-doctor's mod applies.
127
+ */
128
+ export declare function deferrableApp(r: StartsReport): Array<StartServer & {
129
+ usd: number;
130
+ }>;
105
131
  /** The starts section of `overhead`. */
106
- export declare function renderStarts(r: StartsReport): string[];
132
+ export declare function renderStarts(r: StartsReport, applied?: ReadonlySet<string>): string[];