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,353 @@
1
+ /**
2
+ * Codex's footer, drawn by our MCP server (ROADMAP G5).
3
+ *
4
+ * Codex 0.171.0 lets an MCP tool be a status line, behind its
5
+ * `tui_extensions_statusline` experiment (`/experimental`, Custom status
6
+ * line). The shapes here are Codex's own (openai/codex, codex-rs, read
7
+ * 2026-11-20): `tui/src/statusline_provider/descriptor.rs` takes a tool
8
+ * whose `_meta["openai/ui"].entrypoints` holds exactly one
9
+ * `{ type: "statusline", resourceUri: "ui://..." }`, the tool's title being
10
+ * its name in the `/statusline` picker; `tui/src/chatwidget/statusline_reader.rs`
11
+ * then reads that resource with the displayed thread's snapshot in
12
+ * `params._meta["com.openai/codex-statusline-state"]`, gives each read one
13
+ * second, waits a second and reads again; `statusline_reader/resource.rs`
14
+ * wants exactly one text content at the advertised URI, `application/json`,
15
+ * holding a UI tree (`tui/src/ui_tree.rs`: unknown fields refused, 64 KiB,
16
+ * 256 non-null nodes, depth 16, 16 KiB of text; `null` clears the footer).
17
+ * An error or a timeout stops the polling until the person picks the
18
+ * provider again, so a read here never fails: at worst it answers the last
19
+ * line it drew, or `null`.
20
+ *
21
+ * What it shows, short and plain, only what is known:
22
+ * context 412k of 1.0M (41%) $3.21 this session limits: 5h 23%, weekly 41%
23
+ * The context and the plan's windows are the snapshot's own figures. The
24
+ * dollars are the session's price as `spend` and the every-prompt hook count
25
+ * it, at list prices, the agents the thread spawned included (sessionTotal,
26
+ * sharing the hook's per-session entries). That reads the thread's rollout,
27
+ * whole on a change, which on a 70 MB rollout takes longer than a footer
28
+ * may wait, so it runs in a worker thread, at most one at a time, cached
29
+ * per thread and refreshed when the thread's token totals move; a read
30
+ * waits for it at most READ_BUDGET_MS and otherwise draws the last price
31
+ * it had, or, before the first, the snapshot's own totals priced at the
32
+ * model's rates (the thread alone).
33
+ *
34
+ * Nothing is drawn unasked: Codex shows it only to someone who turned the
35
+ * experiment on and picked it in `/statusline`, and the tool is listed only
36
+ * to Codex (mcp.ts).
37
+ */
38
+ import { existsSync, readdirSync } from "node:fs";
39
+ import { homedir } from "node:os";
40
+ import { join } from "node:path";
41
+ import { codexDir } from "./codexdir.js";
42
+ import { codexSessionsRoot, rolloutFiles } from "./limits.js";
43
+ import { openAIUsage, rateCard, ratesAt, usageCost } from "./pricing.js";
44
+ import { formatTokens } from "./tokens.js";
45
+ /** The resource Codex reads; the tool advertises it. */
46
+ export const CODEX_STATUSLINE_URI = "ui://context-doctor/statusline";
47
+ /** Where Codex puts the displayed thread's snapshot in a read's `params._meta`. */
48
+ export const CODEX_STATUSLINE_STATE = "com.openai/codex-statusline-state";
49
+ /** The tool's `_meta`: exactly one statusline entrypoint (Codex ignores a tool with two). */
50
+ export const CODEX_STATUSLINE_META = { "openai/ui": { entrypoints: [{ type: "statusline", resourceUri: CODEX_STATUSLINE_URI }] } };
51
+ /** The worker thread's role, passed as its `workerData`. */
52
+ export const PRICE_WORKER_ROLE = "context-doctor/codex-statusline-price";
53
+ /** Codex gives a read one second; this answers well inside it. */
54
+ export const READ_BUDGET_MS = 200;
55
+ /** The session's price is re-read at least this often while the footer shows (subagents move it too). */
56
+ const PRICE_TTL_MS = 30_000;
57
+ /** A price the worker has not answered in this long is given up on. */
58
+ const ASK_TIMEOUT_MS = 60_000;
59
+ /** And no sooner than this after the last, whatever moved. */
60
+ const PRICE_MIN_GAP_MS = 3_000;
61
+ /** Codex's limits on a tree's JSON (ui_tree/decode.rs). */
62
+ export const TREE_LIMITS = { bytes: 64 * 1024, nodes: 256, depth: 16, textBytes: 16 * 1024 };
63
+ /** A tree's JSON measured as Codex measures it; `ok` when it is within every limit. */
64
+ export function measureTree(json) {
65
+ const bytes = Buffer.byteLength(json, "utf8");
66
+ let nodes = 0, depth = 0, textBytes = 0;
67
+ const walk = (n, d) => {
68
+ if (n === null || n === undefined)
69
+ return;
70
+ nodes++;
71
+ depth = Math.max(depth, d);
72
+ if (typeof n === "string") {
73
+ textBytes += Buffer.byteLength(n, "utf8");
74
+ return;
75
+ }
76
+ for (const c of n.children ?? [])
77
+ walk(c, d + 1);
78
+ };
79
+ walk(JSON.parse(json), 0);
80
+ return { ok: bytes <= TREE_LIMITS.bytes && nodes <= TREE_LIMITS.nodes && depth <= TREE_LIMITS.depth && textBytes <= TREE_LIMITS.textBytes, bytes, nodes, depth, textBytes };
81
+ }
82
+ const finite = (v) => typeof v === "number" && Number.isFinite(v);
83
+ const positive = (v) => finite(v) && v > 0;
84
+ /** "$3.21", "$0.42", "$1,240": the session's cost as the footer shows it. */
85
+ function dollars(n) {
86
+ if (n >= 1000)
87
+ return `$${Math.round(n).toLocaleString("en-US")}`;
88
+ return `$${n.toFixed(2)}`;
89
+ }
90
+ /** "5h", "weekly", "30d": a window's name from its length. */
91
+ function windowName(minutes) {
92
+ if (!positive(minutes))
93
+ return undefined;
94
+ if (minutes === 300)
95
+ return "5h";
96
+ if (minutes === 10_080)
97
+ return "weekly";
98
+ if (minutes % 1440 === 0)
99
+ return `${minutes / 1440}d`;
100
+ if (minutes % 60 === 0)
101
+ return `${minutes / 60}h`;
102
+ return `${minutes}m`;
103
+ }
104
+ /** "14:32" local, or "Fri 14:32" when it is not today. */
105
+ function resetClock(epochSeconds, nowMs) {
106
+ const d = new Date(epochSeconds * 1000);
107
+ if (!Number.isFinite(d.getTime()) || d.getTime() <= nowMs || d.getTime() > nowMs + 31 * 86_400_000)
108
+ return undefined;
109
+ const hm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
110
+ return d.toDateString() === new Date(nowMs).toDateString() ? hm : `${d.toLocaleDateString("en-US", { weekday: "short" })} ${hm}`;
111
+ }
112
+ /**
113
+ * The thread's own token totals priced at its model's list rates, the tier
114
+ * of its current context: the price before the rollout's is known. The
115
+ * thread alone (no spawned agents); undefined for a model with no price.
116
+ */
117
+ export function snapshotUsd(state, at = Date.now()) {
118
+ const t = state.thread?.usage?.total;
119
+ const model = state.thread?.model?.id;
120
+ if (!t || !model)
121
+ return undefined;
122
+ const card = rateCard(model, undefined, at);
123
+ if (!card)
124
+ return undefined;
125
+ const u = openAIUsage({ input_tokens: t.total_input_tokens, cached_input_tokens: t.cache_read_input_tokens, cache_write_input_tokens: t.cache_write_input_tokens, output_tokens: t.output_tokens });
126
+ const usd = usageCost(u, ratesAt(card, finite(state.thread?.usage?.context?.used_tokens) ? state.thread.usage.context.used_tokens : 0)).totalUsd;
127
+ return finite(usd) && usd > 0 ? usd : undefined;
128
+ }
129
+ /**
130
+ * The footer for one snapshot, or null when nothing is known (Codex then
131
+ * clears it). `sessionUsd`: the session's price, when known; otherwise the
132
+ * snapshot's totals priced, then Codex's own figure.
133
+ */
134
+ export function renderCodexStatusline(state, sessionUsd, nowMs = Date.now()) {
135
+ if (!state || typeof state !== "object")
136
+ return null;
137
+ const items = [];
138
+ const text = (s, color) => ({ type: "text", ...(color ? { props: { color } } : {}), children: [s] });
139
+ const ctx = state.thread?.usage?.context;
140
+ const used = ctx?.used_tokens, size = ctx?.context_window_size;
141
+ if (positive(used)) {
142
+ const pct = finite(ctx?.used_percentage) ? ctx.used_percentage : positive(size) ? (used / size) * 100 : undefined;
143
+ const of = positive(size) ? ` of ${formatTokens(size)}` : "";
144
+ const share = pct !== undefined ? ` (${Math.round(pct)}%)` : "";
145
+ items.push(text(`context ${formatTokens(used)}${of}${share}${pct !== undefined && pct >= 70 ? " ⚠" : ""}`, pct !== undefined && pct >= 70 ? "yellow" : "status-usage"));
146
+ }
147
+ const own = state.thread?.usage?.cost?.total_cost_usd;
148
+ const usd = positive(sessionUsd) ? sessionUsd : (snapshotUsd(state, nowMs) ?? (positive(own) ? own : undefined));
149
+ if (usd !== undefined && usd >= 0.005)
150
+ items.push(text(`${dollars(usd)} this session`, "status-usage"));
151
+ const windows = [];
152
+ let worst = 0;
153
+ for (const rl of state.account?.rate_limits ?? []) {
154
+ if (rl?.limit_id !== undefined && rl.limit_id !== "codex")
155
+ continue;
156
+ for (const w of [rl?.primary_limit, rl?.secondary_limit]) {
157
+ if (!w || !finite(w.used_percent) || w.used_percent < 0)
158
+ continue;
159
+ const name = windowName(w.window_minutes);
160
+ if (!name)
161
+ continue;
162
+ const pct = Math.round(w.used_percent);
163
+ worst = Math.max(worst, pct);
164
+ // Near the end of a window, when it comes back is what the person needs.
165
+ const back = pct >= 80 && finite(w.resets_at) ? resetClock(w.resets_at, nowMs) : undefined;
166
+ windows.push(`${name} ${pct}%${back ? ` (resets ${back})` : ""}`);
167
+ }
168
+ }
169
+ if (windows.length)
170
+ items.push(text(`limits: ${windows.join(", ")}`, worst >= 90 ? "red" : worst >= 70 ? "yellow" : "status-limit"));
171
+ return items.length ? { type: "row", props: { gap: 3 }, children: items } : null;
172
+ }
173
+ // -- The session's price, off the main thread ------------------------------------
174
+ /** UUIDv7 thread ids carry their creation time: the rollout's day folder. */
175
+ function threadBorn(id) {
176
+ const m = /^([0-9a-f]{8})-([0-9a-f]{4})-7/i.exec(id);
177
+ if (!m)
178
+ return undefined;
179
+ const ms = parseInt(m[1] + m[2], 16);
180
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
181
+ }
182
+ /**
183
+ * The rollout of a Codex thread: `sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`
184
+ * in the day folders around the time its id was made (local and UTC), then
185
+ * the archive, then every session folder.
186
+ */
187
+ export function rolloutFor(threadId, home = homedir()) {
188
+ if (!/^[0-9a-f-]{8,64}$/i.test(threadId))
189
+ return undefined;
190
+ const suffix = `-${threadId}.jsonl`;
191
+ const root = codexSessionsRoot(home);
192
+ const look = (dir) => {
193
+ try {
194
+ const f = readdirSync(dir).find((n) => n.startsWith("rollout-") && n.endsWith(suffix));
195
+ return f ? join(dir, f) : undefined;
196
+ }
197
+ catch {
198
+ return undefined;
199
+ }
200
+ };
201
+ const born = threadBorn(threadId);
202
+ if (born !== undefined) {
203
+ const days = new Set();
204
+ for (const shift of [0, -86_400_000, 86_400_000]) {
205
+ const d = new Date(born + shift);
206
+ days.add(join(String(d.getFullYear()), String(d.getMonth() + 1).padStart(2, "0"), String(d.getDate()).padStart(2, "0")));
207
+ days.add(join(String(d.getUTCFullYear()), String(d.getUTCMonth() + 1).padStart(2, "0"), String(d.getUTCDate()).padStart(2, "0")));
208
+ }
209
+ for (const day of days) {
210
+ const hit = look(join(root, day));
211
+ if (hit)
212
+ return hit;
213
+ }
214
+ }
215
+ const archived = look(join(codexDir(home), "archived_sessions"));
216
+ if (archived)
217
+ return archived;
218
+ if (!existsSync(root))
219
+ return undefined;
220
+ return rolloutFiles(root, 0).find((f) => f.endsWith(suffix));
221
+ }
222
+ /** The worker side: prices a thread's session on request (sessionprice.ts), one at a time. */
223
+ export async function servePriceWorker() {
224
+ const { parentPort } = await import("node:worker_threads");
225
+ const { sessionTotal } = await import("./sessionprice.js");
226
+ if (!parentPort)
227
+ return;
228
+ const paths = new Map();
229
+ parentPort.on("message", (m) => {
230
+ let reply = { id: m.id };
231
+ try {
232
+ const file = paths.get(m.thread) ?? rolloutFor(m.thread);
233
+ if (file) {
234
+ paths.set(m.thread, file);
235
+ const t = sessionTotal({ sessionId: m.thread, transcript: file });
236
+ // Codex's entries are read whole on a change, so there is nothing to keep (saveIfWorthIt).
237
+ if (finite(t.usd))
238
+ reply = { id: m.id, usd: t.usd };
239
+ }
240
+ }
241
+ catch { /* unpriced this time */ }
242
+ parentPort.postMessage(reply);
243
+ });
244
+ }
245
+ /**
246
+ * One per server process: what each thread's session has cost, kept, and
247
+ * the worker that reads it. `spawn` starts the worker (mcp.ts knows the
248
+ * file it runs from); undefined, or a worker that fails, leaves the
249
+ * snapshot's own figures.
250
+ */
251
+ export class CodexStatusline {
252
+ spawn;
253
+ worker;
254
+ broken = false;
255
+ next = 1;
256
+ waiting = new Map();
257
+ inFlight = new Map();
258
+ prices = new Map();
259
+ lastGood = new Map();
260
+ constructor(spawn) {
261
+ this.spawn = spawn;
262
+ }
263
+ ask(thread) {
264
+ if (!this.worker && !this.broken && this.spawn) {
265
+ try {
266
+ const w = this.spawn();
267
+ w.unref();
268
+ w.on("message", (r) => {
269
+ const done = this.waiting.get(r?.id);
270
+ this.waiting.delete(r?.id);
271
+ done?.(finite(r?.usd) ? r.usd : undefined);
272
+ });
273
+ const fail = () => {
274
+ this.broken = true;
275
+ this.worker = undefined;
276
+ for (const done of this.waiting.values())
277
+ done(undefined);
278
+ this.waiting.clear();
279
+ };
280
+ w.on("error", fail);
281
+ w.on("exit", fail);
282
+ this.worker = w;
283
+ }
284
+ catch {
285
+ this.broken = true;
286
+ }
287
+ }
288
+ const w = this.worker;
289
+ if (!w)
290
+ return Promise.resolve(undefined);
291
+ const id = this.next++;
292
+ return new Promise((resolve) => {
293
+ this.waiting.set(id, resolve);
294
+ // A worker that never answers frees the thread for the next try.
295
+ setTimeout(() => {
296
+ if (this.waiting.delete(id))
297
+ resolve(undefined);
298
+ }, ASK_TIMEOUT_MS).unref();
299
+ w.postMessage({ id, thread });
300
+ });
301
+ }
302
+ /** The thread's session price: cached, refreshed in the background, waited for at most `budgetMs`. */
303
+ async price(thread, key, budgetMs, now) {
304
+ const have = this.prices.get(thread);
305
+ const gap = Math.max(PRICE_MIN_GAP_MS, (have?.tookMs ?? 0) * 10);
306
+ const due = !have || ((have.key !== key || now - have.at >= PRICE_TTL_MS) && now - have.at >= gap);
307
+ if (due && !this.inFlight.has(thread)) {
308
+ const started = Date.now();
309
+ const run = this.ask(thread).then((usd) => {
310
+ this.prices.set(thread, { usd: usd ?? have?.usd, at: Date.now(), key, tookMs: Date.now() - started });
311
+ this.inFlight.delete(thread);
312
+ });
313
+ this.inFlight.set(thread, run);
314
+ }
315
+ const pending = this.inFlight.get(thread);
316
+ if (pending && !have) {
317
+ let timer;
318
+ await Promise.race([pending, new Promise((r) => { timer = setTimeout(r, budgetMs); })]);
319
+ clearTimeout(timer);
320
+ }
321
+ return this.prices.get(thread)?.usd;
322
+ }
323
+ /**
324
+ * The resource's text for one read: a UI tree's JSON, or "null". Never
325
+ * throws and answers within about `budgetMs`: a failure answers the last
326
+ * line drawn for the thread.
327
+ */
328
+ async read(rawState, budgetMs = READ_BUDGET_MS) {
329
+ const state = (rawState && typeof rawState === "object" ? rawState : undefined);
330
+ const thread = typeof state?.thread?.id === "string" ? state.thread.id : "";
331
+ try {
332
+ const t = state?.thread?.usage?.total;
333
+ const key = t ? `${t.total_input_tokens}/${t.output_tokens}` : "";
334
+ const usd = thread && this.spawn ? await this.price(thread, key, budgetMs, Date.now()) : undefined;
335
+ const json = JSON.stringify(renderCodexStatusline(state, usd));
336
+ if (!measureTree(json).ok)
337
+ return this.lastGood.get(thread) ?? "null";
338
+ this.lastGood.set(thread, json);
339
+ return json;
340
+ }
341
+ catch {
342
+ return this.lastGood.get(thread) ?? "null";
343
+ }
344
+ }
345
+ /** Stops the worker (tests). */
346
+ async close() {
347
+ const w = this.worker;
348
+ this.worker = undefined;
349
+ this.broken = true;
350
+ if (w)
351
+ await w.terminate();
352
+ }
353
+ }
@@ -47,8 +47,20 @@ export interface CompactWindowReport {
47
47
  estimates: WindowEstimate[];
48
48
  /** Re-read tokens charged to each simulated compaction (0 when not measured). */
49
49
  rereadTokens?: number;
50
+ /**
51
+ * Sessions not replayed at the windows because most of their requests ran
52
+ * on a model whose window the Desktop app asked about (appwindow.ts): in
53
+ * "as now", saving nothing. Absent when none.
54
+ */
55
+ leftAlone?: {
56
+ sessions: number;
57
+ models: string[];
58
+ };
50
59
  }
