context-doctor 0.48.0 → 0.49.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 (74) hide show
  1. package/README.md +15 -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 +160 -0
  10. package/dist/ccost.js +304 -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/limits.d.ts +222 -14
  28. package/dist/limits.js +684 -33
  29. package/dist/mcp.js +1 -1
  30. package/dist/mcpdefer.d.ts +47 -0
  31. package/dist/mcpdefer.js +91 -0
  32. package/dist/mod/api.d.ts +72 -2
  33. package/dist/mod/api.js +5 -1
  34. package/dist/mod/logic.d.ts +281 -0
  35. package/dist/mod/logic.js +336 -0
  36. package/dist/mod/register.d.ts +35 -2
  37. package/dist/mod/register.js +283 -6
  38. package/dist/modmeasure.d.ts +6 -4
  39. package/dist/modmeasure.js +8 -4
  40. package/dist/opencode.d.ts +57 -0
  41. package/dist/opencode.js +234 -0
  42. package/dist/orgrates.d.ts +7 -0
  43. package/dist/orgrates.js +19 -0
  44. package/dist/overhead.d.ts +3 -0
  45. package/dist/overhead.js +5 -1
  46. package/dist/pricing.d.ts +59 -2
  47. package/dist/pricing.js +125 -10
  48. package/dist/proxy.d.ts +8 -1
  49. package/dist/proxy.js +13 -1
  50. package/dist/savings.d.ts +5 -1
  51. package/dist/savings.js +11 -5
  52. package/dist/scan.d.ts +3 -1
  53. package/dist/scan.js +8 -1
  54. package/dist/sessionprice.d.ts +5 -0
  55. package/dist/sessionprice.js +5 -1
  56. package/dist/spend.d.ts +86 -3
  57. package/dist/spend.js +240 -23
  58. package/dist/spendplace.d.ts +40 -0
  59. package/dist/spendplace.js +93 -0
  60. package/dist/spendteam.d.ts +160 -0
  61. package/dist/spendteam.js +286 -0
  62. package/dist/starts.d.ts +106 -0
  63. package/dist/starts.js +406 -0
  64. package/dist/statusline.d.ts +2 -2
  65. package/dist/statusline.js +2 -2
  66. package/dist/subagentmodel.js +9 -7
  67. package/dist/subagentpay.d.ts +31 -2
  68. package/dist/subagentpay.js +232 -68
  69. package/dist/subagents.js +3 -3
  70. package/dist/tasks.js +3 -2
  71. package/dist/tooloutput.js +5 -5
  72. package/dist/usagepane.d.ts +77 -0
  73. package/dist/usagepane.js +287 -0
  74. package/package.json +1 -1
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Cold returns: a main-conversation request after the prompt cache it left
3
+ * expired, which writes the whole context again. On the author's 30 days
4
+ * (2026-11-15) they were the largest cost no lever reached: 183 returns,
5
+ * $864 above cache-read price (26% of spend), $760 of it on contexts over
6
+ * 300k. `cache-misses` reports them here, each one replayed three ways:
7
+ *
8
+ * - as it went: the return as billed (requestCost, the same figure `spend`
9
+ * adds up);
10
+ * - compacted on return: the cold-resume replay's estimate (coldresume.ts),
11
+ * /compact right after the return, net of the compaction, counting what it
12
+ * saves on the requests after it until the next return;
13
+ * - kept warm: a cache read of the whole context every 55 minutes while away
14
+ * (4.5 minutes on a 5-minute cache), so the return reads the context
15
+ * instead of writing it. A ping is the context at the cache-read rate plus
16
+ * a short prompt and reply (Claude Code's mods API `$.model.fork`: the main
17
+ * thread's last request again, with one message after it, nothing kept in
18
+ * the transcript).
19
+ *
20
+ * By how long the person was away. The replay knows the gap; a keep-warm
21
+ * timer does not, so the policies below price keeping warm for up to N
22
+ * hours, counting every ping it would have sent: every pause past the first
23
+ * ping, the returns past the cap (cold anyway) and the sessions never
24
+ * returned to.
25
+ *
26
+ * Also #107157 (anthropics/claude-code): the Desktop app's transcript gains a
27
+ * copy of a segment a compaction had already removed (its rows, its
28
+ * `compact_boundary` included, with their original uuids), and a resume then
29
+ * rebuilds the conversation through it: one request went from 390k to 862k
30
+ * tokens and wrote 817k to the cache. Found here as a compaction boundary
31
+ * whose uuid the transcript already held, followed by a jump in context with
32
+ * no real compaction between.
33
+ */
34
+ import { type ModelPricing } from "./pricing.js";
35
+ /** A ping every this long keeps a 1-hour cache warm (5 minutes of margin)... */
36
+ export declare const PING_EVERY_1H_MS: number;
37
+ /** ...and a 5-minute one (30 seconds of margin). */
38
+ export declare const PING_EVERY_5M_MS = 270000;
39
+ /** A ping's own prompt (uncached) and reply, a short answer and a little thinking: an estimate. */
40
+ export declare const PING_PROMPT_TOKENS = 30;
41
+ export declare const PING_OUTPUT_TOKENS = 100;
42
+ /** The keep-warm caps priced, hours. */
43
+ export declare const KEEP_WARM_HOURS: number[];
44
+ export declare const GAP_BUCKETS: readonly ["<1h", "1-2h", "2-4h", "4-8h", ">8h"];
45
+ export type GapBucket = (typeof GAP_BUCKETS)[number];
46
+ export declare function gapBucket(ms: number): GapBucket;
47
+ export declare const pingEveryMs: (ttlMs: number) => number;
48
+ /** Pings a timer sends in a pause of `gapMs`: one each `every` until the person is back. */
49
+ export declare const pingsIn: (gapMs: number, every: number) => number;
50
+ /** One ping: the context read from the cache, the ping's prompt and its reply. */
51
+ export declare function pingUsd(contextTokens: number, p: ModelPricing): number;
52
+ export interface ColdReturn {
53
+ path: string;
54
+ at: number;
55
+ gapMs: number;
56
+ /** The lifetime of the cache the previous request left. */
57
+ ttlMs: number;
58
+ model: string;
59
+ /** The previous request's whole context: what a warm cache would have served. */
60
+ contextTokens: number;
61
+ tokens: number;
62
+ writeTokens: number;
63
+ /** As it went: the request as billed. */
64
+ billedUsd: number;
65
+ /** The part of it above cache-read price: the context written again. */
66
+ rewriteUsd: number;
67
+ /** Compacted on return: billed minus the compaction's net saving (undefined: not offered, under 150k or within 5 minutes of the lifetime). */
68
+ compactedUsd?: number;
69
+ /** Kept warm: billed without the re-write, plus the pings. A model switch misses anyway: no re-write avoided. */
70
+ keptWarmUsd: number;
71
+ pings: number;
72
+ /** One ping's price on this context. */
73
+ pingUsd: number;
74
+ sameModel: boolean;
75
+ }
76
+ /** A pause a keep-warm timer would have pinged through: every gap between main requests, and the time since the last. */
77
+ export interface Pause {
78
+ gapMs: number;
79
+ ttlMs: number;
80
+ pingUsd: number;
81
+ /** The rewrite a ping would have avoided: a cold return on the same model (0 otherwise). */
82
+ avoidableUsd: number;
83
+ }
84
+ /** #107157: a segment a compaction removed, put back. */
85
+ export interface ReAdded {
86
+ path: string;
87
+ /** When the copy of the old compaction boundary was written. */
88
+ copiedAt: number;
89
+ /** The request whose context jumped, and by how much. */
90
+ at: number;
91
+ fromTokens: number;
92
+ toTokens: number;
93
+ writeTokens: number;
94
+ /** The jump written to the cache, at the request's own write rate. */
95
+ extraWriteUsd: number;
96
+ /** What each later request pays to read it again. */
97
+ perRequestUsd: number;
98
+ }
99
+ export interface KeepWarmPolicy {
100
+ hours: number;
101
+ pings: number;
102
+ pingUsd: number;
103
+ /** Cold returns it would have kept warm, and the re-writes they would not have paid. */
104
+ keptWarm: number;
105
+ avoidedUsd: number;
106
+ netUsd: number;
107
+ }
108
+ export interface GapRow {
109
+ bucket: GapBucket | "all";
110
+ returns: number;
111
+ asItWentUsd: number;
112
+ rewriteUsd: number;
113
+ compactedUsd: number;
114
+ keptWarmUsd: number;
115
+ pings: number;
116
+ cheapest: "as it went" | "compacted" | "kept warm";
117
+ }
118
+ export interface ColdReturnReport {
119
+ days: number;
120
+ returns: number;
121
+ billedUsd: number;
122
+ rewriteUsd: number;
123
+ /** Of rewriteUsd, on previous contexts over 300k. */
124
+ over300kUsd: number;
125
+ byGap: GapRow[];
126
+ total: GapRow;
127
+ policies: KeepWarmPolicy[];
128
+ /** The cap that nets the most, when any nets more than nothing. */
129
+ best?: KeepWarmPolicy;
130
+ readded: ReAdded[];
131
+ /** For `--json`: the costliest returns. */
132
+ largest: ColdReturn[];
133
+ }
134
+ /** One transcript's cold returns, pauses and re-added segments; `now` ends the last pause. */
135
+ export declare function coldReturnsInTranscript(path: string, since?: number, now?: number, runRows?: Set<string>, coldRows?: Set<string>): {
136
+ returns: ColdReturn[];
137
+ pauses: Pause[];
138
+ readded: ReAdded[];
139
+ };
140
+ /** Keeping warm for up to `hours` after each request, not knowing when the person is back. */
141
+ export declare function keepWarmPolicy(pauses: Pause[], hours: number): KeepWarmPolicy;
142
+ /** Every main transcript of the last `days` (or `paths`). */
143
+ export declare function coldReturns(days?: number, paths?: string[], now?: number): ColdReturnReport;
144
+ /** The `cache-misses` section, or nothing when there were no cold returns. */
145
+ export declare function renderColdReturns(r: ColdReturnReport): string[];
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Cold returns: a main-conversation request after the prompt cache it left
3
+ * expired, which writes the whole context again. On the author's 30 days
4
+ * (2026-11-15) they were the largest cost no lever reached: 183 returns,
5
+ * $864 above cache-read price (26% of spend), $760 of it on contexts over
6
+ * 300k. `cache-misses` reports them here, each one replayed three ways:
7
+ *
8
+ * - as it went: the return as billed (requestCost, the same figure `spend`
9
+ * adds up);
10
+ * - compacted on return: the cold-resume replay's estimate (coldresume.ts),
11
+ * /compact right after the return, net of the compaction, counting what it
12
+ * saves on the requests after it until the next return;
13
+ * - kept warm: a cache read of the whole context every 55 minutes while away
14
+ * (4.5 minutes on a 5-minute cache), so the return reads the context
15
+ * instead of writing it. A ping is the context at the cache-read rate plus
16
+ * a short prompt and reply (Claude Code's mods API `$.model.fork`: the main
17
+ * thread's last request again, with one message after it, nothing kept in
18
+ * the transcript).
19
+ *
20
+ * By how long the person was away. The replay knows the gap; a keep-warm
21
+ * timer does not, so the policies below price keeping warm for up to N
22
+ * hours, counting every ping it would have sent: every pause past the first
23
+ * ping, the returns past the cap (cold anyway) and the sessions never
24
+ * returned to.
25
+ *
26
+ * Also #107157 (anthropics/claude-code): the Desktop app's transcript gains a
27
+ * copy of a segment a compaction had already removed (its rows, its
28
+ * `compact_boundary` included, with their original uuids), and a resume then
29
+ * rebuilds the conversation through it: one request went from 390k to 862k
30
+ * tokens and wrote 817k to the cache. Found here as a compaction boundary
31
+ * whose uuid the transcript already held, followed by a jump in context with
32
+ * no real compaction between.
33
+ */
34
+ import { listSessions, isClaudeSession, replyCounter } from "./session.js";
35
+ import { rowsOf } from "./scan.js";
36
+ import { coldResumeEvents, REQUEST_ROWS, writtenTtlMs } from "./coldresume.js";
37
+ import { rateCard, ratesAt, requestCost } from "./pricing.js";
38
+ import { formatTokens, realModel } from "./tokens.js";
39
+ const MIN = 60_000;
40
+ const HOUR = 60 * MIN;
41
+ const FIVE_MIN = 5 * MIN;
42
+ /** Smaller previous contexts are noise (as `cache-misses`). */
43
+ const MIN_CONTEXT = 20_000;
44
+ /** A return that wrote more than this share of the previous context wrote it again. */
45
+ const REWRITE_SHARE = 0.6;
46
+ /** A ping every this long keeps a 1-hour cache warm (5 minutes of margin)... */
47
+ export const PING_EVERY_1H_MS = 55 * MIN;
48
+ /** ...and a 5-minute one (30 seconds of margin). */
49
+ export const PING_EVERY_5M_MS = 270_000;
50
+ /** A ping's own prompt (uncached) and reply, a short answer and a little thinking: an estimate. */
51
+ export const PING_PROMPT_TOKENS = 30;
52
+ export const PING_OUTPUT_TOKENS = 100;
53
+ /** The keep-warm caps priced, hours. */
54
+ export const KEEP_WARM_HOURS = [1, 2, 4, 8];
55
+ /** A jump in context this large after a copied segment is #107157's. */
56
+ const READDED_MIN_TOKENS = 100_000;
57
+ const READDED_MIN_SHARE = 1.3;
58
+ export const GAP_BUCKETS = ["<1h", "1-2h", "2-4h", "4-8h", ">8h"];
59
+ export function gapBucket(ms) {
60
+ return ms < HOUR ? "<1h" : ms < 2 * HOUR ? "1-2h" : ms < 4 * HOUR ? "2-4h" : ms < 8 * HOUR ? "4-8h" : ">8h";
61
+ }
62
+ export const pingEveryMs = (ttlMs) => (ttlMs >= HOUR ? PING_EVERY_1H_MS : PING_EVERY_5M_MS);
63
+ /** Pings a timer sends in a pause of `gapMs`: one each `every` until the person is back. */
64
+ export const pingsIn = (gapMs, every) => Math.max(0, Math.ceil(gapMs / every) - 1);
65
+ /** One ping: the context read from the cache, the ping's prompt and its reply. */
66
+ export function pingUsd(contextTokens, p) {
67
+ return (contextTokens * p.cacheReadPerM + PING_PROMPT_TOKENS * p.inputPerM + PING_OUTPUT_TOKENS * p.outputPerM) / 1e6;
68
+ }
69
+ /** One transcript's cold returns, pauses and re-added segments; `now` ends the last pause. */
70
+ export function coldReturnsInTranscript(path, since = 0, now = Date.now(), runRows, coldRows) {
71
+ const returns = [], pauses = [], readded = [];
72
+ const sighting = replyCounter(runRows);
73
+ const boundaries = new Set();
74
+ let ttl = HOUR;
75
+ let prev;
76
+ /** A real compaction since prev, and when. */
77
+ let compactedAt;
78
+ /** A copied boundary (#107157) not yet followed by a real compaction, and the context before it. */
79
+ let copied;
80
+ for (const e of rowsOf(path, REQUEST_ROWS)) {
81
+ if (!e || e.isSidechain)
82
+ continue;
83
+ if (e.type === "system" && e.subtype === "compact_boundary") {
84
+ const at = Date.parse(e.timestamp);
85
+ if (typeof e.uuid === "string" && boundaries.has(e.uuid)) {
86
+ // A copy of a boundary already in the file: the segment after it was compacted away once.
87
+ copied ??= { at, before: prev?.total };
88
+ continue;
89
+ }
90
+ if (typeof e.uuid === "string")
91
+ boundaries.add(e.uuid);
92
+ if (Number.isFinite(at))
93
+ compactedAt = at;
94
+ copied = undefined;
95
+ continue;
96
+ }
97
+ if (e.type !== "assistant" || !e.message?.usage)
98
+ continue;
99
+ const seen = sighting(e);
100
+ if (seen === "repeat")
101
+ continue;
102
+ const model = realModel(e.message.model);
103
+ const at = Date.parse(e.timestamp);
104
+ const u = e.message.usage;
105
+ const write = num(u.cache_creation_input_tokens);
106
+ const total = num(u.input_tokens) + num(u.cache_read_input_tokens) + write;
107
+ if (!model || !Number.isFinite(at) || !(total > 0))
108
+ continue;
109
+ const prevTtl = ttl;
110
+ ttl = writtenTtlMs(u) ?? ttl;
111
+ const r = { at, total, write, u, model, ttl, copy: seen === "copy" };
112
+ if (prev && at >= since && prev.total > MIN_CONTEXT) {
113
+ // The pause a keep-warm timer would have pinged through: until the person came back, or until a compaction.
114
+ const gap = (compactedAt ?? at) - prev.at;
115
+ const card = rateCard(prev.model, prev.u, prev.at);
116
+ const ping = card ? pingUsd(prev.total, ratesAt(card, prev.total)) : 0;
117
+ let avoidable = 0;
118
+ if (compactedAt === undefined && gap > prevTtl && write > REWRITE_SHARE * prev.total && !r.copy) {
119
+ const c = requestCost(model, u, at);
120
+ if (c) {
121
+ const rewrite = write > 0 ? (Math.min(write, prev.total) * (c.writeUsd / write - c.rates.cacheReadPerM / 1e6)) : 0;
122
+ const sameModel = prev.model === model;
123
+ const pings = pingsIn(gap, pingEveryMs(prevTtl));
124
+ avoidable = sameModel ? rewrite : 0;
125
+ returns.push({
126
+ path, at, gapMs: gap, ttlMs: prevTtl, model, contextTokens: prev.total, tokens: total, writeTokens: write,
127
+ billedUsd: c.totalUsd, rewriteUsd: rewrite,
128
+ keptWarmUsd: c.totalUsd - avoidable + pings * ping, pings, pingUsd: ping, sameModel,
129
+ });
130
+ }
131
+ }
132
+ pauses.push({ gapMs: gap, ttlMs: prevTtl, pingUsd: ping, avoidableUsd: avoidable });
133
+ }
134
+ if (copied && prev && at >= since && compactedAt === undefined && total > prev.total * READDED_MIN_SHARE && total - prev.total > READDED_MIN_TOKENS) {
135
+ const c = requestCost(model, u, at);
136
+ const jump = total - prev.total;
137
+ const writeRate = c && write > 0 ? c.writeUsd / write : 0;
138
+ readded.push({
139
+ path, copiedAt: copied.at, at, fromTokens: prev.total, toTokens: total, writeTokens: write,
140
+ extraWriteUsd: Math.min(jump, write) * writeRate,
141
+ perRequestUsd: c ? (jump * c.rates.cacheReadPerM) / 1e6 : 0,
142
+ });
143
+ copied = undefined;
144
+ }
145
+ prev = r;
146
+ compactedAt = undefined;
147
+ }
148
+ // The pause after the last request: a timer pings it until the cap whether or not the person comes back.
149
+ if (prev && prev.at >= since && prev.total > MIN_CONTEXT && compactedAt === undefined && now > prev.at) {
150
+ const card = rateCard(prev.model, prev.u, prev.at);
151
+ pauses.push({ gapMs: now - prev.at, ttlMs: ttl, pingUsd: card ? pingUsd(prev.total, ratesAt(card, prev.total)) : 0, avoidableUsd: 0 });
152
+ }
153
+ // Compacted on return: the cold-resume replay's figure for the same request.
154
+ if (returns.length) {
155
+ const net = new Map(coldResumeEvents(path, undefined, undefined, coldRows).map((c) => [c.at, c.netUsd]));
156
+ for (const r of returns) {
157
+ const n = net.get(r.at);
158
+ if (n !== undefined)
159
+ r.compactedUsd = r.billedUsd - n;
160
+ }
161
+ }
162
+ return { returns, pauses, readded };
163
+ }
164
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
165
+ /** Keeping warm for up to `hours` after each request, not knowing when the person is back. */
166
+ export function keepWarmPolicy(pauses, hours) {
167
+ let pings = 0, usd = 0, kept = 0, avoided = 0;
168
+ for (const p of pauses) {
169
+ const every = pingEveryMs(p.ttlMs);
170
+ const all = pingsIn(p.gapMs, every);
171
+ const sent = Math.min(all, Math.floor((hours * HOUR) / every));
172
+ pings += sent;
173
+ usd += sent * p.pingUsd;
174
+ // Kept warm only when the pings lasted until the return.
175
+ if (p.avoidableUsd > 0 && sent === all) {
176
+ kept++;
177
+ avoided += p.avoidableUsd;
178
+ }
179
+ }
180
+ return { hours, pings, pingUsd: usd, keptWarm: kept, avoidedUsd: avoided, netUsd: avoided - usd };
181
+ }
182
+ function row(bucket, rs) {
183
+ const sum = (f) => rs.reduce((n, r) => n + f(r), 0);
184
+ const asItWentUsd = sum((r) => r.billedUsd);
185
+ const compactedUsd = sum((r) => r.compactedUsd ?? r.billedUsd);
186
+ const keptWarmUsd = sum((r) => r.keptWarmUsd);
187
+ const least = Math.min(asItWentUsd, compactedUsd, keptWarmUsd);
188
+ return {
189
+ bucket,
190
+ returns: rs.length,
191
+ asItWentUsd,
192
+ rewriteUsd: sum((r) => r.rewriteUsd),
193
+ compactedUsd,
194
+ keptWarmUsd,
195
+ pings: sum((r) => r.pings),
196
+ cheapest: least === asItWentUsd ? "as it went" : least === keptWarmUsd ? "kept warm" : "compacted",
197
+ };
198
+ }
199
+ /** Every main transcript of the last `days` (or `paths`). */
200
+ export function coldReturns(days = 30, paths, now = Date.now()) {
201
+ const since = now - days * 86_400_000;
202
+ const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
203
+ const returns = [], pauses = [], readded = [];
204
+ const runRows = new Set(), coldRows = new Set();
205
+ for (const p of targets) {
206
+ try {
207
+ const one = coldReturnsInTranscript(p, since, now, runRows, coldRows);
208
+ returns.push(...one.returns);
209
+ pauses.push(...one.pauses);
210
+ readded.push(...one.readded);
211
+ }
212
+ catch {
213
+ /* one unreadable transcript must not sink the report */
214
+ }
215
+ }
216
+ const policies = KEEP_WARM_HOURS.map((h) => keepWarmPolicy(pauses, h));
217
+ const best = policies.reduce((b, p) => (p.netUsd > (b?.netUsd ?? 0) ? p : b), undefined);
218
+ return {
219
+ days,
220
+ returns: returns.length,
221
+ billedUsd: returns.reduce((n, r) => n + r.billedUsd, 0),
222
+ rewriteUsd: returns.reduce((n, r) => n + r.rewriteUsd, 0),
223
+ over300kUsd: returns.filter((r) => r.contextTokens > 300_000).reduce((n, r) => n + r.rewriteUsd, 0),
224
+ byGap: GAP_BUCKETS.map((b) => row(b, returns.filter((r) => gapBucket(r.gapMs) === b))).filter((r) => r.returns > 0),
225
+ total: row("all", returns),
226
+ policies,
227
+ best,
228
+ readded: readded.sort((a, b) => b.extraWriteUsd - a.extraWriteUsd),
229
+ largest: [...returns].sort((a, b) => b.rewriteUsd - a.rewriteUsd).slice(0, 10),
230
+ };
231
+ }
232
+ /** "$1,925", "$12.26", "$0". */
233
+ function money(n) {
234
+ if (!(Math.abs(n) > 0))
235
+ return "$0";
236
+ if (n < 0)
237
+ return `-${money(-n)}`;
238
+ if (n >= 100)
239
+ return `$${Math.round(n).toLocaleString("en-US")}`;
240
+ if (n >= 0.01)
241
+ return `$${n.toFixed(2)}`;
242
+ return "<$0.01";
243
+ }
244
+ /** The `cache-misses` section, or nothing when there were no cold returns. */
245
+ export function renderColdReturns(r) {
246
+ const out = [];
247
+ if (r.returns > 0) {
248
+ out.push("COLD RETURNS: BACK AFTER THE CACHE EXPIRED", "─".repeat(60), `${r.returns} return${r.returns === 1 ? "" : "s"} to a conversation after its cache expired wrote the`, `context again: ${money(r.billedUsd)} billed, ${money(r.rewriteUsd)} of it above cache-read price` + (r.over300kUsd > 0 ? "" : "."), ...(r.over300kUsd > 0 ? [`(${money(r.over300kUsd)} on contexts over 300k).`] : []), "", "Each return three ways, by how long you were away:", ` ${"away".padEnd(6)} ${"returns".padStart(7)} ${"as it went".padStart(11)} ${"compacted".padStart(10)} ${"kept warm".padStart(10)} cheapest`);
249
+ for (const g of [...r.byGap, r.total]) {
250
+ out.push(` ${g.bucket.padEnd(6)} ${String(g.returns).padStart(7)} ${money(g.asItWentUsd).padStart(11)} ${money(g.compactedUsd).padStart(10)} ${money(g.keptWarmUsd).padStart(10)} ${g.cheapest}`);
251
+ }
252
+ out.push("As it went: the returns as billed. Compacted: /compact right after the", "return, net of the compaction, with what it saves on the requests after it", "until the next return (offered over 150k tokens). Kept warm: a cache read of", "the whole context every 55 min while away (4.5 min on a 5-minute cache) and", `~${PING_OUTPUT_TOKENS} output tokens each, so the return reads it instead of writing it.`, "Each alone; the replay knows the gap, which a timer does not.");
253
+ if (r.policies.some((p) => p.pings > 0)) {
254
+ out.push("", "Keeping warm without knowing when you come back, for up to:");
255
+ for (const p of r.policies) {
256
+ out.push(` ${`${p.hours} h`.padEnd(4)} ${String(p.pings).padStart(6)} pings ${money(p.pingUsd).padStart(8)}, ${`${p.keptWarm} return${p.keptWarm === 1 ? "" : "s"} kept warm`.padEnd(20)} ${money(p.avoidedUsd).padStart(8)}, net ${money(p.netUsd)}`);
257
+ }
258
+ out.push("Pings count every pause past 55 minutes (4.5 on a 5-minute cache), the", "returns after the cap (cold anyway) and the sessions never returned to.");
259
+ out.push(...(r.best
260
+ ? [
261
+ `Kept warm up to ${r.best.hours} h would have saved ${money(r.best.netUsd)} net. In Claude Code with the`,
262
+ `plugin, type /context-doctor-keep-warm ${r.best.hours}h before you step away: it pings only`,
263
+ "after that, stops at the cap or its dollar limit, and never arms itself.",
264
+ "On a subscription the pings come out of your usage limit, as the re-writes",
265
+ "they replace do.",
266
+ ]
267
+ : ["No cap nets a saving on your history: the pings would cost more than the", "re-writes they avoid."]));
268
+ }
269
+ }
270
+ if (r.readded.length) {
271
+ if (out.length)
272
+ out.push("");
273
+ const extra = r.readded.reduce((n, x) => n + x.extraWriteUsd, 0);
274
+ const worst = r.readded[0];
275
+ out.push(`A compacted segment put back (anthropics/claude-code#107157): ${r.readded.length} time${r.readded.length === 1 ? "" : "s"} the`, "transcript held a copy of history a compaction had removed, and the context", `jumped after it (worst ~${formatTokens(worst.fromTokens)} to ~${formatTokens(worst.toTokens)} tokens): ${money(extra)} written to the cache again,`, `and each later request re-reads it (~${money(worst.perRequestUsd)} each in the worst).`, "/compact again only summarizes it again: start a new session from a handoff", "(context-doctor handoff) or /clear.");
276
+ for (const x of r.readded.slice(0, 5)) {
277
+ const file = x.path.split(/[\\/]/).pop()?.slice(0, 12) ?? "";
278
+ out.push(` ${new Date(x.at).toISOString().slice(0, 16).replace("T", " ")} ~${formatTokens(x.fromTokens)} to ~${formatTokens(x.toTokens)}, ${money(x.extraWriteUsd)} ${file}`);
279
+ }
280
+ }
281
+ return out;
282
+ }
@@ -14,10 +14,16 @@
14
14
  * Estimated from what the transcript does record, at the model of the reply
