context-doctor 0.48.0 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +16 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +195 -0
  10. package/dist/ccost.js +400 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/install.js +1 -1
  28. package/dist/limits.d.ts +232 -14
  29. package/dist/limits.js +739 -33
  30. package/dist/mcp.js +19 -19
  31. package/dist/mcpdefer.d.ts +47 -0
  32. package/dist/mcpdefer.js +91 -0
  33. package/dist/mod/api.d.ts +72 -2
  34. package/dist/mod/api.js +5 -1
  35. package/dist/mod/logic.d.ts +289 -16
  36. package/dist/mod/logic.js +362 -38
  37. package/dist/mod/register.d.ts +37 -2
  38. package/dist/mod/register.js +290 -9
  39. package/dist/modmeasure.d.ts +6 -4
  40. package/dist/modmeasure.js +8 -4
  41. package/dist/opencode.d.ts +57 -0
  42. package/dist/opencode.js +234 -0
  43. package/dist/orgrates.d.ts +7 -0
  44. package/dist/orgrates.js +19 -0
  45. package/dist/overhead.d.ts +3 -0
  46. package/dist/overhead.js +5 -1
  47. package/dist/pricing.d.ts +59 -2
  48. package/dist/pricing.js +130 -10
  49. package/dist/proxy.d.ts +8 -1
  50. package/dist/proxy.js +13 -1
  51. package/dist/savings.d.ts +5 -1
  52. package/dist/savings.js +11 -5
  53. package/dist/scan.d.ts +3 -1
  54. package/dist/scan.js +8 -1
  55. package/dist/sessionprice.d.ts +5 -0
  56. package/dist/sessionprice.js +5 -1
  57. package/dist/sidecost.d.ts +65 -0
  58. package/dist/sidecost.js +117 -0
  59. package/dist/spend.d.ts +94 -3
  60. package/dist/spend.js +251 -23
  61. package/dist/spendplace.d.ts +40 -0
  62. package/dist/spendplace.js +93 -0
  63. package/dist/spendteam.d.ts +160 -0
  64. package/dist/spendteam.js +286 -0
  65. package/dist/starts.d.ts +106 -0
  66. package/dist/starts.js +406 -0
  67. package/dist/statusline.d.ts +2 -2
  68. package/dist/statusline.js +2 -2
  69. package/dist/subagentmodel.js +9 -7
  70. package/dist/subagentpay.d.ts +31 -2
  71. package/dist/subagentpay.js +232 -68
  72. package/dist/subagents.js +3 -3
  73. package/dist/tasks.js +3 -2
  74. package/dist/tooloutput.js +5 -5
  75. package/dist/usagepane.d.ts +77 -0
  76. package/dist/usagepane.js +287 -0
  77. package/package.json +1 -1
package/dist/limits.js CHANGED
@@ -1,16 +1,21 @@
1
1
  /**
2
2
  * `context-doctor limits`: your plan's usage limits, in their own unit.
3
3
  *
4
- * Subscriptions are billed in % of a 5-hour and a weekly window (Claude
5
- * Pro/Max), or in credits per token (Codex since April 2026), and neither
6
- * vendor shows where the percentage went. Two local sources say:
4
+ * Subscriptions are billed in % of a weekly window and, on most plans, a
5
+ * 5-hour one (Claude Pro, Max and Ultra; since 2026-10-30 Max 5x is called
6
+ * Max and Max 20x Ultra, and Ultra has no 5-hour window), or in credits per
7
+ * token (Codex since April 2026), and neither vendor shows where the
8
+ * percentage went. Local sources say:
7
9
  *
8
10
  * - Claude Code hands its status line command `rate_limits.five_hour` and
9
11
  * `.seven_day`, each `{used_percentage, resets_at}` (documented at
10
12
  * code.claude.com/docs/en/statusline; built in 2.1.308 as
11
13
  * Math.round(utilization*1000)/10, so 0.1% steps; present only for
12
- * Pro/Max subscribers, after the first reply). `context-doctor statusline`
13
- * appends each new reading to a small local log (recordLimits).
14
+ * subscribers, after the first reply; `five_hour` absent on Ultra), and
15
+ * the same windows to the plugin's mod (`session.measure`). The status
16
+ * line, the mod and the proxy (from the API's
17
+ * `anthropic-ratelimit-unified-5h-*` / `-7d-*` headers) append each new
18
+ * reading to a small local log (recordLimits).
14
19
  * - Codex records `rate_limits.primary` / `.secondary`
15
20
  * `{used_percent, window_minutes, resets_at}` on every token_count event of
16
21
  * its rollouts (~/.codex/sessions), next to that request's usage, in
@@ -32,15 +37,19 @@ import { codexDir } from "./codexdir.js";
32
37
  import { statePath } from "./ledger.js";
33
38
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
34
39
  import { subagentFiles } from "./subagents.js";
35
- import { pick, rowsOf, slimUsage } from "./scan.js";
36
- import { isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
40
+ import { pick, prescan, rowsOf, slimUsage } from "./scan.js";
41
+ import { costStateRecord, refusalRecord } from "./ccost.js";
42
+ import { addModifiers, extraIterations, isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
37
43
  import { realModel } from "./tokens.js";
38
44
  import { isCompactionRow, newTrack, slimSummary, trackCompaction } from "./compactcost.js";
45
+ import { PROXY_VERSION } from "./proxy.js";
46
+ import { contentOutputTokens, unsettledVersion } from "./sidecost.js";
39
47
  const MIN = 60_000;
40
48
  const HOUR = 60 * MIN;
41
49
  const DAY = 24 * HOUR;
42
50
  /** Claude Code's two windows, as its status line input names them. */
43
51
  export const CLAUDE_WINDOWS = ["five_hour", "seven_day"];
52
+ const SOURCES = ["statusline", "mod", "proxy"];
44
53
  // ---------------------------------------------------------------------------
45
54
  // The Claude readings log, written by the status line
46
55
  // ---------------------------------------------------------------------------
@@ -91,16 +100,18 @@ function parseLogLine(line) {
91
100
  return undefined;
92
101
  if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
93
102
  return undefined;
94
- return { ts, app: "claude", w, pct, reset: typeof reset === "number" && Number.isFinite(reset) && reset > 0 ? reset : undefined };
103
+ const src = e.src;
104
+ return { ts, app: "claude", w, pct, reset: typeof reset === "number" && Number.isFinite(reset) && reset > 0 ? reset : undefined, ...(typeof src === "string" && SOURCES.includes(src) ? { src: src } : {}) };
95
105
  }
96
106
  /**
97
107
  * Append what changed in Claude Code's `rate_limits` to the log: a window
98
108
  * whose % or reset time moved since its last line, or that has not been
99
109
  * written for 15 minutes. Nothing when there are no limits (an API key,
100
- * Bedrock, Vertex). Never throws: the status line must stay silent. Returns
101
- * the lines written.
110
+ * Bedrock, Vertex). A window that is not there (Ultra's 5-hour one) is
111
+ * simply not written. Never throws: the status line must stay silent.
112
+ * Returns the lines written.
102
113
  */
103
- export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath()) {
114
+ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath(), source) {
104
115
  if (!rateLimits || typeof rateLimits !== "object")
105
116
  return 0;
106
117
  const fresh = [];
@@ -110,7 +121,7 @@ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath(
110
121
  if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
111
122
  continue;
112
123
  const reset = typeof r.resets_at === "number" && Number.isFinite(r.resets_at) && r.resets_at > 0 ? Math.round(r.resets_at) : undefined;
113
- fresh.push({ ts: now, app: "claude", w, pct: Math.round(pct * 10) / 10, ...(reset ? { reset } : {}) });
124
+ fresh.push({ ts: now, app: "claude", w, pct: Math.round(pct * 10) / 10, ...(reset ? { reset } : {}), ...(source ? { src: source } : {}) });
114
125
  }
115
126
  if (!fresh.length)
116
127
  return 0;
@@ -169,10 +180,32 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
169
180
  const l = parseLogLine(line);
170
181
  if (!l || l.ts < since)
171
182
  continue;
172
- out.push({ ts: l.ts, app: "claude", window: l.w, pct: l.pct, resetsAt: l.reset ? l.reset * 1000 : undefined, windowMs: l.w === "five_hour" ? 5 * HOUR : 7 * DAY });
183
+ out.push({ ts: l.ts, app: "claude", window: l.w, pct: l.pct, resetsAt: l.reset ? l.reset * 1000 : undefined, windowMs: l.w === "five_hour" ? 5 * HOUR : 7 * DAY, ...(l.src ? { source: l.src } : {}) });
173
184
  }