51
- export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number, onProgress?: (done: number, total: number) => void): CompactWindowReport;
60
+ export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number, onProgress?: (done: number, total: number) => void, opts?: {
61
+ /** Models whose window the Desktop app asked about: a session mostly on one is left as it ran. */
62
+ leaveModels?: string[];
63
+ }): CompactWindowReport;
52
64
  /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
53
65
  export declare function sessionsLabel(sessions: number, transcripts: number): string;
54
66
  export declare function settingsPath(home?: string): string;
@@ -80,4 +92,4 @@ export interface SetWindowResult {
80
92
  export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
81
93
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
82
94
  export declare function parseWindow(raw: string): number | undefined;
83
- export declare function renderCompactWindows(r: CompactWindowReport, current?: number, limitLines?: (estimates: WindowEstimate[]) => string[]): string;
95
+ export declare function renderCompactWindows(r: CompactWindowReport, current?: number, limitLines?: (estimates: WindowEstimate[]) => string[], appLines?: string[], serverSet?: boolean): string;
@@ -32,6 +32,7 @@ import { withInvocation } from "./invocation.js";
32
32
  import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
33
33
  import { rowsOf } from "./scan.js";
34
34
  import { claudeDir, tilde } from "./claudedir.js";
35
+ import { sameModel } from "./appwindow.js";
35
36
  /** Claude Code compacts at about this share of the window (970k of 1M, measured). */
36
37
  const TRIGGER_SHARE = 0.97;
37
38
  /** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
@@ -52,6 +53,7 @@ const UNPRICED = { inputPerM: 0, outputPerM: 0, cacheReadPerM: 0 };
52
53
  */
53
54
  function readRequests(path, runRows) {
54
55
  const reqs = [];
56
+ const models = new Map();
55
57
  let model, writes5m = 0, writes1h = 0, priced = false;
56
58
  const sighting = replyCounter(runRows);
57
59
  rowsOf(path, REQUEST_ROWS).forEach((e) => {
@@ -83,6 +85,8 @@ function readRequests(path, runRows) {
83
85
  return;
84
86
  // Each request at its own model's price; "<synthetic>" rows carry no usage.
85
87
  model = realModel(e.message.model) ?? model;
88
+ if (model && seen !== "copy")
89
+ models.set(model, (models.get(model) ?? 0) + 1);
86
90
  const card = rateCard(model, u, at);
87
91
  if (card)
88
92
  priced = true;
@@ -91,7 +95,7 @@ function readRequests(path, runRows) {
91
95
  writes1h += w.oneHour;
92
96
  reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: billedCost(model, u, at)?.promptUsd ?? 0 });
93
97
  });
94
- return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
98
+ return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced, models };
95
99
  }