15
15
  * before it (rateCard, as every request: the organization's rates, the day's
16
16
  * price, its fast mode and US-only):
17
- * - the context it read, `preTokens`: at the cache-read rate when the cache
18
- * the last reply left was still alive (an automatic compaction mid-turn,
19
- * Claude Code's idle compaction before expiry), else written again at the
20
- * session's lifetime (a /compact after the cache went cold);
17
+ * - the context it read, `preTokens`, at the cache-read rate, however long
18
+ * the session sat idle before it. That is how Claude Code's own cost-state
19
+ * shows them billed: on the author's machine, 33 compactions fall between
20
+ * two of a session's cost-state rows, and in the 24 brackets that hold
21
+ * nothing else no row records, Claude Code's figure moved by about the
22
+ * cache-read price (a 221k-token Fable 5.1 compaction after 5.4 hours idle:
23
+ * $0.44 over our rows, read $0.29, written again $4.66), never by a write.
24
+ * Pricing a compaction past the cache's lifetime as written again (as
25
+ * before) put one session 10.7% over Claude Code's figure. `warm` still
26
+ * says whether the last reply's cache was within its lifetime;
21
27
  * - its output, the summary: the summary row's text, in tokens.
22
28
  * Not counted: the request's own instruction (a few hundred tokens) and any
