context-doctor 0.49.1 → 0.51.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 (57) hide show
  1. package/README.md +19 -17
  2. package/dist/apptools.d.ts +89 -0
  3. package/dist/apptools.js +203 -0
  4. package/dist/appwindow.d.ts +75 -0
  5. package/dist/appwindow.js +161 -0
  6. package/dist/budget.d.ts +20 -2
  7. package/dist/budget.js +43 -3
  8. package/dist/cachemisses.d.ts +70 -0
  9. package/dist/cachemisses.js +126 -0
  10. package/dist/ccost.js +8 -4
  11. package/dist/claudedir.d.ts +15 -0
  12. package/dist/claudedir.js +19 -1
  13. package/dist/cli.js +77 -29
  14. package/dist/clihelp.d.ts +5 -1
  15. package/dist/clihelp.js +9 -1
  16. package/dist/codexstatusline.d.ts +176 -0
  17. package/dist/codexstatusline.js +353 -0
  18. package/dist/compactwindow.d.ts +14 -2
  19. package/dist/compactwindow.js +30 -5
  20. package/dist/credits.d.ts +192 -0
  21. package/dist/credits.js +350 -0
  22. package/dist/doctor.d.ts +18 -0
  23. package/dist/doctor.js +62 -3
  24. package/dist/fanout.d.ts +2 -0
  25. package/dist/fanout.js +12 -2
  26. package/dist/fileparams.js +15 -3
  27. package/dist/fix.d.ts +48 -3
  28. package/dist/fix.js +112 -19
  29. package/dist/limits.d.ts +87 -2
  30. package/dist/limits.js +329 -29
  31. package/dist/mcp.d.ts +1 -0
  32. package/dist/mcp.js +106 -100
  33. package/dist/mod/api.d.ts +27 -1
  34. package/dist/mod/api.js +2 -1
  35. package/dist/mod/logic.d.ts +85 -1
  36. package/dist/mod/logic.js +118 -5
  37. package/dist/mod/register.d.ts +16 -2
  38. package/dist/mod/register.js +59 -5
  39. package/dist/modelids.d.ts +15 -0
  40. package/dist/modelids.js +35 -2
  41. package/dist/modmeasure.d.ts +7 -0
  42. package/dist/modmeasure.js +9 -0
  43. package/dist/orgrates.d.ts +4 -2
  44. package/dist/orgrates.js +21 -3
  45. package/dist/overhead.js +10 -3
  46. package/dist/pricing.js +7 -0
  47. package/dist/progresssummaries.d.ts +103 -1
  48. package/dist/progresssummaries.js +187 -11
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +9 -4
  51. package/dist/savings.js +3 -1
  52. package/dist/spend.d.ts +32 -3
  53. package/dist/spend.js +68 -6
  54. package/dist/starts.d.ts +34 -1
  55. package/dist/starts.js +88 -21
  56. package/dist/usagepane.js +1 -1
  57. package/package.json +1 -1
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The auto-compact window the Desktop app chose, and the one Anthropic's
3
+ * server sets: read (never written) so `compact-window` and `fix` do not
4
+ * offer a second window over one the person just answered.
5
+ *
6
+ * Read from the 2.1.329 binary (`strings`; ROADMAP "Research 2026-11-20"):
7
+ * - The Code tab is testing an offer of a lower auto-compact window. It
8
+ * passes the person's answer to Claude Code in its own (flag) settings,
9
+ * `autoCompactOfferAnswer: { model, choice: 'accept'|'keep'|'undo',
10
+ * tokens, at }` ("`tokens` is the window they chose or kept, and `at` is
11
+ * when they answered"), and Claude Code records it in `~/.claude.json`
12
+ * as `autoCompactOfferCodeTab[account][model] = { choice, tokens, at }`
13
+ * (the account lowercased, the model as its settings key). Claude Code
14
+ * reads that record back only to keep an older answer from replacing a
15
+ * newer one: nothing in the binary sets a window from it. Whether
16
+ * accepting changes the window Claude Code uses depends on what the app
17
+ * passes in its own settings, which are not on disk. So this says what
18
+ * the app offered and what the person chose, and assumes nothing about
19
+ * the window that followed.
20
+ * - `autoCompactRaisedForLoad` (also the app's own settings only): true
21
+ * "lets a conversation compact at twice what is still in each request
22
+ * after a summary (system prompt, tools, instruction files), where that is
23
+ * above its auto-compact threshold".
24
+ * - `autoCompactWindowsCache` in `~/.claude.json`: the per-model windows
25
+ * Anthropic's server sends with the account (`auto_compact_windows`, on
26
+ * the Anthropic API only). Claude Code uses one for its model when no
27
+ * environment variable or settings file sets a window (its "server"
28
+ * source), so this one is a window in effect.
29
+ */
30
+ import { readFileSync } from "node:fs";
31
+ import { claudeJsonPath, tilde } from "./claudedir.js";
32
+ import { settingsSources } from "./effective.js";
33
+ import { modelName } from "./subagentmodel.js";
34
+ const CHOICES = new Set(["accept", "keep", "undo"]);
35
+ function answerOf(v, model, where) {
36
+ if (!v || typeof v !== "object")
37
+ return undefined;
38
+ const m = typeof model === "string" && model ? model : typeof v.model === "string" ? v.model : undefined;
39
+ if (!m || !CHOICES.has(v.choice))
40
+ return undefined;
41
+ if (!(typeof v.tokens === "number" && Number.isInteger(v.tokens) && v.tokens > 0))
42
+ return undefined;
43
+ // A time a Date can hold (its range is ±8.64e15 ms): the lines print it as a day, which throws past it.
44
+ if (!(typeof v.at === "number" && Number.isFinite(v.at) && v.at > 0 && v.at <= 8.64e15))
45
+ return undefined;
46
+ return { model: m, choice: v.choice, tokens: v.tokens, at: v.at, where };
47
+ }
48
+ /** Read-only: ~/.claude.json and the settings files. Nothing found: empty lists. */
49
+ export function readAppWindows(opts = {}) {
50
+ const env = opts.env ?? process.env;
51
+ const out = { answers: [], served: [] };
52
+ const byModel = new Map();
53
+ const keep = (a) => {
54
+ if (!a)
55
+ return;
56
+ const k = modelKey(a.model);
57
+ const had = byModel.get(k);
58
+ if (!had || a.at > had.at)
59
+ byModel.set(k, a);
60
+ };
61
+ const path = claudeJsonPath(opts.home, env);
62
+ let j;
63
+ try {
64
+ j = JSON.parse(readFileSync(path, "utf8"));
65
+ }
66
+ catch {
67
+ j = undefined;
68
+ }
69
+ if (j && typeof j === "object") {
70
+ // Every account's answers on this machine: the Code tab's account need not be the terminal's login.
71
+ const tab = j.autoCompactOfferCodeTab;
72
+ if (tab && typeof tab === "object") {
73
+ for (const models of Object.values(tab)) {
74
+ if (!models || typeof models !== "object")
75
+ continue;
76
+ for (const [model, v] of Object.entries(models))
77
+ keep(answerOf(v, model, tilde(path)));
78
+ }
79
+ }
80
+ const cache = j.autoCompactWindowsCache;
81
+ if (cache && typeof cache === "object" && !Array.isArray(cache)) {
82
+ for (const [model, w] of Object.entries(cache))
83
+ if (typeof w === "number" && Number.isInteger(w) && w > 0)
84
+ out.served.push({ model, window: w });
85
+ }
86
+ }
87
+ for (const s of settingsSources({ home: opts.home, cwd: opts.cwd, env })) {
88
+ keep(answerOf(s.settings.autoCompactOfferAnswer, undefined, tilde(s.path)));
89
+ if (s.settings.autoCompactRaisedForLoad === true && !out.raisedForLoad)
90
+ out.raisedForLoad = tilde(s.path);
91
+ }
92
+ out.answers = [...byModel.values()].sort((a, b) => a.at - b.at);
93
+ out.served.sort((a, b) => a.model.localeCompare(b.model));
94
+ return out;
95
+ }
96
+ /** Anything to say: an answer, a served window, or the raised-for-load switch. */
97
+ export const hasAppWindows = (a) => !!a && (a.answers.length > 0 || a.served.length > 0 || !!a.raisedForLoad);
98
+ /** A model id as a settings key: lowercase, no "[1m]", no date suffix, no Bedrock or Vertex wrapping. */
99
+ export function modelKey(model) {
100
+ return model.trim().toLowerCase()
101
+ .replace(/\[1m\]$/, "")
102
+ .replace(/^(?:[a-z]{2,4}\.)?anthropic\./, "")
103
+ .replace(/-v\d+(?::\d+)?$/, "")
104
+ .replace(/@\d{8}$/, "")
105
+ .replace(/-\d{8}$/, "");
106
+ }
107
+ /** Whether a transcript's model is the one an answer names ("opus" and the like match their family). */
108
+ export function sameModel(answer, model) {
109
+ const a = modelKey(answer);
110
+ const m = modelKey(model);
111
+ if (/^(opus|sonnet|haiku|fable|mythos)$/.test(a))
112
+ return m.includes(a);
113
+ return a === m;
114
+ }
115
+ /** A window in tokens: "300k", "1M", "1.5M" (a 1M window read "1000k"). */
116
+ const k = (n) => (n >= 999_500 ? `${Number((n / 1_000_000).toFixed(1))}M` : `${Math.round(n / 1000)}k`);
117
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
118
+ const nameOf = (m) => modelName(m) === m ? m : modelName(m);
119
+ /**
120
+ * `doctor`'s one line: each answer on file, in plain words ("on 2026-11-18
121
+ * the Desktop app offered a 400k auto-compact window for Opus 5.5 and you
122
+ * accepted it"). Undefined when there is none.
123
+ */
124
+ export function appAnswerText(a) {
125
+ if (!a.answers.length)
126
+ return undefined;
127
+ const one = (x) => x.choice === "accept" ? `on ${day(x.at)} the Desktop app offered a ${k(x.tokens)} auto-compact window for ${nameOf(x.model)} and you accepted it`
128
+ : x.choice === "keep" ? `on ${day(x.at)} the Desktop app offered a lower auto-compact window for ${nameOf(x.model)} and you kept yours (${k(x.tokens)})`
129
+ : `on ${day(x.at)} you undid the lower auto-compact window the Desktop app had set for ${nameOf(x.model)} (on record: ${k(x.tokens)})`;
130
+ return a.answers.map(one).join("; ");
131
+ }
132
+ /**
133
+ * The lines `compact-window` and `fix` say about it (none when nothing is on
134
+ * file). `left`: the sessions the replay left as they ran, when known.
135
+ */
136
+ export function appWindowLines(a, left) {
137
+ const lines = [];
138
+ for (const x of a.answers) {
139
+ const who = `The Desktop app, ${nameOf(x.model)}`;
140
+ if (x.choice === "accept")
141
+ lines.push(`${who}: on ${day(x.at)} it offered a ${k(x.tokens)} auto-compact window and you accepted it.`);
142
+ else if (x.choice === "keep")
143
+ lines.push(`${who}: on ${day(x.at)} it offered a lower auto-compact window and you kept yours (${k(x.tokens)}).`);
144
+ else
145
+ lines.push(`${who}: on ${day(x.at)} you undid the lower auto-compact window it had set (on record: ${k(x.tokens)}).`);
146
+ }
147
+ if (a.answers.length) {
148
+ const models = a.answers.map((x) => nameOf(x.model)).join(", ");
149
+ lines.push(`Whether that answer changes the window Claude Code uses is not recorded on this computer`);
150
+ lines.push(`(the app passes it in its own settings), so nothing here assumes it does: sessions`);
151
+ const n = left === undefined ? "" : left === 0 ? " (none here)" : left === 1 ? " (1 here)" : ` (${left} here)`;
152
+ lines.push(`mostly on ${models}${n} are left as they ran, and only the rest are replayed.`);
153
+ }
154
+ if (a.served.length) {
155
+ lines.push(`Anthropic's server sets an auto-compact window on your account: ${a.served.map((s) => `${k(s.window)} for ${nameOf(s.model)}`).join(", ")}`);
156
+ lines.push(`(Claude Code uses it where no autoCompactWindow is set).`);
157
+ }
158
+ if (a.raisedForLoad)
159
+ lines.push(`autoCompactRaisedForLoad in ${a.raisedForLoad} does nothing: Claude Code reads it from the app's settings only.`);
160
+ return lines;
161
+ }
package/dist/budget.d.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  * replies count once. Measured on the author's history: docs/spend.md.
24
24
  */
25
25
  import { type Tool } from "./spend.js";
26
+ import { type CreditsAhead, type CreditsSummary } from "./credits.js";
26
27
  import { type CompactTrack } from "./compactcost.js";
27
28
  export type Period = "day" | "week";
28
29
  export interface Budget {
@@ -155,6 +156,19 @@ export declare function periodSpend(period: Period, now?: number, home?: string,
155
156
  export declare const THRESHOLDS: readonly [50, 80, 100];
156
157
  /** The highest threshold `usd` has reached of `budget` (0 below the first). */
157
158
  export declare function levelOf(usd: number, budget: number): number;
159
+ /**
160
+ * Claude Code's part of the period that ran past the plan's limit, paid from
161
+ * usage credits (credits.ts): already in the period's dollars, said apart.
162
+ * Reads the limits ledger, and the transcripts only when the ledger says a
163
+ * limit ran out or credits were in use. Undefined when nothing was; never
164
+ * throws (a damaged ledger must not cost the budget its line).
165
+ */
166
+ export declare function periodCredits(start: number, now?: number, home?: string): CreditsSummary | undefined;
167
+ /**
168
+ * "$4.20 of this was paid from usage credits, past your plan's limit (37
169
+ * requests, at API list prices, an estimate)." Inferred ones say so.
170
+ */
171
+ export declare function creditsLine(c: CreditsSummary | undefined): string | undefined;
158
172
  export interface BudgetVerdict {
159
173
  /** A line for the user, once per threshold per period. */
160
174
  message?: string;
@@ -170,7 +184,11 @@ export interface BudgetVerdict {
170
184
  export declare function budgetVerdict(now?: number, home?: string): BudgetVerdict | undefined;
171
185
  /** The status line's part: "$12/$50 today", or undefined with no budget set. */
172
186
  export declare function budgetStatus(now?: number, home?: string): string | undefined;
173
- /** `budget` with no argument, and after setting one: the budget and where the period stands. */
174
- export declare function renderBudgetStatus(b: Budget | undefined, s: PeriodSpend | undefined, hookInstalled: boolean): string;
187
+ /**
188
+ * `budget` with no argument, and after setting one: the budget and where the
189
+ * period stands. `ahead`: the weekly limit running out before its reset with
190
+ * extra usage on (credits.ts creditsAheadNow), said in one line.
191
+ */
192
+ export declare function renderBudgetStatus(b: Budget | undefined, s: PeriodSpend | undefined, hookInstalled: boolean, credits?: CreditsSummary, ahead?: CreditsAhead, now?: number): string;
175
193
  /** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
176
194
  export declare function promptHookInstalled(home?: string): boolean;
package/dist/budget.js CHANGED
@@ -34,6 +34,7 @@ import { subagentFiles } from "./subagents.js";
34
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
35
35
  import { billedCost, isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
36
36
  import { orgRates, orgRatesLine } from "./orgrates.js";
37
+ import { creditsAheadLine, creditsSince } from "./credits.js";
37
38
  import { anchorOf, rowsOf } from "./scan.js";
38
39
  import { realModel } from "./tokens.js";
39
40
  import { isCompactionRow, isTrack, newTrack, trackCompaction } from "./compactcost.js";
@@ -683,6 +684,33 @@ function resets(p) {
683
684
  function raised(b, spent) {
684
685
  return Math.ceil(Math.max(b.usd * 1.5, spent * 1.2) / 5) * 5;
685
686
  }
687
+ /**
688
+ * Claude Code's part of the period that ran past the plan's limit, paid from
689
+ * usage credits (credits.ts): already in the period's dollars, said apart.
690
+ * Reads the limits ledger, and the transcripts only when the ledger says a
691
+ * limit ran out or credits were in use. Undefined when nothing was; never
692
+ * throws (a damaged ledger must not cost the budget its line).
693
+ */
694
+ export function periodCredits(start, now = Date.now(), home) {
695
+ try {
696
+ return creditsSince(start, { now, ...(home ? { home } : {}) });
697
+ }
698
+ catch {
699
+ return undefined;
700
+ }
701
+ }
702
+ /**
703
+ * "$4.20 of this was paid from usage credits, past your plan's limit (37
704
+ * requests, at API list prices, an estimate)." Inferred ones say so.
705
+ */
706
+ export function creditsLine(c) {
707
+ if (!c || !c.requests)
708
+ return undefined;
709
+ const n = `${c.requests.toLocaleString("en-US")} request${c.requests === 1 ? "" : "s"}`;
710
+ const how = c.inferred && !c.fromHeaders ? "was most likely paid" : "was paid";
711
+ const why = !c.inferred ? "" : !c.fromHeaders ? "; inferred: they went through after a limit read 100%" : `; ${c.inferred.toLocaleString("en-US")} of them inferred from a limit at 100%`;
712
+ return `${money(c.usd)} of this ${how} from usage credits, past your plan's limit (${n}, at API list prices, an estimate${why}).`;
713
+ }
686
714
  /**
687
715
  * The hook's check: undefined with no budget set (one failed read: the hot
688
716
  * path stays a stat), otherwise the spend so far and what to say or do.
@@ -704,9 +732,12 @@ export function budgetVerdict(now = Date.now(), home = homedir()) {
704
732
  const unpriced = spend.unpricedNew && spend.unpriced ? unpricedText(spend.unpriced) : undefined;
705
733
  if (!spend.warn)
706
734
  return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
707
- const message = spend.warn >= 100
735
+ const base = spend.warn >= 100
708
736
  ? `${head}${byToolText(spend.byTool)}: over your ${amount(b.usd)}/${per(b.period)} budget (${pct}%). Raise it with context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}, or add --block to hold prompts over it.`
709
737
  : `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
738
+ // Once per threshold, so the ledger (and the transcripts only past a limit) is read only then.
739
+ const credits = creditsLine(periodCredits(spend.start, now, home));
740
+ const message = credits ? `${base} ${credits}` : base;
710
741
  return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
711
742
  }
712
743
  /** The status line's part: "$12/$50 today", or undefined with no budget set. */
@@ -718,14 +749,23 @@ export function budgetStatus(now = Date.now(), home = homedir()) {
718
749
  const short = (n) => (n >= 10 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
719
750
  return `${short(s.usd)}/${amount(b.usd)} ${span(b.period)}${s.usd >= b.usd ? " ⚠" : ""}`;
720
751
  }
721
- /** `budget` with no argument, and after setting one: the budget and where the period stands. */
722
- export function renderBudgetStatus(b, s, hookInstalled) {
752
+ /**
753
+ * `budget` with no argument, and after setting one: the budget and where the
754
+ * period stands. `ahead`: the weekly limit running out before its reset with
755
+ * extra usage on (credits.ts creditsAheadNow), said in one line.
756
+ */
757
+ export function renderBudgetStatus(b, s, hookInstalled, credits, ahead, now = Date.now()) {
723
758
  if (!b || !s)
724
759
  return "No spend budget set. Set one: context-doctor budget 50/day (or 200/week; --block to hold prompts over it).";
725
760
  const lines = [
726
761
  `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
727
762
  `${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)}`,
728
763
  ];
764
+ const paid = creditsLine(credits);
765
+ if (paid)
766
+ lines.push(paid);
767
+ if (ahead)
768
+ lines.push(creditsAheadLine(ahead, now));
729
769
  const org = orgRatesLine();
730
770
  if (org)
731
771
  lines.push(org);
@@ -127,6 +127,8 @@ export interface CacheMissReport {
127
127
  };
128
128
  /** Returns after the cache expired, replayed as billed, compacted and kept warm (coldreturns.ts). */
129
129
  coldReturns: ColdReturnReport;
130
+ /** Requests the cache never saw (#111948); only when there are any. */
131
+ uncached?: UncachedReport;
130
132
  }
131
133
  /** One Claude Code version's requests (the `version` every transcript line carries). */
132
134
  export interface VersionStats {
@@ -196,6 +198,74 @@ export declare function missesInTranscript(path: string, since?: number, add?: (
196
198
  }, miss?: CacheMiss) => void, onRequest?: (writeUsd: number, info: RequestInfo) => void,
197
199
  /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
198
200
  runRows?: Set<string>, onLate?: (late: LateRewrite) => void): void;
201
+ /**
202
+ * Requests the prompt cache never saw (anthropics/claude-code#111948): on
203
+ * Claude Code 2.1.329 a cache breakpoint can land on a `role:"system"`
204
+ * message inside `messages[]`, which writes nothing, so every turn bills the
205
+ * whole prompt as new input (~$80 a long session reported). They write and
206
+ * read (almost) nothing, so the misses above, re-writes, never count them.
207
+ *
208
+ * One counts when all of these hold:
209
+ * - a Claude model, and a transcript that used the cache elsewhere (a
210
+ * session that never wrote or read it had caching off, or a provider
211
+ * that does not cache: uncached by choice, not by fault);
212
+ * - it wrote nothing to the cache, sent over 20k tokens as new input, and
213
+ * that input was over half the prompt (a tiny context, or a cache read
214
+ * with a few new turns after it, is normal);
215
+ * - not a session's first request, nor the first after a compaction, a
216
+ * model switch or an hour's pause: a working cache would have had to
217
+ * write those anyway.
218
+ * Priced as what a working cache would have read instead: the input, up to
219
+ * the previous request's prompt, at the input rate minus the cache-read
220
+ * rate. What it would have written (the new turns) is left out, so the
221
+ * figure is a floor.
222
+ */
223
+ export interface UncachedRequest {
224
+ path: string;
225
+ at: string;
226
+ /** The Claude Code version on the transcript line, when recorded. */
227
+ version?: string;
228
+ model: string;
229
+ /** Billed as new input. */
230
+ inputTokens: number;
231
+ /** The whole prompt: input, cache read and cache write. */
232
+ promptTokens: number;
233
+ /** Above what a working cache would have charged; undefined when the model has no known price. */
234
+ extraUsd?: number;
235
+ }
236
+ export interface UncachedReport {
237
+ days: number;
238
+ requests: number;
239
+ sessions: number;
240
+ inputTokens: number;
241
+ extraUsd: number;
242
+ /** On models with no known price (not in extraUsd). */
243
+ unpriced: number;
244
+ /** Per Claude Code version, costliest first ("unknown" when the line carried none). */
245
+ byVersion: Array<{
246
+ version: string;
247
+ requests: number;
248
+ sessions: number;
249
+ inputTokens: number;
250
+ extraUsd: number;
251
+ models: string[];
252
+ from: string;
253
+ to: string;
254
+ }>;
255
+ largest: UncachedRequest[];
256
+ }
257
+ /** Requests in one transcript the cache never saw; `since` drops earlier ones. `seen`: uuids of rows already read (a fork's copied rows count once). */
258
+ export declare function uncachedInTranscript(path: string, since?: number, seen?: Set<string>): UncachedRequest[];
259
+ /** The requests the cache never saw in the last `days`, by Claude Code version. */
260
+ export declare function uncachedRequests(days?: number, paths?: string[], now?: number): UncachedReport;
261
+ /** The section in `cache-misses`, or nothing when there are none. */
262
+ export declare function renderUncached(u: UncachedReport | undefined): string[];
263
+ /** `doctor`'s line when the last `days` hold any; undefined otherwise. */
264
+ export declare function uncachedCheck(days?: number, paths?: string[]): {
265
+ label: string;
266
+ status: "warn";
267
+ detail: string;
268
+ } | undefined;
199
269
  export declare function cacheMisses(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void, missLog?: string): CacheMissReport;
200
270
  /** The late re-writes section, or nothing when there are none. */
201
271
  export declare function renderLate(l: CacheMissReport["late"]): string[];
@@ -262,6 +262,124 @@ runRows, onLate = () => { }) {
262
262
  blocks = 0;
263
263
  }
264
264
  }
265
+ const CLAUDE_MODEL = /claude|opus|sonnet|haiku|fable|mythos/i;
266
+ /** Requests in one transcript the cache never saw; `since` drops earlier ones. `seen`: uuids of rows already read (a fork's copied rows count once). */
267
+ export function uncachedInTranscript(path, since = 0, seen) {
268
+ const found = [];
269
+ let cached = false;
270
+ let prev;
271
+ let compacted = false;
272
+ for (const r of rowsOf(path, MISS_ROWS)) {
273
+ if (r.k === "c") {
274
+ compacted = true;
275
+ continue;
276
+ }
277
+ if (r.k !== "r")
278
+ continue;
279
+ const { model, at, u } = r;
280
+ const write = num(u.cache_creation_input_tokens);
281
+ const read = num(u.cache_read_input_tokens);
282
+ const input = num(u.input_tokens);
283
+ const total = write + read + input;
284
+ if (write > 0 || read > 0)
285
+ cached = true;
286
+ const copied = r.uuid !== undefined && seen !== undefined && seen.has(r.uuid);
287
+ if (r.uuid !== undefined)
288
+ seen?.add(r.uuid);
289
+ if (at >= since && !copied && write === 0 && input > MIN_CONTEXT && input > total / 2 && CLAUDE_MODEL.test(model) &&
290
+ prev && !compacted && prev.model === model && at - prev.at < HOUR) {
291
+ const rates = requestCost(model, u, at)?.rates;
292
+ found.push({
293
+ path,
294
+ at: new Date(at).toISOString(),
295
+ ...(r.version ? { version: r.version } : {}),
296
+ model,
297
+ inputTokens: input,
298
+ promptTokens: total,
299
+ extraUsd: rates ? (Math.min(input, prev.total) * Math.max(0, rates.inputPerM - rates.cacheReadPerM)) / 1e6 : undefined,
300
+ });
301
+ }
302
+ prev = { at, total, model };
303
+ compacted = false;
304
+ }
305
+ return cached ? found : [];
306
+ }
307
+ /** The requests the cache never saw in the last `days`, by Claude Code version. */
308
+ export function uncachedRequests(days = 30, paths, now = Date.now()) {
309
+ const since = now - days * 86_400_000;
310
+ const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
311
+ const seen = new Set();
312
+ const all = [];
313
+ for (const p of targets) {
314
+ try {
315
+ all.push(...uncachedInTranscript(p, since, seen));
316
+ }
317
+ catch {
318
+ /* one unreadable transcript must not sink the report */
319
+ }
320
+ }
321
+ const versions = new Map();
322
+ for (const q of all) {
323
+ const v = q.version ?? "unknown";
324
+ versions.set(v, [...(versions.get(v) ?? []), q]);
325
+ }
326
+ const usd = (qs) => qs.reduce((n, q) => n + (q.extraUsd ?? 0), 0);
327
+ return {
328
+ days,
329
+ requests: all.length,
330
+ sessions: new Set(all.map((q) => q.path)).size,
331
+ inputTokens: all.reduce((n, q) => n + q.inputTokens, 0),
332
+ extraUsd: usd(all),
333
+ unpriced: all.filter((q) => q.extraUsd === undefined).length,
334
+ byVersion: [...versions.entries()]
335
+ .map(([version, qs]) => ({
336
+ version,
337
+ requests: qs.length,
338
+ sessions: new Set(qs.map((q) => q.path)).size,
339
+ inputTokens: qs.reduce((n, q) => n + q.inputTokens, 0),
340
+ extraUsd: usd(qs),
341
+ models: [...new Set(qs.map((q) => q.model))],
342
+ from: qs.reduce((a, q) => (q.at < a ? q.at : a), qs[0].at),
343
+ to: qs.reduce((a, q) => (q.at > a ? q.at : a), qs[0].at),
344
+ }))
345
+ .sort((a, b) => b.extraUsd - a.extraUsd || b.requests - a.requests),
346
+ largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.inputTokens - a.inputTokens).slice(0, 10),
347
+ };
348
+ }
349
+ /** "Claude Code 2.1.329" or "Claude Code 2.1.329 and 2.1.330": the versions that sent them, most costly first. */
350
+ function versionsText(u) {
351
+ const named = u.byVersion.filter((v) => v.version !== "unknown").map((v) => v.version);
352
+ const list = named.length > 3 ? `${named.slice(0, 3).join(", ")} and ${named.length - 3} more` : named.join(", ").replace(/, ([^,]+)$/, " and $1");
353
+ return named.length ? `Claude Code ${list}` : "Claude Code";
354
+ }
355
+ /** The section in `cache-misses`, or nothing when there are none. */
356
+ export function renderUncached(u) {
357
+ if (!u || u.requests === 0)
358
+ return [];
359
+ const out = [
360
+ ...wrap(`Requests the cache never saw: ${versionsText(u)} sent ${u.requests} request${u.requests === 1 ? "" : "s"} that wrote nothing to the ` +
361
+ `prompt cache and billed ~${formatTokens(u.inputTokens)} tokens as new input. With the cache working they would have ` +
362
+ `cost ${money(u.extraUsd)} less${u.unpriced ? ` (${u.unpriced} on unpriced models not included)` : ""}. Claude Code 2.1.329 does this when hooks add text at session ` +
363
+ "start (anthropics/claude-code#111948): update Claude Code when a fixed version is out.", 82),
364
+ ` ${"version".padEnd(10)} ${"requests".padStart(8)} ${"sessions".padStart(8)} ${"new input".padStart(10)} ${"cost".padStart(9)}`,
365
+ ];
366
+ for (const v of u.byVersion.slice(0, 8)) {
367
+ out.push(` ${v.version.padEnd(10)} ${String(v.requests).padStart(8)} ${String(v.sessions).padStart(8)} ${`~${formatTokens(v.inputTokens)}`.padStart(10)} ${money(v.extraUsd).padStart(9)}`);
368
+ }
369
+ out.push(" Not counted: contexts under 20k, a session's first request, the first after a", " compaction, a model switch or an hour's pause, and sessions that never cached.");
370
+ return out;
371
+ }
372
+ /** `doctor`'s line when the last `days` hold any; undefined otherwise. */
373
+ export function uncachedCheck(days = 30, paths) {
374
+ const u = uncachedRequests(days, paths);
375
+ if (u.requests === 0)
376
+ return undefined;
377
+ return {
378
+ label: "Prompt cache",
379
+ status: "warn",
380
+ detail: `${versionsText(u)} sent ${u.requests} request${u.requests === 1 ? "" : "s"} in the last ${days} days that the prompt cache never saw: ${money(u.extraUsd)} more than cached (anthropics/claude-code#111948). Update Claude Code when a fixed version is out; context-doctor cache-misses has the detail`,
381
+ };
382
+ }
265
383
  /** Two rates differ beyond chance (two-proportion z-test, 99%). */
266
384
  function differs(a, b) {
267
385
  const p = (a.misses + b.misses) / (a.eligible + b.eligible);
@@ -397,6 +515,7 @@ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath(
397
515
  }
398
516
  }
399
517
  onProgress?.(targets.length, targets.length);
518
+ const uncached = uncachedRequests(days, targets);
400
519
  const finish = (s) => ({ ...s, rate: s.eligible ? s.misses / s.eligible : 0 });
401
520
  const byModel = [...models.entries()].map(([model, s]) => ({ model, ...finish(s) })).sort((a, b) => b.rate - a.rate);
402
521
  const bySize = SIZE_BUCKETS.filter(([b]) => sizes.has(b)).map(([bucket]) => ({ bucket, ...finish(sizes.get(bucket)) }));
@@ -419,6 +538,7 @@ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath(
419
538
  diagnosed: diagnosedMisses(since, missLog),
420
539
  late: lateReport(late),
421
540
  coldReturns: coldReturns(days, targets),
541
+ ...(uncached.requests ? { uncached } : {}),
422
542
  };
423
543
  }
424
544
  /**
@@ -662,6 +782,9 @@ export function renderCacheMisses(r, limitLines) {
662
782
  const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
663
783
  if (r.eligible === 0) {
664
784
  out.push(`No Claude Code requests in the last ${r.days} days that could have read a warm cache (consecutive, within the cache lifetime, over 20k tokens).`);
785
+ const never = renderUncached(r.uncached);
786
+ if (never.length)
787
+ out.push("", ...never);
665
788
  const late = renderLate(r.late);
666
789
  if (late.length)
667
790
  out.push("", ...late);
@@ -691,6 +814,9 @@ export function renderCacheMisses(r, limitLines) {
691
814
  out.push(" \"Nothing visible\": no model switch, compaction, context edit, API error or", " long tool run before it. The system prompt, tools or memory changing, or the", " provider evicting the cache early, would look like this from the client.");
692
815
  }
693
816
  }
817
+ const never = renderUncached(r.uncached);
818
+ if (never.length)
819
+ out.push("", ...never);
694
820
  const late = renderLate(r.late);
695
821
  if (late.length)
696
822
  out.push("", ...late);
package/dist/ccost.js CHANGED
@@ -343,11 +343,12 @@ export function gapText(sessions) {
343
343
  nUns ? `the output of ${nUns.toLocaleString("en-US")} subagent repl${nUns === 1 ? "y" : "ies"} whose rows never settled it (${usd(uns)})` : "",
344
344
  ].filter(Boolean);
345
345
  const compText = ests.length ? `${ests.length > 1 ? `${ests.slice(0, -1).join(", ")} and ${ests[ests.length - 1]}` : ests[0]}, which we estimate` : "";
346
- const sugText = nSug ? `; about ${nSug.toLocaleString("en-US")} of them Claude Code's prompt suggestions (the line it suggests after a turn, reading the conversation from the cache; counted by the ${SUGGESTION_PROMPT_TOKENS} input tokens each adds), about ${usd(sug)}` : "";
347
- const hung = stalled ? `; ${stalled.toLocaleString("en-US")} request${stalled === 1 ? "" : "s"} hung and ${stalled === 1 ? "was" : "were"} sent again (no reply, retried a minute or more later, most while the network was down): Claude Code bills those the API had begun, and no file says which` : "";
346
+ // Plain words first, the method in brackets: the owner read the old run-on sentence as noise.
347
+ const sugText = nSug ? `; about ${nSug.toLocaleString("en-US")} of them prompt suggestions (the next message Claude Code offers after a turn; counted by the ${SUGGESTION_PROMPT_TOKENS} input tokens each adds), about ${usd(sug)}` : "";
348
+ const hung = stalled ? `; ${stalled.toLocaleString("en-US")} request${stalled === 1 ? "" : "s"} hung and ${stalled === 1 ? "was" : "were"} sent again (most while the network was down): Claude Code bills one if the API had begun it, and no file says which` : "";
348
349
  if (Math.abs(p.tokensUsd) >= 0.005) {
349
350
  parts.push([p.tokensUsd, p.tokensUsd > 0
350
- ? `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: requests no row records the usage of${compText ? `, beyond our ${compText}` : ""}${sugText}${hung}`
351
+ ? `Claude Code counts ${more(p.tokensUsd)} for requests no transcript records${compText ? ` (beyond our ${compText})` : ""}${sugText}${hung}`
351
352
  : `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: ${compText ? `our ${compText}, are above what it counted` : "requests we count that it does not"}`]);
352
353
  }
353
354
  if (Math.abs(p.priceUsd) >= 0.005)
@@ -396,5 +397,8 @@ export function comparisonCheck(sessions, days) {
396
397
  const head = `${usd(ours)} against Claude Code's ${usd(cc)} (${pct(gap)}) on ${worth.length} session${worth.length === 1 ? "" : "s"} of the last ${days} days (its cost-state records); ${within} within ${CC_GAP_TARGET * 100}%`;
397
398
  if (Math.abs(gap) <= CC_GAP_TARGET)
398
399
  return { label, status: "ok", detail: head };
399
- return { label, status: "warn", detail: `${head}. The gap: ${gapText(worth).join("; ")}` };
400
+ // The biggest part only, and where the rest is: every part on one doctor line was a paragraph nobody could act on.
401
+ const parts = gapText(worth);
402
+ const rest = parts.length > 1 ? ` context-doctor spend lists the other ${parts.length - 1} part${parts.length === 2 ? "" : "s"}.` : "";
403
+ return { label, status: "warn", detail: `${head}. Most of the gap: ${parts[0] ?? "not taken apart"}.${rest}` };
400
404
  }
@@ -21,5 +21,20 @@ export declare function claudeJsonPath(home?: string, env?: NodeJS.ProcessEnv):
21
21
  * made `install` wire a Claude Code that is not there.
22
22
  */
23
23
  export declare function claudeCodePresent(home?: string, env?: NodeJS.ProcessEnv): boolean;
24
+ /**
25
+ * Whether the signed-in account pays past its plan's limit from usage
26
+ * credits ("extra usage"), as Claude Code last cached it in `~/.claude.json`:
27
+ * `oauthAccount.hasExtraUsageEnabled` (from the account's profile) and the
28
+ * top-level `cachedExtraUsageDisabledReason` (the last reply's
29
+ * `anthropic-ratelimit-unified-overage-disabled-reason`, null when it had
30
+ * none: read from the 2.1.311 binary). Undefined when the file has neither
31
+ * (an API key, Bedrock, Vertex, never signed in) or cannot be read.
32
+ */
33
+ export interface ExtraUsage {
34
+ enabled?: boolean;
35
+ /** Why the last reply said credits are off ("out_of_credits", "org_level_disabled"...); null: it said nothing against them. */
36
+ disabledReason?: string | null;
37
+ }
38
+ export declare function readExtraUsage(home?: string, env?: NodeJS.ProcessEnv): ExtraUsage | undefined;
24
39
  /** A path for messages: the home folder as `~`. */
25
40
  export declare function tilde(p: string): string;
package/dist/claudedir.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * (tests, a throwaway home) gets that home's folders: the variable describes
10
10
  * the real user's setup, not someone else's.
11
11
  */
12
- import { existsSync, readdirSync } from "node:fs";
12
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
13
13
  import { homedir } from "node:os";
14
14
  import { join, resolve } from "node:path";
15
15
  function configDirEnv(home, env) {
@@ -44,6 +44,24 @@ export function claudeCodePresent(home, env = process.env) {
44
44
  return false;
45
45
  }
46
46
  }
47
+ export function readExtraUsage(home, env = process.env) {
48
+ try {
49
+ const j = JSON.parse(readFileSync(claudeJsonPath(home, env), "utf8"));
50
+ if (!j || typeof j !== "object")
51
+ return undefined;
52
+ const out = {};
53
+ const en = j.oauthAccount?.hasExtraUsageEnabled;
54
+ if (typeof en === "boolean")
55
+ out.enabled = en;
56
+ const r = j.cachedExtraUsageDisabledReason;
57
+ if (r === null || (typeof r === "string" && /^[a-z_]{1,60}$/.test(r)))
58
+ out.disabledReason = r;
59
+ return Object.keys(out).length ? out : undefined;
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
47
65
  /** A path for messages: the home folder as `~`. */
48
66
  export function tilde(p) {
49
67
  const h = homedir();