96
100
  /**
97
101
  * Replay one session twice: as it ran, and with compaction whenever the
@@ -173,11 +177,12 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
173
177
  }
174
178
  return { base, sim, extra, actual, idle };
175
179
  }
176
- export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
180
+ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress, opts = {}) {
177
181
  const since = Date.now() - days * 86_400_000;
178
182
  const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
179
183
  const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
180
- let sessions = 0, actualCompactions = 0, idleCompactions = 0;
184
+ let sessions = 0, actualCompactions = 0, idleCompactions = 0, left = 0;
185
+ const leftModels = new Set();
181
186
  // Shared by every transcript of the run, so a fork's copy counts once.
182
187
  const runRows = new Set();
183
188
  for (const [i, p] of targets.entries()) {
@@ -199,6 +204,19 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
199
204
  const asNow = replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult);
200
205
  actualCompactions += asNow.actual;
201
206
  idleCompactions += asNow.idle;
207
+ // Most of its requests on a model the Desktop app asked about: that window is the person's, left alone.
208
+ const main = [...parsed.models.entries()].sort((x, y) => y[1] - x[1])[0]?.[0];
209
+ const leave = main ? opts.leaveModels?.find((m) => sameModel(m, main)) : undefined;
210
+ if (leave) {
211
+ left++;
212
+ leftModels.add(leave);
213
+ for (const a of acc) {
214
+ a.billed += billed;
215
+ a.replayBase += asNow.base / 1e6;
216
+ a.extra += asNow.actual;
217
+ }
218
+ continue;
219
+ }
202
220
  for (const a of acc) {
203
221
  const r = replay(parsed.reqs, a.window, since, rereadTokens, parsed.writeMult);
204
222
  // The replay's share saved, applied to what this session was billed.
@@ -217,6 +235,7 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
217
235
  actualCompactions,
218
236
  idleCompactions,
219
237
  rereadTokens,
238
+ ...(left ? { leftAlone: { sessions: left, models: [...leftModels] } } : {}),
220
239
  estimates: acc.map((a) => ({
221
240
  window: a.window,
222
241
  baselineUsd: a.billed,
@@ -282,13 +301,19 @@ export function parseWindow(raw) {
282
301
  }
283
302
  const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
284
303
  const k = (n) => `${Math.round(n / 1000)}k`;
285
- export function renderCompactWindows(r, current, limitLines) {
304
+ export function renderCompactWindows(r, current, limitLines, appLines = [], serverSet = false) {
286
305
  const lines = [];
287
306
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
288
307
  // Counted and said exactly as `savings` says it, so the two screens agree.
289
308
  lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, ${priceBasis()}`);
290
309
  lines.push("─".repeat(66));
291
- lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
310
+ // `serverSet`: Anthropic's server sets a window for some model (appwindow.ts), which Claude Code uses where no setting does.
311
+ const unset = serverSet
312
+ ? "not set in your settings: Claude Code compacts at the window Anthropic's server sets (below), else near the model's full window"
313
+ : "not set: Claude Code compacts near the model's full window";
314
+ lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : unset}`);
315
+ // What the Desktop app asked, and what the server sets: only when something is on file.
316
+ lines.push(...appLines);
292
317
  if (r.sessions === 0) {
293
318
  lines.push("No sessions with 10+ requests in the window to replay.");
294
319
  return withInvocation(lines.join("\n"));
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Past the plan's limit: which Claude Code requests were paid from usage
3
+ * credits ("extra usage"), and about how much.
4
+ *
5
+ * With extra usage on, Claude Code keeps working when a weekly or 5-hour
6
+ * limit runs out and the requests are paid from credits: real money that
7
+ * the limits' % no longer shows. Two sources say when:
8
+ *
9
+ * - The proxy records the API's `anthropic-ratelimit-unified-overage-*`
10
+ * headers into the limits ledger (limits.ts recordOverage). A request
11
+ * made while the newest of those readings (at most 16 minutes old) said
12
+ * `in-use: true` was paid from credits; `false` says it was not.
13
+ * - The plugin's mod and the status line hand over only the windows' %,
14
+ * nothing about credits. A request that still went through (it has
15
+ * usage in its transcript) after a window read 100% and before that
16
+ * window reset is past the limit, and with extra usage on most likely
17
+ * paid from credits: counted as inferred, and said to be. With extra
18
+ * usage off (`~/.claude.json`, claudedir.ts readExtraUsage) nothing is
19
+ * inferred.
20
+ *
21
+ * Dollars are each request at API list prices, as `spend` prices it.
22
+ * Whether usage credits are billed at exactly those prices is not verified
23
+ * here, so every figure is said to be an estimate. Read only by commands
24
+ * the user runs (`limits`, `spend`, `doctor`, `budget`), and by the
25
+ * budget's hook at a threshold it already speaks at: nothing is drawn or sent.
26
+ */
27
+ import { type ExtraUsage } from "./claudedir.js";
28
+ import { type LimitReading, type OverageReading, type UsagePoint, type WindowStatus } from "./limits.js";
29
+ /** A window that read 100%: from that reading until it reset. */
30
+ export interface SpentSpan {
31
+ window: "five_hour" | "seven_day";
32
+ /** The first reading at 100% or more. */
33
+ from: number;
34
+ /** Its reset, else the next reading of a new period, else its last reading at 100% plus the keepalive. */
35
+ to: number;
36
+ resetsAt?: number;
37
+ }
38
+ /**
39
+ * The stretches in which a Claude window stood at 100% or more: from its
40
+ * first such reading to the window's reset. Within a period the % never
41
+ * falls, so once a window reads 100% it is spent until it resets.
42
+ */
43
+ export declare function spentSpans(readings: LimitReading[]): SpentSpan[];
44
+ /** How a request was found to be on credits: the API's replies said so, or a window read 100% and it still went through. */
45
+ export type CreditsHow = "headers" | "inferred";
46
+ /** One run of requests past the limit: one window's period, or one stretch the API's replies alone mark. */
47
+ export interface CreditsEpisode {
48
+ /** The window that ran out, when a reading says which. */
49
+ window?: "five_hour" | "seven_day";
50
+ /** When it ran out: the first reading at 100%, else the first reply that said credits were in use. */
51
+ ranOutAt: number;
52
+ /** When that window resets (absent when only the API's replies mark the episode). */
53
+ resetsAt?: number;
54
+ /** Still past the limit at the report's time. */
55
+ current: boolean;
56
+ /** The first and last request on credits. */
57
+ first: number;
58
+ last: number;
59
+ requests: number;
60
+ /** At API list prices: an estimate of what the credits paid. */
61
+ usd: number;
62
+ /** Of `requests`: marked by the API's replies, and inferred from a window at 100%. */
63
+ fromHeaders: number;
64
+ inferred: number;
65
+ }
66
+ export interface CreditsSummary {
67
+ episodes: CreditsEpisode[];
68
+ requests: number;
69
+ usd: number;
70
+ fromHeaders: number;
71
+ inferred: number;
72
+ }
73
+ export interface CreditsInputs {
74
+ readings: LimitReading[];
75
+ overage: OverageReading[];
76
+ /** `~/.claude.json`'s word; `enabled: false` turns inference off. */
77
+ extraUsage?: ExtraUsage;
78
+ now: number;
79
+ }
80
+ /**
81
+ * Sort requests (anything with a time and dollars: limits' usage points,
82
+ * spend's items) into runs past the limit. A request counts when the
83
+ * credits reading that speaks for it says in use, or, with no such
84
+ * reading, when it falls in a spent window and extra usage is not off.
85
+ */
86
+ export declare function creditsOf(points: Array<{
87
+ ts: number;
88
+ usd: number;
89
+ }>, inp: CreditsInputs): CreditsSummary;
90
+ export interface CreditsOptions {
91
+ now?: number;
92
+ logPath?: string;
93
+ /** Claude Code transcripts to read (tests); default every one in the period. */
94
+ claudePaths?: string[];
95
+ /** `~/.claude.json`'s word (tests); default read from the home below. */
96
+ extraUsage?: ExtraUsage | null;
97
+ home?: string;
98
+ }
99
+ /** The ledger's readings for a period starting at `since`, a week earlier too (a weekly window spent before it still counts in it). */
100
+ export declare function creditsInputs(since: number, opts?: CreditsOptions): CreditsInputs;
101
+ /** Nothing in the ledger could put a request past the limit: no spent window, no reply that said credits were in use. */
102
+ export declare function nothingPast(inp: CreditsInputs): boolean;
103
+ /**
104
+ * The last `days` days of Claude Code past the plan's limit, for `limits`:
105
+ * the ledger, and the transcripts only when the ledger says something was.
106
+ * Undefined when nothing was.
107
+ */
108
+ export declare function creditsReport(days?: number, opts?: CreditsOptions): (CreditsSummary & {
109
+ extraUsage?: ExtraUsage;
110
+ }) | undefined;
111
+ /** The same from `since` to now (`budget`'s day or week). Undefined when nothing was past the limit. */
112
+ export declare function creditsSince(since: number, opts?: CreditsOptions): (CreditsSummary & {
113
+ extraUsage?: ExtraUsage;
114
+ }) | undefined;
115
+ /**
116
+ * The weekly limit at the recent pace runs out before it resets, and extra
117
+ * usage is on: Claude Code would keep working on usage credits from then
118
+ * until the reset. About how much, at the last 24 hours' dollars an hour on
119
+ * this machine (list prices, an estimate).
120
+ */
121
+ export interface CreditsAhead {
122
+ /** When the weekly limit runs out at the recent pace, and when it resets, ms. */
123
+ runsOutAt: number;
124
+ resetsAt: number;
125
+ /** Hours from the run-out (or now, if later) to the reset. */
126
+ hours: number;
127
+ /** Claude Code's list-price dollars an hour over the last 24 hours, on this machine, subagents included. */
128
+ usdPerHour: number;
129
+ /** hours times usdPerHour. */
130
+ usd: number;
131
+ /** The model most of those dollars went to, and its share, when it is most of them. */
132
+ model?: string;
133
+ modelShare?: number;
134
+ /** The window's average pace (% an hour), and whether the limit lasts to the reset at it. */
135
+ averagePerHour?: number;
136
+ averageLasts?: boolean;
137
+ }
138
+ /** Extra usage on, and nothing in `~/.claude.json` saying credits are not paying now. */
139
+ export declare function extraUsageOn(x: ExtraUsage | undefined): boolean;
140
+ /**
141
+ * The weekly window's run-out and what the hours past it would cost. Pure:
142
+ * `usage` is the last 24 hours' requests. Undefined unless extra usage is on
143
+ * and the weekly window, read recently, runs out before its reset at the
144
+ * recent pace, with dollars to price the hours at.
145
+ */
146
+ export declare function creditsAhead(status: WindowStatus | undefined, extra: ExtraUsage | undefined, usage: Array<Pick<UsagePoint, "ts" | "usd" | "model">>, now: number): CreditsAhead | undefined;
147
+ export interface CreditsAheadOptions {
148
+ now?: number;
149
+ logPath?: string;
150
+ /** Claude Code transcripts to read (tests); default every one touched in the last day. */
151
+ claudePaths?: string[];
152
+ /** `~/.claude.json`'s word (tests); default read from the home below. */
153
+ extraUsage?: ExtraUsage | null;
154
+ home?: string;
155
+ /** The weekly window's status when the caller has it (`limits`); default read from the ledger. */
156
+ status?: WindowStatus;
157
+ }
158
+ /**
159
+ * creditsAhead from this machine: `~/.claude.json` first, then the ledger's
160
+ * weekly window, and the transcripts of the last day only when both say it
161
+ * applies. Never throws: a command's own figures must not be lost to it.
162
+ */
163
+ export declare function creditsAheadNow(opts?: CreditsAheadOptions): CreditsAhead | undefined;
164
+ /**
165
+ * One line: "Extra usage is on: at this pace your weekly limit runs out on
166
+ * Thu, Nov 26 at 18:19, 46 hours before it resets, and Claude Code would
167
+ * keep working on usage credits until then: about $1,234 at API list prices
168
+ * (an estimate), at your last 24 hours' $26.80 an hour, mostly Fable 5.2.
169
+ * At this week's average pace (0.55% an hour) it lasts until the reset."
170
+ */
171
+ export declare function creditsAheadLine(a: CreditsAhead, now: number): string;
172
+ /** "at 14:05" within the day, else "on Tue, Nov 17 at 14:05": local time. */
173
+ export declare function whenText(ms: number, now: number): string;
174
+ /** The dollars, in the words every report uses: list prices, an estimate. */
175
+ export declare const AT_LIST_PRICES = "at API list prices (an estimate)";
176
+ /**
177
+ * One episode in plain words: "Your weekly limit ran out on Tue, Nov 17 at
178
+ * 14:05; 37 requests after that were paid from usage credits, about $41.20
179
+ * at API list prices (an estimate)." Inferred ones say so.
180
+ */
181
+ export declare function episodeLine(e: CreditsEpisode, now: number): string;
182
+ /** Lines for `limits`: one per episode, newest last, and what "inferred" and the dollars mean when it applies. */
183
+ export declare function creditsLines(r: CreditsSummary, now: number): string[];
184
+ /**
185
+ * `doctor`'s line on extra usage, from `~/.claude.json`: on, on but held
186
+ * back (and why), or off. Undefined when the file says nothing (an API key,
187
+ * never signed in).
188
+ */
189
+ export declare function extraUsageText(x: ExtraUsage | undefined): {
190
+ on: boolean;
191
+ text: string;
192
+ } | undefined;