23
29
  * thinking it did. The next request's re-write of the new context is in that
@@ -14,10 +14,16 @@
14
14
  * Estimated from what the transcript does record, at the model of the reply
15
15
  * before it (rateCard, as every request: the organization's rates, the day's
16
16
  * price, its fast mode and US-only):
17
- * - the context it read, `preTokens`: at the cache-read rate when the cache
18
- * the last reply left was still alive (an automatic compaction mid-turn,
19
- * Claude Code's idle compaction before expiry), else written again at the
20
- * session's lifetime (a /compact after the cache went cold);
17
+ * - the context it read, `preTokens`, at the cache-read rate, however long
18
+ * the session sat idle before it. That is how Claude Code's own cost-state
19
+ * shows them billed: on the author's machine, 33 compactions fall between
20
+ * two of a session's cost-state rows, and in the 24 brackets that hold
21
+ * nothing else no row records, Claude Code's figure moved by about the
22
+ * cache-read price (a 221k-token Fable 5.1 compaction after 5.4 hours idle:
23
+ * $0.44 over our rows, read $0.29, written again $4.66), never by a write.
24
+ * Pricing a compaction past the cache's lifetime as written again (as
25
+ * before) put one session 10.7% over Claude Code's figure. `warm` still
26
+ * says whether the last reply's cache was within its lifetime;
21
27
  * - its output, the summary: the summary row's text, in tokens.
