SLOPSHOPPER

Token Almanac

Session and machine-wide token usage, plan limit meters with reset countdowns, and an estimate of how long each limit lasts, fitted to your own history.

panebandcommandprocesstimer
v0.7.1MITupdated 2026-10-14CookPiu/token-almanac
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · token-almanac
│ ┃ Token usage ✕ › fix the failing auth test and add an audit log call │ ┃ [ This session ] [ This machine ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ 5-hour ─────────────────────────────── ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ $0.42 99k 49% ⏺ Bash(bun test) │ ┃ API-equivalent tokens of 200k context ⎿ 3 pass, 1 fail │ ┃ │ ┃ Makeup by API-equivalent cost ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ███████████████████████████████ │ ┃ ● output 33% ● cache write 38% ● cache rea ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Turns last 1 · peak #1 99k › /token-almanac │ ┃ █ ⎿ token-almanac: Token usage pane opened. │ ┃ │ ┃ Covers this session's 0m, subagents included │ ┃ · API-equivalent at list prices │ ┃ │ ┃ [ Close ] │ ◆ $0.42 · context 49% │ 5-hour 31% [ Details ] [ Hide ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
◆ $0.42 · context 49% │ 5-hour 31% [ Details ] [ Hide ]
Pane · Token usage
[ This session ] [ This machine ] 5-hour ──────────────────────────────── 31% $0.42 99k 49% 1 API-equivalent tokens of 200k context turns Makeup by API-equivalent cost ███████████████████████████████ ● output 33% ● cache write 38% ● cache read 20% ● input 9 Turns last 1 · peak #1 99k █ Covers this session's 0m, subagents included · API-equivalent at list prices [ Close ]
README

token-almanac

A Claude Code mod that shows how much of your plan's usage limits you have used, when each limit resets, and how long the rest is likely to last. It also counts the current session's tokens and sums every transcript on your machine into daily, per-project and per-model views, priced at API list prices.

中文说明

What it shows

Band above the prompt: the session's cost and context use, and each limit window (5-hour, weekly) with its percent and, when it will fill before its reset, how soon. It has buttons to open the pane or hide the band.

Pane (/token-almanac, or the band's button), with two views:

ViewContents
This sessionLimit rings, cost, tokens, context, turns; per-turn chart (subagent turns folded into the turn that started them); under Show breakdown, token makeup by API-equivalent cost and the per-model split
This machineLimit rings, each with the API-equivalent dollars a full window holds and what is left; your plan, picked from a list; 30-day or all-time totals; daily chart by model; under Show breakdown, top models and projects, a capacity card per window (whether it fills before the reset at your usual hourly pace, confidence, past limit hits on your plan on a dollar scale) and the estimate details as interval plots, with any earlier plan inferred from the history

Each ring shows the share used, a paler arc for where the window is headed by its reset, and a tick for how far through the window the clock is. In the terminal the same figures are written as text, with meters in place of the rings and the capacity table under them.

The UI is in English or Chinese, picked from the language option, then Claude Code's language setting, then LC_ALL / LANG, then the system locale. It renders in the terminal, the desktop app, VS Code and mobile.

Install

Requires Claude Code 2.1.287 or later (mods support). The machine view needs Node.js 18 or later on PATH, or set its path in the nodePath option.

In a Claude Code session, add this repository as a marketplace, then install from it:

/plugin marketplace add CookPiu/token-almanac
/plugin install token-almanac@token-almanac

Or from a shell, in one step:

claude plugin install token-almanac --marketplace CookPiu/token-almanac

Installed at user scope (the default), it also loads in sessions the desktop app starts. Run /plugin marketplace update token-almanac to pick up new versions.

Options

Set them in /config under the plugin:

OptionDefaultMeaning
languageautoauto, en or zh
nodePathnodeThe Node.js used to read transcript history
motiononon lets meters and charts glide to new values and a spinner turn while scanning; off draws them still

To price models at other rates (Bedrock, Vertex, a gateway) or to add models the built-in table lacks, write <config>/token-almanac/prices.json, with prices in USD per million tokens as [input, output, cache read, cache write 5m, cache write 1h], keyed by model id or id prefix:

{ "claude-opus-5-5": [4, 20, 0.2, 5, 8] }

<config> is CLAUDE_CONFIG_DIR, or ~/.claude.

How the estimate works

Claude Code reports each limit only as a percent and a reset time. To turn that into "how much is left", the mod sums what this machine spent in each window, by model and token kind, at API list prices, and fits how much of a window each API dollar takes:

  • every rise of 5 points or more within a window, and every limit hit (a whole window), is one observation; once a window resets, the observations it was cut into are kept with their exact spend, so the history does not fade;
  • the fit is rise × plan multiple × window size ≈ Σ model factor × Σ token-kind factor × API spend, solved by Levenberg–Marquardt in log parameters with weak priors;
  • the window size has a level and a per-window stray: the level steps at official limit changes (the 2026-05-06 doubling of Claude Code's 5-hour limits, the 2026-09-22 increase) and drifts slowly between them, a day at a time over the last two weeks, so a quiet change is followed within days; each window may run a little large or small (fitted spread), so the pieces of one window share it and a window that ran large says nothing about how token kinds weigh;
  • a piece that rose well past what its spend says is set aside as use from claude.ai or another device (that use only ever adds to a rise); a piece off the other way is weighed down (Huber);
  • the weekly window, with few pieces of its own, leans on the 5-hour fit's token-kind and model factors once that fit is of medium confidence, while its own size is fitted from its own pieces;
  • token-kind factors capture that limits weigh kinds differently from API prices (cache reads count for much less, so one long session lasts longer than many short ones);
  • you pick your plan in the pane, and each window counts under the plan picked when it began, so windows from different plans share one fit with each plan's multiple fitted rather than taken as sold;
  • windows from before your first pick count under that plan, unless their share per API dollar moved by 1.8× or more for 3 windows or more: such a stretch is fitted as a plan of its own and named after the plan sold at about that multiple (shown as inferred in the estimate details). Changes between plans of about the same size, such as Pro and Team, cannot be told this way.

The pane shows the confidence and the fitted factors. Confidence comes from a held-out check: each of the latest 8 windows is foretold from a fit of the others, and ± next to it is the typical miss (high within 12% on 4 windows or more, medium within 30% on 2). An official change of unpublished size after the last window read keeps it low until a window after the change has been read. Use from claude.ai or other devices counts in the official percent but not in this machine's transcripts: pieces it lifts far are set aside, a little of it still makes estimates less certain. How Anthropic counts limits is not published; these figures are inferences.

What it reads, writes and runs

Everything stays on your machine. Nothing is sent anywhere: the mod makes no network requests, and the program it runs makes none either.

  • Reads Claude Code's transcripts under <config>/projects/ to count tokens; message text is parsed only to find turn boundaries and is never stored or sent.
  • Reads Claude Code's language setting and the CLAUDE_CONFIG_DIR, HOME, USERPROFILE, LC_ALL and LANG environment variables.
  • Writes no files itself. Its scanner writes one file of its own, <config>/token-almanac/cache.json (per-file read offsets and 10-minute sums, so later scans read only new lines), which only token-almanac reads; it is not a setting, instruction or script for Claude Code or any other tool. Limit readings, the plans you pick and a compact history of windows that have reset (a reading every 5 points with each model's tokens so far) go in the plugin's own store.
  • Does not read Claude Code's credentials or any token: the plan comes from your pick in the pane.
  • Runs one program: Node.js (node, or the nodePath option) on the bundled scan/scan.mjs, because transcripts are larger than the mod environment can read. The two command lines are
  • node <plugin>/scan/scan.mjs session <this session's transcript>, when a session starts, to count what ran before the mod loaded;
  • node <plugin>/scan/scan.mjs global <config>/projects <config>/token-almanac/cache.json, when the machine view opens or refreshes, with the window start times and limit readings on stdin.

The scanner reads the transcripts and its own cache, writes only cache.json, prints token sums as JSON on stdout for the mod, and makes no network requests. Its source is in scan/scan.mjs.

Development

claude plugin validate .
claude plugin test .
node --test scan/scan.check.mjs

For a working copy, start Claude Code with claude --plugin-dir <this folder>.

License

MIT

Source 3 files
hooks/register.tsx 2739 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionUsage } from 'claude-code'
3
4import type { Fit, GlobalScan, GlobalView, InferredPlan, Machine, Observation, PlanChoice, Reading, Samples, ScanStatus, Snapshot, Tokens, TurnRow, Vec, Window } from '../types'
5
6import { MESSAGES, localeOf } from './i18n'
7import type { Locale, Messages } from './i18n'
8
9const PANE = 'token-almanac'
10// The plan in force when none was ever picked.
11const CURRENT = 'current'
12
13// The words drawn, in the language resolved at load (English until then).
14let t: Messages = MESSAGES.en
15export function setLocale(locale: Locale): void {
16  t = MESSAGES[locale]
17}
18// The Node.js the scanner runs on, from the `nodePath` option.
19let nodeBin = 'node'
20const ZERO: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
21const MINUTE = 60_000
22const HOUR = 60 * MINUTE
23// The forecast reads the growth over this much recent time, and needs at least the minimum.
24const RATE_LOOKBACK_MS = 90 * MINUTE
25const RATE_MIN_SPAN_MS = 10 * MINUTE
26
27const since = atom({ plugin: 'token-almanac', key: 'since' } as const, 0)
28const totals = atom({ plugin: 'token-almanac', key: 'totals' } as const, ZERO)
29const byModel = atom({ plugin: 'token-almanac', key: 'byModel' } as const, {} as Record<string, Tokens>)
30const turns = atom({ plugin: 'token-almanac', key: 'turns' } as const, [] as TurnRow[])
31const snapshot = atom({ plugin: 'token-almanac', key: 'snapshot' } as const, null as Snapshot | null)
32const samples = atom({ plugin: 'token-almanac', key: 'samples' } as const, {} as Record<string, Samples>)
33const isBandHidden = atom({ plugin: 'token-almanac', key: 'isBandHidden' } as const, false)
34const view = atom({ plugin: 'token-almanac', key: 'view' } as const, 'session' as 'session' | 'global')
35const range = atom({ plugin: 'token-almanac', key: 'range' } as const, '30d' as '30d' | 'all')
36const machine = atom({ plugin: 'token-almanac', key: 'machine' } as const, null as Machine | null)
37const scanStatus = atom({ plugin: 'token-almanac', key: 'scanStatus' } as const, { state: 'idle' } as ScanStatus)
38const planChoices = atom({ plugin: 'token-almanac', key: 'planChoices' } as const, [] as PlanChoice[])
39const details = atom({ plugin: 'token-almanac', key: 'details' } as const, false)
40
41// Kinds of token in the pane's palette: clay for output, its soft tint for cache writes, sand and
42// stone for the reads and plain input that carry least weight.
43const KIND_COLOR = { input: '#A39E93', output: '#D97757', cacheRead: '#D6CCBE', cacheWrite: '#E9A88C' } as const
44
45// ---- Pure helpers ---------------------------------------------------------
46
47function add(a: Tokens, b: Tokens): Tokens {
48  return { input: a.input + b.input, output: a.output + b.output, cacheRead: a.cacheRead + b.cacheRead, cacheWrite: a.cacheWrite + b.cacheWrite }
49}
50
51function sum(t: Tokens): number {
52  return t.input + t.output + t.cacheRead + t.cacheWrite
53}
54
55export function fmtTokens(n: number): string {
56  if (n < 1000) return String(n)
57  if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
58  if (n < 1_000_000_000) return `${(n / 1_000_000).toFixed(2)}M`
59  return `${(n / 1_000_000_000).toFixed(2)}B`
60}
61
62export function fmtDuration(ms: number): string {
63  const minutes = Math.max(0, Math.round(ms / MINUTE))
64  const d = Math.floor(minutes / 1440)
65  const hrs = Math.floor((minutes % 1440) / 60)
66  const m = minutes % 60
67  if (d > 0) return `${d}d${hrs}h`
68  if (hrs > 0) return `${hrs}h${m}m`
69  return `${m}m`
70}
71
72function windowLabel(kind: string): string {
73  return t.windows[kind] ?? kind.replace(/_/g, ' ')
74}
75
76function planLabel(plan: string): string {
77  return t.plans[plan] ?? plan.replace(/_/g, ' ')
78}
79
80// True once a reply has come back with no limit readings: an account billed by the API (or a
81// gateway that reports none), not one still waiting for its first reading.
82function hasNoLimits(snap: Snapshot | null): boolean {
83  return snap !== null && snap.windows.length === 0 && snap.contextTokens !== undefined
84}
85
86function levelColor(percent: number): string {
87  return percent >= 90 ? 'error' : percent >= 70 ? 'warning' : 'claude'
88}
89
90// `etaMs` is set only when the window would be full before it resets; `state` says which of the
91// outlooks applies, for the pane to word.
92export type Forecast = { ratePerHour: number | null; etaMs: number | null; state: 'full' | 'unknown' | 'flat' | 'safe' | 'eta' }
93
94// How fast a window fills, from its readings over the last 90 minutes up to now, and when it
95// would be full at that pace. Measuring up to now (not the last reading) lets idle time slow it.
96export function forecast(points: readonly [number, number][], percent: number, now: number, resetsAt?: string): Forecast {
97  if (percent >= 100) return { ratePerHour: null, etaMs: null, state: 'full' }
98  const recent = points.filter(([t]) => t >= now - RATE_LOOKBACK_MS)
99  const base = recent[0] ?? points[points.length - 1]
100  if (base === undefined || now - base[0] < RATE_MIN_SPAN_MS) {
101    return { ratePerHour: null, etaMs: null, state: 'unknown' }
102  }
103  const ratePerHour = ((percent - base[1]) / (now - base[0])) * HOUR
104  if (ratePerHour <= 0) return { ratePerHour: 0, etaMs: null, state: 'flat' }
105  const etaMs = ((100 - percent) / ratePerHour) * HOUR
106  const resetMs = resetsAt ? Date.parse(resetsAt) - now : Number.NaN
107  if (!Number.isNaN(resetMs) && etaMs >= resetMs) {
108    return { ratePerHour, etaMs: null, state: 'safe' }
109  }
110  return { ratePerHour, etaMs, state: 'eta' }
111}
112
113function resetText(resetsAt: string | undefined, now: number): string {
114  if (!resetsAt) return ''
115  const ms = Date.parse(resetsAt) - now
116  return Number.isNaN(ms) ? '' : ms <= 0 ? t.resetting : t.resetsIn(fmtDuration(ms))
117}
118
119function escapeXml(text: string): string {
120  return text.replace(/[<>&"']/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c] ?? c)
121}
122
123function toSnapshot(u: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>, now: number): Snapshot {
124  return {
125    at: now,
126    contextTokens: u.context.tokens,
127    contextWindow: u.context.window,
128    contextPercent: u.context.percent,
129    costUsd: u.cost?.usd,
130    windows: u.rateLimits.map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt })),
131  }
132}
133
134function withReading(all: Record<string, Samples>, w: Window, now: number): Record<string, Samples> {
135  const current = all[w.kind]
136  const series: Samples = current && current.resetsAt === w.resetsAt ? current : { resetsAt: w.resetsAt, points: [] }
137  const last = series.points[series.points.length - 1]
138  if (last && last[1] === w.percentUsed && now - last[0] < 10 * MINUTE) {
139    return all
140  }
141  return { ...all, [w.kind]: { ...series, points: [...series.points, [now, w.percentUsed] as [number, number]].slice(-300) } }
142}
143
144// What `scan/scan.mjs session` prints: the session's counts as its transcript records them.
145export type Parsed = { totals: Tokens; byModel: Record<string, Tokens>; turns: TurnRow[] }
146
147// ---- Prices and the global view --------------------------------------------
148
149// USD per million tokens: [input, output, cache read, cache write 5m, cache write 1h], from
150// https://platform.claude.com/docs/en/about-claude/pricing as read on 2026-10-10. Haiku 5.5's
151// higher rate for prompts over 100k tokens is not applied.
152const PRICES: Record<string, Vec> = {
153  'claude-fable-5-1': [10, 50, 0.25, 12.5, 20],
154  'claude-mythos-5-1': [10, 50, 0.25, 12.5, 20],
155  'claude-fable-5': [10, 50, 1, 12.5, 20],
156  'claude-mythos-5': [10, 50, 1, 12.5, 20],
157  'claude-opus-5-5': [4, 20, 0.2, 5, 8],
158  'claude-opus-5': [5, 25, 0.5, 6.25, 10],
159  'claude-opus-4-8': [5, 25, 0.5, 6.25, 10],
160  'claude-opus-4-7': [5, 25, 0.5, 6.25, 10],
161  'claude-opus-4-6': [5, 25, 0.5, 6.25, 10],
162  'claude-sonnet-5-5': [2, 10, 0.1, 2.5, 4],
163  'claude-sonnet-5': [2, 10, 0.2, 2.5, 4],
164  'claude-sonnet-4-6': [3, 15, 0.3, 3.75, 6],
165  'claude-haiku-5-5': [0.1, 0.5, 0.01, 0.125, 0.2],
166  'claude-haiku-4-5': [1, 5, 0.1, 1.25, 2],
167}
168
169// A model's prices by its id, or by the longest id it starts with (a dated or suffixed id).
170// Prices from <config>/token-almanac/prices.json, over the built-in ones: for another provider's
171// rates (Bedrock, Vertex), a model this table lacks, or a price change before an update.
172let priceOverrides: Record<string, Vec> = {}
173
174export function setPriceOverrides(prices: Record<string, unknown>): void {
175  priceOverrides = Object.fromEntries(
176    Object.entries(prices).filter((e): e is [string, Vec] => Array.isArray(e[1]) && e[1].length === 5 && e[1].every(x => typeof x === 'number')),
177  )
178}
179
180export function priceOf(model: string): Vec | null {
181  const table = { ...PRICES, ...priceOverrides }
182  const exact = table[model]
183  if (exact) return exact
184  const key = Object.keys(table)
185    .filter(k => model.startsWith(k))
186    .sort((a, b) => b.length - a.length)[0]
187  return key === undefined ? null : table[key]!
188}
189
190export function costOf(model: string, v: readonly number[]): number {
191  const p = priceOf(model)
192  if (p === null) return 0
193  let total = 0
194  for (let i = 0; i < 5; i += 1) total += (v[i] ?? 0) * p[i]!
195  return total / 1_000_000
196}
197
198const vsum = (v: readonly number[]) => v.reduce((a, b) => a + b, 0)
199const pad2 = (n: number) => String(n).padStart(2, '0')
200
201function dayValue(day: string): number {
202  const [y, m, d] = day.split('-').map(Number)
203  return Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1)
204}
205
206function dayShift(day: string, delta: number): string {
207  const t = new Date(dayValue(day) + delta * 86_400_000)
208  return `${t.getUTCFullYear()}-${pad2(t.getUTCMonth() + 1)}-${pad2(t.getUTCDate())}`
209}
210
211
212// The scan over the chosen range: cost per day, project and model, and the average cost of each
213// local hour of the day, the day's shape the forecast walks forward.
214export function globalView(scan: GlobalScan, range: '30d' | 'all'): GlobalView {
215  const start = range === '30d' ? dayShift(scan.today, -29) : ''
216  const rows = scan.rows.filter(r => r[0] >= start)
217  const firstDay = rows.reduce<string | null>((a, r) => (a === null || r[0] < a ? r[0] : a), null)
218  const days = firstDay === null ? 0 : Math.round((dayValue(scan.today) - dayValue(firstDay)) / 86_400_000) + 1
219
220  const perDay = new Map<string, Record<string, number>>()
221  const projects = new Map<string, { cost: number; tokens: number }>()
222  const models = new Map<string, { cost: number; tokens: number }>()
223  const hours = new Array<number>(24).fill(0)
224  const hoursByModel: Record<string, number[][]> = {}
225  const unpriced = new Set<string>()
226  let totalCost = 0
227  let totalTokens = 0
228
229  for (const [day, hour, project, model, ...v] of rows) {
230    const cost = costOf(model, v)
231    const tokens = vsum(v)
232    if (priceOf(model) === null && tokens > 0) unpriced.add(model)
233    totalCost += cost
234    totalTokens += tokens
235    const d = perDay.get(day) ?? {}
236    d[model] = (d[model] ?? 0) + cost
237    perDay.set(day, d)
238    const p = projects.get(project) ?? { cost: 0, tokens: 0 }
239    projects.set(project, { cost: p.cost + cost, tokens: p.tokens + tokens })
240    const m = models.get(model) ?? { cost: 0, tokens: 0 }
241    models.set(model, { cost: m.cost + cost, tokens: m.tokens + tokens })
242    hours[hour] = (hours[hour] ?? 0) + cost
243    const hm = (hoursByModel[model] ??= Array.from({ length: 24 }, () => [0, 0, 0, 0]))
244    spendByKind(model, v).forEach((x, k) => (hm[hour]![k]! += x))
245  }
246
247  const daily: GlobalView['daily'] = []
248  for (let i = 0; i < days; i += 1) {
249    const day = dayShift(firstDay ?? scan.today, i)
250    daily.push({ day, byModel: perDay.get(day) ?? {} })
251  }
252  const byCost = <T extends { cost: number; tokens: number }>(a: T, b: T) => b.cost - a.cost || b.tokens - a.tokens
253  return {
254    days,
255    totalCost,
256    totalTokens,
257    daily,
258    byProject: [...projects].map(([project, x]) => ({ project, ...x })).sort(byCost),
259    byModel: [...models].map(([model, x]) => ({ model, ...x })).filter(x => x.tokens > 0).sort(byCost),
260    hourly: hours.map(c => (days > 0 ? c / days : 0)),
261    hourlyByModel: Object.fromEntries(Object.entries(hoursByModel).map(([m, hs]) => [m, hs.map(kinds => kinds.map(x => (days > 0 ? x / days : 0)))])),
262    unpriced: [...unpriced],
263  }
264}
265
266// The length of a limit window, to find where the current one began.
267function windowLength(kind: string): number | null {
268  if (kind === 'five_hour') return 5 * HOUR
269  if (kind.startsWith('seven_day')) return 7 * 24 * HOUR
270  return null
271}
272
273export const fmtUsd = (n: number) => (n >= 100 ? `$${n.toFixed(0)}` : `$${n.toFixed(2)}`)
274// For estimates, where cents would claim a precision they do not have.
275const roughUsd = (n: number) => (n >= 10 ? `$${n.toFixed(0)}` : `$${n.toFixed(1)}`)
276
277// ---- The fit ----------------------------------------------------------------
278
279// Each plan's window as a multiple of Pro's, as sold, where it is sold that way. The fit starts
280// from these and moves them as far as the data says; the sold multiples are not taken as exact.
281// A plan with none (Team, Enterprise, a tier not known here) starts level with the reference.
282const NOMINAL: Record<string, number> = { pro: 1, max5x: 5, max20x: 20 }
283// The plans the pane offers to pick.
284const PLAN_CHOICES = ['pro', 'max5x', 'max20x', 'team', 'team_premium', 'enterprise'] as const
285// The pick that says the plan is not known.
286const UNKNOWN = 'unknown'
287// How much a start with no sold multiple behind it counts: next to nothing.
288const WEAK_PRIOR = 0.05
289
290// One plan's window against another's, as sold; null when either is not sold as a multiple.
291function nominalRatio(plan: string, against: string): number | null {
292  const a = NOMINAL[plan]
293  const b = NOMINAL[against]
294  return a === undefined || b === undefined ? null : a / b
295}
296
297// A plan's window against the fit's reference plan: fitted, else as sold, else unknown.
298function planScale(fit: Fit, plan: string): number | null {
299  const s = fit.s[plan] ?? nominalRatio(plan, fit.refPlan)
300  return s === null ? null : s * (fit.later ?? 1)
301}
302// How many windows' worth of evidence the starting values (API prices, sold multiples) count as.
303const PRIOR_WINDOWS = 0.5
304// The pull of the kinds' weights toward each other, far weaker: a kind the pieces barely tell apart
305// (cache reads, a small share of every piece's weighted spend) was dragged toward the rest, about a
306// third too heavy on test data drawn from known weights; at this pull it is within a tenth, and its
307// band still widens to "unclear" where the pieces cannot say.
308const KIND_PRIOR = 0.05
309// How many windows' worth a longer window kind's fit leans on the five-hour fit's way of weighing
310// kinds and models, when that fit is at least of medium confidence: enough to steady a kind with
311// a few pieces, little enough that a kind with its own evidence goes its own way.
312const BORROW_WINDOWS = 2
313// How many of its own spreads a piece may rise past what its spend says before it is taken for
314// use this machine did not see and set aside. On test data with a few points of such use in three
315// windows in eleven, weighing those pieces down (Huber) left shares about 5% heavy; setting them
316// aside past 2 spreads leaves about 1.5%, with no piece of the clean data set aside, where past
317// 1.5 spreads starts setting clean pieces aside too.
318const UNSEEN_AT = 2
319// Below this many pieces there is no rest to tell a piece apart from (two limit hits a third
320// apart say nothing of which one had help): such fits only weigh down.
321const UNSEEN_MIN_PIECES = 6
322
323// Gaussian elimination with partial pivoting; null when the system is singular.
324function solve(a: number[][], b: number[]): number[] | null {
325  const n = b.length
326  const m = a.map((row, i) => [...row, b[i]!])
327  for (let col = 0; col < n; col += 1) {
328    let pivot = col
329    for (let r = col + 1; r < n; r += 1) if (Math.abs(m[r]![col]!) > Math.abs(m[pivot]![col]!)) pivot = r
330    if (Math.abs(m[pivot]![col]!) < 1e-300) return null
331    ;[m[col], m[pivot]] = [m[pivot]!, m[col]!]
332    for (let r = 0; r < n; r += 1) {
333      if (r === col) continue
334      const f = m[r]![col]! / m[col]![col]!
335      for (let c = col; c <= n; c += 1) m[r]![c]! -= f * m[col]![c]!
336    }
337  }
338  return m.map((row, i) => row[n]! / row[i]!)
339}
340
341function median(xs: number[]): number | null {
342  if (xs.length === 0) return null
343  const s = [...xs].sort((a, b) => a - b)
344  const mid = Math.floor(s.length / 2)
345  return s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2
346}
347
348// The four kinds of token the fit weighs apart: the two cache writes share one weight.
349export const TOKEN_KINDS = ['input', 'output', 'cacheRead', 'cacheWrite'] as const
350
351// A model's spend by kind of token, in API dollars: [input, output, cache read, cache write].
352export function spendByKind(model: string, v: readonly number[]): number[] {
353  const p = priceOf(model)
354  if (p === null) return [0, 0, 0, 0]
355  return [(v[0] ?? 0) * p[0], (v[1] ?? 0) * p[1], (v[2] ?? 0) * p[2], (v[3] ?? 0) * p[3] + (v[4] ?? 0) * p[4]].map(x => x / 1_000_000)
356}
357
358type Segment = { window: number; plan: string; dy: number; c: Record<string, number[]>; hit: boolean }
359
360// The pieces the fit learns from. Within a window, from its start (0%, nothing spent) through
361// its readings, a piece closes each time the percent has risen 5 points or more: what that piece
362// spent, by model and kind, against how far the percent rose. A limit hit is the whole window
363// to 100%. Pieces let the different ways a window was used (a long session's cache reads, many
364// sessions' cache writes) each speak, where a window's running total would blur them.
365export function segmentsOf(kind: string, all: readonly Observation[]): Segment[] {
366  const byWindow = new Map<number, Observation[]>()
367  for (const o of all) {
368    if (o.kind !== kind) continue
369    byWindow.set(o.resetsAt, [...(byWindow.get(o.resetsAt) ?? []), o])
370  }
371  const kindsOf = (byModel: Record<string, Vec>) =>
372    Object.fromEntries(Object.entries(byModel).map(([m, v]) => [m, spendByKind(m, v)]).filter(([, c]) => (c as number[]).some(x => x > 0)))
373  const minus = (a: Record<string, number[]>, b: Record<string, number[]>) =>
374    Object.fromEntries(Object.entries(a).map(([m, c]) => [m, c.map((x, k) => Math.max(0, x - (b[m]?.[k] ?? 0)))]))
375  const out: Segment[] = []
376  for (const [window, list] of byWindow) {
377    for (const obs of list.filter(o => o.hit)) out.push({ window, plan: CURRENT, dy: 1, c: kindsOf(obs.byModel), hit: true })
378    let anchor = { y: 0, c: {} as Record<string, number[]> }
379    for (const o of list.filter(o => !o.hit).sort((a, b) => a.t - b.t)) {
380      if (o.y - anchor.y < 0.05) continue
381      const c = kindsOf(o.byModel)
382      out.push({ window, plan: CURRENT, dy: o.y - anchor.y, c: minus(c, anchor.c), hit: false })
383      anchor = { y: o.y, c }
384    }
385  }
386  return out.filter(s => Object.values(s.c).some(c => c.some(x => x > 0)))
387}
388
389// One window's observations cut down to those segmentsOf closes a piece on: each reading 5 points
390// or more past the last one kept, and the window's first hit. The pieces they make are the same.
391export function compactWindow(obs: readonly Observation[]): Observation[] {
392  const kept: Observation[] = []
393  let last = 0
394  for (const o of obs.filter(o => !o.hit).sort((a, b) => a.t - b.t)) {
395    if (o.y - last < 0.05) continue
396    kept.push(o)
397    last = o.y
398  }
399  const hit = obs.filter(o => o.hit).sort((a, b) => a.t - b.t)[0]
400  return hit === undefined ? kept : [...kept, hit]
401}
402
403// Official changes to the size of a window kind: a window that begins on or after `at` holds `x`
404// times what one before it held, or an amount not published (null). The fit gives the windows on
405// each side a level of their own, so a change is not taken for a way of use or a model's weight.
406export const OFFICIAL_CHANGES: readonly { at: number; kind: string; x: number | null }[] = [
407  // https://www.anthropic.com/news/higher-limits-spacex: Claude Code's five-hour limits doubled.
408  { at: Date.parse('2026-05-06T00:00:00Z'), kind: 'five_hour', x: 2 },
409  // https://www.anthropic.com/claude-opus-5-5: five-hour limits raised, by how much not said.
410  { at: Date.parse('2026-09-22T00:00:00Z'), kind: 'five_hour', x: null },
411]
412// How far a published change may be off what was announced ("doubled"), in logs.
413const ANNOUNCED_SD = 0.3
414// How far a window's size may drift in a week, in logs, with no change announced: limits are
415// tuned quietly too. A start, fitted to how far the levels moved with DRIFT_PRIOR steps' worth of
416// it, between DRIFT_MIN and DRIFT_MAX. The level is held a day at a time over the latest two weeks
417// (a window at a time for windows longer than a day), a week at a time before that.
418const DRIFT = 0.08
419const DRIFT_MIN = 0.02
420const DRIFT_MAX = 0.4
421const DRIFT_PRIOR = 2
422const FINE_STEPS = 14
423const COARSE_STEP = 7
424// How far one window's size strays from its stretch's level, in logs, before the windows say:
425// what the transcripts cannot see (the web app, another device) and how each was used. Fitted
426// from the windows once there are MIN_TAU_WINDOWS of them, between TAU_MIN and TAU_MAX.
427const TAU_START = 0.12
428const TAU_MIN = 0.02
429const TAU_MAX = 0.5
430const MIN_TAU_WINDOWS = 5
431// How many of the latest windows the held-out check takes out in turn, and the least rise one
432// needs for its miss to say something next to rounding.
433const HELD_OUT_WINDOWS = 8
434const HELD_OUT_MIN_RISE = 0.15
435
436// What a fit carries beyond what the pane draws: its parameters, for a held-out refit to start
437// from, and each piece's place.
438type Solved = {
439  fit: Fit
440  p: number[]
441  u: number[]
442  tau: number
443  drift: number
444  robust: number[]
445  // Each piece's window (index into the windows).
446  pieceWindow: number[]
447  predict: (i: number, withWindow: boolean) => number
448}
449
450// Fits one window kind on its pieces: rise × s[plan] × e^(level + u[window]) ≈ Σ f[model] × Σ g[kind]
451// × spend[model][kind]. g (one per kind of token, shared by every model) is the share of a window
452// one API dollar of that kind of the reference model takes, on the reference plan (the one picked
453// now, else the one with the most windows) at the latest level; f scales another model against
454// the reference model (1); s is another plan's window against the reference plan's (1). The level
455// is the window's size over time: a step at each official change, and a slow drift between them
456// (DRIFT). u is each window's own stray from its level (sd tau, fitted), so the pieces of one
457// window share it: a window that ran large tells nothing of how the kinds weigh. All are fitted in
458// logs, together (Levenberg–Marquardt, each window's u eliminated in closed form, so the cost grows
459// with the pieces, not with the windows squared). A piece's miss is told against what it can be
460// off by: the limit reports whole percents, so each end of a piece may be half a point off
461// (ROUNDING), and how the piece was used adds a share of the rise (SPREAD). Each parameter starts
462// where API prices and sold multiples put it (the kinds' g equal, f at 1, s at the sold ratio where
463// both plans have one, else at 1), that start weighing as much as half a piece (PRIOR_WINDOWS, or
464// WEAK_PRIOR with no sold ratio; the kinds' g far less, KIND_PRIOR), so the pieces move it as far
465// as they agree to. Once the rest have settled, a piece that rose more than UNSEEN_AT of its own
466// spreads past what its spend says is set aside: use this machine did not see (another device, the
467// web app) only ever adds to a rise. A piece off the other way by more than 2.5 spreads, which no
468// unseen use explains, is weighed down (Huber).
469function solveSegments(
470  kind: string,
471  segs: Segment[],
472  preferRef: string,
473  borrow: Fit | null,
474  opts: { drift?: number; warm?: Solved; heldOut?: number; maxIter?: number; quick?: boolean } = {},
475): Solved {
476  const drift = opts.drift ?? DRIFT
477  const spend = new Map<string, number>()
478  for (const sg of segs) for (const [m, c] of Object.entries(sg.c)) spend.set(m, (spend.get(m) ?? 0) + c.reduce((a, b) => a + b, 0))
479  const models = [...spend].sort((a, b) => b[1] - a[1]).map(([m]) => m)
480  const ref = models[0]!
481  const others = models.slice(1)
482  const planWindows: Record<string, number> = {}
483  for (const p of new Set(segs.map(sg => sg.plan))) planWindows[p] = new Set(segs.filter(sg => sg.plan === p).map(sg => sg.window)).size
484  const refPlan = planWindows[preferRef] !== undefined ? preferRef : Object.entries(planWindows).sort((a, b) => b[1] - a[1] || (a[0] === 'pro' ? -1 : 1))[0]![0]
485  const plans = Object.keys(planWindows).filter(p => p !== refPlan)
486  const startScale = (pl: string) => (pl === refPlan ? 1 : (nominalRatio(pl, refPlan) ?? 1))
487  const priorWeight = (pl: string) => (nominalRatio(pl, refPlan) === null ? WEAK_PRIOR : PRIOR_WINDOWS)
488  // Another window kind's fit to start from: its kinds' weights as a shape (logs about their mean),
489  // and its models against this fit's reference model where it has that one. The size of the
490  // window is never lent: it is this kind's own.
491  const lent =
492    borrow === null || !borrow.g.every(x => x > 0)
493      ? null
494      : (() => {
495          const logs = borrow.g.map(Math.log)
496          const mean = logs.reduce((a, b) => a + b, 0) / logs.length
497          const base = borrow.f[ref]
498          const f: Record<string, number> = base === undefined ? {} : Object.fromEntries(Object.entries(borrow.f).map(([m, x]) => [m, Math.log(x / base)]))
499          return { g: logs.map(x => x - mean), f }
500        })()
501
502  // Windows, and the stretches of level they fall in: an era between official changes (0 the
503  // latest), cut into days, then weeks, counted back from the era's last window when the level
504  // may drift.
505  const length = windowLength(kind) ?? HOUR
506  const wins = [...new Set(segs.map(sg => sg.window))].sort((a, b) => a - b)
507  const nW = wins.length
508  const windowIndex = new Map(wins.map((w, i) => [w, i]))
509  const latestStart = wins[nW - 1]! - length
510  // The changes the windows span: those before the first window or after the latest say nothing here.
511  const changes = OFFICIAL_CHANGES.filter(c => c.kind === kind && c.at > wins[0]! - length && c.at <= latestStart).sort((a, b) => a.at - b.at)
512  const eraOf = (w: number) => changes.filter(c => w - length < c.at).length
513  const eraLast = new Map<number, number>()
514  for (const w of wins) eraLast.set(eraOf(w), Math.max(eraLast.get(eraOf(w)) ?? -Infinity, w))
515  // A stretch is counted in steps back from its era's last window: a fine step (a day, or the
516  // window's length if longer) for FINE_STEPS of them, then COARSE_STEP fine steps at a time.
517  const fine = Math.max(24 * HOUR, length)
518  const binOf = (w: number): [number, number] => {
519    const era = eraOf(w)
520    if (drift === 0) return [era, 0]
521    const back = Math.floor((eraLast.get(era)! - w) / fine)
522    return [era, back < FINE_STEPS ? back : FINE_STEPS + COARSE_STEP * Math.floor((back - FINE_STEPS) / COARSE_STEP)]
523  }
524  const binKeys = [...new Set(wins.map(w => binOf(w).join('|')))]
525    .map(k => k.split('|').map(Number) as [number, number])
526    .sort((a, b) => a[0] - b[0] || a[1] - b[1])
527  const binIndex = new Map(binKeys.map((k, i) => [k.join('|'), i]))
528  const windowBin = wins.map(w => binIndex.get(binOf(w).join('|'))!)
529  // The pull between each stretch and the next older one: its expected step (the announced
530  // changes between them) and how far it may stray from that: the drift over the weeks between
531  // them, and how far each change crossed may be off what was announced.
532  const weeksPerStep = fine / (7 * 24 * HOUR)
533  const steps = binKeys.slice(1).map((older, i) => {
534    const newer = binKeys[i]!
535    const crossed = changes.slice(changes.length - older[0], changes.length - newer[0])
536    return {
537      newer: i,
538      older: i + 1,
539      weeks: weeksPerStep * Math.max(1, newer[0] === older[0] ? older[1] - newer[1] : 1),
540      mean: -crossed.reduce((a, c) => a + Math.log(c.x ?? 1), 0),
541      announced: crossed.reduce((a, c) => a + (c.x === null ? 9 : ANNOUNCED_SD * ANNOUNCED_SD), 0),
542    }
543  })
544  // The drift, fitted to how far the levels moved (DRIFT_PRIOR steps' worth of DRIFT to start).
545  let driftNow = opts.warm?.drift ?? drift
546  const stepWeight = (st: (typeof steps)[number]) => {
547    const v = driftNow * driftNow * st.weeks + st.announced
548    return v > 0 ? 1 / v : 1e6
549  }
550
551  // Parameters, in logs: g[0..3], then f of each other model, then s of each other plan, then the
552  // level of each stretch but the latest (0). Each window's u is kept apart.
553  const nG = 4
554  const nF = others.length
555  const nP = plans.length
556  const n = nG + nF + nP + binKeys.length - 1
557  const levelAt = (b: number) => (b === 0 ? -1 : nG + nF + nP + b - 1)
558  const planIndex = segs.map(sg => (sg.plan === refPlan ? -1 : nG + nF + plans.indexOf(sg.plan)))
559  const pieceWindow = segs.map(sg => windowIndex.get(sg.window)!)
560  const pieceLevel = pieceWindow.map(wi => levelAt(windowBin[wi]!))
561  // Each piece's spend as [model][kind], the reference model first, and the other models it has.
562  const spendOf = segs.map(sg => models.map(m => sg.c[m] ?? [0, 0, 0, 0]))
563  const othersIn = spendOf.map(c => others.flatMap((_, k) => (c[k + 1]!.some(x => x > 0) ? [k + 1] : [])))
564  // The parameters each window's pieces touch: the only ones its u ties to.
565  const touched = wins.map(() => new Set<number>([0, 1, 2, 3]))
566  segs.forEach((_, i) => {
567    const set = touched[pieceWindow[i]!]!
568    for (const m of othersIn[i]!) set.add(nG + m - 1)
569    if (planIndex[i]! >= 0) set.add(planIndex[i]!)
570    if (pieceLevel[i]! >= 0) set.add(pieceLevel[i]!)
571  })
572  const touchedList = touched.map(set => [...set])
573  // Each piece's row touches the same parameters every round: the kinds' weights, the other
574  // models it has, its plan's multiple and its stretch's level.
575  const pieceIdx = segs.map((_, i) => [
576    0,
577    1,
578    2,
579    3,
580    ...othersIn[i]!.map(m => nG + m - 1),
581    ...(planIndex[i]! >= 0 ? [planIndex[i]!] : []),
582    ...(pieceLevel[i]! >= 0 ? [pieceLevel[i]!] : []),
583  ])
584  const pieceVal = pieceIdx.map(idx => new Array<number>(idx.length).fill(0))
585  const totalOf = (sg: Segment) => Object.values(sg.c).reduce((a, c) => a + c.reduce((x, y) => x + y, 0), 0)
586
587  let p: number[]
588  let u: number[]
589  if (opts.warm !== undefined) {
590    p = [...opts.warm.p]
591    u = [...opts.warm.u]
592  } else {
593    let num = 0
594    let den = 0
595    for (const sg of segs) {
596      const target = sg.dy * startScale(sg.plan)
597      num += totalOf(sg) / target
598      den += (totalOf(sg) / target) ** 2
599    }
600    const start = Math.log(num / den)
601    p = [...new Array<number>(nG).fill(start), ...new Array<number>(nF).fill(0), ...plans.map(pl => Math.log(startScale(pl))), ...new Array<number>(binKeys.length - 1).fill(0)]
602    // Start each older stretch where the announced changes put it.
603    let level = 0
604    steps.forEach(st => {
605      level += st.mean
606      p[levelAt(st.older)] = level
607    })
608    u = new Array<number>(nW).fill(0)
609  }
610  let tau = opts.warm?.tau ?? TAU_START
611  // A quick fit (for how far each window strayed, no more) keeps tau and weighs down once.
612  const isTauFitted = opts.warm === undefined && opts.quick !== true && nW >= MIN_TAU_WINDOWS
613
614  // A hit is the whole window, exact at 100%: it counts double, unless the window's readings already
615  // cut it into pieces, which say the same spend again. A window held out counts for nothing.
616  const read = new Set(segs.filter(sg => !sg.hit).map(sg => sg.window))
617  const base = segs.map((sg, i) => (pieceWindow[i] === opts.heldOut ? 0 : sg.hit && !read.has(sg.window) ? 2 : 1))
618  let robust = opts.warm !== undefined ? [...opts.warm.robust] : segs.map(() => 1)
619  const ROUNDING = 0.006
620  const SPREAD = 0.1
621
622  // One piece's share by the parameters (g and f taken out of logs once per round, in `ex`), and,
623  // into `perKind` and `perModel`, the share each kind's weight and each model's moves it by.
624  const perKind = [0, 0, 0, 0]
625  const perModel = new Array<number>(models.length).fill(0)
626  const expOf = (q: number[]) => ({ g: q.slice(0, nG).map(Math.exp), f: [1, ...others.map((_, k) => Math.exp(q[nG + k]!))] })
627  const pieceAt = (i: number, q: number[], ex: { g: number[]; f: number[] }, uw: number) => {
628    const c = spendOf[i]!
629    const scale = Math.exp((planIndex[i]! >= 0 ? q[planIndex[i]!]! : 0) + (pieceLevel[i]! >= 0 ? q[pieceLevel[i]!]! : 0) + uw)
630    const g = ex.g
631    perKind[0] = perKind[1] = perKind[2] = perKind[3] = 0
632    const add = (m: number) => {
633      const fm = ex.f[m]!
634      const cm = c[m]!
635      let byG = 0
636      for (let k = 0; k < 4; k += 1) {
637        perKind[k]! += fm * cm[k]!
638        byG += g[k]! * cm[k]!
639      }
640      perModel[m] = (fm * byG) / scale
641    }
642    add(0)
643    for (const m of othersIn[i]!) add(m)
644    let share = 0
645    for (let k = 0; k < 4; k += 1) {
646      perKind[k] = (g[k]! * perKind[k]!) / scale
647      share += perKind[k]!
648    }
649    return share
650  }
651  const spreadOf = (dy: number) => Math.hypot(ROUNDING, SPREAD * dy)
652
653  // Residuals with their Jacobians, sparse: one row per piece, then the starts' pulls and the
654  // steps between stretches (globals only), then each window's pull toward its level (u only).
655  type Row = { r: number; idx: number[]; val: number[]; wi: number; ju: number; w: number }
656  const NONE: number[] = []
657  const system = (q: number[], uq: number[], withJ = true, withPieces = true) => {
658    const rows: Row[] = []
659    const ex = expOf(q)
660    for (let i = 0; i < (withPieces ? segs.length : 0); i += 1) {
661      const wi = pieceWindow[i]!
662      const share = pieceAt(i, q, ex, uq[wi]!)
663      const dy = segs[i]!.dy
664      const d = spreadOf(dy)
665      const r = (share - dy) / d
666      const w = base[i]! * robust[i]!
667      if (!withJ) {
668        rows.push({ r, idx: NONE, val: NONE, wi, ju: 0, w })
669        continue
670      }
671      // The same order as pieceIdx: kinds, other models, plan, level.
672      const val = pieceVal[i]!
673      let at = 0
674      for (let k = 0; k < 4; k += 1) val[at++] = perKind[k]! / d
675      for (const m of othersIn[i]!) val[at++] = perModel[m]! / d
676      while (at < val.length) val[at++] = -share / d
677      rows.push({ r, idx: pieceIdx[i]!, val, wi, ju: -share / d, w })
678    }
679    const meanG = (q[0]! + q[1]! + q[2]! + q[3]!) / nG
680    for (let k = 0; k < nG; k += 1) {
681      const val = [0, 1, 2, 3].map(c => (c === k ? 1 : 0) - 1 / nG)
682      rows.push(lent === null ? { r: q[k]! - meanG, idx: [0, 1, 2, 3], val, wi: -1, ju: 0, w: KIND_PRIOR } : { r: q[k]! - meanG - lent.g[k]!, idx: [0, 1, 2, 3], val, wi: -1, ju: 0, w: BORROW_WINDOWS })
683    }
684    others.forEach((m, i) => {
685      const at = lent?.f[m]
686      rows.push(at === undefined ? { r: q[nG + i]!, idx: [nG + i], val: [1], wi: -1, ju: 0, w: PRIOR_WINDOWS } : { r: q[nG + i]! - at, idx: [nG + i], val: [1], wi: -1, ju: 0, w: BORROW_WINDOWS })
687    })
688    plans.forEach((pl, i) => rows.push({ r: q[nG + nF + i]! - Math.log(startScale(pl)), idx: [nG + nF + i], val: [1], wi: -1, ju: 0, w: priorWeight(pl) }))
689    for (const st of steps) {
690      const a = levelAt(st.newer)
691      const b = levelAt(st.older)
692      const idx = a >= 0 ? [b, a] : [b]
693      const val = a >= 0 ? [1, -1] : [1]
694      rows.push({ r: q[b]! - (a >= 0 ? q[a]! : 0) - st.mean, idx, val, wi: -1, ju: 0, w: stepWeight(st) })
695    }
696    for (let wi = 0; wi < nW; wi += 1) rows.push({ r: uq[wi]!, idx: NONE, val: NONE, wi, ju: 1, w: 1 / (tau * tau) })
697    return rows
698  }
699  const sumSquares = (rows: Row[]) => rows.reduce((acc, row) => acc + row.w * row.r * row.r, 0)
700  // The same sum for a trial step, the pieces' part without building their rows.
701  const costAt = (q: number[], uq: number[]) => {
702    const ex = expOf(q)
703    let cost = 0
704    for (let i = 0; i < segs.length; i += 1) {
705      const w = base[i]! * robust[i]!
706      if (w === 0) continue
707      const dy = segs[i]!.dy
708      const r = (pieceAt(i, q, ex, uq[pieceWindow[i]!]!) - dy) / spreadOf(dy)
709      cost += w * r * r
710    }
711    return cost + sumSquares(system(q, uq, false, false))
712  }
713
714  // The normal equations, each window's u eliminated: (A − B D⁻¹ Bᵀ) δp = b − B D⁻¹ bu, then
715  // δu = D⁻¹ (bu − Bᵀ δp). With `damp`, the diagonals are raised by that factor (Marquardt).
716  const normal = (rows: Row[], damp: number) => {
717    const a = Array.from({ length: n }, () => new Array<number>(n).fill(0))
718    const b = new Array<number>(n).fill(0)
719    // B, window by window: row wi * n + parameter.
720    const bm = new Float64Array(nW * n)
721    const dd = new Array<number>(nW).fill(0)
722    const bu = new Array<number>(nW).fill(0)
723    for (const { r, idx, val, wi, ju, w } of rows) {
724      if (w === 0) continue
725      for (let x = 0; x < idx.length; x += 1) {
726        const ix = idx[x]!
727        const wx = w * val[x]!
728        b[ix]! -= wx * r
729        const ax = a[ix]!
730        for (let y = 0; y < idx.length; y += 1) ax[idx[y]!]! += wx * val[y]!
731        if (wi >= 0) bm[wi * n + ix]! += wx * ju
732      }
733      if (wi >= 0) {
734        dd[wi]! += w * ju * ju
735        bu[wi]! -= w * ju * r
736      }
737    }
738    for (let x = 0; x < n; x += 1) a[x]![x]! *= 1 + damp
739    for (let wi = 0; wi < nW; wi += 1) dd[wi]! *= 1 + damp
740    const schur = a.map(row => [...row])
741    const rhs = [...b]
742    // Each window's u ties only to the parameters its pieces touch: the update stays that small.
743    for (let wi = 0; wi < nW; wi += 1) {
744      const at = wi * n
745      const inv = 1 / dd[wi]!
746      const list = touchedList[wi]!
747      for (const x of list) {
748        const cx = bm[at + x]!
749        if (cx === 0) continue
750        rhs[x]! -= cx * bu[wi]! * inv
751        const sx = schur[x]!
752        for (const y of list) sx[y]! -= cx * bm[at + y]! * inv
753      }
754    }
755    return { schur, rhs, bm, dd, bu }
756  }
757  const stepOf = (rows: Row[], damp: number) => {
758    const { schur, rhs, bm, dd, bu } = normal(rows, damp)
759    const dp = solve(schur, rhs)
760    if (dp === null) return null
761    const du = bu.map((x, wi) => (x - touchedList[wi]!.reduce((acc, k) => acc + bm[wi * n + k]! * dp[k]!, 0)) / dd[wi]!)
762    return { dp, du }
763  }
764
765  // Weighs down the pieces the rest cannot explain, and fits tau to how far the windows stray:
766  // each time the fit has settled or had 30 rounds, whichever comes first, three times at most.
767  let mu = 1e-3
768  let reweighs = opts.warm !== undefined ? 3 : opts.quick === true ? 2 : 0
769  let since = 0
770  const maxIter = opts.maxIter ?? 300
771  for (let iter = 0; iter < maxIter; iter += 1) {
772    const rows = system(p, u)
773    const step = stepOf(rows, mu)
774    if (step === null) break
775    const clamp = (x: number) => Math.max(-2, Math.min(2, x))
776    const nextP = p.map((v, i) => v + clamp(step.dp[i]!))
777    const nextU = u.map((v, i) => v + clamp(step.du[i]!))
778    let isSettled = false
779    if (costAt(nextP, nextU) < sumSquares(rows)) {
780      p = nextP
781      u = nextU
782      mu = Math.max(1e-9, mu / 3)
783      isSettled = Math.max(...step.dp.map(Math.abs), ...step.du.map(Math.abs)) < 1e-7
784    } else {
785      mu *= 4
786      isSettled = mu > 1e9
787    }
788    since += 1
789    if (isSettled || since >= 30) {
790      if (reweighs === 3) {
791        if (isSettled) break
792        continue
793      }
794      const residuals = system(p, u, false).slice(0, segs.length)
795      robust = residuals.map(row => (row.r < -UNSEEN_AT && segs.length >= UNSEEN_MIN_PIECES ? 0.01 : Math.abs(row.r) <= 2.5 ? 1 : 2.5 / Math.abs(row.r)))
796      if (isTauFitted) {
797        // The windows' strays and how sure each is (expectation–maximization).
798        const { dd } = normal(system(p, u), 0)
799        const counted = u.map((x, wi) => (base.some((b, i) => b > 0 && pieceWindow[i] === wi) ? x * x + 1 / dd[wi]! : null)).filter((x): x is number => x !== null)
800        tau = Math.min(TAU_MAX, Math.max(TAU_MIN, Math.sqrt(counted.reduce((a, b) => a + b, 0) / Math.max(1, counted.length))))
801      }
802      const drifting = steps.filter(st => st.announced === 0)
803      if (isTauFitted && drift > 0 && drifting.length > 0) {
804        // Each step's expected square, its uncertainty from the curvature included.
805        const { schur } = normal(system(p, u), 0)
806        const columns = new Map<number, number[] | null>()
807        const cov = (x: number, y: number) => {
808          if (x < 0 || y < 0) return 0
809          if (!columns.has(y)) columns.set(y, solve(schur, schur.map((_, i) => (i === y ? 1 : 0))))
810          return columns.get(y)?.[x] ?? 0
811        }
812        const moved = drifting.map(st => {
813          const a = levelAt(st.newer)
814          const b = levelAt(st.older)
815          const d = p[b]! - (a >= 0 ? p[a]! : 0)
816          return (d * d + cov(b, b) + cov(a, a) - 2 * cov(a, b)) / st.weeks
817        })
818        driftNow = Math.min(DRIFT_MAX, Math.max(DRIFT_MIN, Math.sqrt((DRIFT_PRIOR * drift * drift + moved.reduce((x, y) => x + y, 0)) / (DRIFT_PRIOR + moved.length))))
819      }
820      reweighs += 1
821      since = 0
822      mu = 1e-3
823    }
824  }
825
826  const g = p.slice(0, nG).map(Math.exp)
827  const f = { [ref]: 1, ...Object.fromEntries(others.map((m, i) => [m, Math.exp(p[nG + i]!)])) } as Record<string, number>
828  const s = { [refPlan]: 1, ...Object.fromEntries(plans.map((pl, i) => [pl, Math.exp(p[nG + nF + i]!)])) } as Record<string, number>
829  // The pieces set aside as unseen use, and the rest weighed down.
830  const unseen = robust.filter(w => w === 0.01).length
831
832  // 95% bands for each kind's weight against output's, from the curvature at the fit (each
833  // window's u taken out): wide where the pieces cannot tell two kinds apart (they always came
834  // together in the same proportion).
835  const gBand: [number, number][] = (() => {
836    const rows = system(p, u)
837    const { schur } = normal(rows, 0)
838    const rss = sumSquares(rows)
839    const sigma2 = rss / Math.max(1, segs.length - n)
840    const column = (k: number) => solve(schur, new Array<number>(n).fill(0).map((_, i) => (i === k ? 1 : 0)))
841    const c1 = column(1)
842    return [0, 1, 2, 3].map(k => {
843      const ck = column(k)
844      const rel = g[k]! / g[1]!
845      if (ck === null || c1 === null) return [0, Infinity] as [number, number]
846      const v = Math.max(0, sigma2 * (ck[k]! + c1[1]! - 2 * ck[1]!))
847      const half = 1.96 * Math.sqrt(v)
848      return [rel * Math.exp(-half), rel * Math.exp(half)] as [number, number]
849    })
850  })()
851
852  const exAt = expOf(p)
853  const predict = (i: number, withWindow: boolean) => pieceAt(i, p, exAt, withWindow ? u[pieceWindow[i]!]! : 0)
854  const misses = segs.map((sg, i) => Math.abs(predict(i, true) - sg.dy) * 100)
855  const mae = median(misses)
856  // How well the pieces pin the two kinds that set a way of use apart: cache reads and writes.
857  const bandOf = (k: number) => {
858    const [lo, hi] = gBand[k] ?? [0, Infinity]
859    return Number.isFinite(hi) && lo > 0 ? hi / lo : Infinity
860  }
861  const spread = Math.max(bandOf(2), bandOf(3))
862  const confidence = segs.length >= 12 && nW >= 3 && (mae ?? 99) <= 3 && spread <= 4 ? 'high' : segs.length >= 5 && spread <= 15 ? 'medium' : 'low'
863  const fit: Fit = {
864    kind,
865    windows: nW,
866    segments: segs.filter(sg => !sg.hit).length,
867    hits: segs.filter(sg => sg.hit).length,
868    f,
869    g,
870    gBand,
871    s,
872    refPlan,
873    planWindows,
874    windowPlans: {},
875    latest: null,
876    inferred: [],
877    mae,
878    outliers: robust.filter(r => r < 1).length - unseen,
879    unseen,
880    confidence,
881    ref,
882    lent: lent === null ? null : (borrow?.kind ?? null),
883    tau,
884    eras: changes.length,
885  }
886  return {
887    fit,
888    p,
889    u,
890    tau,
891    drift: driftNow,
892    robust,
893    pieceWindow,
894    predict,
895  }
896}
897
898// How far the fit misses windows it has not seen: each of the latest windows with a rise enough to
899// say is taken out in turn, the rest fitted again from where the whole fit settled, and the rise
900// of its pieces (those not set aside as unseen use) foretold at its stretch's level. Returns the
901// root mean square of the misses, in logs, and how many windows it rests on.
902function heldOutMiss(kind: string, segs: Segment[], preferRef: string, borrow: Fit | null, whole: Solved): { miss: number; windows: number } | null {
903  const wins = [...new Set(segs.map(sg => sg.window))].sort((a, b) => a - b)
904  if (wins.length < 3) return null
905  const checks: number[] = []
906  for (let wi = wins.length - 1; wi >= 0 && checks.length < HELD_OUT_WINDOWS; wi -= 1) {
907    const pieces = segs.map((sg, i) => i).filter(i => whole.pieceWindow[i] === wi && whole.robust[i]! > 0.5)
908    // A window cut into pieces says its rise by them; its hit would say the same spend again.
909    const own = pieces.some(i => !segs[i]!.hit) ? pieces.filter(i => !segs[i]!.hit) : pieces
910    const rise = own.reduce((a, i) => a + segs[i]!.dy, 0)
911    if (rise < HELD_OUT_MIN_RISE) continue
912    const out = solveSegments(kind, segs, preferRef, borrow, { warm: whole, heldOut: wi, maxIter: 3 })
913    const told = own.reduce((a, i) => a + out.predict(i, false), 0)
914    if (told > 0) checks.push(Math.log(told / rise))
915  }
916  if (checks.length === 0) return null
917  return { miss: Math.sqrt(checks.reduce((a, x) => a + x * x, 0) / checks.length), windows: checks.length }
918}
919
920// The plan a pick puts in force at a moment; null before any pick, or after "not sure".
921export function planAt(choices: readonly PlanChoice[], t: number): string | null {
922  let plan: string | null = null
923  for (const c of choices) if (c.at <= t) plan = c.plan
924  return plan
925}
926
927// The plan picked last, passing over "not sure".
928export function pickedPlan(choices: readonly PlanChoice[]): string | null {
929  return [...choices].reverse().find(c => c.plan !== null)?.plan ?? null
930}
931
932// A move in share per API dollar this large, between stretches of 3 windows or more, reads as a
933// change of plan: smaller ones are the noise of how a window was used.
934const LOG_JUMP = Math.log(1.8)
935const MIN_STRETCH = 3
936
937// Splits a series into stretches with a level of their own: the cut with the clearest difference
938// of means, while that difference is at least LOG_JUMP and 4 spreads of the means (the spread
939// within the two sides, or the one given if larger), then each half again, three levels deep at
940// most.
941export function stretchesOf(xs: readonly number[], spread: number): [number, number][] {
942  const mean = (a: number, b: number) => xs.slice(a, b).reduce((acc, x) => acc + x, 0) / (b - a)
943  const squares = (a: number, b: number) => {
944    const m = mean(a, b)
945    return xs.slice(a, b).reduce((acc, x) => acc + (x - m) ** 2, 0)
946  }
947  const out: [number, number][] = []
948  const split = (a: number, b: number, depth: number) => {
949    let best = -1
950    let bestZ = 4
951    if (depth < 3) {
952      for (let k = a + MIN_STRETCH; k <= b - MIN_STRETCH; k += 1) {
953        const d = Math.abs(mean(a, k) - mean(k, b))
954        const within = Math.max(spread, Math.sqrt((squares(a, k) + squares(k, b)) / (b - a - 2)))
955        const z = d / (within * Math.sqrt(1 / (k - a) + 1 / (b - k)))
956        if (d >= LOG_JUMP && z >= bestZ) {
957          bestZ = z
958          best = k
959        }
960      }
961    }
962    if (best < 0) {
963      out.push([a, b])
964      return
965    }
966    split(a, best, depth + 1)
967    split(best, b, depth + 1)
968  }
969  if (xs.length > 0) split(0, xs.length, 0)
970  return out
971}
972
973// The plan sold at about this multiple of another, within a factor of 2; null when none is, or
974// when the other is not sold as a multiple.
975export function guessPlan(ratio: number, against: string): string | null {
976  const base = NOMINAL[against]
977  if (base === undefined || !(ratio > 0)) return null
978  let best: string | null = null
979  let miss = Math.LN2
980  for (const [plan, n] of Object.entries(NOMINAL)) {
981    const d = Math.abs(Math.log(ratio) - Math.log(n / base))
982    if (plan !== against && d <= miss) {
983      miss = d
984      best = plan
985    }
986  }
987  return best
988}
989
990// Fits one window kind, with each window counted under the plan picked when it began. Windows no
991// pick covers count under the plan picked next (else the last one picked, else the current plan),
992// unless their share per API dollar stood apart: a first fit gives each window how far its rise
993// strayed from what its spend predicts, and stretches that moved by LOG_JUMP or more from the ones
994// next to the picks are each fitted again as a plan of their own, then named by the sold multiple
995// they come closest to.
996export function fitKind(kind: string, all: readonly Observation[], choices: readonly PlanChoice[] = [], borrow: Fit | null = null): Fit {
997  const none: Fit = {
998    kind, windows: 0, segments: 0, hits: 0, f: {}, g: [0, 0, 0, 0], gBand: [], s: {}, refPlan: CURRENT, planWindows: {},
999    windowPlans: {}, latest: null, inferred: [], mae: null, outliers: 0, confidence: 'none', ref: null,
1000  }
1001  const raw = segmentsOf(kind, all)
1002  if (raw.length === 0) return none
1003  const sorted = [...choices].sort((a, b) => a.at - b.at)
1004  const length = windowLength(kind) ?? 0
1005  const windows = [...new Set(raw.map(sg => sg.window))].sort((a, b) => a - b)
1006  const picked = windows.map(w => planAt(sorted, w - length))
1007  const preferRef = pickedPlan(sorted) ?? CURRENT
1008
1009  // Each stretch of windows no pick covers, and the plan it counts under until shown otherwise.
1010  const runs: { from: number; to: number; plan: string }[] = []
1011  for (let i = 0; i < windows.length; i += 1) {
1012    if (picked[i] !== null || (i > 0 && picked[i - 1] === null)) continue
1013    let j = i
1014    while (j + 1 < windows.length && picked[j + 1] === null) j += 1
1015    const next = sorted.find(c => c.at > windows[j]! - length && c.plan !== null)
1016    runs.push({ from: i, to: j, plan: next?.plan ?? preferRef })
1017  }
1018  const labels = picked.map(p => p ?? '')
1019  for (const run of runs) for (let i = run.from; i <= run.to; i += 1) labels[i] = run.plan
1020  const withLabels = () => {
1021    const at = new Map(windows.map((w, i) => [w, labels[i]!]))
1022    return raw.map(sg => ({ ...sg, plan: at.get(sg.window)! }))
1023  }
1024  // The first fit holds the level still within each era between official changes: a quiet drift
1025  // would follow a change of plan and hide it.
1026  const first = solveSegments(kind, withLabels(), preferRef, borrow, { drift: 0, quick: true })
1027
1028  // How far each window's rise strayed from its spend, in logs: positive where a dollar took more.
1029  const byWindow = new Map<number, number[]>(windows.map(w => [w, []]))
1030  raw.forEach((sg, i) => byWindow.get(sg.window)!.push(Math.log(sg.dy / first.predict(i, false))))
1031  const strays = windows.map(w => median(byWindow.get(w)!.filter(Number.isFinite)))
1032
1033  const inferredRuns: { label: string; members: number[]; against: string }[] = []
1034  for (const run of runs) {
1035    // The run, with the picked windows next to it under the same plan as its anchor.
1036    const anchors: number[] = []
1037    for (let j = run.to + 1; j < windows.length && picked[j] === run.plan && anchors.length < 12; j += 1) anchors.push(j)
1038    if (anchors.length === 0) for (let j = run.from - 1; j >= 0 && picked[j] === run.plan && anchors.length < 12; j -= 1) anchors.unshift(j)
1039    const members = [...new Set([...anchors, ...Array.from({ length: run.to - run.from + 1 }, (_, k) => run.from + k)])]
1040      .sort((a, b) => a - b)
1041      .filter(i => strays[i] !== null)
1042    if (members.length < 2 * MIN_STRETCH) continue
1043    const xs = members.map(i => strays[i]!)
1044    const steps = xs.slice(1).map((x, k) => Math.abs(x - xs[k]!))
1045    const spread = Math.max(0.05, (1.4826 * (median(steps) ?? 0)) / Math.SQRT2)
1046    const parts = stretchesOf(xs, spread)
1047    if (parts.length < 2) continue
1048    const level = ([a, b]: [number, number]) => xs.slice(a, b).reduce((acc, x) => acc + x, 0) / (b - a)
1049    const home = parts.find(([a, b]) => members.slice(a, b).some(i => anchors.includes(i))) ?? parts[parts.length - 1]!
1050    for (const part of parts) {
1051      if (part === home || Math.abs(level(part) - level(home)) < LOG_JUMP) continue
1052      const own = members.slice(part[0], part[1]).filter(i => !anchors.includes(i))
1053      if (own.length === 0) continue
1054      const label = `~${inferredRuns.length + 1}`
1055      for (const i of own) labels[i] = label
1056      inferredRuns.push({ label, members: own, against: run.plan })
1057    }
1058  }
1059
1060  const segs = withLabels()
1061  const solved = solveSegments(kind, segs, preferRef, borrow)
1062  const fit = solved.fit
1063  const inferred: InferredPlan[] = inferredRuns.map(({ label, members, against }) => {
1064    const ratio = (fit.s[label] ?? 1) / (planScale(fit, against) ?? 1)
1065    return {
1066      label,
1067      from: windows[members[0]!]! - length,
1068      to: windows[members[members.length - 1]!]!,
1069      windows: members.length,
1070      ratio,
1071      against,
1072      guess: guessPlan(ratio, against),
1073    }
1074  })
1075  // Official changes since the latest window began: a published one scales the window to come, one
1076  // of unknown size leaves the fit to say nothing sure until a window after it is read.
1077  const since = OFFICIAL_CHANGES.filter(c => c.kind === kind && c.at > windows[windows.length - 1]! - length)
1078  const later = since.some(c => c.x === null) ? null : since.reduce((a, c) => a * c.x!, 1)
1079  // Sure as far as the windows it has not seen bear it out: high within 12% (a typical miss, in
1080  // logs) on four windows or more, medium within 30% on two; never above low while the kinds that
1081  // set a way of use apart are not told apart (cache bands wider than 15 times), or a change of
1082  // unknown size has come since.
1083  const held = heldOutMiss(kind, segs, preferRef, borrow, solved)
1084  const bandOf = (k: number) => {
1085    const [lo, hi] = fit.gBand[k] ?? [0, Infinity]
1086    return Number.isFinite(hi) && lo > 0 ? hi / lo : Infinity
1087  }
1088  const isTold = Math.max(bandOf(2), bandOf(3)) <= 15
1089  const confidence: Fit['confidence'] =
1090    later === null || held === null || !isTold
1091      ? 'low'
1092      : held.windows >= 4 && held.miss <= 0.12
1093        ? 'high'
1094        : held.windows >= 2 && held.miss <= 0.3
1095          ? 'medium'
1096          : 'low'
1097  return {
1098    ...fit,
1099    windowPlans: Object.fromEntries(windows.map((w, i) => [String(w), labels[i]!])),
1100    latest: labels[labels.length - 1] ?? null,
1101    inferred,
1102    confidence,
1103    heldOut: held?.miss ?? null,
1104    heldOutWindows: held?.windows ?? 0,
1105    later,
1106  }
1107}
1108
1109// The share of a plan's window a spend takes, by the fit.
1110export function shareOf(fit: Fit, plan: string, byModel: Record<string, Vec>): number {
1111  const s = planScale(fit, plan) ?? 1
1112  let share = 0
1113  for (const [m, v] of Object.entries(byModel)) {
1114    share += ((fit.f[m] ?? 1) * spendByKind(m, v).reduce((acc, x, k) => acc + fit.g[k]! * x, 0)) / s
1115  }
1116  return share
1117}
1118
1119export type FittedEstimate = {
1120  plan: string
1121  capacityUsd: number
1122  remainingUsd: number
1123  explained: number
1124  etaMs: number | null
1125  // The share used at the reset when it does not fill before; null when there is no reset time.
1126  atReset: number | null
1127}
1128
1129// Reads the current window through a fit. What is left comes from the official percent (so other
1130// devices' use counts). Dollars are told at this window's own way of using it: its API spend over
1131// the share the fit gives that spend. The coming hours each spend what that hour of the day has
1132// averaged, by model and kind, until what is left is used.
1133export function fittedWindow(
1134  w: Window,
1135  fit: Fit | undefined,
1136  plan: string | null,
1137  windowByModel: Record<string, Vec> | undefined,
1138  hourly: Record<string, number[][]>,
1139  tzOffsetMin: number,
1140  now: number,
1141): FittedEstimate | null {
1142  if (fit === undefined || fit.confidence === 'none') return null
1143  const s = planScale(fit, plan ?? CURRENT)
1144  if (s === null) return null
1145
1146  const y = w.percentUsed / 100
1147  const left = Math.max(0, 1 - y)
1148  const explained = shareOf(fit, plan ?? CURRENT, windowByModel ?? {})
1149  const windowUsd = Object.entries(windowByModel ?? {}).reduce((acc, [m, v]) => acc + costOf(m, v), 0)
1150
1151  const perHour = new Array<number>(24).fill(0)
1152  const usdHour = new Array<number>(24).fill(0)
1153  for (const [m, hours] of Object.entries(hourly)) {
1154    hours.forEach((kinds, hour) => {
1155      perHour[hour]! += ((fit.f[m] ?? 1) * kinds.reduce((acc, x, k) => acc + fit.g[k]! * x, 0)) / s
1156      usdHour[hour]! += kinds.reduce((a, b) => a + b, 0)
1157    })
1158  }
1159  // Dollars per whole window: this window's if it has spent enough to say, else the day's average.
1160  const profileShare = perHour.reduce((a, b) => a + b, 0)
1161  const usdPerWindow = explained >= 0.03 ? windowUsd / explained : profileShare > 0 ? usdHour.reduce((a, b) => a + b, 0) / profileShare : 0
1162
1163  const reset = Date.parse(w.resetsAt ?? '')
1164  let etaMs: number | null = null
1165  let used = 0
1166  if (!Number.isNaN(reset)) {
1167    const offset = tzOffsetMin * MINUTE
1168    let t = now
1169    while (t < reset && etaMs === null) {
1170      const end = Math.min((Math.floor((t + offset) / HOUR) + 1) * HOUR - offset, reset)
1171      const rate = perHour[new Date(t + offset).getUTCHours()]! / HOUR
1172      if (rate > 0 && used + rate * (end - t) >= left) etaMs = t + (left - used) / rate - now
1173      used += rate * (end - t)
1174      t = end
1175    }
1176  }
1177  const atReset = Number.isNaN(reset) || etaMs !== null ? null : Math.min(1, y + used)
1178  return { plan: plan ?? CURRENT, capacityUsd: usdPerWindow, remainingUsd: left * usdPerWindow, explained, etaMs, atReset }
1179}
1180
1181// ---- Engine calls ---------------------------------------------------------
1182
1183// Claude Code's own folder: CLAUDE_CONFIG_DIR, else ~/.claude.
1184async function configDir($: EngineInterface): Promise<string> {
1185  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? ''
1186  return (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`
1187}
1188
1189// Where Claude Code keeps this session's transcript: <config>/projects/<root, each
1190// character outside [A-Za-z0-9] made '-'>/<session id>.jsonl.
1191async function transcriptPath($: EngineInterface): Promise<string> {
1192  const id = await $.session.id()
1193  const root = await $.session.root()
1194  return `${await configDir($)}/projects/${root.replace(/[^a-zA-Z0-9]/g, '-')}/${id}.jsonl`
1195}
1196
1197// Fills the session's counts from its transcript and its subagents', so what ran before the mod
1198// loaded counts. The scanner reads them: a transcript outgrows what `$.fs.read` takes (4 MiB).
1199// Answers whether it read one; the live counts stand when it cannot.
1200async function backfill($: EngineInterface, path: string): Promise<boolean> {
hooks/i18n.ts 244 lines
1// The words token-almanac draws, in each language it speaks. English is the fallback and the
2// shape every other table follows; a new language is one more table of the same type.
3
4export type Locale = 'en' | 'zh'
5
6const en = {
7  kinds: { input: 'input', output: 'output', cacheRead: 'cache read', cacheWrite: 'cache write' },
8  windows: {
9    five_hour: '5-hour',
10    seven_day: 'Weekly',
11    seven_day_opus: 'Weekly Opus',
12    seven_day_sonnet: 'Weekly Sonnet',
13    spend_limit: 'Spend limit',
14  } as Record<string, string>,
15  plans: {
16    pro: 'Pro',
17    max5x: 'Max 5x',
18    max20x: 'Max 20x',
19    team: 'Team',
20    team_premium: 'Team Premium',
21    enterprise: 'Enterprise',
22    current: 'Current plan',
23  } as Record<string, string>,
24  confidence: { none: 'no data', low: 'low', medium: 'medium', high: 'high' },
25
26  resetsIn: (d: string) => `resets in ${d}`,
27  resetting: 'resetting',
28  fullIn: (d: string) => `full in ~${d}`,
29  full: 'used up',
30  flat: 'not rising lately',
31  safe: 'on pace to last',
32  atReset: (p: string) => `~${p}% at reset`,
33  updatedNow: 'just now',
34  updatedAgo: (d: string) => `${d} ago`,
35
36  paneTitle: 'Token usage',
37  paneOpened: 'Token usage pane opened.',
38  paneWaiting: 'The token usage pane is waiting for room to open.',
39  commandDescription: 'Open the token usage pane and show its band again',
40
41  bandContext: (p: number) => `context ${p}%`,
42  bandFull: (d: string) => `full in ${d}`,
43  bandWaiting: 'limits: waiting for a reply',
44  bandNoLimits: 'API billing · no plan limits',
45  bandOpen: 'Details',
46  bandHide: 'Hide',
47
48  tabSession: 'This session',
49  tabGlobal: 'This machine',
50  waitingLimits: 'Limits show after the next reply',
51  noLimits: 'This account has no plan limits (API billing)',
52  close: 'Close',
53
54  statCost: 'API-equivalent',
55  statTokens: 'tokens',
56  statContext: (w: string) => `of ${w} context`,
57  statTurns: 'turns',
58  statRange30: 'last 30 days',
59  statRangeAll: 'all time',
60  statPerDay: 'per day',
61  statSpan: 'span',
62  days: (n: number) => `${n} d`,
63
64  composition: 'Makeup',
65  byCost: 'by API-equivalent cost',
66  perTurn: 'Turns',
67  perTurnAside: (n: number, peakN: number, peak: string) => `last ${n} · peak #${peakN} ${peak}`,
68  noTurns: 'No finished turns yet',
69  turnTitle: (n: number, tokens: string, out: string, write: string, read: string, subagents: number) =>
70    `Turn ${n}  ${tokens} tokens\noutput ${out} · cache write ${write} · cache read ${read}${subagents ? `\nwith ${subagents} subagent${subagents > 1 ? 's' : ''}` : ''}`,
71  models: 'Models',
72  projects: 'Projects',
73  daily: 'Daily',
74  peak: (usd: string) => `peak ${usd}`,
75  noUsage: 'No usage in this range',
76  other: 'other',
77  sessionNote: (d: string) => `Covers this session's ${d}, subagents included · API-equivalent at list prices`,
78
79  scanning: 'Scanning…',
80  scanFailed: (m: string) => `Scan failed: ${m}`,
81  nodeMissing: 'Reading history needs Node.js 18+ (set its path in /config). Session figures still work.',
82  files: (n: number, ago: string) => `${n} files · ${ago}`,
83  range30: '30 days',
84  rangeAll: 'All',
85  refresh: 'Refresh',
86  history: 'Usage history',
87  keyElapsed: 'time through the window',
88  keyProjected: 'where it is headed by the reset',
89  showMore: 'Show breakdown',
90  showLess: 'Hide breakdown',
91  firstScan: 'The first scan reads every transcript under your Claude config folder and takes a few seconds; later ones read only what is new.',
92
93  capacity: 'Capacity',
94  capacityAside: (plan: string) => `${plan} · API-equivalent`,
95  colWhole: 'Window',
96  colLeft: 'Left',
97  colOutlook: 'At your usual pace',
98  colConfidence: 'Confidence',
99  capacityNone: 'Not enough history yet: estimates start once a window has risen 5 points.',
100  hitsLine: (kind: string, n: number, lo: string, hi: string) => `${kind}: hit the limit ${n} time${n > 1 ? 's' : ''}, at ${n > 1 ? `${lo}–${hi}` : lo} each`,
101  details: 'How it is estimated',
102  hideDetails: 'Hide estimate details',
103  fitHead: (conf: string, segments: number, hits: number) => `· confidence ${conf} · ${segments} pieces · ${hits} limit hits`,
104  fitCounts: (segments: number, hits: number) => `${segments} pieces · ${hits} limit hits`,
105  fitMiss: (x: string) => ` · off by ${x} pts`,
106  fitOutliers: (n: number) => ` · ${n} outliers`,
107  fitLent: (kind: string) => ` · leaning on the ${kind} fit`,
108  fitUnseen: (n: number) => ` · ${n} piece${n > 1 ? 's' : ''} likely with use from elsewhere, set aside`,
109  fitHeldOut: (n: number) => ` · ± is the typical miss on the latest ${n} window${n > 1 ? 's' : ''}, each foretold from the rest`,
110  fitEras: (n: number) => ` · split at ${n} official limit change${n > 1 ? 's' : ''}`,
111  fitPending: ' · limits changed officially after the last window read: unsure until a window after the change',
112  kindWeights: 'Per API dollar, against output: ',
113  undetermined: 'unclear',
114  against: (ref: string) => `Against ${ref}: `,
115  multipleNote: (nominal: number | null, n: number) => (nominal !== null ? ` (sold as ×${nominal}, ${n} windows)` : ` (${n} windows)`),
116  planPick: 'Plan',
117  planUnknown: 'Not sure',
118  planHint: 'Pick your plan to have estimates told against it; until then they are relative to whatever plan you are on.',
119  inferredLine: (from: string, to: string, ratio: string, against: string, guess: string | null, n: number) =>
120    `${from} – ${to}: ×${ratio} of ${against}${guess !== null ? `, likely ${guess}` : ''} (inferred, ${n} windows)`,
121  dataNote:
122    'From the Claude Code transcripts on this machine (subagents included); claude.ai and other devices are not in them. API-equivalent uses list prices (override in token-almanac/prices.json). Estimates fit pieces of 5 points or more and past limit hits, as model factor × token kind factor and plan multiples, with each window free to run a little large or small, a level that steps at official limit changes and drifts slowly between them. Before the plan you pick, a stretch whose rate moved by 1.8× or more is taken as another plan. Confidence is how well the latest windows are foretold from the others. How limits are counted is not published: these are inferences.',
123  unpriced: (list: string) => ` Not priced, counted as 0: ${list}.`,
124}
125
126export type Messages = typeof en
127
128const zh: Messages = {
129  kinds: { input: 'input', output: 'output', cacheRead: 'cache 读', cacheWrite: 'cache 写' },
130  windows: { five_hour: '5 小时', seven_day: '每周', seven_day_opus: '每周 Opus', seven_day_sonnet: '每周 Sonnet', spend_limit: '花费上限' },
131  plans: { pro: 'Pro', max5x: 'Max 5x', max20x: 'Max 20x', team: 'Team', team_premium: 'Team Premium', enterprise: 'Enterprise', current: '当前套餐' },
132  confidence: { none: '无数据', low: '低', medium: '中', high: '高' },
133
134  resetsIn: d => `${d}后重置`,
135  resetting: '即将重置',
136  fullIn: d => `约 ${d} 后用满`,
137  full: '已用满',
138  flat: '近期未增长',
139  safe: '按当前节奏用不满',
140  atReset: p => `重置时约 ${p}%`,
141  updatedNow: '刚刚更新',
142  updatedAgo: d => `${d}前更新`,
143
144  paneTitle: 'Token 用量',
145  paneOpened: 'Token 用量面板已打开。',
146  paneWaiting: 'Token 用量面板等待空间打开。',
147  commandDescription: '打开 Token 用量面板,并重新显示横条',
148
149  bandContext: p => `上下文 ${p}%`,
150  bandFull: d => `${d} 后满`,
151  bandWaiting: '限额:等待首个响应',
152  bandNoLimits: 'API 计费 · 无订阅限额',
153  bandOpen: '详情',
154  bandHide: '隐藏',
155
156  tabSession: '本次会话',
157  tabGlobal: '本机全局',
158  waitingLimits: '等待首个响应带回限额读数',
159  noLimits: '这个账户没有订阅限额(API 计费)',
160  close: '关闭',
161
162  statCost: '折算花费',
163  statTokens: 'tokens',
164  statContext: w => `上下文 ${w}`,
165  statTurns: '轮',
166  statRange30: '近 30 天折算',
167  statRangeAll: '全部折算',
168  statPerDay: '日均',
169  statSpan: '跨度',
170  days: n => `${n} 天`,
171
172  composition: '构成',
173  byCost: '按折算花费',
174  perTurn: '每轮',
175  perTurnAside: (n, peakN, peak) => `最近 ${n} 轮 · 峰值第 ${peakN} 轮 ${peak}`,
176  noTurns: '还没有完成的轮次',
177  turnTitle: (n, tokens, out, write, read, subagents) =>
178    `第 ${n} 轮  ${tokens} tokens\noutput ${out} · cache 写 ${write} · cache 读 ${read}${subagents ? `\n含子代理 ${subagents} 个` : ''}`,
179  models: '模型',
180  projects: '项目',
181  daily: '每日',
182  peak: usd => `峰值 ${usd}`,
183  noUsage: '这段时间没有用量',
184  other: '其他',
185  sessionNote: d => `覆盖本会话 ${d},含子代理 · 折算按 API 价格`,
186
187  scanning: '扫描中…',
188  scanFailed: m => `扫描失败:${m}`,
189  nodeMissing: '读取历史记录需要 Node.js 18 以上(可在 /config 里设置路径),会话内统计不受影响。',
190  files: (n, ago) => `${n} 个文件 · ${ago}`,
191  range30: '近 30 天',
192  rangeAll: '全部',
193  refresh: '刷新',
194  history: '历史用量',
195  keyElapsed: '窗口时间进度',
196  keyProjected: '按节奏预计到重置',
197  showMore: '展开明细',
198  showLess: '收起明细',
199  firstScan: '首次扫描读取 Claude 配置目录下的全部会话记录,约需数秒;之后只读新增部分。',
200
201  capacity: '容量推算',
202  capacityAside: plan => `${plan} · 按 API 价格折算`,
203  colWhole: '整窗',
204  colLeft: '剩余',
205  colOutlook: '按历史节奏',
206  colConfidence: '可信度',
207  capacityNone: '历史数据不足:窗口用量涨满 5 个点后开始推算。',
208  hitsLine: (kind, n, lo, hi) => `${kind}历史触限 ${n} 次,每次折合 ${n > 1 ? `${lo}–${hi}` : lo}`,
209  details: '推算细节',
210  hideDetails: '收起推算细节',
211  fitHead: (conf, segments, hits) => `· 可信度 ${conf} · ${segments} 段 · ${hits} 次触限`,
212  fitCounts: (segments, hits) => `${segments} 段 · ${hits} 次触限`,
213  fitMiss: x => ` · 误差 ${x} 点`,
214  fitOutliers: n => ` · ${n} 段离群`,
215  fitLent: kind => ` · 参照 ${kind}窗口`,
216  fitUnseen: n => ` · ${n} 段疑似有本机之外的用量,已排除`,
217  fitHeldOut: n => ` · ± 为最近 ${n} 个窗口逐个留出、用其余窗口预测的典型误差`,
218  fitEras: n => ` · 按 ${n} 次官方额度调整分段`,
219  fitPending: ' · 最后读到的窗口之后官方调整过额度,读到调整后的窗口前不作准',
220  kindWeights: '每 API 美元相对 output:',
221  undetermined: '未定',
222  against: ref => `相对 ${ref}:`,
223  multipleNote: (nominal, n) => (nominal !== null ? `(标称 ×${nominal},${n} 个窗口)` : `(${n} 个窗口)`),
224  planPick: '套餐',
225  planUnknown: '不确定',
226  planHint: '选择你的套餐后,推算会按该套餐给出;未选择时按相对倍数显示。',
227  inferredLine: (from, to, ratio, against, guess, n) => `${from} – ${to}:约为 ${against} 的 ×${ratio}${guess !== null ? `,可能是 ${guess}` : ''}(推测,${n} 个窗口)`,
228  dataNote:
229    '数据来自本机的 Claude Code 会话记录(含子代理),不含网页版和其他设备。折算按官方 API 价格(可用 token-almanac/prices.json 覆盖)。推算用每涨 5 个点的分段和历史触限,拟合模型系数 × token 类型系数与套餐倍数,允许每个窗口略大或略小,额度水平在官方调整处分段、其间缓慢漂移;所选套餐之前,比率变化 1.8 倍以上的时段视为另一个套餐。可信度看最近的窗口能否由其余窗口预测准。限额的真实算法未公开,结果是推断。',
230  unpriced: list => ` 未定价、按 0 计:${list}。`,
231}
232
233export const MESSAGES: Record<Locale, Messages> = { en, zh }
234
235// A locale from a language name or tag, as Claude Code's `language` setting, LANG or Intl give
236// it ("chinese", "简体中文", "zh_CN.UTF-8", "en-US"); null when it names none we speak.
237export function localeOf(value: string | undefined | null): Locale | null {
238  const v = String(value ?? '').trim().toLowerCase()
239  if (v === '' || v === 'c' || v === 'posix') return null
240  if (/^zh|chinese|中文|汉语|漢語/.test(v)) return 'zh'
241  if (/^en|english/.test(v)) return 'en'
242  return null
243}
244
types/index.d.ts 152 lines
1// Token counts in the four kinds the API reports.
2export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
3
4// One main-thread turn, with the subagent turns that finished while it ran.
5export type TurnRow = { n: number; at: number; tokens: Tokens; subagentTurns: number }
6
7// One rate-limit window as the last API response reported it.
8export type Window = { kind: string; percentUsed: number; resetsAt?: string }
9
10// The status line's figures, as `$.session.usage()` and `session.measure` give them.
11export type Snapshot = {
12  at: number
13  contextTokens?: number
14  contextWindow: number
15  contextPercent?: number
16  costUsd?: number
17  windows: Window[]
18}
19
20// Readings of one window's percent over time, for the burn-rate forecast.
21export type Samples = { resetsAt?: string; points: [number, number][] }
22
23// [input, output, cacheRead, cacheWrite5m, cacheWrite1h], as the scanner sums them.
24export type Vec = [number, number, number, number, number]
25
26// One local day and hour of one project and model: [day, hour, project, model, ...Vec].
27export type ScanRow = [string, number, string, string, number, number, number, number, number]
28
29// A plan picked in the pane, in force from that moment on; null for "not sure".
30export type PlanChoice = { at: number; plan: string | null }
31
32// A limit reading kept by the mod: [at, window kind, percent used, resets at].
33export type Reading = [number, string, number, number]
34
35// A reading or a limit hit (100% at that moment), with what each model cost in its window so far.
36export type Observation = { t: number; kind: string; y: number; resetsAt: number; hit: boolean; exact?: boolean; byModel: Record<string, Vec> }
37
38// One window kind's fit: rise × plan multiple ≈ Σ f[model] × Σ g[kind] × API spend[model][kind].
39export type Fit = {
40  kind: string
41  windows: number
42  // Pieces of windows (5 points or more each) and limit hits it learned from.
43  segments: number
44  hits: number
45  // Per model, against the reference model (1).
46  f: Record<string, number>
47  // Per kind of token (input, output, cache read, cache write): the share of a Pro window one API
48  // dollar of it takes, on the reference model.
49  g: number[]
50  // 95% band of each kind's weight against output's.
51  gBand: [number, number][]
52  // Per plan: its window's size as a multiple of the reference plan's.
53  s: Record<string, number>
54  // The plan picked now if it has windows, else the one with the most; 'current' stands for
55  // the plan in force when none was ever picked.
56  refPlan: string
57  planWindows: Record<string, number>
58  // The plan each window (keyed by when it resets) was counted under: picked, or inferred.
59  windowPlans: Record<string, string>
60  // The plan of the latest window.
61  latest: string | null
62  // Stretches with no pick whose rate stood apart from the plan next to them.
63  inferred: InferredPlan[]
64  // Median miss, in percentage points; pieces weighed down as unexplained.
65  mae: number | null
66  outliers: number
67  // Pieces that rose far past their spend, set aside as use this machine did not see.
68  unseen?: number
69  confidence: 'none' | 'low' | 'medium' | 'high'
70  // The model with the most spend.
71  ref: string | null
72  // The window kind whose fit this one leaned on for its kinds' and models' weights, if any.
73  lent?: string | null
74  // How far one window's size strays from its kind's level, in logs.
75  tau?: number
76  // Official changes to the window's size the windows span, each given a level of its own.
77  eras?: number
78  // The typical miss (root mean square, in logs) on the latest windows, each foretold by a fit of
79  // the rest, and how many windows that rests on; null when too few windows say.
80  heldOut?: number | null
81  heldOutWindows?: number
82  // Published changes to the window's size since the latest window began, multiplied; null when
83  // one of them was of a size not published.
84  later?: number | null
85}
86
87// A stretch of windows with no pick behind it whose share per API dollar moved apart from the
88// plan next to it, fitted as a plan of its own: its window against that plan's, and the plan sold
89// at about that multiple, if one is.
90export type InferredPlan = { label: string; from: number; to: number; windows: number; ratio: number; against: string; guess: string | null }
91
92// What `scan/scan.mjs global` prints: every transcript on this machine, summed.
93export type GlobalScan = {
94  rows: ScanRow[]
95  windows: Record<string, { start: number; byModel: Record<string, Vec>; byProject: Record<string, Vec> }>
96  observations: Observation[]
97  today: string
98  tzOffsetMin: number
99  files: number
100  readBytes: number
101  ms: number
102  at: number
103}
104
105// The machine view over one range: cost per day, project and model, and each local hour's average.
106export type GlobalView = {
107  days: number
108  totalCost: number
109  totalTokens: number
110  daily: { day: string; byModel: Record<string, number> }[]
111  byProject: { project: string; cost: number; tokens: number }[]
112  byModel: { model: string; cost: number; tokens: number }[]
113  hourly: number[]
114  // Per model, per local hour of the day, the average API spend by kind of token.
115  hourlyByModel: Record<string, number[][]>
116  unpriced: string[]
117}
118
119// What the machine view draws, worked out once per scan or pick rather than at each drawing: both
120// ranges, the fits, and the API-equivalent cost of each limit hit under the plan in force now.
121export type Machine = {
122  at: number
123  files: number
124  tzOffsetMin: number
125  windows: GlobalScan['windows']
126  views: { '30d': GlobalView; all: GlobalView }
127  fits: Record<string, Fit>
128  hits: Record<string, number[]>
129}
130
131export type ScanStatus = { state: 'idle' | 'scanning' | 'error'; message?: string }
132
133declare module 'claude-code' {
134  interface PluginState {
135    'token-almanac': {
136      since: number
137      totals: Tokens
138      byModel: Record<string, Tokens>
139      turns: TurnRow[]
140      snapshot: Snapshot | null
141      samples: Record<string, Samples>
142      isBandHidden: boolean
143      view: 'session' | 'global'
144      range: '30d' | 'all'
145      machine: Machine | null
146      scanStatus: ScanStatus
147      planChoices: PlanChoice[]
148      details: boolean
149    }
150  }
151}
152