174
185
  return out.sort((a, b) => a.ts - b.ts);
175
186
  }
187
+ /**
188
+ * The windows an Anthropic response's `anthropic-ratelimit-unified-5h-*` and
189
+ * `-7d-*` headers carry (a claude.ai sign-in, or a gateway), in the status
190
+ * line's shape for recordLimits: utilization is a fraction, the reset epoch
191
+ * seconds. Claude Code reads the same headers into its status line and its
192
+ * mods (Math.round(utilization*1000)/10). Undefined when there are none; a
193
+ * response with only the weekly pair (Ultra) gives only the weekly window.
194
+ */
195
+ export function rateLimitsFromHeaders(get) {
196
+ const out = {};
197
+ for (const [h, w] of [["5h", "five_hour"], ["7d", "seven_day"]]) {
198
+ const raw = get(`anthropic-ratelimit-unified-${h}-utilization`);
199
+ if (raw === null || raw === undefined || raw === "")
200
+ continue;
201
+ const u = Number(raw);
202
+ if (!Number.isFinite(u) || u < 0 || u > 10)
203
+ continue;
204
+ const reset = Number(get(`anthropic-ratelimit-unified-${h}-reset`));
205
+ out[w] = { used_percentage: Math.round(u * 1000) / 10, ...(Number.isFinite(reset) && reset > 0 ? { resets_at: Math.round(reset) } : {}) };
206
+ }
207
+ return Object.keys(out).length ? out : undefined;
208
+ }
176
209
  // ---------------------------------------------------------------------------
177
210
  // Codex: readings and usage, both from its rollouts
178
211
  // ---------------------------------------------------------------------------
@@ -333,17 +366,33 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
333
366
  /**
334
367
  * What the usage fit takes from a Claude Code transcript (subagents' too):
335
368
  * every assistant row with usage, in order. A later row of a reply already
336
- * met keeps only its id and output tokens: it is a repeat, read only for the
337
- * output a streamed reply settles on its last row. `isSidechain` is kept for
338
- * `spend`, which tells a subagent inlined in an older transcript from the
339
- * main thread.
369
+ * met keeps only its id, its output tokens and its billed iterations: it is
370
+ * a repeat, read only for what a streamed reply settles on its last row.
371
+ * `isSidechain` is kept for `spend`, which tells a subagent inlined in an
372
+ * older transcript from the main thread. A request's `usage.iterations` is
373
+ * kept only where some bill beyond its top-level usage (extraIterations).
374
+ * Also Claude Code's own running cost: each `cost-state` row as
375
+ * costStateRecord keeps it, with the Claude Code version of the replies
376
+ * before it (ccost.ts compares it with ours). A reply row keeps its
377
+ * `stop_reason` and `entrypoint` (a prompt suggestion follows a main-thread
378
+ * turn's end, sidecost.ts) and, where it has no `stop_reason`, its content
379
+ * as output tokens (`oc`: what a reply whose rows never settled cost,
380
+ * sidecost.ts). Each `api-request` row (what Claude Code sent, 2.1.308+) as
381
+ * its id, the request it repeats or extends and the time, a reply's
382
+ * `requestRef` to it, and an `api_error` row's code: a request no reply
383
+ * answers and Claude Code sent again a minute or more later is one that hung
384
+ * (ccost.ts names them).
340
385
  */
341
386
  export const USAGE_ROWS = {
342
- id: "usage.4",
387
+ id: "usage.6",
343
388
  init: () => ({ ids: {} }),
344
389
  line(line, row, out, st) {
345
390
  const compaction = isCompactionRow(line);
346
- if (!compaction && !line.includes('"usage"'))
391
+ const cost = !compaction && line.startsWith('{"type":"cost-state"');
392
+ const refusal = !compaction && !cost && line.includes('"model_refusal_fallback"');
393
+ const sent = !compaction && !cost && line.startsWith('{"type":"api-request",');
394
+ const failed = !compaction && !cost && !sent && line.includes('"subtype":"api_error"');
395
+ if (!compaction && !cost && !refusal && !sent && !failed && !line.includes('"usage"'))
347
396
  return;
348
397
  let e;
349
398
  try {
@@ -352,6 +401,23 @@ export const USAGE_ROWS = {
352
401
  catch {
353
402
  return;
354
403
  }
404
+ if (sent) {
405
+ if (e?.type === "api-request" && typeof e.id === "string")
406
+ out.push({ type: "api-request", id: e.id, ...(typeof e.base === "string" ? { base: e.base } : {}), t: Array.isArray(e.tail) ? e.tail.length : 0, timestamp: e.timestamp });
407
+ return;
408
+ }
409
+ if (failed) {
410
+ if (e?.type === "system" && e.subtype === "api_error")
411
+ out.push({ type: "system", subtype: "api_error", timestamp: e.timestamp, code: String(e.error?.connection?.code ?? e.error?.status ?? "").slice(0, 40) });
412
+ return;
413
+ }
414
+ if (cost || refusal) {
415
+ const r = cost ? costStateRecord(e, st.v) : refusalRecord(e);
416
+ if (r)
417
+ out.push(r);
418
+ if (cost || r)
419
+ return;
420
+ }
355
421
  // A compaction's boundary (the context it read) and its summary (the output): what its own request is estimated from (compactcost.ts).
356
422
  if (compaction && e?.type === "system" && e.subtype === "compact_boundary") {
357
423
  out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, compactMetadata: pick(e.compactMetadata ?? {}, ["preTokens"]) }, ["type", "subtype", "uuid", "sessionId", "timestamp", "isSidechain", "compactMetadata"]));
@@ -364,16 +430,29 @@ export const USAGE_ROWS = {
364
430
  const m = e?.message;
365
431
  if (e?.type !== "assistant" || !m?.usage)
366
432
  return;
433
+ if (typeof e.version === "string")
434
+ st.v = e.version.slice(0, 40);
367
435
  if (typeof m.id === "string") {
368
436
  if (st.ids[m.id]) {
369
- out.push({ type: "assistant", message: { id: m.id, usage: pick(m.usage, ["output_tokens"]) } });
437
+ // Its billed iterations too: a streamed reply may settle those on a later row as well.
438
+ const its = slimUsage(m.usage, { iterations: true });
439
+ out.push({ type: "assistant", message: { id: m.id, usage: { ...pick(m.usage, ["output_tokens"]), ...(its?.iterations ? { iterations: its.iterations } : {}) }, ...settling(m, e.version) } });
370
440
  return;
371
441
  }
372
442
  st.ids[m.id] = 1;
373
443
  }
374
- out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
444
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: { ...pick({ ...m, usage: slimUsage(m.usage, { iterations: true }) }, ["id", "model", "usage"]), ...settling(m, e.version) } }, ["type", "uuid", "timestamp", "isSidechain", "entrypoint", "requestRef", "message"]));
375
445
  },
376
446
  };
447
+ /** A reply row's `stop_reason`, or (none, from a Claude Code that left replies unsettled: unsettledVersion) its content as output tokens. */
448
+ function settling(m, version) {
449
+ if (typeof m.stop_reason === "string" && m.stop_reason)
450
+ return { stop_reason: m.stop_reason.slice(0, 40) };
451
+ if (!unsettledVersion(version))
452
+ return {};
453
+ const oc = contentOutputTokens(m.content);
454
+ return oc > 0 ? { oc } : {};
455
+ }
377
456
  /** A compaction's estimated request as a request point (no message id: its key is the boundary's uuid). */