22
28
  * Not counted: the request's own instruction (a few hundred tokens) and any
23
29
  * thinking it did. The next request's re-write of the new context is in that
@@ -50,9 +56,8 @@ function priced(st, summaryTokens) {
50
56
  return undefined;
51
57
  const ttl = th.ttl ?? HOUR_MS;
52
58
  const warm = th.at !== undefined && p.at - th.at <= ttl;
53
- const usage = warm
54
- ? { input_tokens: 0, cache_read_input_tokens: p.pre, cache_creation_input_tokens: 0, output_tokens: summaryTokens, ...th.b }
55
- : { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: p.pre, cache_creation: ttl >= HOUR_MS ? { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: p.pre } : { ephemeral_5m_input_tokens: p.pre, ephemeral_1h_input_tokens: 0 }, output_tokens: summaryTokens, ...th.b };
59
+ // Read from the cache either way: what Claude Code's cost-state shows (above).
60
+ const usage = { input_tokens: 0, cache_read_input_tokens: p.pre, cache_creation_input_tokens: 0, output_tokens: summaryTokens, ...th.b };
56
61
  const cost = requestCost(th.m, usage, p.at);
57
62
  if (!cost)
58
63
  return undefined;
@@ -22,7 +22,7 @@
22
22
  */
23
23
  import { join } from "node:path";
24
24
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
- import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
25
+ import { billedCost, cacheWriteSplit, rateCard, ratesAt, writeMultiplier, writePerM } from "./pricing.js";
26
26
  import { priceBasis } from "./orgrates.js";
27
27
  import { realModel } from "./tokens.js";
28
28
  import { backupOnce } from "./install.js";
@@ -89,7 +89,7 @@ function readRequests(path, runRows) {
89
89
  const w = cacheWriteSplit(u);
90
90
  writes5m += w.fiveMinute;
91
91
  writes1h += w.oneHour;
92
- reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: requestCost(model, u, at)?.promptUsd ?? 0 });
92
+ reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: billedCost(model, u, at)?.promptUsd ?? 0 });
93
93
  });