378
457
  export function compactionPoint(c) {
379
458
  const u = c.usage;
@@ -383,6 +462,37 @@ export function compactionPoint(c) {
383
462
  ...(c.uuid ? { uuid: c.uuid } : {}), ...(c.sidechain ? { sidechain: true } : {}), ...(c.cost.estimated ? { estimated: true } : {}), ...(c.cost.changedOn ? { changedOn: c.cost.changedOn } : {}),
384
463
  };
385
464
  }
465
+ /** A request's iterations billed beyond its top-level usage, each priced at its own model (the request's when it names none) at `ts`. */
466
+ export function iterationPoints(model, u, ts) {
467
+ return extraIterations(u).map((x) => {
468
+ const m = realModel(x.model ?? model);
469
+ const c = requestCost(m, x.usage, ts);
470
+ return {
471
+ type: x.type, ...(m ? { model: m } : {}),
472
+ input: num(x.usage.input_tokens), read: num(x.usage.cache_read_input_tokens), write: num(x.usage.cache_creation_input_tokens), output: num(x.usage.output_tokens),
473
+ usd: c?.totalUsd ?? 0, promptUsd: c?.promptUsd ?? 0, priced: Boolean(c), modifiers: c ? c.modifiers : { ...NO_MODIFIERS },
474
+ ...(c?.estimated ? { estimated: true } : {}), ...(c?.changedOn ? { changedOn: c.changedOn } : {}),
475
+ };
476
+ });
477
+ }
478
+ /** `p`'s extra iterations set to `extra`, its dollars and modifiers moved by what changed. */
479
+ function setExtra(p, extra) {
480
+ for (const x of p.extra ?? []) {
481
+ p.usd -= x.usd;
482
+ p.promptUsd -= x.promptUsd;
483
+ addModifiers(p.modifiers, negated(x.modifiers));
484
+ }
485
+ if (extra.length)
486
+ p.extra = extra;
487
+ else
488
+ delete p.extra;
489
+ for (const x of extra) {
490
+ p.usd += x.usd;
491
+ p.promptUsd += x.promptUsd;
492
+ addModifiers(p.modifiers, x.modifiers);
493
+ }
494
+ }
495
+ const negated = (m) => ({ fastUsd: -m.fastUsd, geoUsd: -m.geoUsd, longUsd: -m.longUsd, webSearchUsd: -m.webSearchUsd, webSearches: -m.webSearches });
386
496
  /**
387
497
  * The requests of one Claude Code transcript between `since` and `until`,
388
498
  * each reply once, its output settled on its last row (billed at the
@@ -396,6 +506,8 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
396
506
  const sighting = replyCounter(runRows);
397
507
  const settle = outputSettler();
398
508
  const byId = new Map();
509
+ // Per reply: whether a row of it settled (has a stop_reason), and what its rows' content took to write (sidecost.ts).
510
+ const settled = new Map();
399
511
  const track = newTrack();
400
512
  rowsOf(file, USAGE_ROWS).forEach((e) => {
401
513
  const done = trackCompaction(track, e);
@@ -404,6 +516,12 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
404
516
  const m = e?.message;
405
517
  if (e?.type !== "assistant" || !m?.usage)
406
518
  return;
519
+ if (typeof m.id === "string") {
520
+ const s = settled.get(m.id) ?? settled.set(m.id, { stop: false, oc: 0 }).get(m.id);
521
+ if (m.stop_reason)
522
+ s.stop = true;
523
+ s.oc += typeof m.oc === "number" ? m.oc : 0;
524
+ }
407
525
  const seen = sighting(e);
408
526
  if (seen === "repeat") {
409
527
  const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
@@ -413,11 +531,20 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
413
531
  p.output += more;
414
532
  if (p.rates) {
415
533
  p.usd += (more * p.rates.outputPerM) / 1e6;
416
- // What the modifiers added grows with the output: priced again whole.
417
- if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd)
418
- p.modifiers = requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers;
534
+ // What the modifiers added grows with the output: priced again whole (the iterations' added back).
535
+ if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd) {
536
+ p.modifiers = { ...requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers };
537
+ for (const x of p.extra ?? [])
538
+ addModifiers(p.modifiers, x.modifiers);
539
+ }
419
540
  }
420
541
  }
542
+ // Iterations a later row settles on (an advisor's call, once it ran): priced again, replacing the earlier ones.
543
+ if (known && m.usage.iterations) {
544
+ const extra = iterationPoints(known.point.model, { ...known.u, iterations: m.usage.iterations }, known.point.ts);
545
+ if (JSON.stringify(extra) !== JSON.stringify(known.point.extra ?? []))
546
+ setExtra(known.point, extra);
547
+ }
421
548
  return;
422
549
  }
423
550
  if (seen !== "new")
@@ -450,10 +577,31 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
450
577
  if (c.changedOn)
451
578
  point.changedOn = c.changedOn;
452
579
  }
580
+ // The iterations its top-level usage leaves out, each at its own model (counted even when the request's own model has no price).
581
+ const extra = iterationPoints(point.model, u, ts);
582
+ if (extra.length)
583
+ setExtra(point, extra);
453
584
  out.push(point);
454
585
  if (typeof m.id === "string")
455
586
  byId.set(m.id, { point, u });
456
587
  });
588
+ // A reply none of whose rows settled (Claude Code 2.1.284-2.1.299's subagents): its output from its content, where that is more.
589
+ for (const [id, s] of settled) {
590
+ const known = byId.get(id);
591
+ if (s.stop || !known || s.oc <= known.point.output)
592
+ continue;
593
+ const p = known.point, more = s.oc - p.output;
594
+ p.output += more;
595
+ p.unsettled = more;
596
+ if (p.rates) {
597
+ p.usd += (more * p.rates.outputPerM) / 1e6;
598
+ if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd) {
599
+ p.modifiers = { ...requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers };
600
+ for (const x of p.extra ?? [])
601
+ addModifiers(p.modifiers, x.modifiers);
602
+ }
603
+ }
604
+ }
457
605
  return out;
458
606
  }
459
607
  /**
@@ -477,16 +625,88 @@ export function claudeUsageFiles(since, tops) {
477
625
  }
478
626
  /** How long before a period a session may have been last written and still have subagents running into it. */
479
627
  export const SUBAGENT_LOOKBACK_MS = 2 * 86_400_000;
628
+ /** A Claude Code entrypoint or version as a report may show it: a short token, never free text. */
629
+ const ENTRYPOINT = /^[a-z][\w.-]{0,39}$/i;
630
+ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(?:[-+][\w.]{1,20})?$/;
631
+ /**
632
+ * Which Claude Code wrote a transcript, and when that changed: every row
633
+ * carries `entrypoint` ("cli", "claude-desktop", "sdk-cli" for `claude -p`,
634
+ * "claude-vscode"...) and `version`; a record is kept only where either
635
+ * changes (a session resumed after an update), so a file has one or two.
636
+ */
637
+ export const HOST_ROWS = {
638
+ id: "host.1",
639
+ init: () => ({}),
640
+ line(line, row, out, st) {
641
+ if (!line.includes('"entrypoint"') && !line.includes('"version"'))
642
+ return;
643
+ let e;
644
+ try {
645
+ e = row();
646
+ }
647
+ catch {
648
+ return;
649
+ }
650
+ const ep = typeof e?.entrypoint === "string" && ENTRYPOINT.test(e.entrypoint) ? e.entrypoint : undefined;
651
+ const v = typeof e?.version === "string" && VERSION.test(e.version) ? e.version : undefined;
652
+ if ((!ep || ep === st.ep) && (!v || v === st.v))
653
+ return;
654
+ if (ep)
655
+ st.ep = ep;
656
+ if (v)
657
+ st.v = v;
658
+ const ts = Date.parse(String(e.timestamp ?? ""));
659
+ out.push({ ts: Number.isFinite(ts) ? ts : 0, ...(st.ep ? { ep: st.ep } : {}), ...(st.v ? { v: st.v } : {}) });
660
+ },
661
+ };
662
+ /** Each request's entrypoint and version: the transcript's own as of the request, else (a subagent's file with none) its session's. */
663
+ function stampHost(points, hosts, fallback) {
664
+ let h = 0;
665
+ for (const p of points) {
666
+ while (h + 1 < hosts.length && hosts[h + 1].ts <= p.ts)
667
+ h++;
668
+ const at = hosts[h] ?? fallback;
669
+ if (!at)
670
+ continue;
671
+ if (at.ep)
672
+ p.entrypoint = at.ep;
673
+ if (at.v)
674
+ p.version = at.v;
675
+ }
676
+ }
480
677
  /**
481
678
  * Every Claude Code request between `since` and `until`, main threads and
482
- * subagents alike (both draw on the same limits), each reply once.
679
+ * subagents alike (both draw on the same limits), each reply once, with
680
+ * the entrypoint and Claude Code version it was made from.
483
681
  */
484
682
  export function claudeUsage(since, until = Infinity, paths) {
485
683
  const out = [];
486
684
  const runRows = new Set();
487
- for (const { file } of claudeUsageFiles(since, paths)) {
685
+ const files = claudeUsageFiles(since, paths);
686
+ // One read of each transcript for both extractors.
687
+ prescan([{ paths: files.map((f) => f.file), extractors: [USAGE_ROWS, HOST_ROWS] }]);
688
+ const topHost = new Map();
689
+ for (const { file, top, subagent } of files) {
488
690
  try {
489
- out.push(...claudeFileUsage(file, since, until, runRows));
691
+ const points = claudeFileUsage(file, since, until, runRows);
692
+ let hosts = [];
693
+ try {
694
+ hosts = rowsOf(file, HOST_ROWS);
695
+ }
696
+ catch { /* no host: the points go unstamped */ }
697
+ if (!subagent && hosts.length)
698
+ topHost.set(top, hosts[0]);
699
+ // A subagent's file with no host of its own takes its session's (read here when the session itself is outside the period).
700
+ if (subagent && !hosts.length && !topHost.has(top)) {
701
+ try {
702
+ topHost.set(top, rowsOf(top, HOST_ROWS)[0]);
703
+ }
704
+ catch {
705
+ topHost.set(top, undefined);
706
+ }
707
+ }
708
+ stampHost(points, hosts, topHost.get(top));
709
+ out.push(...points);
490
710
  }
491
711
  catch {
492
712
  /* skip an unreadable transcript */
@@ -576,7 +796,10 @@ export function windowStatus(readings, now = Date.now()) {
576
796
  if (last.ts - start >= 10 * MIN)
577
797
  status.averagePerHour = Math.max(0, (last.pct / (last.ts - start)) * HOUR);
578
798
  }
579
- if (status.recentPerHour && status.recentPerHour > 0 && last.pct < 100) {
799
+ // A reading older than the pace's own stretch says nothing about now: no run-out time from it (it could already be past).
800
+ if (now - last.ts > lookback)
801
+ status.stale = true;
802
+ if (!status.stale && status.recentPerHour && status.recentPerHour > 0 && last.pct < 100) {
580
803
  status.runsOutAt = last.ts + ((100 - last.pct) / status.recentPerHour) * HOUR;
581
804
  status.beforeReset = last.resetsAt === undefined || status.runsOutAt < last.resetsAt;
582
805
  }
@@ -855,6 +1078,320 @@ export function fitWindow(readings, usage, stretchMs) {
855
1078
  fit.usable = true;
856
1079
  return fit;
857
1080
  }
1081
+ /** A window's figure is quoted from this many stretches and this many points matched by usage here. */
1082
+ const MIN_RESET_STRETCHES = 3;
1083
+ const MIN_RESET_PCT = 1;
1084
+ /** Above this relative error the figure is too loose to compare. */
1085
+ const MAX_RESET_REL_SE = 0.25;
1086
+ /** A move is reported from 1.5x either way, and only beyond this many standard errors (more inside a window, where the split is searched for). */
1087
+ const MIN_FACTOR = 1.5;
1088
+ const RESET_SIGMA = 3;
1089
+ const WITHIN_SIGMA = 4;
1090
+ /** Each side of a split inside a window holds at least this many stretches. */
1091
+ const MIN_SIDE = 4;
1092
+ /** A key with under this share of a window's dollars is pooled into "other". */
1093
+ const MIN_KEY_SHARE = 0.05;
1094
+ /** A key's own figure is quoted under this relative error. */
1095
+ const MAX_KEY_REL_SE = 0.3;
1096
+ /** Windows this long or longer are fitted per reset (Claude's weekly; Codex's weekly and monthly). */
1097
+ const PER_RESET_MIN_MS = 7 * DAY - HOUR;
1098
+ /** Ratio of sums, sum(u) / sum(d), and its relative standard error (the ratio estimator's, across stretches). */
1099
+ function ratio(u, d) {
1100
+ const n = u.length;
1101
+ const su = u.reduce((a, v) => a + v, 0), sd = d.reduce((a, v) => a + v, 0);
1102
+ if (!(sd > 0) || !(su > 0))
1103
+ return undefined;
1104
+ const r = su / sd;
1105
+ if (n < 2)
1106
+ return { r, relSe: Infinity };
1107
+ const dbar = sd / n;
1108
+ const s2 = u.reduce((a, v, i) => a + (v - r * d[i]) ** 2, 0) / (n - 1);
1109
+ return { r, relSe: Math.sqrt(s2 / n) / dbar / r };
1110
+ }
1111
+ /** Least squares through the origin with each coefficient's standard error; undefined when singular or with too few rows. */
1112
+ function olsSe(rows, y) {
1113
+ const n = rows.length, k = rows[0]?.length ?? 0;
1114
+ if (!k || n <= k + 1)
1115
+ return undefined;
1116
+ // [XᵀX | I], inverted in place by Gauss-Jordan.
1117
+ const a = Array.from({ length: k }, (_, p) => [...Array.from({ length: k }, (_, q) => rows.reduce((s, r) => s + r[p] * r[q], 0)), ...Array.from({ length: k }, (_, q) => (p === q ? 1 : 0))]);
1118
+ for (let c = 0; c < k; c++) {
1119
+ let piv = c;
1120
+ for (let r = c + 1; r < k; r++)
1121
+ if (Math.abs(a[r][c]) > Math.abs(a[piv][c]))
1122
+ piv = r;
1123
+ if (Math.abs(a[piv][c]) < 1e-12 * Math.max(1e-300, ...a.map((row) => Math.abs(row[c]))))
1124
+ return undefined;
1125
+ [a[c], a[piv]] = [a[piv], a[c]];
1126
+ const d = a[c][c];
1127
+ for (let q = 0; q < 2 * k; q++)
1128
+ a[c][q] /= d;
1129
+ for (let r = 0; r < k; r++) {
1130
+ if (r === c)
1131
+ continue;
1132
+ const f = a[r][c];
1133
+ for (let q = 0; q < 2 * k; q++)
1134
+ a[r][q] -= f * a[c][q];
1135
+ }
1136
+ }
1137
+ const inv = a.map((row) => row.slice(k));
1138
+ const xty = Array.from({ length: k }, (_, p) => rows.reduce((s, r, i) => s + r[p] * y[i], 0));
1139
+ const coef = inv.map((row) => row.reduce((s, v, q) => s + v * xty[q], 0));
1140
+ const sse = rows.reduce((s, r, i) => s + (y[i] - r.reduce((t, v, j) => t + v * coef[j], 0)) ** 2, 0);
1141
+ const s2 = sse / (n - k);
1142
+ return { coef, se: inv.map((row, j) => Math.sqrt(Math.max(0, s2 * row[j]))) };
1143
+ }
1144
+ const tokensOf = (p) => p.input + p.read + p.write + p.output;
1145
+ /**
1146
+ * Shares by `keyOf` over the stretches, and, with two keys or more and
1147
+ * enough stretches, each key's own dollars per 1%: the rise in each stretch
1148
+ * fitted on each key's dollars in it. A key's figure is kept only when it is
1149
+ * known to ±30%; a single key's figure is the window's own.
1150
+ */
1151
+ function splitBy(segments, inSeg, keyOf, whole) {
1152
+ const totals = new Map();
1153
+ let all = 0;
1154
+ for (const pts of inSeg)
1155
+ for (const p of pts) {
1156
+ const k = keyOf(p);
1157
+ const t = totals.get(k) ?? totals.set(k, { key: k, usd: 0, tokens: 0, requests: 0, share: 0 }).get(k);
1158
+ t.usd += p.usd;
1159
+ t.tokens += tokensOf(p);
1160
+ t.requests++;
1161
+ all += p.usd;
1162
+ }
1163
+ let list = [...totals.values()].sort((a, b) => b.usd - a.usd);
1164
+ // Small keys pooled, so the fit has a column only for what can be told apart.
1165
+ const small = list.filter((t) => all > 0 && t.usd / all < MIN_KEY_SHARE);
1166
+ if (small.length > 1) {
1167
+ const other = { key: "other", usd: 0, tokens: 0, requests: 0, share: 0 };
1168
+ for (const t of small) {
1169
+ other.usd += t.usd;
1170
+ other.tokens += t.tokens;
1171
+ other.requests += t.requests;
1172
+ }
1173
+ list = [...list.filter((t) => !small.includes(t)), other];
1174
+ }
1175
+ for (const t of list)
1176
+ t.share = all > 0 ? t.usd / all : 0;
1177
+ if (list.length === 1 && whole) {
1178
+ list[0].usdPerPct = whole.r;
1179
+ list[0].relSe = whole.relSe;
1180
+ }
1181
+ else if (list.length > 1 && segments.length >= MIN_SEGMENTS) {
1182
+ const col = new Map(list.map((t, i) => [t.key, i]));
1183
+ const otherCol = col.get("other");
1184
+ const rows = inSeg.map((pts) => {
1185
+ const r = new Array(list.length).fill(0);
1186
+ for (const p of pts)
1187
+ r[col.get(keyOf(p)) ?? otherCol ?? 0] += p.usd;
1188
+ return r;
1189
+ });
1190
+ const fit = olsSe(rows, segments.map((s) => s.dpct));
1191
+ if (fit)
1192
+ list.forEach((t, j) => {
1193
+ const k = fit.coef[j], se = fit.se[j];
1194
+ if (k > 0 && se / k <= MAX_KEY_REL_SE) {
1195
+ t.usdPerPct = 1 / k;
1196
+ t.relSe = se / k;
1197
+ }
1198
+ });
1199
+ }
1200
+ return list;
1201
+ }
1202
+ /** One window's readings cut at each reset: the periods, oldest first. */
1203
+ function periodsOf(readings) {
1204
+ const clean = cleanReadings(readings);
1205
+ const res = resolutionOf(clean);
1206
+ const out = [];
1207
+ for (const r of clean) {
1208
+ const cur = out[out.length - 1];
1209
+ if (cur && samePeriod(cur[cur.length - 1], r, res))
1210
+ cur.push(r);
1211
+ else
1212
+ out.push([r]);
1213
+ }
1214
+ return out;
1215
+ }
1216
+ /**
1217
+ * Each reset window of one weekly window's readings: % used, dollars and
1218
+ * tokens per 1% (over the stretches with usage here; rises with none are
1219
+ * counted apart), the split by entrypoint and by model, and the Claude Code
1220
+ * versions. `usage` in time order.
1221
+ */
1222
+ export function resetWindowsOf(readings, usage, opts = {}) {
1223
+ const now = opts.now ?? Date.now();
1224
+ const out = [];
1225
+ for (const period of periodsOf(readings)) {
1226
+ const first = period[0], last = period[period.length - 1];
1227
+ const windowMs = last.windowMs ?? 7 * DAY;
1228
+ const resetsAt = last.resetsAt ?? first.ts + windowMs;
1229
+ const { segments, elsewherePct } = segmentsOf(period, usage, opts.stretchMs);
1230
+ // The requests of each stretch: both lists are in time order.
1231
+ const inSeg = segments.map(() => []);
1232
+ let g = 0;
1233
+ for (const p of usage) {
1234
+ while (g < segments.length && segments[g].to < p.ts)
1235
+ g++;
1236
+ if (g >= segments.length)
1237
+ break;
1238
+ if (p.ts > segments[g].from)
1239
+ inSeg[g].push(p);
1240
+ }
1241
+ const usd = segments.reduce((a, s) => a + s.usd, 0);
1242
+ const tokens = inSeg.reduce((a, pts) => a + pts.reduce((b, p) => b + tokensOf(p), 0), 0);
1243
+ const pctMatched = segments.reduce((a, s) => a + s.dpct, 0);
1244
+ const w = {
1245
+ window: last.window,
1246
+ label: windowLabel(last.window, last.windowMs),
1247
+ app: last.app,
1248
+ start: resetsAt - windowMs,
1249
+ resetsAt,
1250
+ current: resetsAt > now,
1251
+ readings: period.length,
1252
+ firstReading: first.ts,
1253
+ lastReading: last.ts,
1254
+ pctUsed: Math.max(...period.map((r) => r.pct)),
1255
+ pctMatched,
1256
+ pctElsewhere: elsewherePct,
1257
+ stretches: segments.length,
1258
+ requests: segments.reduce((a, s) => a + s.requests, 0),
1259
+ usd,
1260
+ tokens,
1261
+ byEntrypoint: [],
1262
+ byModel: [],
1263
+ versions: [],
1264
+ };
1265
+ const fit = ratio(segments.map((s) => s.usd), segments.map((s) => s.dpct));
1266
+ if (segments.length < MIN_RESET_STRETCHES)
1267
+ w.why = `${segments.length} stretch${segments.length === 1 ? "" : "es"} of readings with usage here; ${MIN_RESET_STRETCHES} make a figure`;
1268
+ else if (pctMatched < MIN_RESET_PCT)
1269
+ w.why = `the limit rose ${pts(pctMatched)} points beside usage here; ${MIN_RESET_PCT} make a figure`;
1270
+ else if (!fit || !(usd > 0))
1271
+ w.why = "no priced usage beside the rises";
1272
+ else {
1273
+ w.usdPerPct = fit.r;
1274
+ w.tokensPerPct = tokens / pctMatched;
1275
+ w.relSe = fit.relSe;
1276
+ if (!(fit.relSe <= MAX_RESET_REL_SE))
1277
+ w.why = `known only to ±${Number.isFinite(fit.relSe) ? Math.round(fit.relSe * 100) : "∞"}%: the rises follow the usage here loosely`;
1278
+ }
1279
+ const quoted = w.usdPerPct !== undefined && !w.why ? fit : undefined;
1280
+ w.byEntrypoint = splitBy(segments, inSeg, (p) => p.entrypoint ?? (p.app === "codex" ? "codex" : "unknown"), quoted);
1281
+ w.byModel = splitBy(segments, inSeg, (p) => reportModel(p.model), quoted);
1282
+ w.versions = [...new Set(inSeg.flat().map((p) => p.version).filter((v) => !!v))].sort(compareVersions);
1283
+ out.push(w);
1284
+ }
1285
+ return out;
1286
+ }
1287
+ /** "2.1.9" before "2.1.10". */
1288
+ function compareVersions(a, b) {
1289
+ const pa = a.split(/[.-]/).map(Number), pb = b.split(/[.-]/).map(Number);
1290
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1291
+ const d = (pa[i] || 0) - (pb[i] || 0);
1292
+ if (d)
1293
+ return d;
1294
+ }
1295
+ return a.localeCompare(b);
1296
+ }
1297
+ /**
1298
+ * A model id as a report may carry it: a model's name, never a cloud
1299
+ * resource (a Bedrock ARN holds an account number) or anything path-shaped.
1300
+ */
1301
+ export function reportModel(model) {
1302
+ if (!model)
1303
+ return "unknown";
1304
+ if (!/^[a-z][\w.:@[\]-]{0,59}$/i.test(model) || /^arn:/i.test(model) || /\d{8,}/.test(model))
1305
+ return "custom model id";
1306
+ return model;
1307
+ }
1308
+ /** The two sides of a move, each a ratio with its error: how many standard errors apart (log scale). */
1309
+ function sigmaOf(a, b, factor) {
1310
+ const se = Math.sqrt(a.relSe ** 2 + b.relSe ** 2);
1311
+ return se > 0 ? Math.abs(Math.log(factor)) / se : Infinity;
1312
+ }
1313
+ /**
1314
+ * Where what 1% costs moved: between consecutive windows that each have a
1315
+ * figure (dated at the reset), and inside a window at the one split of its
1316
+ * stretches that separates two rates best (dated at that stretch). Reported
1317
+ * from a 1.5x move either way, beyond 3 standard errors between windows and
1318
+ * 4 inside one (the split is searched for).
1319
+ */
1320
+ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1321
+ const out = [];
1322
+ const quoted = windows.filter((w) => w.usdPerPct !== undefined && w.relSe !== undefined && Number.isFinite(w.relSe) && !w.why);
1323
+ for (let i = 1; i < quoted.length; i++) {
1324
+ const a = quoted[i - 1], b = quoted[i];
1325
+ if (a.window !== b.window)
1326
+ continue;
1327
+ const factor = b.usdPerPct / a.usdPerPct;
1328
+ const sigma = sigmaOf({ relSe: a.relSe }, { relSe: b.relSe }, factor);
1329
+ if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < RESET_SIGMA)
1330
+ continue;
1331
+ out.push({
1332
+ window: b.window, label: b.label, kind: "reset", at: b.start, prevEnd: a.resetsAt,
1333
+ usdPerPctBefore: a.usdPerPct, usdPerPctAfter: b.usdPerPct, tokensPerPctBefore: a.tokensPerPct, tokensPerPctAfter: b.tokensPerPct,
1334
+ factor, sigma, versionsBefore: a.versions, versionsAfter: b.versions,
1335
+ });
1336
+ }
1337
+ // Inside a window: its own stretches again, split once where two rates fit best.
1338
+ const periods = readings.length ? periodsOf(readings) : [];
1339
+ // Every window with a figure, loose ones too: a move inside a window is what makes its figure loose.
1340
+ for (const w of windows.filter((x) => x.usdPerPct !== undefined)) {
1341
+ const period = periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1342
+ if (!period)
1343
+ continue;
1344
+ const segs = segmentsOf(period, usage, stretchMs).segments;
1345
+ if (segs.length < 2 * MIN_SIDE)
1346
+ continue;
1347
+ const u = segs.map((s) => s.usd), d = segs.map((s) => s.dpct);
1348
+ const sse = (from, to) => {
1349
+ const r = ratio(u.slice(from, to), d.slice(from, to));
1350
+ return r ? u.slice(from, to).reduce((a, v, i) => a + (v - r.r * d[from + i]) ** 2, 0) : Infinity;
1351
+ };
1352
+ let best;
1353
+ for (let s = MIN_SIDE; s <= segs.length - MIN_SIDE; s++) {
1354
+ const cost = sse(0, s) + sse(s, segs.length);
1355
+ if (!best || cost < best.cost)
1356
+ best = { at: s, cost };
1357
+ }
1358
+ if (!best)
1359
+ continue;
1360
+ const before = ratio(u.slice(0, best.at), d.slice(0, best.at)), after = ratio(u.slice(best.at), d.slice(best.at));
1361
+ if (!before || !after)
1362
+ continue;
1363
+ const factor = after.r / before.r;
1364
+ const sigma = sigmaOf(before, after, factor);
1365
+ if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < WITHIN_SIGMA)
1366
+ continue;
1367
+ const tok = (from, to) => {
1368
+ const t = usage.filter((p) => p.ts > segs[from].from && p.ts <= segs[to - 1].to).reduce((a, p) => a + tokensOf(p), 0);
1369
+ const pct = d.slice(from, to).reduce((a, v) => a + v, 0);
1370
+ return pct > 0 ? t / pct : undefined;
1371
+ };
1372
+ const vers = (from, to) => [...new Set(usage.filter((p) => p.ts > segs[from].from && p.ts <= segs[to - 1].to).map((p) => p.version).filter((v) => !!v))].sort(compareVersions);
1373
+ out.push({
1374
+ window: w.window, label: w.label, kind: "within", at: segs[best.at].from,
1375
+ usdPerPctBefore: before.r, usdPerPctAfter: after.r, tokensPerPctBefore: tok(0, best.at), tokensPerPctAfter: tok(best.at, segs.length),
1376
+ factor, sigma, versionsBefore: vers(0, best.at), versionsAfter: vers(best.at, segs.length),
1377
+ });
1378
+ }
1379
+ return out.sort((a, b) => a.at - b.at);
1380
+ }
1381
+ /** Every weekly window's resets and the moves between them, for one app's readings and usage. */
1382
+ function perReset(readings, usage, now) {
1383
+ const resets = [];
1384
+ const changes = [];
1385
+ for (const [, rs] of byWindow(readings)) {
1386
+ const ms = rs[rs.length - 1]?.windowMs ?? 0;
1387
+ if (ms < PER_RESET_MIN_MS)
1388
+ continue;
1389
+ const ws = resetWindowsOf(rs, usage, { now });
1390
+ resets.push(...ws);
1391
+ changes.push(...slopeChanges(ws, usage, rs));
1392
+ }
1393
+ return { resets, changes };
1394
+ }
858
1395
  function byWindow(readings) {
859
1396
  const m = new Map();
860
1397
  for (const r of readings) {
@@ -879,6 +1416,11 @@ export function limitsReport(days = 30, opts = {}) {
879
1416
  const fits = [];
880
1417
  // Claude usage is read only when there are readings to fit it against, and only over their span.
881
1418
  const claudeUse = claude.length >= 2 ? claudeUsage(claude[0].ts - HOUR, claude[claude.length - 1].ts, opts.claudePaths) : [];
1419
+ const claudeReset = perReset(claude, claudeUse, now);
1420
+ const codexReset = perReset(codex.readings, codex.usage, now);
1421
+ const claudeSources = {};
1422
+ for (const r of claude)
1423
+ claudeSources[r.source ?? "earlier"] = (claudeSources[r.source ?? "earlier"] ?? 0) + 1;
882
1424
  for (const [, rs] of byWindow(claude)) {
883
1425
  const s = windowStatus(rs, now);
884
1426
  if (s)
@@ -895,7 +1437,24 @@ export function limitsReport(days = 30, opts = {}) {
895
1437
  if (f)
896
1438
  fits.push(f);
897
1439
  }
898
- return { days, now, claudeLog: logPath, claudeReadings: claude.length, codexReadings: codex.readings.length, windows, fits };
1440
+ return {
1441
+ days, now, claudeLog: logPath, claudeReadings: claude.length, codexReadings: codex.readings.length, windows, fits,
1442
+ resets: [...claudeReset.resets, ...codexReset.resets],
1443
+ changes: [...claudeReset.changes, ...codexReset.changes],
1444
+ claudeWindows: CLAUDE_WINDOWS.filter((w) => claude.some((r) => r.window === w)),
1445
+ claudeSources,
1446
+ };
1447
+ }
1448
+ /**
1449
+ * The per-reset view of the limits, for a pane or a script: every window's
1450
+ * current state, every weekly window with its dollars and tokens per 1%
1451
+ * (by entrypoint and model where the readings allow) and every move in that
1452
+ * figure, dated. Reads the limits ledger, Codex's rollouts and the
1453
+ * transcripts over the readings' span; never writes.
1454
+ */
1455
+ export function limitsByReset(days = 30, opts = {}) {
1456
+ const r = limitsReport(days, opts);
1457
+ return { now: r.now, windows: r.windows, resets: r.resets, changes: r.changes, noFiveHour: r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day", readings: r.claudeReadings + r.codexReadings };
899
1458
  }
900
1459
  /** The Claude fit to quote savings in: the weekly window first (savings are weekly), then the 5-hour one. */
901
1460
  export function claudeLimitFit(r) {
@@ -953,10 +1512,60 @@ function clock(ms, now) {
953
1512
  return Math.abs(ms - now) < 20 * HOUR ? t : `${d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} ${t}`;
954
1513
  }
955
1514
  const pts = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
1515
+ /**
1516
+ * The one line that says how to start recording Claude readings: the
1517
+ * plugin's mod (after each turn, in the Desktop app, the terminal and VS
1518
+ * Code), or the autopilot proxy (from the API's rate-limit headers).
1519
+ */
1520
+ export const HOW_TO_RECORD = "To record them: `context-doctor install` (the plugin's mod writes them after each turn, Claude Code 2.1.286+; `install --statusline` on older ones), or `context-doctor autopilot on` (its proxy reads them from the API's replies).";
1521
+ /** "2026-11-03" and "2026-11-03 14:00 UTC": the same date for whoever reads a pasted report. */
1522
+ const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
1523
+ const utcMinute = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;
1524
+ /** "$25.10", "$4.02", "$130". */
1525
+ const dollars = (v) => (v >= 100 ? `$${Math.round(v)}` : `$${v.toFixed(2)}`);
1526
+ /** "21.0M", "450k". */
1527
+ const tokenCount = (v) => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
1528
+ const plusMinus = (relSe) => (relSe !== undefined && Number.isFinite(relSe) ? ` ±${Math.max(1, Math.round(relSe * 100))}%` : "");
1529
+ /** "2.1.321", "2.1.321 to 2.1.325 (3)". */
1530
+ const versionSpan = (vs) => (!vs.length ? "unknown" : vs.length === 1 ? vs[0] : `${vs[0]} to ${vs[vs.length - 1]}${vs.length > 2 ? ` (${vs.length})` : ""}`);
1531
+ /** "claude-desktop 88%, cli 12%". */
1532
+ const sharesLine = (list) => list.map((t) => `${t.key} ${Math.round(t.share * 100)}%`).join(", ");
1533
+ /** Two windows of the same kind with a figure each: something to compare. */
1534
+ const comparable = (ws) => {
1535
+ const seen = new Map();
1536
+ for (const w of ws)
1537
+ if (w.usdPerPct !== undefined && !w.why)
1538
+ seen.set(w.window, (seen.get(w.window) ?? 0) + 1);
1539
+ return [...seen.values()].some((n) => n > 1);
1540
+ };
1541
+ /** Two keys or more with a real share of the dollars: a split worth a line. */
1542
+ const mixed = (list) => list.filter((t) => t.share >= MIN_KEY_SHARE).length >= 2;
1543
+ /** A move in words: when, from what to what, how many times, and the Claude Code versions either side. */
1544
+ function changeLine(c) {
1545
+ const when = c.kind === "reset"
1546
+ ? c.prevEnd !== undefined && Math.abs(c.prevEnd - c.at) > SAME_RESET_MS
1547
+ ? `between the reset of ${utcMinute(c.prevEnd)} and the window from ${utcMinute(c.at)}`
1548
+ : `at the reset of ${utcMinute(c.at)}`
1549
+ : `within the window, around ${utcMinute(c.at)}`;
1550
+ const times = c.factor < 1 ? `${(1 / c.factor).toFixed(1)}x less use per 1%: the limit drains faster` : `${c.factor.toFixed(1)}x more use per 1%: the limit drains slower`;
1551
+ const tok = c.tokensPerPctBefore !== undefined && c.tokensPerPctAfter !== undefined ? `; tokens per 1% ${tokenCount(c.tokensPerPctBefore)} to ${tokenCount(c.tokensPerPctAfter)}` : "";
1552
+ const ver = versionSpan(c.versionsBefore) !== versionSpan(c.versionsAfter) ? `; Claude Code ${versionSpan(c.versionsBefore)} before, ${versionSpan(c.versionsAfter)} after` : "";
1553
+ return `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use (${times})${tok}${ver}.`;
1554
+ }
1555
+ /** Each key's own dollars per 1%, where the fit told them apart: "sdk-cli $13.90 ±9%, cli $25.00 ±7% (sdk-cli drains 1.8x per dollar)". */
1556
+ function splitLine(list) {
1557
+ const known = list.filter((t) => t.usdPerPct !== undefined);
1558
+ if (known.length < 2)
1559
+ return undefined;
1560
+ const sorted = [...known].sort((a, b) => a.usdPerPct - b.usdPerPct);
1561
+ const fast = sorted[0], slow = sorted[sorted.length - 1];
1562
+ const ratio = slow.usdPerPct / fast.usdPerPct;
1563
+ return `${sorted.map((t) => `${t.key} ${dollars(t.usdPerPct)}${plusMinus(t.relSe)}`).join(", ")} per 1%${ratio >= 1.1 ? ` (${fast.key} drains ${ratio.toFixed(1)}x per dollar against ${slow.key})` : ""}`;
1564
+ }
956
1565
  export function renderLimits(r) {
957
1566
  const out = ["USAGE LIMITS", "═".repeat(60)];
958
- if (!r.windows.length) {
959
- out.push("No limit readings yet.", "", "Claude (Pro and Max): `context-doctor statusline` records the 5-hour and weekly", "windows as Claude Code reports them. Set it up with", " context-doctor install --statusline", `(or keep your own status line and pipe its input to it too). Readings: ${r.claudeLog.replace(homedir(), "~")}`, "Codex: read from ~/.codex/sessions; none found in the period.");
1567
+ if (!r.windows.length && !r.resets.length) {
1568
+ out.push(`No limit readings yet. ${HOW_TO_RECORD}`, "", `Claude readings are kept in ${r.claudeLog.replace(homedir(), "~")}; Codex's are read from ~/.codex/sessions (none in the period).`);
960
1569
  return out.join("\n");
961
1570
  }
962
1571
  for (const s of r.windows) {
@@ -968,7 +1577,9 @@ export function renderLimits(r) {
968
1577
  }
969
1578
  if (s.resetsAt)
970
1579
  out.push(` Resets ${clock(s.resetsAt, r.now)} (in ${hm(s.resetsAt - r.now)}).`);
971
- if (s.recentPerHour === undefined)
1580
+ if (s.stale)
1581
+ out.push(` The newest reading is ${hm(age)} old: no pace or run-out time from it until a new one comes in.`);
1582
+ else if (s.recentPerHour === undefined)
972
1583
  out.push(" Pace: not enough recent readings.");
973
1584
  else if (s.recentPerHour === 0)
974
1585
  out.push(" Pace: no rise over the recent readings.");
@@ -982,6 +1593,43 @@ export function renderLimits(r) {
982
1593
  }
983
1594
  }
984
1595
  }
1596
+ if (r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day") {
1597
+ out.push("", "No 5-hour window in Claude's readings: a plan without one (Ultra), so the weekly window is the limit.");
1598
+ }
1599
+ if (r.resets.length) {
1600
+ out.push("", "Each weekly (or longer) window, reset to reset: API-equivalent use per 1% (UTC dates)");
1601
+ out.push("─".repeat(60));
1602
+ for (const w of r.resets) {
1603
+ const head = `${w.label}, ${utcDay(w.start)} to ${utcDay(w.resetsAt)}${w.current ? " (now)" : ""}: ${pts(w.pctUsed)}% used`;
1604
+ if (w.usdPerPct !== undefined && !w.why)
1605
+ out.push(`${head}; ${dollars(w.usdPerPct)} per 1%${plusMinus(w.relSe)}, ${tokenCount(w.tokensPerPct ?? 0)} tokens per 1%`);
1606
+ else
1607
+ out.push(`${head}; no figure: ${w.why}`);
1608
+ if (w.pctElsewhere > 0)
1609
+ out.push(` ${pts(w.pctElsewhere)} points rose with no usage here (used elsewhere), left out.`);
1610
+ if (w.byEntrypoint.length)
1611
+ out.push(` By entrypoint (share of dollars): ${sharesLine(w.byEntrypoint)}`);
1612
+ const ep = splitLine(w.byEntrypoint);
1613
+ if (ep)
1614
+ out.push(` ${ep}`);
1615
+ if (mixed(w.byModel))
1616
+ out.push(` By model: ${sharesLine(w.byModel)}`);
1617
+ const md = splitLine(w.byModel);
1618
+ if (md)
1619
+ out.push(` ${md}`);
1620
+ if (w.versions.length)
1621
+ out.push(` Claude Code ${versionSpan(w.versions)}`);
1622
+ }
1623
+ if (r.changes.length) {
1624
+ out.push("", "What 1% buys moved:");
1625
+ for (const c of r.changes)
1626
+ out.push(` ${changeLine(c)}`);
1627
+ }
1628
+ else if (comparable(r.resets)) {
1629
+ out.push("", "What 1% buys held steady across these windows (no move of 1.5x or more beyond the error).");
1630
+ }
1631
+ out.push("`context-doctor limits --report` prints this as a block to paste into a bug report.");
1632
+ }
985
1633
  out.push("", "What 1M tokens cost in each limit (fitted on your own readings)");
986
1634
  out.push("─".repeat(60));
987
1635
  for (const f of r.fits) {
@@ -998,7 +1646,65 @@ export function renderLimits(r) {
998
1646
  out.push(` rate known to ±${Math.round((f.byPrice.relSe ?? 0) * 100)}%; explains ${Math.round(Math.max(0, f.byPrice.r2) * 100)}% of the rises; predicts each within ±${pts(f.byPrice.looRmse)} points (${Math.round(f.byPrice.relError * 100)}%)`);
999
1647
  }
1000
1648
  out.push(f.usable ? " Good enough to show savings in this limit (savings, cache-misses, compact-window)." : ` Too thin to quote: ${f.why}.`);
1649
+ if (r.changes.some((c) => c.window === f.window))
1650
+ out.push(" This fit spans the move in what 1% buys (above): read the per-window figures.");
1651
+ }
1652
+ out.push("", "Readings: Claude Code's (Pro, Max and Ultra; 0.1% steps) from the plugin's mod,", "the status line or the proxy, and Codex's rollouts (whole percents). Usage", "elsewhere (the web app, another computer) moves the limit without a transcript", "here, so it widens the error.");
1653
+ return out.join("\n");
1654
+ }
1655
+ /**
1656
+ * `limits --report`: a block to paste into a GitHub issue. Per weekly
1657
+ * window: % used, dollars and tokens per 1%, the split by entrypoint and
1658
+ * model, Claude Code's versions, and every move in what 1% buys, dated. It
1659
+ * carries figures, dates, model and entrypoint names and version numbers
1660
+ * only: no prompt, no path, no session or account id (reportModel masks a
1661
+ * model id that is a cloud resource).
1662
+ */
1663
+ export function renderLimitsReport(r) {
1664
+ if (!r.windows.length && !r.resets.length)
1665
+ return `No limit readings yet. ${HOW_TO_RECORD}`;
1666
+ const out = ["### Usage limits, measured on my machine", ""];
1667
+ const versions = [...new Set(r.resets.filter((w) => w.app === "claude").flatMap((w) => w.versions))].sort(compareVersions);
1668
+ const claude = r.claudeWindows.length
1669
+ ? r.claudeWindows.includes("five_hour") ? "weekly and 5-hour" : "weekly only (no 5-hour window in the readings)"
1670
+ : "none";
1671
+ const srcNames = { mod: "the plugin's mod", statusline: "the status line", proxy: "the proxy", earlier: "an earlier recorder" };
1672
+ const sources = Object.entries(r.claudeSources).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} from ${srcNames[k] ?? k}`).join(", ");
1673
+ out.push(`- Measured with context-doctor ${PROXY_VERSION} (\`context-doctor limits --report\`), ${r.days} days to ${utcMinute(r.now)}`, `- Claude windows read: ${claude}${r.claudeReadings ? `; ${r.claudeReadings} readings (${sources})` : ""}${r.codexReadings ? `; Codex: ${r.codexReadings} readings` : ""}`, ...(r.claudeReadings ? [`- Claude Code version${versions.length === 1 ? "" : "s"}: ${versions.length ? versions.join(", ") : "unknown"}`] : []), "- Dollars are API-equivalent: this machine's requests priced at API list rates, not a bill. % matched: the rise in stretches with usage here; the rest came with no transcript here (claude.ai, another computer).", "");
1674
+ if (r.resets.length) {
1675
+ out.push("| Window, reset to reset (UTC) | % used | % matched | $ per 1% | Tokens per 1% | By entrypoint ($ share) | Claude Code |", "|---|---|---|---|---|---|---|");
1676
+ for (const w of r.resets) {
1677
+ const fig = w.usdPerPct !== undefined && !w.why;
1678
+ out.push(`| ${w.label.replace(/ weekly$/, "")} ${utcDay(w.start)} to ${utcDay(w.resetsAt)}${w.current ? " (now)" : ""} | ${pts(w.pctUsed)} | ${pts(w.pctMatched)} | ${fig ? `${dollars(w.usdPerPct)}${plusMinus(w.relSe)}` : "n/a"} | ${fig ? tokenCount(w.tokensPerPct ?? 0) : "n/a"} | ${sharesLine(w.byEntrypoint) || "none"} | ${w.app === "claude" ? versionSpan(w.versions) : "n/a"} |`);
1679
+ }
1680
+ out.push("");
1681
+ out.push(r.changes.length ? "**What 1% buys moved:**" : comparable(r.resets) ? "**What 1% buys:** no move of 1.5x or more beyond the error between these windows." : "**What 1% buys:** fewer than two windows with a figure, nothing to compare yet.");
1682
+ for (const c of r.changes)
1683
+ out.push(`- ${changeLine(c)}`);
1684
+ const splits = r.resets.flatMap((w) => {
1685
+ const lines = [];
1686
+ const ep = splitLine(w.byEntrypoint), md = splitLine(w.byModel);
1687
+ if (ep)
1688
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, by entrypoint: ${ep}`);
1689
+ if (md)
1690
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, by model: ${md}`);
1691
+ if (!md && mixed(w.byModel))
1692
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, models ($ share): ${sharesLine(w.byModel)}`);
1693
+ return lines;
1694
+ });
1695
+ if (splits.length)
1696
+ out.push("", "**Per entrypoint and model** (each one's own $ per 1%, where the stretches tell them apart):", ...splits);
1697
+ const thin = r.resets.filter((w) => w.why);
1698
+ if (thin.length)
1699
+ out.push("", ...thin.map((w) => `- No figure for ${utcDay(w.start)} to ${utcDay(w.resetsAt)}: ${w.why}.`));
1700
+ }
1701
+ else {
1702
+ out.push("No weekly window with readings in the period yet.");
1001
1703
  }
1002
- out.push("", "Readings: Claude Code's status line input (Pro/Max, 0.1% steps) and Codex's", "rollouts (whole percents). Usage elsewhere (the web app, another computer)", "moves the limit without a transcript here, so it widens the error.");
1704
+ const now5h = r.windows.find((w) => w.window === "five_hour");
1705
+ const nowWeek = r.windows.find((w) => w.window === "seven_day");
1706
+ if (nowWeek || now5h)
1707
+ out.push("", `Now: ${[nowWeek ? `weekly ${pts(nowWeek.pct)}%` : "", now5h ? `5-hour ${pts(now5h.pct)}%` : ""].filter(Boolean).join(", ")}.`);
1708
+ out.push("", "No prompts, file paths, session or account ids are included.");
1003
1709
  return out.join("\n");
1004
1710
  }