94
94
  return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
95
95
  }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * GitHub Copilot CLI's own record of what it sent: `session.usage_record`
3
+ * events in `~/.copilot/session-state/<session>/events.jsonl` (or
4
+ * `$COPILOT_HOME`), one per model call. Checked 2026-11-15 against the
5
+ * readers that parse them (GitHub's own agent-radar collector in
6
+ * github/awesome-copilot, qualitylayer, tokscale, agentsview) and
7
+ * ccusage#2069 (1,142 records and no shutdown in one user's sessions).
8
+ * GitHub documents none of it; the shape:
9
+ *
10
+ * {"type":"session.usage_record","id":"…","timestamp":"…","data":{"usage":{
11
+ * "model":"claude-opus-4.6-1m","inputTokens":…,"outputTokens":…,
12
+ * "cacheReadTokens":…,"cacheWriteTokens":…,"reasoningTokens":…,
13
+ * "cost":1,"duration":…,"apiCallId":"…","isByok":false,
14
+ * "accounting":{"sourceSessionId":"…","usageId":"…"},
15
+ * "copilotUsage":{"totalNanoAiu":…}}}}
16
+ *
17
+ * - `inputTokens` holds the cached tokens too (read and written): the
18
+ * uncached input is what is left after both.
19
+ * - `reasoningTokens` is part of `outputTokens`, not added again.
20
+ * - `cost` is the request's premium-request multiplier (1, or 14 for a
21
+ * premium model), not dollars. `copilotUsage.totalNanoAiu` is the AI
22
+ * credits it used, in billionths: one credit is $0.01.
23
+ * - The same call can be written twice (Copilot CLI 1.0.108: "count each
24
+ * newly recorded model call once, even when its usage event is received
25
+ * again"): one call is its accounting id, else its API call id, else the
26
+ * event's id.
27
+ * - A compaction (`session.compaction_complete`, `compactionTokensUsed`) is
28
+ * a model call of its own, unless a usage record already names its
29
+ * request.
30
+ * - Where it ran: `session.start` (and `session.resume`) carry
31
+ * `data.context` with `cwd`, `gitRoot`, `branch` and `repository`.
32
+ *
33
+ * Sessions from Copilot CLI versions that write no usage records (only
34
+ * cumulative `session.shutdown` totals) are not read: their per-resume
35
+ * figures cannot be told apart reliably (ccusage's notes on it run a page).
36
+ */
37
+ import { type Extractor } from "./scan.js";
38
+ /** One Copilot CLI model call, as the session recorded it. */
39
+ export interface CopilotCall {
40
+ ts: number;
41
+ session: string;
42
+ /** The model as Copilot named it, less the context-size suffix ("-1m") and a BYOK provider's id. */
43
+ model: string;
44
+ /** Uncached input (inputTokens less both cache counts). */
45
+ input: number;
46
+ read: number;
47
+ write: number;
48
+ output: number;
49
+ /** AI credits it used (totalNanoAiu / 1e9); absent when the record has none. */
50
+ credits?: number;
51
+ /** Premium requests it counted (the legacy `cost` multiplier); absent when the record has none. */
52
+ premium?: number;
53
+ /** Billed to the user's own key (BYOK), not the Copilot plan. */
54
+ byok?: boolean;
55
+ /** Where the session ran, from session.start's context. */
56
+ cwd?: string;
57
+ gitRoot?: string;
58
+ branch?: string;
59
+ }
60
+ /** Copilot's home: $COPILOT_HOME when set (and `home` is this user's), else <home>/.copilot. */
61
+ export declare function copilotDataDir(home?: string): string;
62
+ /** "claude-opus-4.6-1m" -> "claude-opus-4.6"; "<provider uuid>/gpt-x" -> "gpt-x". */
63
+ export declare function copilotModel(raw: string): string;
64
+ /**
65
+ * What `spend` takes from a Copilot CLI session: each usage record's
66
+ * numbers and ids, each compaction's, and each start's context. No message
67
+ * text, no tool call.
68
+ */
69
+ export declare const COPILOT_USAGE_ROWS: Extractor<Record<string, never>>;
70
+ /** The model calls of one session's events file between `since` and `until`, each once. Throws when it cannot be read. */
71
+ export declare function copilotFileCalls(file: string, session: string, since: number, until?: number): CopilotCall[];
72
+ /** Each session's events file written since `since`: `session-state/<id>/events.jsonl`, and the flat `session-state/<id>.jsonl` some versions write. */
73
+ export declare function copilotSessionFiles(since: number, home?: string): Array<{
74
+ file: string;
75
+ session: string;
76
+ }>;
77
+ /** Every Copilot CLI model call between `since` and `until`. An unreadable session is skipped. */
78
+ export declare function copilotCalls(since: number, until?: number, home?: string): CopilotCall[];