SLOPSHOPPER

usage-dollars

Shows subscription usage for the 5-hour window and the week as API-equivalent dollars: estimated allowance first, then used and left, with 90% ranges; spending…

rowscommandtoaststatusprocess
v0.8.0no licenseupdated 2026-10-13hyvanmielenpelit/ClaudeCodeMods/usage-dollars
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-dollars
› fix the failing auth test and add an audit log call ● usage-dollars: usage-dollars: history: helper exited with 0 ● usage-dollars: usage-dollars: RangeError: Invalid Date ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /usage-dollars ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ │ │ Waiting for the first usage reading · usage-dollars │ │ │ │ ✓ Everything is in order. The plugin is installed and running; it has simply not received a usage reading yet. │ │ This is expected right after the plugin is installed or updated, and on its first use on this machine. │ │ │ │ Why there are no figures yet │ │ Claude Code learns how much of the 5-hour window and the week has been used only from the API, and the API │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Command output
╭─────────────────────────────────────────────────────────────────────────────────────────────────── │ │ Waiting for the first usage reading · usage-dollars │ │ ✓ Everything is in order. The plugin is installed and running; it has simply not received a │ usage reading yet. This is expected right after the plugin is installed or updated, and on its │ first use on this machine. │ │ Why there are no figures yet │ Claude Code learns how much of the 5-hour window and the week has been used only from the API, │ and the API reports it alongside each model reply: the percent used and when each window │ resets. Every figure on this card is built on that reading, and this installation has not │ stored one yet. │ │ This sign-in has no subscription usage limits, so there is nothing to show; spending reports │ still work. │ │ If no figures appear after a reply, /usage-dollars check shows what is missing. │ ╰───────────────────────────────────────────────────────────────────────────────────────────────────
README

Claude Code Mods

Mods for Claude Code by Hyvän Mielen Pelit, written as function-hook plugins. The repository is also a plugin marketplace.

ModWhat it does
usage-dollarsSubscription usage for the 5-hour window and the week as API-equivalent dollars: the estimated allowance first, then used and left, with 90% ranges; spending reports by date range.

Installing

From inside Claude Code:

/plugin marketplace add hyvanmielenpelit/ClaudeCodeMods
/plugin install usage-dollars@hyvanmielenpelit-claude-code-mods

To load a working copy for one session instead:

claude --plugin-dir C:\hmp\ClaudeCodeMods\usage-dollars

Sessions the desktop app starts take no flags; name the folder in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json instead.

Function-hook plugins are an early-access Claude Code surface and may change between releases. Check a mod with claude plugin validate <folder>.

usage-dollars

Shows on the status line, what is left of each window's estimated allowance:

usage-dollars  5h ~$850 left of $913 · Week ~$2.7k left of $2.8k

While a window has no estimate yet it reads 5h $40 used, estimating, and once nothing is left, 5h at limit. ⚠ Plan changed means a plan change was observed and the card has not been opened since.

Commands

CommandShows
/usage-dollarsThe window card: plan, notices, each window's allowance first, then used, left, the next tick, and spending per model
/usage-dollars helpThe quick start: setup, everyday commands, good habits
/usage-dollars help advancedThe full guide: every command, reading the card, calibration, the setup check, troubleshooting
/usage-dollars reportSpending in the last 24 hours, per day and per model
/usage-dollars 24h, /usage-dollars 7dSpending in the last N hours or days, up to 90 days
/usage-dollars todaySpending since local midnight
/usage-dollars 2026-10-01Spending on one local day
/usage-dollars 2026-10-01..2026-10-05Spending over local days, both inclusive
/usage-dollars resetRestarts the estimates for this subscription (see below)
/usage-dollars reset undoUndoes the latest reset
/usage-dollars checkA setup check: the helper, the subscription, other sessions' hooks and price table, this session's readings, the stored dollars per model, the prices; each ✓, ✗ with the fix, or ℹ
/usage-dollars calibrateWhat each window's estimate rests on: percent levels and ticks read, whether each spread and the rounding rule are measured and from how many windows, the current range
/usage-dollars modelsA read-only study, as seen from this machine, of how each model counts against the limit relative to its API price: the selected meter model with each weight's 90% interval, the cross-validated comparisons behind it, whether the weights hold for the week, and the prospective check

The window card is allowance-first: a headline row gives each window's estimated allowance, its 90% range and a confidence label (good within about ±10%, fair within ±30%, rough beyond), followed by "calibrated" once both spreads and the rounding rule are measured. Each window then shows what is used and what is left, a bar of used dollars against the allowance range, the percent the estimate rests on ("Limit reports 10% · read 2 min ago"), and "next tick": about how many more dollars until the reported percent moves again. Before the first estimate a window reads "estimating…"; the first estimate follows the first reply that finds the window above 0%, or comes at once from past windows when there are any.

Until an installation has stored a reading, /usage-dollars and /usage-dollars calibrate show a "Waiting for the first usage reading" card instead. A reading comes only with a reply in the main conversation. Interactive terminal sessions rarely need to wait, because Claude Code sends a minimal request of its own at startup there. A new desktop session has no reading until its first reply. The card's button, "Send a short check message (uses one turn)", sends one self-describing message asking for a one-word reply and no tools. It is sent only when pressed and is not offered again until a turn completes. A plugin's own model request does not bring a reading, so nothing is sent automatically. A sign-in without a subscription never gets a reading, and the card says so.

A spending report covers only as far back as this machine's transcripts do. When the range starts earlier, the report says where the transcripts begin.

Getting rigorous estimates

The quick start (/usage-dollars help) has the short version. The full guide (/usage-dollars help advanced) covers these steps in detail, with what each line of check and calibrate means, how long calibration takes, and what to do when something changes.

  1. Load one copy, then restart every session. Sessions that started before an update keep running the old hooks and can lose readings.
  2. Run /usage-dollars check and fix every ✗.
  3. Use Claude Code as you would anyway. A reading is taken after every reply in any session of the subscription. The first ranges are wide, because both spreads are still assumptions; they narrow as the percent ticks over and as windows close.
  4. Run /usage-dollars calibrate to see what has been measured. Every closed window that reached 10% counts, weighted by how much it says; a window that hit the limit counts in full. Light use calibrates more slowly. A window reads "Calibrated" once the within-window spread rests on 2 closed windows, the between-window spread on about 3 past windows' worth of information, and the rounding rule on 5 closed windows.
  5. After a plan change or a promotion the card says so, or run /usage-dollars reset; calibration starts again from the next window. A change of the price table does the same.

The plan line and plan changes

The plan comes from the signed-in account profile in ~/.claude.json (or $CLAUDE_CONFIG_DIR/.claude.json), for example "Plan: Max 20x · profile as of Mon 5 Oct, 10:23". Claude Code refreshes that profile on its own schedule, sometimes a day or more apart, so the card always says how old it is and adds "(may be out of date)" after a week. The profile describes only the subscription Claude Code is signed in to now: a session that bills another subscription shows "Plan: unknown for this subscription", with the plan last seen for it. Plan values the mod does not know are shown verbatim, never guessed.

The mod tells two kinds of change apart:

  • Observed. The profile reported a different plan. The card says "Plan changed: Max 5x → Max 20x (between … and …)". The change is known only between the two profile fetches, and estimates restart from the later one, so no reading taken under the old plan is used.
  • Inferred. The current window no longer fits recent windows. The card says limits may have changed and suggests a reset, but changes nothing by itself. Usage on another device, or on claude.ai, raises the percent without raising this machine's dollars, and looks exactly like a lowered limit.

Promotions that Claude Code has cached for the signed-in subscription are shown too. A new promotion restarts the estimates for the window it names, and so does its end date passing.

Starting over: /usage-dollars reset

Use it after changing plans when the card does not show the change yet, when a promotion starts or ends that the card did not report, or after the inferred-change notice when you know the limits really changed.

DataAfter reset
Closed windows' readings and rate-limit rejections from before the resetNo longer feed the prior or the measured spreads. Both spreads fall back to their assumed values until new windows close.
The current window's readings taken before the resetExcluded. The estimate rebuilds from readings taken after it; the first scan after it takes one at once.
The current window's used dollarsUnchanged: they are a fact about spending, not about the limit.
The plan ledger, spending reports, the 24-hour figure, per-model tablesUnchanged.
Stored dataNothing is deleted. Readings stay until the normal 28-day pruning.
Other subscriptionsUnaffected.

Ranges widen to what the current readings alone support, then narrow again as the percent ticks over: under an hour of normal work on a 5-hour window, about a day on the week. /usage-dollars reset undo restores the earlier estimates, apart from readings taken in between. Two resets are undone one at a time. A reset followed by an observed plan or promotion change can no longer be undone.

How the figures are made

  • Used prices every request in this machine's transcripts since the window began at API list rates: input, output, cache reads, 5-minute and 1-hour cache writes, fast mode and web searches. Only requests billed to the subscription the session runs on count, matched through the bridge-session records the desktop app writes; a session with no record is taken to bill the signed-in subscription. Checked against Claude Code's own per-session costs it usually comes within a few percent, and up to a quarter low on long sessions, because some billed calls never reach a transcript.
  • Readings. The API reports the window's usage in whole percent, and the percent a response carries includes that response. A reading is taken when this session has just received the percent, and pairs it with the dollars counted up to the moment it arrived, not up to when the scan runs. Another session's request in the 30 seconds before that moment may or may not be in the percent yet; its dollars are kept with the reading as slack. Running sessions share the freshest percent between them, and a reading is also taken for a percent another session stored without one, with the dollars up to when that session received it. No reading is taken while more than 2% of a window's requests go to unpriced models, and readings priced with an older price table are dropped. Each reading also stores its dollars per model and token class (input, output, cache reads, each cache write, web searches), its "features", for both window kinds. Readings from before are backfilled from the transcripts where they still exist; a window that cannot be rebuilt is marked and left out of the model study only.
  • Allowance rests on the newest percent level. When the level below it was read too, the percent ticked over between those two readings, and the dollars at that moment divided by the share at the tick give the dollars per percent; otherwise the share anywhere in the level's interval does. Until closed windows show whether the API rounds or truncates, the tick is either rule's, and the range covers both. A level of 100% is used only through its crossing: spending can continue past the limit. A level of 0% is not used either, since it only says the share is under one tick; while it is the only level read, the estimate is the prior from past windows alone, when there is one, and the basis line says so.
  • The 90% range comes from a stated model. The dollars one percent costs vary within a window, because API prices weight tokens differently from the limit. Read at share s, the dollars per percent so far differ from the whole window's by a relative spread omega · √(1/s − 1/100), which vanishes as the window fills; so "left" narrows as it is used. Between windows the allowance itself varies by tau. Past windows act as a prior that is combined with the current reading by precision, unless the two disagree beyond chance; then the reading alone counts and the card says limits may have changed. The interval uses Student's t, so few past windows widen it.
  • Two spreads start as assumptions: omega = 0.5 within a window and tau = 10% between windows. Each is shrunk toward what this machine's own closed windows show: omega from how far the dollars per percent at each tick of a closed window strayed from its end, tau from the scatter of past allowances. The card's basis line says which is assumed and which measured. Past windows come from the mod's own readings of closed windows that reached 10%, each weighted by how much it says, and from rate-limit rejections in the last 14 days of transcripts, each a window seen exactly full; a window seen both ways counts once. Older windows count for less: a past 5-hour window loses half its weight every day, a past week every 14 days, so the estimate follows a change of limits quickly. The card's "history weight" is the effective number of past windows behind the prior.

How fast the allowance can be known, with no past windows, from the coverage simulation in tests/coverage.test.mjs (scenario S1: steady requests of about $0.60 against a $650 window). The first column holds once omega has been measured on 30 closed windows, the second with the assumed omega:

Window usedRange, spread measuredRange, spread assumed
3%±21%about a factor of two
10%±9%±39%
25%±5%±21%
50%±3%±11%
90%±1%±4%

Past windows narrow the early figures further. In the simulation the range holds the true allowance 89% to 96% of the time from 3% used on, when the rounding rule is known, and somewhat more often while it is not (scenarios S1 to S4). Past windows that closed short of their limit err on the wide side: closed at 10% to 60% used (S7), the range holds the truth 96% to 98% of the time; with an allowance that varies 20% between windows and past windows closed at 10% to 20% (S9), 88% at 3% used and 96% to 100% from 10% on.

Upgrading from 0.3.0 restarts the estimates once: the readings it kept cannot be attributed to a subscription. Upgrading from 0.4.0 drops the stored readings once: some paired a session's old percent with current dollars. Upgrading from 0.5.0 drops them once more: they paired the percent with the dollars at the time of the scan. Rate-limit history is kept.

Upgrading from 0.6.0 or 0.7.0, which share schema 4, keeps the readings and backfills their features. A session still on older hooks that starts after the upgrade deletes the stored limits and readings, as every schema change always did, so restart every session first. Estimates do not change in 0.8.0: /usage-dollars models is a read-only study of how each model counts against the limit relative to its API price.

Limits

  • Usage from other machines, or from claude.ai, on the same subscription is not counted, and makes the allowance look smaller than it is.
  • The model assumes the dollars per percent vary from request to request independently. When the mix of work stays expensive or cheap for long stretches (say, one model for an hour, then another), the range is too narrow: in the simulation, with the within-window spread measured, it holds the true allowance 85% to 94% of the time when past windows ran to their limit (S5), and 81% to 89% when they closed at 10% to 60% used (S8), rather than 90%; less while that spread is still assumed.
  • Before the within-window spread is measured, a subscription whose allowance varies between windows much more than 10% can see early ranges (at a few percent used) hold the truth about 80% of the time.
  • Model prices live in scripts/usage-cost.mjs. A model missing there is reported as unpriced, never guessed; add new models as they ship.
  • Requires Node.js on PATH; the transcript scan runs as a child process.
  • Without a subscription (an API key), there are no limits to read and no estimates.

Files

PathRole
.claude-plugin/plugin.jsonManifest
QUICKSTART.mdSetup, everyday commands and good habits in brief; shown by /usage-dollars help
GUIDE.mdCommands, the card, calibration, the setup check, best practices and troubleshooting; shown by /usage-dollars help advanced
hooks/register.tsxHooks: events, the /usage-dollars command forms, toasts
hooks/measure.tsThe scan, stored readings and plan history per subscription, the estimates
hooks/estimate.tsAllowance estimate, its 90% range, rounding inference, next tick
hooks/meter.tsMeter weights per model and token class: segments, fits, model selection, the weekly transfer check, the prospective score
hooks/plan.tsPlan ledger, promotions, regimes, reset and undo
hooks/card.tsxThe window, report, check, calibration, models and guide cards, their Markdown fallbacks, the status line
scripts/usage-cost.mjsTranscript scan, pricing, the profile, date labels (Node)
types/index.d.tsType contract for the mod's session state
tests/*.test.tsUnit tests: claude plugin test usage-dollars (see below)
tests/meter.test.tsUnit tests of the meter weights, run with the other unit tests
tests/helper.test.mjsHelper tests: node --test usage-dollars/tests/helper.test.mjs
tests/coverage.test.mjsCoverage of the 90% range in simulated windows: node --test usage-dollars/tests/coverage.test.mjs
tests/meter-coverage.test.mjsThe meter weights' model selection and coverage in simulated weeks of requests: node --test usage-dollars/tests/meter-coverage.test.mjs
tests/fixtures/Synthetic profiles and transcripts for the helper tests

claude plugin test and a claude plugin validate that knows every hook this mod uses need a recent Claude Code. The claude on PATH may be older than the build the desktop app bundles, under %APPDATA%\Claude\claude-code\<version>\<build>\claude.exe on Windows; run that one if plugin test is an unknown command.

node usage-dollars/scripts/usage-cost.mjs --check sets each session's computed cost beside the cost Claude Code recorded for it.

Source 8 files
hooks/register.tsx 252 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { CalibrationReport, CheckReport, GuideReport, ModelsReport, SpendReport, UsageReport, WaitingReport } from '../types'
5import {
6  calibrationCard,
7  checkCard,
8  guideCard,
9  guideOf,
10  markdownCalibration,
11  markdownCheck,
12  markdownGuide,
13  markdownModels,
14  markdownSpend,
15  markdownWaiting,
16  markdownWindows,
17  modelsCard,
18  spendCard,
19  waitingCard,
20  windowCard,
21} from './card'
22import {
23  checkReport,
24  markNoticesSeen,
25  modelsReport,
26  refresh,
27  refreshHistory,
28  resetEstimates,
29  resolveSubscription,
30  spendReport,
31  statusOf,
32  takeToasts,
33  toCalibrationReport,
34  toReport,
35  undoReset,
36} from './measure'
37import type { Host } from './measure'
38import { CHECK_PROMPT, waitingReport } from './probe'
39
40const HOUR_MS = 60 * 60 * 1000
41const MAX_REPORT_HOURS = 90 * 24
42const KEPT_REPORTS = 20
43const MARK = /usage-dollars:report:(\d+)/
44
45const USAGE =
46  'Usage: /usage-dollars [help [advanced] | check | calibrate | models | report | <N>h | <N>d | today | YYYY-MM-DD | YYYY-MM-DD..YYYY-MM-DD | reset | reset undo]' +
47  ' · /usage-dollars help explains them.'
48
49/* The files `help` and `help advanced` show, in the plugin folder. */
50const GUIDE_FILES = new Map([
51  ['help', 'QUICKSTART.md'],
52  ['help advanced', 'GUIDE.md'],
53])
54
55const reports = atom({ plugin: 'usage-dollars', key: 'reports' } as const, {})
56
57/* From a press of the first-reading card's button until the next turn completes. */
58let isCheckInFlight = false
59
60/* $ never crosses an import, so the measure module reaches the engine through these. */
61function hostOf($: EngineInterface): Host {
62  return {
63    root: $.plugin.root,
64    now: () => $.clock.now(),
65    sessionId: () => $.session.id(),
66    rateLimits: async () => (await $.session.usage()).rateLimits,
67    run: (argv, options) => $.process.run(argv, options),
68    get: key => $.store.get(key),
69    set: (key, value) => $.store.set(key, value),
70    delete: key => $.store.delete(key),
71    status: text => $.ui.status(text),
72    log: text => $.ui.log(text, { to: 'debug' }),
73  }
74}
75
76async function toastNotices($: EngineInterface) {
77  for (const text of await takeToasts(hostOf($))) $.ui.toast(text, { timeoutMs: 10000 })
78}
79
80function measureThen($: EngineInterface, limits?: readonly SessionRateLimit[], isForced = false, isFresh = false, receivedAt?: number) {
81  return refresh(hostOf($), limits, isForced, isFresh, receivedAt).then(async summary => {
82    await toastNotices($)
83    return summary
84  })
85}
86
87async function keep(
88  $: EngineInterface,
89  report: UsageReport | SpendReport | CheckReport | CalibrationReport | ModelsReport | GuideReport | WaitingReport,
90) {
91  const id = String(Date.now())
92  await update($, reports, all => {
93    const kept = Object.entries(all ?? {}).slice(-(KEPT_REPORTS - 1))
94    return { ...Object.fromEntries(kept), [id]: report }
95  })
96  return id
97}
98
99/* The first-reading card, while this installation holds no reading to show. */
100async function waiting($: EngineInterface, command: string) {
101  const report: WaitingReport = waitingReport(command, await resolveSubscription(hostOf($)), isCheckInFlight)
102  return { text: markdownWaiting(report, await keep($, report)) }
103}
104
105async function setCanSend($: EngineInterface, id: string, canSend: boolean) {
106  await update($, reports, all => {
107    const r = all?.[id]
108    return r?.type === 'waiting' ? { ...all, [id]: { ...r, canSend } } : (all ?? {})
109  })
110}
111
112/* The check message, sent once per press: the card stops offering it, and no card offers
113   it again until a turn completes or the message does not enter. */
114async function sendCheck($: EngineInterface, id: string) {
115  if (isCheckInFlight) return
116  isCheckInFlight = true
117  await setCanSend($, id, false)
118  const fail = async (reason: string) => {
119    isCheckInFlight = false
120    $.ui.log(`usage-dollars: check message: ${reason}`, { to: 'debug' })
121    await setCanSend($, id, true)
122  }
123  void $.prompt.submit({ text: CHECK_PROMPT }).then(
124    result => (result.drop !== undefined ? fail('dropped') : undefined),
125    error => fail(String(error)),
126  )
127}
128
129/* The helper's range arguments for a report form, or undefined when the form is not one. */
130function reportRange(args: string, now: number) {
131  const iso = (ms: number) => new Date(ms).toISOString()
132  if (args === 'report') return ['--report', `${iso(now - 24 * HOUR_MS)},${iso(now)}`]
133  const last = /^(\d+)([hd])$/.exec(args)
134  if (last) {
135    const hours = Number(last[1]) * (last[2] === 'd' ? 24 : 1)
136    if (hours < 1 || hours > MAX_REPORT_HOURS) return undefined
137    return ['--report', `${iso(now - hours * HOUR_MS)},${iso(now)}`]
138  }
139  if (args === 'today') return ['--report-local', 'today,today']
140  const day = /^(\d{4}-\d{2}-\d{2})$/.exec(args)
141  if (day) return ['--report-local', `${day[1]},${day[1]}`]
142  const range = /^(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(args)
143  if (range) return ['--report-local', `${range[1]},${range[2]}`]
144  return undefined
145}
146
147export const register: Register = on => {
148  on('session.start', async ($, e, next) => {
149    await $.command.register({
150      name: 'usage-dollars',
151      description: 'Subscription usage in API-equivalent dollars: allowance, calibration, model weights, spending reports, reset; "help" for the guide',
152      argumentHint: '[help [advanced] | check | calibrate | models | report | 24h | 7d | today | YYYY-MM-DD[..YYYY-MM-DD] | reset [undo]]',
153    })
154    void measureThen($, undefined, true)
155    void refreshHistory(hostOf($)).catch(error => $.ui.log(`usage-dollars: history: ${String(error)}`, { to: 'debug' }))
156    return next(e)
157  })
158
159  /* Only here does the session hold a percent it has just received: a billed response, or
160     a window that moved a whole point. Its readings pair the percent with the dollars up
161     to the moment it arrived, not to when the scan runs. */
162  on('session.measure', async ($, e, next) => {
163    const receivedAt = await $.clock.now()
164    const isFresh = e.changed.includes('cost') || e.changed.includes('rateLimits')
165    void measureThen($, e.rateLimits, e.changed.includes('rateLimits'), isFresh, receivedAt)
166    return next(e)
167  })
168
169  on('turn.complete', async ($, e, next) => {
170    isCheckInFlight = false
171    return next(e)
172  })
173
174  on('command.run', { command: 'usage-dollars' }, async ($, e) => {
175    const args = e.args.trim().toLowerCase().replace(/\s+/g, ' ')
176
177    if (args === '') {
178      const summary = await measureThen($, undefined, true)
179      if (!summary) return waiting($, '/usage-dollars')
180      await markNoticesSeen(hostOf($))
181      $.ui.status(statusOf(summary, false))
182      const report = toReport(summary, await $.clock.now())
183      return { text: markdownWindows(report, await keep($, report)) }
184    }
185
186    if (args === 'reset') {
187      await resetEstimates(hostOf($))
188      await toastNotices($)
189      return {
190        text: 'Estimates restarted for this subscription. Ranges widen until new readings arrive. Undo with /usage-dollars reset undo.',
191      }
192    }
193    if (args === 'reset undo') {
194      const isUndone = await undoReset(hostOf($))
195      return { text: isUndone ? 'Reset undone.' : 'Nothing to undo.' }
196    }
197
198    const guideFile = GUIDE_FILES.get(args)
199    if (guideFile) {
200      let text: string
201      try {
202        text = await $.fs.read(`${$.plugin.root}/${guideFile}`)
203      } catch (error) {
204        $.ui.log(`usage-dollars: help: ${String(error)}`, { to: 'debug' })
205        return { text: `The guide could not be read: ${guideFile} is missing from the plugin folder.\n\n${USAGE}` }
206      }
207      const report: GuideReport = guideOf(text)
208      return { text: markdownGuide(report, await keep($, report)) }
209    }
210    if (args === 'check') {
211      const report = await checkReport(hostOf($))
212      await toastNotices($)
213      return { text: markdownCheck(report, await keep($, report)) }
214    }
215    if (args === 'calibrate') {
216      const summary = await measureThen($, undefined, true)
217      if (!summary) return waiting($, '/usage-dollars calibrate')
218      const report = toCalibrationReport(summary)
219      return { text: markdownCalibration(report, await keep($, report)) }
220    }
221    if (args === 'models') {
222      const report = await modelsReport(hostOf($))
223      await toastNotices($)
224      return { text: markdownModels(report, await keep($, report)) }
225    }
226
227    const range = reportRange(args, await $.clock.now())
228    if (!range) return { text: USAGE }
229    const report = await spendReport(hostOf($), range)
230    if ('error' in report) {
231      $.ui.log(`usage-dollars: report: ${report.error}`, { to: 'debug' })
232      return { text: USAGE }
233    }
234    return { text: markdownSpend(report, await keep($, report)) }
235  })
236
237  on('ui.render', { component: 'CommandOutput', props: { command: 'usage-dollars' } }, async ($, e, next) => {
238    const id = MARK.exec(e.props.text)?.[1]
239    const r = id ? (await read($, reports))?.[id] : undefined
240    const ui = $.ui.resolve(e)
241    const columns = e.viewport?.columns ?? 60
242    if (r?.type === 'windows' && Array.isArray(r.windows)) return windowCard(ui, r, columns)
243    if (r?.type === 'report' && Array.isArray(r.byDay)) return spendCard(ui, r, columns)
244    if (r?.type === 'check' && Array.isArray(r.items)) return checkCard(ui, r)
245    if (r?.type === 'calibration' && Array.isArray(r.windows)) return calibrationCard(ui, r)
246    if (r?.type === 'models' && Array.isArray(r.fits)) return modelsCard(ui, r)
247    if (r?.type === 'guide' && Array.isArray(r.sections)) return guideCard(ui, r)
248    if (r?.type === 'waiting' && id) return waitingCard(ui, r, () => void sendCheck($, id))
249    return next(e)
250  })
251}
252
hooks/card.tsx 890 lines
1/* Drawing: the allowance-first window card, the spending report card, the setup check,
2   calibration, model study, guide and first-reading cards, their Markdown fallbacks, and
3   the status line. Every date shown arrives already labeled by the helper. */
4
5import type { Elements, RenderSurface } from 'claude-code'
6
7import type {
8  CalibrationReport,
9  CalibrationWindow,
10  CheckItem,
11  CheckReport,
12  GuideReport,
13  MeterModel,
14  ModelsComparison,
15  ModelsFit,
16  ModelsGroup,
17  ModelsReport,
18  ModelsSpread,
19  PlanReport,
20  RangeReport,
21  SpendReport,
22  UsageReport,
23  WaitingReport,
24  WindowReport,
25} from '../types'
26import { CHECK_LABEL } from './probe'
27
28type Ui = Elements[RenderSurface]
29
30export const money = (usd: number) =>
31  usd >= 100 ? `$${Math.round(usd).toLocaleString('en-US')}` : `$${usd.toFixed(2)}`
32
33/** $4.20, $913, $2.8k, $28k: the status line's figures. */
34export function compact(usd: number) {
35  if (usd < 10) return `$${usd.toFixed(2)}`
36  if (Math.round(usd) < 1000) return `$${Math.round(usd)}`
37  const k = usd / 1000
38  return Math.round(k * 10) < 100 ? `$${k.toFixed(1)}k` : `$${Math.round(k)}k`
39}
40
41const span = (r: RangeReport) => `${money(r.low)} – ${money(r.high)}`
42
43const count = (n: number) => n.toLocaleString('en-US')
44
45/* claude-opus-5-5 reads as "Opus 5.5"; a date suffix or [1m] tag is dropped. */
46export function modelName(id: string) {
47  const parts = id
48    .replace(/^claude-/, '')
49    .replace(/\[.*\]$/, '')
50    .split('-')
51    .filter(part => !/^\d{8}$/.test(part))
52  const words = parts.filter(part => !/^\d+$/.test(part)).map(w => w.charAt(0).toUpperCase() + w.slice(1))
53  const version = parts.filter(part => /^\d+$/.test(part)).join('.')
54  return [...words, version].filter(Boolean).join(' ')
55}
56
57const FOOTNOTE =
58  "Priced at API list rates from this machine's transcripts. Ranges are 90% intervals from a model of " +
59  'how far dollars per percent vary within and between windows; see the README.'
60
61const FOOTER =
62  '/usage-dollars 24h · 7d · YYYY-MM-DD..YYYY-MM-DD for a spending report · /usage-dollars reset after a plan change · ' +
63  '/usage-dollars help · check · calibrate · models'
64
65const NO_ESTIMATE = 'first estimate after the next reply'
66
67const confidenceLabel = (w: WindowReport) => (w.confidence ? `${w.confidence}${w.isCalibrated ? ' · calibrated' : ''}` : '')
68
69export type StatusWindow = { short: string; usedUsd: number; allowance?: RangeReport; left?: RangeReport }
70
71/* "5h ~$850 left of $913 · Week ~$2.7k left of $2.8k": one tilde per window, since both
72   figures come from one estimate. */
73export function statusLine(windows: readonly StatusWindow[], isPlanUnseen: boolean) {
74  const text = windows
75    .map(w =>
76      !w.allowance || !w.left
77        ? `${w.short} ${compact(w.usedUsd)} used, estimating`
78        : w.left.value <= 0
79          ? `${w.short} at limit`
80          : `${w.short} ~${compact(w.left.value)} left of ${compact(w.allowance.value)}`,
81    )
82    .join(' · ')
83  return `${isPlanUnseen ? '⚠ Plan changed · ' : ''}${text}`
84}
85
86export function planLine(p: PlanReport) {
87  if (p.isUnknown) {
88    const last = p.lastKnown ? `; last seen as ${p.lastKnown}` : ''
89    return p.unknownReason === 'other-subscription'
90      ? `Plan: unknown for this subscription — Claude Code is signed in to another${last}`
91      : `Plan: unknown — no account profile found${last}`
92  }
93  const asOf = p.asOfLabel ? ` · profile as of ${p.asOfLabel}` : ''
94  return `Plan: ${p.label ?? 'unknown'}${asOf}${p.isStale ? ' (may be out of date)' : ''}`
95}
96
97const headlineLabel = (w: WindowReport) => (w.short === '5h' ? '5-HOUR ALLOWANCE' : 'WEEKLY ALLOWANCE')
98
99const ageOf = (minutes: number) =>
100  minutes < 1 ? 'just now' : minutes < 60 ? `${minutes} min ago` : `${Math.floor(minutes / 60)} h ago`
101
102const percentLine = (w: WindowReport) =>
103  w.percent === undefined
104    ? undefined
105    : `Limit reports ${w.percent}%${w.percentAgeMinutes !== undefined ? ` · read ${ageOf(w.percentAgeMinutes)}` : ''}`
106
107const nextTickLine = (w: WindowReport) =>
108  w.nextTick ? `Next tick in about ${money(w.nextTick.value)} (between ${money(w.nextTick.low)} and ${money(w.nextTick.high)})` : undefined
109
110/* The row the model reads, and what the transcript shows where the card cannot be drawn. */
111export function markdownWindows(r: UsageReport, id: string) {
112  const lines = ['### Usage · API-equivalent dollars', '', planLine(r.plan), '']
113  if (r.notices.length > 0) lines.push(...r.notices.map(n => `- ${n}`), '')
114  lines.push(
115    '| Window | Allowance | 90% range | Confidence |',
116    '|:--|--:|--:|:--|',
117    ...r.windows.map(w =>
118      w.allowance
119        ? `| ${w.title} | ~${money(w.allowance.value)} | ${span(w.allowance)} | ${confidenceLabel(w)} |`
120        : `| ${w.title} | estimating… | | |`,
121    ),
122    '',
123  )
124  for (const w of r.windows) {
125    const reported = percentLine(w)
126    const tick = nextTickLine(w)
127    lines.push(
128      `**${w.title}** · resets ${w.resetLong}${w.resetIn ? ` (in ${w.resetIn})` : ''}`,
129      '',
130      '| | Estimate | 90% range |',
131      '|:--|--:|--:|',
132      `| Used | ${money(w.usedUsd)} | ${count(w.requests)} requests |`,
133      `| Left | ${w.left ? `~${money(w.left.value)}` : '—'} | ${w.left ? span(w.left) : ''} |`,
134      '',
135      ...(reported ? [reported, ''] : []),
136      ...(tick ? [tick, ''] : []),
137      `_${w.basis}_`,
138      '',
139    )
140  }
141  if (r.last24hUsd !== undefined) lines.push(`Last 24 hours: ${money(r.last24hUsd)}`, '')
142  lines.push(
143    `**${r.byModelTitle}**`,
144    '',
145    '| Model | Requests | Cost |',
146    '|:--|--:|--:|',
147    ...r.byModel.map(m => `| ${modelName(m.model)} | ${count(m.requests)} | ${money(m.usd)} |`),
148    '',
149    ...r.notes.map(line => `- ${line}`),
150    `_${FOOTNOTE}_`,
151    '',
152    `_${FOOTER}_`,
153    '',
154    `[//]: # (usage-dollars:report:${id})`,
155  )
156  return lines.join('\n')
157}
158
159export function markdownSpend(r: SpendReport, id: string) {
160  return [
161    `### Spending · ${r.fromLabel} – ${r.toLabel}`,
162    '',
163    `**${money(r.usedUsd)}** in ${count(r.requests)} requests, API-equivalent dollars`,
164    '',
165    '| Day | Requests | Cost |',
166    '|:--|--:|--:|',
167    ...r.byDay.map(d => `| ${d.label} | ${count(d.requests)} | ${money(d.usd)} |`),
168    '',
169    '| Model | Requests | Cost |',
170    '|:--|--:|--:|',
171    ...r.byModel.map(m => `| ${modelName(m.model)} | ${count(m.requests)} | ${money(m.usd)} |`),
172    '',
173    ...r.notes.map(line => `- ${line}`),
174    '',
175    `[//]: # (usage-dollars:report:${id})`,
176  ].join('\n')
177}
178
179/* Used dollars in solid blue, the 90% range of the allowance as a pale band, and the
180   allowance estimate as a tick, all on one scale ending at the range's top. */
181function meterSvg(w: WindowReport) {
182  const width = 600
183  const height = 12
184  const top = w.allowance?.high ?? w.usedUsd
185  const x = (usd: number) => Math.round((width * Math.min(usd, top)) / Math.max(top, 0.01))
186  const used = w.usedUsd > 0 ? Math.max(4, x(w.usedUsd)) : 0
187  const band = w.allowance ? `<rect x="${x(w.allowance.low)}" width="${x(w.allowance.high) - x(w.allowance.low)}" height="${height}" fill="#3b82f6" fill-opacity="0.2"/>` : ''
188  const tick = w.allowance ? `<rect x="${Math.min(width - 2, x(w.allowance.value))}" width="2" height="${height}" fill="#3b82f6" fill-opacity="0.7"/>` : ''
189  return (
190    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
191    `<rect width="${width}" height="${height}" rx="3" fill="#8a8a8a" fill-opacity="0.18"/>` +
192    band +
193    `<rect width="${used}" height="${height}" rx="3" fill="#3b82f6"/>` +
194    tick +
195    `</svg>`
196  )
197}
198
199function meterCells(w: WindowReport, cells: number) {
200  const top = w.allowance?.high ?? w.usedUsd
201  const at = (usd: number) => Math.round((cells * Math.min(usd, top)) / Math.max(top, 0.01))
202  const used = w.usedUsd > 0 ? Math.max(1, at(w.usedUsd)) : 0
203  const low = w.allowance ? Math.max(used, at(w.allowance.low)) : used
204  return { used, band: Math.max(0, cells - low), free: Math.max(0, low - used) }
205}
206
207/* One day's spending as a bar on the scale of the busiest day. */
208function daySvg(usd: number, top: number) {
209  const width = 240
210  const height = 10
211  const used = usd > 0 ? Math.max(2, Math.round((width * usd) / Math.max(top, 0.01))) : 0
212  return (
213    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
214    `<rect width="${width}" height="${height}" rx="2" fill="#8a8a8a" fill-opacity="0.18"/>` +
215    `<rect width="${used}" height="${height}" rx="2" fill="#3b82f6"/>` +
216    `</svg>`
217  )
218}
219
220function modelTable(ui: Ui, title: string, rows: UsageReport['byModel']) {
221  const { Box, Text } = ui
222  return (
223    <Box flexDirection="column">
224      <Text bold>{title}</Text>
225      <Box flexDirection="row">
226        <Box flexGrow={1}>
227          <Text dimColor>MODEL</Text>
228        </Box>
229        <Box width={12} justifyContent="flex-end">
230          <Text dimColor>REQUESTS</Text>
231        </Box>
232        <Box width={12} justifyContent="flex-end">
233          <Text dimColor>COST</Text>
234        </Box>
235      </Box>
236      {rows.map(m => (
237        <Box flexDirection="row">
238          <Box flexGrow={1}>
239            <Text>{modelName(m.model)}</Text>
240          </Box>
241          <Box width={12} justifyContent="flex-end">
242            <Text>{count(m.requests)}</Text>
243          </Box>
244          <Box width={12} justifyContent="flex-end">
245            <Text bold>{money(m.usd)}</Text>
246          </Box>
247        </Box>
248      ))}
249    </Box>
250  )
251}
252
253function notesBlock(ui: Ui, notes: readonly string[]) {
254  const { Box, Text } = ui
255  if (notes.length === 0) return undefined
256  return (
257    <Box flexDirection="column">
258      {notes.map(line => (
259        <Text>{line}</Text>
260      ))}
261    </Box>
262  )
263}
264
265export function windowCard(ui: Ui, r: UsageReport, columns: number) {
266  const { Box, Text } = ui
267  const cells = Math.max(10, Math.min(48, columns - 12))
268
269  const headline = (w: WindowReport) => (
270    <Box flexDirection="column" flexGrow={1} minWidth={22} borderStyle="round" borderDimColor paddingX={1}>
271      <Text dimColor>{headlineLabel(w)}</Text>
272      <Text bold>{w.allowance ? `~${money(w.allowance.value)}` : 'estimating…'}</Text>
273      <Text dimColor>{w.allowance ? span(w.allowance) : NO_ESTIMATE}</Text>
274      {w.allowance && w.confidence ? <Text dimColor>{confidenceLabel(w)}</Text> : undefined}
275    </Box>
276  )
277
278  const section = (w: WindowReport) => {
279    const tiles = [
280      { label: 'USED', value: money(w.usedUsd), note: `${count(w.requests)} requests` },
281      { label: 'LEFT', value: w.left ? `~${money(w.left.value)}` : '—', note: w.left ? span(w.left) : 'no estimate yet' },
282    ]
283    const bar = meterCells(w, cells)
284    const reported = percentLine(w)
285    const tick = nextTickLine(w)
286    return (
287      <Box flexDirection="column" rowGap={1}>
288        <Box flexDirection="row" justifyContent="space-between" flexWrap="wrap" columnGap={2}>
289          <Text bold>{w.title}</Text>
290          <Text dimColor>
291            Resets {w.resetLong}
292            {w.resetIn ? ` · in ${w.resetIn}` : ''}
293          </Text>
294        </Box>
295        <Box flexDirection="row" flexWrap="wrap" columnGap={4} rowGap={1}>
296          {tiles.map(tile => (
297            <Box flexDirection="column" flexGrow={1} minWidth={16}>
298              <Text dimColor>{tile.label}</Text>
299              <Text bold>{tile.value}</Text>
300              <Text dimColor>{tile.note}</Text>
301            </Box>
302          ))}
303        </Box>
304        {'Svg' in ui ? (
305          <ui.Svg source={meterSvg(w)} alt={`Used ${money(w.usedUsd)} of the allowance`} />
306        ) : (
307          <Text>
308            <Text color="blue">{'█'.repeat(bar.used)}</Text>
309            <Text dimColor>{'░'.repeat(bar.free)}</Text>
310            <Text color="blue" dimColor>
311              {'▒'.repeat(bar.band)}
312            </Text>
313          </Text>
314        )}
315        {reported ? <Text>{reported}</Text> : undefined}
316        {tick ? <Text>{tick}</Text> : undefined}
317        <Text dimColor>{w.basis}</Text>
318      </Box>
319    )
320  }
321
322  return (
323    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={2}>
324      <Box flexDirection="column">
325        <Box flexDirection="row" columnGap={1}>
326          <Text bold>Usage</Text>
327          <Text dimColor>· API-equivalent dollars</Text>
328        </Box>
329        <Text dimColor>{planLine(r.plan)}</Text>
330      </Box>
331
332      {r.notices.length > 0 ? (
333        <Box flexDirection="column">
334          {r.notices.map(line => (
335            <Text color="yellow">{line}</Text>
336          ))}
337        </Box>
338      ) : undefined}
339
340      <Box flexDirection="row" flexWrap="wrap" columnGap={2} rowGap={1}>
341        {r.windows.map(headline)}
342      </Box>
343
344      {r.windows.map(section)}
345
346      {r.last24hUsd !== undefined ? <Text>Last 24 hours: {money(r.last24hUsd)}</Text> : undefined}
347
348      {modelTable(ui, r.byModelTitle, r.byModel)}
349
350      {notesBlock(ui, r.notes)}
351      <Text dimColor italic>
352        {FOOTNOTE}
353      </Text>
354      <Text dimColor>{FOOTER}</Text>
355    </Box>
356  )
357}
358
359export function spendCard(ui: Ui, r: SpendReport, columns: number) {
360  const { Box, Text } = ui
361  const cells = Math.max(10, Math.min(40, columns - 34))
362  const top = Math.max(0, ...r.byDay.map(d => d.usd))
363  const cellsOf = (usd: number) => (usd > 0 ? Math.max(1, Math.round((cells * usd) / Math.max(top, 0.01))) : 0)
364
365  return (
366    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={2}>
367      <Box flexDirection="row" columnGap={1} flexWrap="wrap">
368        <Text bold>Spending</Text>
369        <Text dimColor>
370          · {r.fromLabel} – {r.toLabel}
371        </Text>
372      </Box>
373
374      <Box flexDirection="row" flexWrap="wrap" columnGap={4} rowGap={1}>
375        <Box flexDirection="column" minWidth={16}>
376          <Text dimColor>TOTAL</Text>
377          <Text bold>{money(r.usedUsd)}</Text>
378          <Text dimColor>API-equivalent dollars</Text>
379        </Box>
380        <Box flexDirection="column" minWidth={16}>
381          <Text dimColor>REQUESTS</Text>
382          <Text bold>{count(r.requests)}</Text>
383        </Box>
384      </Box>
385
386      <Box flexDirection="column">
387        <Text bold>By day</Text>
388        {r.byDay.map(d => (
389          <Box flexDirection="row" columnGap={2}>
390            <Box width={12}>
391              <Text>{d.label}</Text>
392            </Box>
393            <Box flexGrow={1}>
394              {'Svg' in ui ? (
395                <ui.Svg source={daySvg(d.usd, top)} alt={`${d.label}: ${money(d.usd)}`} />
396              ) : (
397                <Text color="blue">{'█'.repeat(cellsOf(d.usd)) || ' '}</Text>
398              )}
399            </Box>
400            <Box width={12} justifyContent="flex-end">
401              <Text bold={d.usd > 0} dimColor={d.usd === 0}>
402                {money(d.usd)}
403              </Text>
404            </Box>
405          </Box>
406        ))}
407      </Box>
408
409      {modelTable(ui, 'By model', r.byModel)}
410
411      {notesBlock(ui, r.notes)}
412    </Box>
413  )
414}
415
416const MARK_OF: Record<CheckItem['state'], string> = { ok: '✓', fail: '✗', info: 'ℹ' }
417
418const COLOR_OF: Record<CheckItem['state'], string | undefined> = { ok: 'green', fail: 'red', info: undefined }
419
420export function markdownCheck(r: CheckReport, id: string) {
421  return [
422    '### Setup check · usage-dollars',
423    '',
424    ...r.items.map(item => `- ${MARK_OF[item.state]} **${item.label}** · ${item.text}`),
425    '',
426    `[//]: # (usage-dollars:report:${id})`,
427  ].join('\n')
428}
429
430export function checkCard(ui: Ui, r: CheckReport) {
431  const { Box, Text } = ui
432  return (
433    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={1}>
434      <Box flexDirection="row" columnGap={1}>
435        <Text bold>Setup check</Text>
436        <Text dimColor>· usage-dollars</Text>
437      </Box>
438      {r.items.map(item => (
439        <Box flexDirection="row" columnGap={1}>
440          <Box width={2}>
441            <Text color={COLOR_OF[item.state]} dimColor={item.state === 'info'}>
442              {MARK_OF[item.state]}
443            </Text>
444          </Box>
445          <Box width={16}>
446            <Text bold>{item.label}</Text>
447          </Box>
448          <Box flexGrow={1} flexShrink={1}>
449            <Text>{item.text}</Text>
450          </Box>
451        </Box>
452      ))}
453    </Box>
454  )
455}
456
457const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
458
459/* Facts about the data behind one window's estimate, never what to do about them. */
460function calibrationLines(w: CalibrationWindow) {
461  const lines = [`This window: ${plural(w.levels, 'percent level')} read, ${plural(w.ticks, 'tick')} seen`]
462  if (w.closedWindows === 0) lines.push('No closed window with readings yet')
463  lines.push(
464    w.isWithinMeasured
465      ? `Within-window spread: measured, from ${plural(w.closedForWithin, 'closed window')}`
466      : `Within-window spread: assumed; ${plural(w.closedForWithin, 'closed window')} with a tick, 2 needed`,
467    `Between-window spread: ${w.isBetweenMeasured ? 'measured' : 'assumed'}; ` +
468      `${plural(w.pastPoints, 'past window')} (rejections included), history weight ${w.pastWeight}`,
469    w.isRoundingKnown
470      ? `Rounding rule: known (the API ${w.rounding === 'round' ? 'rounds' : 'truncates'}), from ${plural(w.closedForRounding, 'closed window')}`
471      : `Rounding rule: not known; ${w.closedForRounding} of ${w.roundingNeeded} closed windows needed`,
472  )
473  if (w.halfWidth !== undefined) lines.push(`90% range now: ±${Math.round(w.halfWidth * 100)}%`)
474  return lines
475}
476
477const calibrationStatus = (w: CalibrationWindow) => (w.isCalibrated ? 'Calibrated' : `Calibrating: ${w.measured} of 3 measured`)
478
479export function markdownCalibration(r: CalibrationReport, id: string) {
480  const lines = ['### Calibration · usage-dollars', '']
481  for (const w of r.windows)
482    lines.push(`**${w.title}** · ${calibrationStatus(w)}`, '', ...calibrationLines(w).map(line => `- ${line}`), '')
483  lines.push(`[//]: # (usage-dollars:report:${id})`)
484  return lines.join('\n')
485}
486
487export function calibrationCard(ui: Ui, r: CalibrationReport) {
488  const { Box, Text } = ui
489  return (
490    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={2}>
491      <Box flexDirection="row" columnGap={1}>
492        <Text bold>Calibration</Text>
493        <Text dimColor>· usage-dollars</Text>
494      </Box>
495      {r.windows.map(w => (
496        <Box flexDirection="column">
497          <Box flexDirection="row" justifyContent="space-between" flexWrap="wrap" columnGap={2}>
498            <Text bold>{w.title}</Text>
499            <Text color={w.isCalibrated ? 'green' : undefined} dimColor={!w.isCalibrated}>
500              {calibrationStatus(w)}
501            </Text>
502          </Box>
503          {calibrationLines(w).map(line => (
504            <Text>{line}</Text>
505          ))}
506        </Box>
507      ))}
508    </Box>
509  )
510}
511
512const MODEL_TITLE: Record<MeterModel, string> = {
513  M0: 'the API ratio',
514  M1: 'a weight per model',
515  M2: 'a weight per model for cache reads and for the rest',
516}
517
518const ROUNDING_TEXT: Record<ModelsReport['rounding'], string> = {
519  round: 'the API rounds',
520  truncate: 'the API truncates',
521  union: 'not known yet; the fit allows both',
522}
523
524const MODELS_SUBTITLE = "How each model's API dollars count against the limit, as seen from this machine"
525
526const MODELS_FOOTNOTE =
527  'Weights compare models with each other: each is measured against the reference group, not against the limit itself. ' +
528  'Usage on other machines and on claude.ai is not in these dollars. The estimates do not use these weights.'
529
530/* 1.8x, 0.44x, 12x: a meter weight. */
531const times = (w: number) => `${w >= 10 ? w.toFixed(0) : w >= 1 ? w.toFixed(1) : w.toFixed(2)}x`
532
533/* Nats to one decimal, with a minus sign, and never "−0.0". */
534const nats = (x: number) => (Math.abs(x) < 0.05 ? '0.0' : x.toFixed(1).replace('-', '−'))
535
536const deltaOf = (c: { delta: number; se: number }) => `Δ ${nats(c.delta)} ± ${nats(c.se)}`
537
538const intervalOf = (g: ModelsGroup) => `90%: ${times(g.weight.low)}–${times(g.weight.high)}`
539
540const spreadText = (s: ModelsSpread) => `${s.omega.toFixed(2)} (${s.isAssumed ? 'assumed' : `from ${plural(s.windows, 'window')}`})`
541
542type ModelsLine = { text: string; isNested?: boolean }
543
544/* What the weeks use: the API ratio under M0, otherwise the 5-hour weights unless the
545   weekly segments rejected them. */
546function transferLine(r: ModelsReport) {
547  const t = r.transfer
548  if (r.selected === 'M0') return 'Week: uses the API ratio, as the 5-hour windows do'
549  if (!t.isChecked) return `Week: uses the 5-hour weights; not yet checked on weeks (${plural(t.days, 'day')} so far)`
550  return t.isRejected
551    ? `Week: falls back to the API ratio; the 5-hour weights fit the weeks worse on ${plural(t.days, 'day')} (${deltaOf(t)})`
552    : `Week: uses the 5-hour weights; checked on ${plural(t.days, 'day')}, consistent (${deltaOf(t)})`
553}
554
555const groupHeadline = (g: ModelsGroup, windows: number) =>
556  `${g.label}: ${times(g.weight.value)} its API price against the limit (${intervalOf(g)}), from ${plural(windows, '5-hour window')}`
557
558const notSelected = (c: ModelsComparison) => (c.folds > 0 ? `${c.to} not supported: ${deltaOf(c)} nats` : `${c.to} not compared`)
559
560/* The selected outcome: its title, then the weights it gives and what the weeks use. */
561function modelsHeadline(r: ModelsReport) {
562  if (!r.isFitted) {
563    const title =
564      r.qualifying < r.needed
565        ? `Not fitted yet: ${r.qualifying} of ${r.needed} 5-hour windows with readings per model`
566        : `Not fitted: ${plural(r.qualifying, '5-hour window')} with readings per model gave no fit`
567    return { title, lines: [transferLine(r)] }
568  }
569  if (r.selected === 'M0') {
570    const against = r.comparisons.map(notSelected).join('; ')
571    return { title: `API ratio holds${against ? ` (${against})` : ''}`, lines: [transferLine(r)] }
572  }
573  const fit = r.fits.find(f => f.model === r.selected)
574  const won = r.comparisons.find(c => c.to === r.selected && c.isSelected)
575  const weights = fit
576    ? [...fit.groups.map(g => groupHeadline(g, fit.windows)), `Measured against ${fit.referenceLabel}, held at 1x its API price`]
577    : []
578  return {
579    title: `${r.selected} selected: ${MODEL_TITLE[r.selected]}${won ? ` (${deltaOf(won)} nats over ${won.from})` : ''}`,
580    lines: [...weights, transferLine(r)],
581  }
582}
583
584function fitLines(f: ModelsFit, title: string): ModelsLine[] {
585  const against = f.model === 'M0' ? '' : f.groups.length > 0 ? `, against ${f.referenceLabel}` : `; every group merged into ${f.referenceLabel}`
586  return [
587    { text: `${title}: ω ${f.omega.toFixed(2)}, ${plural(f.segments, 'segment')}${against}` },
588    ...f.groups.map(g => ({
589      text: `${g.label}: ${times(g.weight.value)} (${intervalOf(g)}), information ${Math.round(g.information)}`,
590      isNested: true,
591    })),
592  ]
593}
594
595/* The details behind the headline: data, fits, comparisons, weeks, spreads, and the
596   prospective check. */
597function modelsSections(r: ModelsReport) {
598  const t = r.transfer
599  const sections: { title: string; lines: ModelsLine[] }[] = [
600    {
601      title: 'Data',
602      lines: [
603        { text: `5-hour windows: ${r.windows.used} used` },
604        ...r.windows.excluded.map(e => ({ text: `${e.count} left out: ${e.reason}`, isNested: true })),
605        { text: `Segments: ${r.segments} used${r.excludedSegments > 0 ? `, ${r.excludedSegments} left out as outliers` : ''}` },
606        { text: `Rounding rule: ${ROUNDING_TEXT[r.rounding]}` },
607      ],
608    },
609  ]
610  if (r.fits.length > 0) sections.push({ title: 'Fits', lines: r.fits.flatMap(f => fitLines(f, `${f.model}, ${MODEL_TITLE[f.model]}`)) })
611  if (r.comparisons.length > 0)
612    sections.push({
613      title: 'Comparisons',
614      lines: r.comparisons.map(c => ({
615        text:
616          c.folds > 0
617            ? `${c.to} over ${c.from}: ${deltaOf(c)} nats in ${plural(c.folds, 'fold')}, ${c.isSelected ? 'selected' : 'not selected'}`
618            : `${c.to} over ${c.from}: not compared, no group left to weigh`,
619      })),
620    })
621  sections.push({
622    title: 'Weeks',
623    lines: [
624      { text: `Closed weeks that qualify: ${t.weeks}` },
625      ...(t.weeklyFit
626        ? fitLines(t.weeklyFit, `Weekly-only ${t.weeklyFit.model}, for comparison only, from ${plural(t.weeklyFit.windows, 'week')}`)
627        : []),
628    ],
629  })
630  if (r.omegas.length > 0)
631    sections.push({
632      title: 'Spread within windows',
633      lines: r.omegas.map(o => ({
634        text:
635          r.selected === 'M0'
636            ? `${o.title}: ω ${spreadText(o.M0)}`
637            : `${o.title}: ω ${spreadText(o.M0)} under the API ratio, ${spreadText(o.selected)} under the selected weights`,
638      })),
639    })
640  sections.push({
641    title: 'Prospective check',
642    lines: [
643      ...r.prospective.map(p => ({
644        text: `${p.title}: ${p.n === 0 ? 'none yet' : `${plural(p.n, 'new window')} scored, Σ d ${nats(p.sum)} ± ${nats(p.se)} nats`}`,
645      })),
646      { text: 'Each window that closes is scored before the next refit, under the stored weights less under the API ratio; a sum above 0 favors the weights' },
647    ],
648  })
649  return sections
650}
651
652export function markdownModels(r: ModelsReport, id: string) {
653  const head = modelsHeadline(r)
654  const lines = ['### Models · usage-dollars', '', `_${MODELS_SUBTITLE}_`, '', `**${head.title}**`, '', ...head.lines.map(line => `- ${line}`), '']
655  for (const s of modelsSections(r))
656    lines.push(`**${s.title}**`, '', ...s.lines.map(line => `${line.isNested ? '  ' : ''}- ${line.text}`), '')
657  lines.push(`_${MODELS_FOOTNOTE}_`, '', `[//]: # (usage-dollars:report:${id})`)
658  return lines.join('\n')
659}
660
661export function modelsCard(ui: Ui, r: ModelsReport) {
662  const { Box, Text } = ui
663  const head = modelsHeadline(r)
664  return (
665    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={1}>
666      <Box flexDirection="column">
667        <Box flexDirection="row" columnGap={1}>
668          <Text bold>Models</Text>
669          <Text dimColor>· usage-dollars</Text>
670        </Box>
671        <Text dimColor>{MODELS_SUBTITLE}</Text>
672      </Box>
673      <Box flexDirection="column">
674        <Text bold>{head.title}</Text>
675        {head.lines.map(line => (
676          <Text>{line}</Text>
677        ))}
678      </Box>
679      {modelsSections(r).map(s => (
680        <Box flexDirection="column">
681          <Text bold>{s.title}</Text>
682          {s.lines.map(line =>
683            line.isNested ? (
684              <Box flexDirection="row" columnGap={1}>
685                <Box width={2}>
686                  <Text dimColor>·</Text>
687                </Box>
688                <Box flexGrow={1} flexShrink={1}>
689                  <Text>{line.text}</Text>
690                </Box>
691              </Box>
692            ) : (
693              <Text>{line.text}</Text>
694            ),
695          )}
696        </Box>
697      ))}
698      <Text dimColor italic>
699        {MODELS_FOOTNOTE}
700      </Text>
701    </Box>
702  )
703}
704
705/* The first run on an installation, before any reply has brought a reading. */
706const WAITING_TITLE = 'Waiting for the first usage reading'
707
708const WAITING_ALL_RIGHT =
709  'Everything is in order. The plugin is installed and running; it has simply not received a usage reading yet. ' +
710  'This is expected right after the plugin is installed or updated, and on its first use on this machine.'
711
712const WAITING_WHY =
713  'Claude Code learns how much of the 5-hour window and the week has been used only from the API, and the API ' +
714  'reports it alongside each model reply: the percent used and when each window resets. Every figure on this card ' +
715  'is built on that reading, and this installation has not stored one yet.'
716
717const waitingSteps = (command: string) => [
718  'Send Claude any message in this session. A short question is enough.',
719  `When the reply has finished, run ${command} again.`,
720  command.endsWith('calibrate')
721    ? 'The card then shows what each window’s estimate rests on.'
722    : 'The card then shows each window: the estimated allowance, what is used and what is left.',
723]
724
725const WAITING_UNSUBSCRIBED =
726  'This sign-in has no subscription usage limits, so there is nothing to show; spending reports still work.'
727
728const WAITING_SEND = 'Or let the plugin send one for you:'
729
730const checkSent = (command: string) => `A check message was sent. When its reply has finished, run ${command} again.`
731
732const WAITING_NEXT = [
733  'Every reply refreshes the reading, and the status line keeps showing what is left in each window.',
734  'Readings are stored for this installation, so later sessions show figures at once, before their first reply.',
735  'The first estimates are rough and narrow as readings accumulate over the coming windows; /usage-dollars calibrate shows how far that has come.',
736  'Spending reports read this machine’s transcripts and need no reading: /usage-dollars 24h, 7d or a date range work now.',
737]
738
739const WAITING_FOOTER = 'If no figures appear after a reply, /usage-dollars check shows what is missing.'
740
741export function markdownWaiting(r: WaitingReport, id: string) {
742  return [
743    `### ${WAITING_TITLE}`,
744    '',
745    `✓ ${WAITING_ALL_RIGHT}`,
746    '',
747    '**Why there are no figures yet**',
748    '',
749    WAITING_WHY,
750    '',
751    ...(r.isUnsubscribed
752      ? [WAITING_UNSUBSCRIBED, '']
753      : [
754          '**What to do**',
755          '',
756          ...waitingSteps(r.command).map((step, i) => `${i + 1}. ${step}`),
757          '',
758          ...(r.canSend === false ? [checkSent(r.command), ''] : []),
759          '**How it works from here**',
760          '',
761          ...WAITING_NEXT.map(line => `- ${line}`),
762          '',
763        ]),
764    `_${WAITING_FOOTER}_`,
765    '',
766    `[//]: # (usage-dollars:report:${id})`,
767  ].join('\n')
768}
769
770/* onSend sends the check message; without it the card offers no button. */
771export function waitingCard(ui: Ui, r: WaitingReport, onSend?: () => void) {
772  const { Box, Button, Text } = ui
773  const heading = (text: string) => <Text bold>{text}</Text>
774  return (
775    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={2} paddingY={1} rowGap={1}>
776      <Box flexDirection="row" columnGap={1} flexWrap="wrap">
777        <Text bold>{WAITING_TITLE}</Text>
778        <Text dimColor>· usage-dollars</Text>
779      </Box>
780
781      <Box flexDirection="row" columnGap={1}>
782        <Box width={2}>
783          <Text color="green">✓</Text>
784        </Box>
785        <Box flexGrow={1} flexShrink={1}>
786          <Text>{WAITING_ALL_RIGHT}</Text>
787        </Box>
788      </Box>
789
790      <Box flexDirection="column">
791        {heading('Why there are no figures yet')}
792        <Text>{WAITING_WHY}</Text>
793      </Box>
794
795      {r.isUnsubscribed ? (
796        <Text>{WAITING_UNSUBSCRIBED}</Text>
797      ) : (
798        <Box flexDirection="column">
799          {heading('What to do')}
800          {waitingSteps(r.command).map((step, i) => (
801            <Box flexDirection="row" columnGap={1}>
802              <Box width={3}>
803                <Text color="blue" bold>
804                  {`${i + 1}.`}
805                </Text>
806              </Box>
807              <Box flexGrow={1} flexShrink={1}>
808                <Text>{step}</Text>
809              </Box>
810            </Box>
811          ))}
812        </Box>
813      )}
814
815      {!r.isUnsubscribed && r.canSend && onSend ? (
816        <Box flexDirection="row" columnGap={1} flexWrap="wrap" alignItems="center">
817          <Text>{WAITING_SEND}</Text>
818          <Button key="send-check" label={CHECK_LABEL} onPress={() => onSend()} />
819        </Box>
820      ) : undefined}
821      {!r.isUnsubscribed && r.canSend === false ? <Text dimColor>{checkSent(r.command)}</Text> : undefined}
822
823      {r.isUnsubscribed ? undefined : (
824        <Box flexDirection="column">
825          {heading('How it works from here')}
826          {WAITING_NEXT.map(line => (
827            <Box flexDirection="row" columnGap={1}>
828              <Box width={2}>
829                <Text dimColor>•</Text>
830              </Box>
831              <Box flexGrow={1} flexShrink={1}>
832                <Text>{line}</Text>
833              </Box>
834            </Box>
835          ))}
836        </Box>
837      )}
838
839      <Text dimColor>{WAITING_FOOTER}</Text>
840    </Box>
841  )
842}
843
844/* What one Markdown element draws at most. */
845const MAX_MARKDOWN = 10000
846
847/** The guide's text in sections that each fit one Markdown element: split before every
848    level-2 heading, and a longer section between paragraphs. Carriage returns, which the
849    element refuses, are dropped. */
850export function guideSections(text: string) {
851  const sections: string[] = []
852  for (const section of text.replace(/\r/g, '').split(/\n(?=## )/)) {
853    let chunk = ''
854    for (const paragraph of section.split(/\n{2,}/)) {
855      const next = chunk ? `${chunk}\n\n${paragraph}` : paragraph
856      if (next.length <= MAX_MARKDOWN) chunk = next
857      else {
858        if (chunk) sections.push(chunk)
859        chunk = paragraph.slice(0, MAX_MARKDOWN)
860      }
861    }
862    if (chunk.trim()) sections.push(chunk.trim())
863  }
864  return sections
865}
866
867/** A guide's title, its leading level-1 heading, and the rest in sections. */
868export function guideOf(text: string): GuideReport {
869  const [first = '', ...rest] = guideSections(text)
870  const heading = /^# (.+)(?:\n+|$)/.exec(first)
871  const lead = heading ? first.slice(heading[0].length).trim() : first
872  return { type: 'guide', title: heading?.[1]?.trim() ?? 'usage-dollars', sections: lead ? [lead, ...rest] : rest }
873}
874
875export function markdownGuide(r: GuideReport, id: string) {
876  return [`# ${r.title}`, ...r.sections, `[//]: # (usage-dollars:report:${id})`].join('\n\n')
877}
878
879export function guideCard(ui: Ui, r: GuideReport) {
880  const { Box, Markdown, Text } = ui
881  return (
882    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={3} paddingY={1} rowGap={1}>
883      <Text bold>{r.title}</Text>
884      {r.sections.map(text => (
885        <Markdown text={text} />
886      ))}
887    </Box>
888  )
889}
890
hooks/measure.ts 1498 lines
1/* Measurement: runs the transcript scan, keeps readings and plan history in $.store keyed
2   by subscription, and turns them into estimates. The engine reaches this module through
3   a Host that register.tsx builds, since $ itself never crosses an import. After a measure,
4   a second helper call rebuilds the per-feature dollars of readings stored without them,
5   and the meter-weight model fit is refreshed; the estimates do not use it.
6
7   $.store is one store shared by every running session, so each key is read immediately
8   before it is written, with no wait on the helper in between, and the plan, regime,
9   promotion and notice keys are written only when they changed. */
10
11import type { SessionRateLimit } from 'claude-code'
12
13import type {
14  CalibrationReport,
15  CheckItem,
16  CheckReport,
17  ModelSpend,
18  ModelsFit,
19  ModelsReport,
20  PlanReport,
21  SpendReport,
22  UsageReport,
23  WindowReport,
24} from '../types'
25import { money, statusLine } from './card'
26import {
27  MIN_ROUNDING_WINDOWS,
28  calibrateOmega,
29  calibrationOf,
30  estimate,
31  pastPoints,
32  prior,
33  record,
34  regimeView,
35  resolutionOf,
36  roundingEvidence,
37  tQuantile,
38} from './estimate'
39import type { Calibration, Estimate, Rounding, WindowReadings } from './estimate'
40import { UNIT_WEIGHTS, fingerprintOf, isFeatureComplete, prospectiveScore, selectModel, transferCheck, weightedView } from './meter'
41import type { FitResult, ProspectiveRecord, Selection, StoredFit, Transfer } from './meter'
42import { activePromotions, addRegimes, currentRegime, observePlan, observePromotions, planLabel, regimeStart, startOver, undoStartOver } from './plan'
43import type { Kind, Ledger, NoticeDraft, PlanEntry, Profile, Promotions, Regime, Regimes } from './plan'
44
45const MINUTE_MS = 60 * 1000
46const HOUR_MS = 60 * MINUTE_MS
47const DAY_MS = 24 * HOUR_MS
48const MIN_GAP_MS = MINUTE_MS
49const FRESH_MS = 5 * MINUTE_MS
50const READINGS_KEPT_MS = 28 * DAY_MS
51const HISTORY_DAYS = 14
52const HISTORY_REFRESH_MS = 6 * HOUR_MS
53const NOTICE_SHOWN_MS = 7 * DAY_MS
54const STALE_PROFILE_MS = 7 * DAY_MS
55const KEPT_NOTICES = 20
56/* Above this share of a window's requests going to unpriced models, its dollars no longer
57   track the limit. */
58const MAX_UNPRICED_SHARE = 0.02
59const SCHEMA = 5
60/* What the limits and readings this module stores mean; raise it whenever that changes.
61   A stored limit without one is stamp 0. */
62const HOOKS_STAMP = 2
63/* The engine rejects a store over 4 MiB of JSON text in all keys together; the readings
64   stay within 3 MiB and the other keys are small. */
65const MAX_READINGS_CHARS = 3 * 1024 * 1024
66/* The backfill: window specs per helper call, and its timeout. */
67const BACKFILL_MAX_SPECS = 100
68const BACKFILL_TIMEOUT_MS = 120_000
69/* A side's backfilled dollars match its stored ones within max(relative · usd, absolute),
70   the tolerance of a feature-complete window in meter.ts. */
71const FEATURE_TOLERANCE_RELATIVE = 1e-6
72const FEATURE_TOLERANCE_ABSOLUTE = 2e-4
73/* Per-feature dollars are stored in units of 1e-6, as record() stores them. */
74const X_UNIT = 1e6
75/* Qualifying 5-hour windows a model fit needs, as in meter.ts. */
76const FIT_MIN_WINDOWS = 4
77/* ω of a stored fit without a fitted model; unused, since its weights are M0's. */
78const UNFITTED_OMEGA = 0.5
79/* Prospective records kept per subscription. */
80const PROSPECTIVE_KEPT = 100
81const NONE = 'none'
82/* The suffixes of a window's further tallies: up to the moment this session received its
83   percent, and up to the moment the stored percent was received. */
84const AT_READ = '@read'
85const AT_STORED = '@stored'
86/* Median ratio of these dollars to Claude Code's own costs outside which the price table
87   is out of date. */
88const MIN_PRICE_RATIO = 0.9
89const MAX_PRICE_RATIO = 1.1
90
91const SCHEMA_KEY = 'schema'
92const LIMITS_KEY = 'limits'
93const READINGS_KEY = 'readings'
94const HISTORY_KEY = 'history'
95const PLANS_KEY = 'plans'
96const REGIMES_KEY = 'regimes'
97const PROMOTIONS_KEY = 'promotions'
98const NOTICES_KEY = 'notices'
99const METER_KEY = 'meter'
100
101export const INFERRED_TEXT =
102  'Usage no longer matches recent windows: limits may have changed, or this subscription was used elsewhere ' +
103  '(inferred from usage, not from the plan). If you changed plans, run /usage-dollars reset.'
104
105const WINDOWS: readonly { kind: Kind; name: string; title: string; short: string; spanMs: number }[] = [
106  { kind: 'five_hour', name: 'session', title: '5-hour window', short: '5h', spanMs: 5 * HOUR_MS },
107  { kind: 'seven_day', name: 'week', title: 'This week', short: 'Week', spanMs: 7 * DAY_MS },
108]
109
110const SPAN_MS: Record<string, number> = { five_hour: 5 * HOUR_MS, seven_day: 7 * DAY_MS }
111
112const KINDS: readonly Kind[] = ['five_hour', 'seven_day']
113
114const KIND_TITLES: Record<Kind, string> = { five_hour: '5-hour windows', seven_day: 'Weeks' }
115
116/** What this module needs from the engine: the clock, the session, the helper process,
117    $.store, the status line and the debug log. */
118export type Host = {
119  root: string
120  now: () => Promise<number>
121  sessionId: () => Promise<string>
122  rateLimits: () => Promise<readonly SessionRateLimit[]>
123  run: (argv: string[], options: { timeoutMs: number }) => Promise<{ stdout: string; stderr: string; exitCode: number | null }>
124  get: (key: string) => Promise<unknown>
125  set: (key: string, value: unknown) => Promise<void>
126  delete: (key: string) => Promise<void>
127  status: (text: string) => void
128  log: (text: string) => void
129}
130
131type OrgSource = 'session' | 'profile' | 'most recent'
132
133/* observedAt: when a session last received this percent from the API; absent for a reset
134   rolled forward without one. */
135type Limit = { percentUsed?: number; resetsAt: string; observedAt?: number }
136
137/* sessionId: the session that received the percent; stamp: its HOOKS_STAMP. */
138type StoredLimit = { percentUsed?: number; resetsAt: string; observedAt: number; sessionId?: string; stamp?: number }
139
140type StoredLimits = Record<string, Record<string, StoredLimit>>
141
142/* featuresUnverified: the backfill could not rebuild the window's per-feature dollars, and
143   does not try again. */
144type StoredReading = WindowReadings & { org: string; featuresUnverified?: boolean }
145
146type StoredReadings = Record<string, StoredReading>
147
148/* The model fit of one subscription, refitted only when its fingerprint changes.
149   included: the keys of the qualifying closed windows per kind; regimeStarts: per kind;
150   rounding: the rule of the second pass; fits: per kind, the weights in use with their ω
151   and M0's; prospective: new windows scored before each refit, the latest kept. */
152type MeterEntry = {
153  fingerprint: string
154  included: Record<string, string[]>
155  regimeStarts: Record<string, number>
156  pricesId?: string
157  rounding: Rounding
158  selection: Selection
159  transfer: Transfer
160  fits: Record<string, StoredFit>
161  prospective: ProspectiveRecord[]
162}
163
164type StoredMeter = Record<string, MeterEntry>
165
166/* The subscription and price table whose readings a measure wrote. */
167type MeterContext = { subscription: string; pricesId?: string }
168
169type Observation = { kind: string; resetsAt: string; at: string; usd: number }
170
171type History = Record<string, { scannedAt: number; observations: Observation[] }>
172
173export type Notice = {
174  id: string
175  kind: NoticeDraft['kind']
176  org: string
177  text: string
178  at: number
179  isToasted: boolean
180  isSeen: boolean
181}
182
183type WindowTally = {
184  usd: number
185  requests: number
186  byModel: Record<string, { usd: number; requests: number }>
187  /* usd by feature `<priceKey>[+fast]/<class>` or `web`; keys above 0 only. */
188  byFeature?: Record<string, number>
189  otherSubscriptionsUsd: number
190  unattributedUsd: number
191  unpricedRequests: number
192  unpricedModels: string[]
193  /* Other sessions' dollars just before the tally's end, which its percent may lack. */
194  slackUsd?: number
195  resetLabel?: string
196  resetLong?: string
197  resetIn?: string
198}
199
200type HelperBase = {
201  org?: string | null
202  orgSource?: OrgSource | null
203  profile?: Profile | null
204  labels?: Record<string, string>
205  error?: string
206}
207
208type WindowsOutput = HelperBase & { windows?: Record<string, WindowTally>; pricesId?: string; files: number; ms: number }
209
210type ReportOutput = HelperBase & {
211  usd: number
212  requests: number
213  byModel: Record<string, { usd: number; requests: number }>
214  byDay: { date: string; label: string; usd: number; requests: number }[]
215  otherSubscriptionsUsd: number
216  unattributedUsd: number
217  unpricedRequests: number
218  unpricedModels: string[]
219  fromLabel: string
220  toLabel: string
221  transcriptsBeginLabel?: string
222}
223
224/* closedWindows: closed windows of this kind and regime that hold readings. halfWidth: of
225   the current 90% range, in proportion. */
226type WindowCalibration = Calibration & { closedWindows: number; rounding: Rounding; halfWidth?: number }
227
228type WindowState = {
229  title: string
230  short: string
231  resetsAt: string
232  tally: WindowTally
233  estimate?: Estimate
234  isUnpriced: boolean
235  sinceResetLabel?: string
236  percent?: number
237  percentAt?: number
238  calibration: WindowCalibration
239}
240
241/* Why a percent a measure could have recorded was not: `missing` when nothing explains it. */
242type Outcome = 'recorded' | 'unpriced' | 'unattributed' | 'missing'
243
244/* A percent that may be recorded: this session's fresh one, or one stored by a session
245   whose reading of it may have been lost. sessionId: the session that received it. */
246type Candidate = { source: 'mine' | 'stored'; tally: string; percent: number; at: number; sessionId: string }
247
248/* A candidate a measure tried to record, under the window key, and what became of it. */
249type Attempt = { title: string; key: string; c: Candidate; outcome?: Outcome }
250
251export type Diagnostics = {
252  /* Another session stored a percent with other hooks since this module first measured:
253     older or newer than this one's. */
254  otherHooks?: 'older' | 'newer'
255  /* Stored windows dropped for another price table, over this session's measures. */
256  droppedForPrices: number
257  /* Closed windows dropped to keep the readings within MAX_READINGS_CHARS. */
258  droppedForSize: number
259  /* Per window title, what became of the percents the latest measure that had any could
260     record. */
261  outcomes: Record<string, { source: Candidate['source']; outcome: Outcome }[]>
262}
263
264export type Summary = {
265  subscription: string
266  orgSource?: OrgSource | null
267  windows: WindowState[]
268  plan: PlanReport
269  notices: string[]
270  last24hUsd?: number
271  /* The last 7 days' dollars by feature. */
272  last7dX?: Record<string, number>
273  sinceResetLabel?: string
274  files: number
275  ms: number
276}
277
278/* The session's subscription, once a helper run attributed it through the session's own
279   record; until then each measure asks the helper first. */
280let sessionOrg: string | undefined
281let lastSubscription: string | undefined
282let isMigrated = false
283let last: Summary | undefined
284let lastRunAt = 0
285let running: Promise<Summary | undefined> | undefined
286/* When this session last received its percents; their age decides between them and the
287   ones other sessions stored. */
288let lastFreshAt: number | undefined
289/* A fresh measure that arrived while another ran, with the time its percents arrived;
290   the latest wins. */
291let pendingFresh: { host: Host; limits?: readonly SessionRateLimit[]; receivedAt?: number } | undefined
292let firstMeasureAt: number | undefined
293const diagnostics: Diagnostics = { droppedForPrices: 0, droppedForSize: 0, outcomes: {} }
294/* The latest measure that wrote readings; the backfill and the model fit follow it. */
295let meterContext: MeterContext | undefined
296/* The backfill and model fit in flight, and the measure queued after it; the latest wins. */
297let followUp: Promise<void> | undefined
298let queuedFollowUp: { host: Host; context: MeterContext } | undefined
299/* Every write of the readings from this module, one at a time. */
300let readingsTurn: Promise<unknown> = Promise.resolve()
301
302const subscriptionOf = (org: string | null | undefined) => org ?? NONE
303
304const isSame = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
305
306const windowKey = (subscription: string, kind: string, resetsAt: string) =>
307  `${subscription}|${kind}@${new Date(Math.round(Date.parse(resetsAt) / MINUTE_MS) * MINUTE_MS).toISOString()}`
308
309const helperArgv = (host: Host) => ['node', `${host.root}/scripts/usage-cost.mjs`]
310
311async function runHelper<T extends HelperBase>(host: Host, extra: readonly string[], timeoutMs: number) {
312  return runScript<T>(host, ['--session', await host.sessionId(), ...extra], timeoutMs)
313}
314
315async function runScript<T extends { error?: string }>(host: Host, extra: readonly string[], timeoutMs: number) {
316  const run = await host.run([...helperArgv(host), ...extra], { timeoutMs })
317  let out: T | undefined
318  try {
319    out = JSON.parse(run.stdout || '{}') as T
320  } catch {
321    out = undefined
322  }
323  if (run.exitCode !== 0 || !out || out.error) {
324    const error = out?.error ?? run.stderr.slice(0, 200)
325    return { error: error || `helper exited with ${run.exitCode}` }
326  }
327  return { out }
328}
329
330/* v0.3.0 kept limits, readings and history without a subscription; they cannot be
331   attributed, so they are dropped once and the estimates start again.
332   Before schema 3 any session paired its own last percent, however old, with the dollars
333   of the moment and stored the pair; nothing tells those readings or limits from sound
334   ones, so both are dropped once more. Schema-3 readings paired the percent with the
335   dollars at the time of the scan and carry no slack or price table, so they are dropped
336   once again. History comes from rate-limit rejections in the transcripts, not from
337   percents, and is kept from schema 2 on. Schema-4 limits and readings lack only the
338   per-feature dollars, which the backfill rebuilds, so they are kept. */
339async function migrate(host: Host) {
340  if (isMigrated) return
341  const was = await host.get(SCHEMA_KEY)
342  if (was !== SCHEMA) {
343    if (was !== 4) {
344      await host.delete(LIMITS_KEY)
345      await host.delete(READINGS_KEY)
346      if (was !== 2 && was !== 3) await host.delete(HISTORY_KEY)
347    }
348    await host.set(SCHEMA_KEY, SCHEMA)
349  }
350  isMigrated = true
351}
352
353/* Runs `work`, which reads the readings and writes them, after every such work of this
354   module started before it. */
355function exclusively<T>(work: () => Promise<T>): Promise<T> {
356  const turn = readingsTurn.then(work)
357  readingsTurn = turn.catch(() => undefined)
358  return turn
359}
360
361/* The readings within MAX_READINGS_CHARS of JSON text: the oldest closed windows give way
362   first, each one counted. */
363function withinSize(readings: StoredReadings, now: number): StoredReadings {
364  let size = JSON.stringify(readings).length
365  if (size <= MAX_READINGS_CHARS) return readings
366  const kept = { ...readings }
367  const oldest = Object.entries(kept)
368    .filter(([, r]) => Date.parse(r.resetsAt) <= now)
369    .sort(([, a], [, b]) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt))
370  for (const [key, r] of oldest) {
371    if (size <= MAX_READINGS_CHARS) break
372    size -= JSON.stringify(key).length + JSON.stringify(r).length + 2
373    delete kept[key]
374    diagnostics.droppedForSize++
375  }
376  return kept
377}
378
379/** The session's subscription key: its own record, else the signed-in one, else "none". */
380export async function resolveSubscription(host: Host) {
381  await migrate(host)
382  if (sessionOrg) return sessionOrg
383  const { out } = await runHelper<HelperBase>(host, ['--whoami'], 30_000)
384  if (out?.orgSource === 'session' && out.org) sessionOrg = out.org
385  return subscriptionOf(out?.org)
386}
387
388/* The limit as last stored for the subscription: a 7-day window rolls forward a week at a
389   time, without a percent; a 5-hour one only holds until its reset. */
390function storedLimitOf(kind: Kind, kept: StoredLimit | undefined, now: number): Limit | undefined {
391  if (!kept) return undefined
392  let reset = Date.parse(kept.resetsAt)
393  if (reset > now) return { percentUsed: kept.percentUsed, resetsAt: kept.resetsAt, observedAt: kept.observedAt }
394  if (kind !== 'seven_day') return undefined
395  while (reset <= now) reset += 7 * DAY_MS
396  return { resetsAt: new Date(reset).toISOString() }
397}
398
399/* The limit this session holds, received at liveAt, or the one stored by any session,
400   whichever was received later. A live limit of unknown age loses to a stored one. */
401function limitOf(kind: Kind, live: readonly SessionRateLimit[], liveAt: number | undefined, kept: StoredLimit | undefined, now: number) {
402  const found = live.find(l => l.kind === kind && l.resetsAt)
403  const stored = storedLimitOf(kind, kept, now)
404  if (!found) return stored
405  const mine: Limit = { percentUsed: found.percentUsed, resetsAt: found.resetsAt!, observedAt: liveAt }
406  if (!stored) return mine
407  if (liveAt === undefined) return stored
408  return stored.observedAt !== undefined && stored.observedAt > liveAt ? stored : mine
409}
410
411const latestEntry = (plans: Ledger, subscription: string): PlanEntry | undefined => {
412  const entries = plans[subscription] ?? []
413  return entries[entries.length - 1]
414}
415
416/* Every stored instant the card may show, labeled by the helper under its epoch ms. */
417function labelArgs(regimes: Regimes, plans: Ledger, subscription: string, now: number) {
418  const instants = new Set<number>([now])
419  for (const w of WINDOWS) {
420    const r = currentRegime(regimes, subscription, w.kind)
421    if (r && r.startedAt > 0) instants.add(r.startedAt)
422  }
423  const entry = latestEntry(plans, subscription)
424  if (entry?.profileFetchedAt) instants.add(entry.profileFetchedAt)
425  if (entry?.lastSeenAt) instants.add(entry.lastSeenAt)
426  return [...instants].flatMap(ms => ['--label', `${ms},${new Date(ms).toISOString()}`])
427}
428
429async function queueNotices(host: Host, subscription: string, drafts: readonly NoticeDraft[], now: number) {
430  if (drafts.length === 0) return
431  const queue = ((await host.get(NOTICES_KEY)) ?? []) as Notice[]
432  const ids = new Set(queue.map(n => n.id))
433  const added = drafts
434    .filter(d => !ids.has(d.id))
435    .map(d => ({ ...d, org: subscription, at: now, isToasted: false, isSeen: false }) as Notice)
436  if (added.length === 0) return
437  const next = [...queue, ...added]
438  await host.set(NOTICES_KEY, next.slice(Math.max(0, next.length - KEPT_NOTICES)))
439}
440
441function planChangedText(event: { from: PlanEntry; to: PlanEntry; between: [number, number] }, labels: Record<string, string>, profile: Profile) {
442  const from = labels[String(event.between[0])] ?? 'the previous check'
443  const to =
444    (profile.fetchedAt && Date.parse(profile.fetchedAt) === event.between[1] ? profile.fetchedLabel : undefined) ??
445    labels[String(event.between[1])] ??
446    'now'
447  return `Plan changed: ${event.from.label} → ${event.to.label} (between ${from} and ${to}). Estimates restarted.`
448}
449
450function planReport(
451  event: ReturnType<typeof observePlan>['event'],
452  profile: Profile | null | undefined,
453  labels: Record<string, string>,
454  now: number,
455): PlanReport {
456  if (event.kind === 'unknown') {
457    const known = event.lastKnown
458    const on = known ? labels[String(known.lastSeenAt)] : undefined
459    return {
460      isUnknown: true,
461      isStale: false,
462      unknownReason: event.reason,
463      lastKnown: known ? `${known.label}${on ? ` on ${on}` : ''}` : undefined,
464    }
465  }
466  const fetchedAt = profile?.fetchedAt ? Date.parse(profile.fetchedAt) : NaN
467  const label = event.kind === 'changed' ? event.to.label : undefined
468  return {
469    isUnknown: false,
470    label: label ?? (profile ? planLabel(profile) : undefined),
471    asOfLabel: profile?.fetchedLabel ?? undefined,
472    isStale: Number.isFinite(fetchedAt) && now - fetchedAt > STALE_PROFILE_MS,
473  }
474}
475
476/* A closed window that contains a regime start of its own subscription mixes two sets of
477   limits, so it cannot tell how the API rounds. */
478function isStraddling(r: WindowReadings & { org: string }, regimes: Regimes) {
479  const reset = Date.parse(r.resetsAt)
480  const start = reset - (SPAN_MS[r.kind] ?? 0)
481  return (regimes[r.org] ?? []).some(
482    (g: Regime) => !g.isUndone && (!g.kinds || g.kinds.includes(r.kind as Kind)) && g.startedAt > start && g.startedAt <= reset,
483  )
484}
485
486function basisOf(e: Estimate | undefined, isUnpriced: boolean, sinceResetLabel: string | undefined) {
487  const reset = sinceResetLabel ? ` · since reset ${sinceResetLabel}` : ''
488  if (isUnpriced) return `Unpriced models in use: no estimate${reset}.`
489  if (!e) return `No estimate yet: the limit has not reported a usable reading for this window${reset}.`
490  const readings = e.isPriorOnly
491    ? 'From past windows only: no tick read in this window yet'
492    : `${e.readings} percent level${e.readings === 1 ? '' : 's'} read`
493  const within = `within-window spread ${e.isWithinSpreadAssumed ? 'assumed' : 'measured'}`
494  const between = e.isSpreadAssumed
495    ? 'between-window spread assumed'
496    : `between-window spread from ${e.pastWindows} past window${e.pastWindows === 1 ? '' : 's'}`
497  return `${readings} · ${within} · ${between} · history weight ${e.pastWeight}${reset}`
498}
499
500const isUnpricedTally = (t: WindowTally) => t.unpricedRequests > MAX_UNPRICED_SHARE * (t.requests + t.unpricedRequests)
501
502/* The percents of the active window a measure may record: this session's, from `given`,
503   and the stored one when a session with these hooks stored it and it is not the same
504   percent. Whether the stored one has a reading already is decided against the readings
505   read just before they are written. */
506function candidatesOf(
507  w: (typeof WINDOWS)[number],
508  limit: Limit,
509  subscription: string,
510  given: readonly SessionRateLimit[] | undefined,
511  readAt: number,
512  sessionId: string,
513  kept: StoredLimit | undefined,
514): Candidate[] {
515  const key = windowKey(subscription, w.kind, limit.resetsAt)
516  const candidates: Candidate[] = []
517  const fresh = given?.find(l => l.kind === w.kind && l.resetsAt)
518  if (fresh && windowKey(subscription, w.kind, fresh.resetsAt!) === key)
519    candidates.push({ source: 'mine', tally: `${w.name}${AT_READ}`, percent: fresh.percentUsed, at: readAt, sessionId })
520  const isMine = candidates.some(c => c.at === kept?.observedAt && c.sessionId === kept?.sessionId)
521  if (
522    kept?.sessionId &&
523    kept.percentUsed !== undefined &&
524    (kept.stamp ?? 0) === HOOKS_STAMP &&
525    windowKey(subscription, w.kind, kept.resetsAt) === key &&
526    !isMine
527  )
528    candidates.push({ source: 'stored', tally: `${w.name}${AT_STORED}`, percent: kept.percentUsed, at: kept.observedAt, sessionId: kept.sessionId })
529  return candidates
530}
531
532/* Whether a level's bucket holds the reading at `at`, or a later one at that level that
533   took its side. */
534function isHeld(r: WindowReadings | undefined, percent: number, at: number) {
535  const b = r?.byPct[String(percent)]
536  return b !== undefined && (b.minAt === at || b.maxAt >= at)
537}
538
539const hasReadingAt = (r: WindowReadings | undefined, at: number) =>
540  r !== undefined && Object.values(r.byPct).some(b => b.minAt === at || b.maxAt === at)
541
542/* isFresh: `given` holds percents this session received at receivedAt, so they and the
543   dollars counted up to then describe the same moment. Only such a measure records its
544   own percents or shares its limits; every measure records a stored percent that has no
545   reading yet. */
546async function measure(
547  host: Host,
548  given: readonly SessionRateLimit[] | undefined,
549  isFresh: boolean,
550  receivedAt: number | undefined,
551): Promise<Summary | undefined> {
552  const now = await host.now()
553  if (firstMeasureAt === undefined) firstMeasureAt = now
554  const readAt = isFresh && receivedAt !== undefined ? receivedAt : now
555  const live = given ?? (await host.rateLimits())
556  if (isFresh) lastFreshAt = readAt
557  const sessionId = await host.sessionId()
558  let subscription = await resolveSubscription(host)
559
560  let active: { w: (typeof WINDOWS)[number]; limit: Limit; candidates: Candidate[] }[] = []
561  let storedLimits: StoredLimits = {}
562  let out: WindowsOutput | undefined
563  for (let attempt = 0; attempt < 2; attempt++) {
564    storedLimits = ((await host.get(LIMITS_KEY)) ?? {}) as StoredLimits
565    active = []
566    for (const w of WINDOWS) {
567      const kept = storedLimits[subscription]?.[w.kind]
568      const limit = limitOf(w.kind, live, lastFreshAt, kept, now)
569      if (limit) active.push({ w, limit, candidates: candidatesOf(w, limit, subscription, isFresh ? given : undefined, readAt, sessionId, kept) })
570    }
571    if (active.length === 0) {
572      host.status('waiting for the first reply')
573      return undefined
574    }
575
576    const regimes = ((await host.get(REGIMES_KEY)) ?? {}) as Regimes
577    const plans = ((await host.get(PLANS_KEY)) ?? {}) as Ledger
578    const extra: string[] = []
579    for (const { w, limit, candidates } of active) {
580      const since = new Date(Date.parse(limit.resetsAt) - w.spanMs).toISOString()
581      extra.push('--window', `${w.name},${since},${limit.resetsAt}`)
582      for (const c of candidates)
583        extra.push('--window', `${c.tally},${since},${limit.resetsAt},${new Date(c.at).toISOString()},${c.sessionId}`)
584    }
585    extra.push('--window', `last24h,${new Date(now - DAY_MS).toISOString()},${new Date(now).toISOString()}`)
586    extra.push('--window', `last7d,${new Date(now - 7 * DAY_MS).toISOString()},${new Date(now).toISOString()}`)
587    extra.push(...labelArgs(regimes, plans, subscription, now))
588    const result = await runHelper<WindowsOutput>(host, extra, 120_000)
589    if (!result.out?.windows) {
590      host.status('unavailable')
591      host.log(`usage-dollars: ${result.error ?? 'no windows in the helper output'}`)
592      return undefined
593    }
594    out = result.out
595    if (out.orgSource === 'session' && out.org) sessionOrg = out.org
596    const reported = subscriptionOf(out.org)
597    if (reported === subscription) break
598    subscription = reported
599    if (attempt === 1) break
600  }
601  if (!out?.windows) return undefined
602  lastSubscription = subscription
603  const labels = out.labels ?? {}
604  const profile = out.profile ?? null
605
606  /* A stored limit gives way to one received later, or to the next window's. */
607  const liveLimits = isFresh ? live.filter(l => l.resetsAt && WINDOWS.some(w => w.kind === l.kind)) : []
608  if (liveLimits.length > 0) {
609    const stored = ((await host.get(LIMITS_KEY)) ?? {}) as StoredLimits
610    const mine = { ...stored[subscription] }
611    let isChanged = false
612    for (const l of liveLimits) {
613      const was = mine[l.kind] as StoredLimit | undefined
614      if (was && Date.parse(was.resetsAt) >= Date.parse(l.resetsAt!) && was.observedAt >= readAt) continue
615      mine[l.kind] = { percentUsed: l.percentUsed, resetsAt: l.resetsAt!, observedAt: readAt, sessionId, stamp: HOOKS_STAMP }
616      isChanged = true
617    }
618    if (isChanged) await host.set(LIMITS_KEY, { ...stored, [subscription]: mine })
619  }
620
621  /* Hooks of another stamp that stored a percent since this module first measured. */
622  for (const l of Object.values(storedLimits[subscription] ?? {})) {
623    const stamp = l.stamp ?? 0
624    if (stamp !== HOOKS_STAMP && l.observedAt > (firstMeasureAt ?? now)) diagnostics.otherHooks = stamp < HOOKS_STAMP ? 'older' : 'newer'
625  }
626
627  /* A guessed subscription must not write readings; with none at all every request is
628     counted, as on a machine without bridge-session records. A reading takes its percent
629     from a candidate, and only for the window the dollars were scanned for; its dollars
630     and their features end where the percent was received. Readings priced with another
631     table are dropped. */
632  const mayRecord = out.org === null || out.org === undefined || out.orgSource === 'session' || out.orgSource === 'profile'
633  const pricesId = out.pricesId
634  const tallies = out.windows
635  const { kept, attempts } = await exclusively(async () => {
636    const storedReadings = ((await host.get(READINGS_KEY)) ?? {}) as StoredReadings
637    const readings = Object.fromEntries(Object.entries(storedReadings).filter(([, r]) => r.pricesId === pricesId)) as StoredReadings
638    diagnostics.droppedForPrices += Object.keys(storedReadings).length - Object.keys(readings).length
639    const attempts: Attempt[] = []
640    for (const { w, limit, candidates } of active) {
641      const key = windowKey(subscription, w.kind, limit.resetsAt)
642      for (const c of candidates) {
643        if (c.source === 'stored' && hasReadingAt(readings[key], c.at)) continue
644        const tally = tallies[c.tally]
645        const attempt: Attempt = { title: w.title, key, c }
646        attempts.push(attempt)
647        if (!mayRecord) attempt.outcome = 'unattributed'
648        else if (tally && isUnpricedTally(tally)) attempt.outcome = 'unpriced'
649        else if (tally) {
650          const was = readings[key] ?? { kind: w.kind, resetsAt: limit.resetsAt, byPct: {}, org: subscription, pricesId }
651          readings[key] = { ...record(was, c.percent, tally.usd, c.at, tally.slackUsd ?? 0, tally.byFeature), org: subscription, pricesId }
652        }
653      }
654    }
655    const kept = withinSize(
656      Object.fromEntries(Object.entries(readings).filter(([, r]) => Date.parse(r.resetsAt) > now - READINGS_KEPT_MS)) as StoredReadings,
657      now,
658    )
659    await host.set(READINGS_KEY, kept)
660    return { kept, attempts }
661  })
662  const outcomes: Diagnostics['outcomes'] = {}
663  for (const a of attempts) {
664    const outcome = a.outcome ?? (isHeld(kept[a.key], a.c.percent, a.c.at) ? 'recorded' : 'missing')
665    outcomes[a.title] = [...(outcomes[a.title] ?? []), { source: a.c.source, outcome }]
666  }
667  for (const [title, list] of Object.entries(outcomes)) diagnostics.outcomes[title] = list
668
669  const plans = ((await host.get(PLANS_KEY)) ?? {}) as Ledger
670  const observedPlan = observePlan(plans, profile, subscription, now)
671  if (!isSame(observedPlan.ledger, plans)) await host.set(PLANS_KEY, observedPlan.ledger)
672
673  const promotions = ((await host.get(PROMOTIONS_KEY)) ?? {}) as Promotions
674  const observedPromos = observePromotions(promotions, profile, subscription, now)
675  if (!isSame(observedPromos.stored, promotions)) await host.set(PROMOTIONS_KEY, observedPromos.stored)
676
677  const added = [...(observedPlan.regime ? [observedPlan.regime] : []), ...observedPromos.regimes]
678  let regimes = ((await host.get(REGIMES_KEY)) ?? {}) as Regimes
679  if (added.length > 0) {
680    regimes = addRegimes(regimes, subscription, added)
681    await host.set(REGIMES_KEY, regimes)
682  }
683
684  const drafts: NoticeDraft[] = [...observedPromos.notices]
685  const event = observedPlan.event
686  if (event.kind === 'changed' && profile)
687    drafts.push({ id: `plan:${subscription}:${event.to.fingerprint}`, kind: 'plan-changed', text: planChangedText(event, labels, profile) })
688
689  const all = Object.values(kept)
690  const resolution = resolutionOf(all)
691  const roundingSeen = roundingEvidence(
692    all.filter(r => Date.parse(r.resetsAt) <= now && !isStraddling(r, regimes)),
693    resolution,
694  )
695  const rounding = roundingSeen.rule
696  const history = ((await host.get(HISTORY_KEY)) ?? {}) as History
697  const observations = history[subscription]?.observations ?? []
698
699  const windows: WindowState[] = []
700  for (const { w, limit } of active) {
701    const tally = out.windows[w.name]
702    if (!tally) continue
703    const startedAt = regimeStart(regimes, subscription, w.kind)
704    const regime = currentRegime(regimes, subscription, w.kind)
705    /* Closed windows of this subscription and regime: one past point each, and the
706       crossings that measure the within-window spread. */
707    const closed = all
708      .filter(r => r.org === subscription && r.kind === w.kind && Date.parse(r.resetsAt) <= now && Date.parse(r.resetsAt) >= startedAt)
709      .map(r => regimeView(r, startedAt))
710    const rejections = observations.filter(o => Date.parse(o.resetsAt) > now - HISTORY_DAYS * DAY_MS)
711    const spread = calibrateOmega(closed, w.kind, now, resolution, rounding)
712    const past = pastPoints(closed, rejections, w.kind, resolution, rounding, spread.omega).filter(p => p.at >= startedAt)
713    const key = windowKey(subscription, w.kind, limit.resetsAt)
714    const stored = kept[key]
715    const current = stored ? regimeView(stored, startedAt) : undefined
716    const isUnpriced = isUnpricedTally(tally)
717    const e =
718      current && !isUnpriced
719        ? estimate(current, tally.usd, {
720            resolution,
721            rounding,
722            past,
723            kind: w.kind,
724            now,
725            livePercent: limit.observedAt !== undefined && now - limit.observedAt <= FRESH_MS ? limit.percentUsed : undefined,
726            spread,
727          })
728        : undefined
729    if (e?.isPriorContradicted) drafts.push({ id: `inferred:${key}`, kind: 'inferred', text: INFERRED_TEXT })
730    windows.push({
731      title: w.title,
732      short: w.short,
733      resetsAt: limit.resetsAt,
734      tally,
735      estimate: e,
736      isUnpriced,
737      sinceResetLabel: regime?.reason === 'manual' ? labels[String(regime.startedAt)] : undefined,
738      percent: limit.percentUsed,
739      percentAt: limit.percentUsed !== undefined ? limit.observedAt : undefined,
740      calibration: {
741        ...calibrationOf({ current, resolution, spread, prior: prior(past, w.kind, now), rounding: roundingSeen }),
742        closedWindows: closed.filter(r => Object.keys(r.byPct).length > 0).length,
743        rounding,
744        halfWidth: e ? Math.sqrt(e.allowance.high / e.allowance.low) - 1 : undefined,
745      },
746    })
747  }
748  await queueNotices(host, subscription, drafts, now)
749
750  const queue = ((await host.get(NOTICES_KEY)) ?? []) as Notice[]
751  const mine = queue.filter(n => n.org === subscription)
752  const isPlanUnseen = mine.some(n => n.kind === 'plan-changed' && !n.isSeen)
753  host.status(statusOf({ windows }, isPlanUnseen))
754
755  const isShared = Object.keys(observedPlan.ledger).length > 1
756  const notices = [
757    ...mine
758      .filter(n => n.kind === 'plan-changed' && n.at > now - NOTICE_SHOWN_MS)
759      .map(n => n.text),
760    ...activePromotions(observedPromos.stored, subscription).map(t => (isShared ? `${t} Not attributable to one subscription.` : t)),
761    ...mine
762      .filter(n => n.kind === 'promotion' && /^promo-(end|gone):/.test(n.id) && n.at > now - NOTICE_SHOWN_MS)
763      .map(n => n.text),
764    ...(windows.some(s => s.estimate?.isPriorContradicted) ? [INFERRED_TEXT] : []),
765  ]
766
767  const summary: Summary = {
768    subscription,
769    orgSource: out.orgSource,
770    windows,
771    plan: planReport(event, profile, labels, now),
772    notices,
773    last24hUsd: out.windows.last24h?.usd,
774    last7dX: out.windows.last7d?.byFeature,
775    sinceResetLabel: windows.find(s => s.sinceResetLabel)?.sinceResetLabel,
776    files: out.files,
777    ms: out.ms,
778  }
779  if (mayRecord) {
780    meterContext = { subscription, pricesId }
781    follow(host, meterContext)
782  }
783  return summary
784}
785
786/* The backfill and the model fit after a measure, one run at a time; a measure that ends
787   while one runs queues the next. Neither delays nor fails the measure. */
788function follow(host: Host, context: MeterContext) {
789  queuedFollowUp = { host, context }
790  if (followUp) return
791  const takeQueued = () => {
792    const next = queuedFollowUp
793    queuedFollowUp = undefined
794    return next
795  }
796  followUp = (async () => {
797    try {
798      for (let next = takeQueued(); next; next = takeQueued()) {
799        const { host: h, context: c } = next
800        await backfillOnce(h, c).catch(error => h.log(`usage-dollars: backfill: ${String(error)}`))
801        await refreshMeter(h, c).catch(error => h.log(`usage-dollars: model fit: ${String(error)}`))
802      }
803    } finally {
804      followUp = undefined
805    }
806  })().catch(() => undefined)
807}
808
809/** The backfill and model fit that measures started, settled once none is left. */
810export function backfillSettled(): Promise<void> {
811  return followUp ?? Promise.resolve()
812}
813
814const toleranceOf = (usd: number) => Math.max(FEATURE_TOLERANCE_RELATIVE * Math.abs(usd), FEATURE_TOLERANCE_ABSOLUTE)
815
816/* One bucket side without per-feature dollars, and the --window name its dollars come
817   back under. */
818type BackfillSide = { key: string; pct: string; isMin: boolean; at: number; usd: number; name: string }
819
820/* Up to BACKFILL_MAX_SPECS window specs for the sides that lack features, newest windows
821   first, open ones included; sides read at the same moment share a spec. Windows the
822   backfill could not rebuild are left out. */
823function backfillPlanOf(readings: StoredReadings, context: MeterContext) {
824  const sides: BackfillSide[] = []
825  const names = new Map<string, string>()
826  const newestFirst = Object.entries(readings)
827    .filter(([, r]) => r.org === context.subscription && r.pricesId === context.pricesId && !r.featuresUnverified && SPAN_MS[r.kind])
828    .sort(([, a], [, b]) => Date.parse(b.resetsAt) - Date.parse(a.resetsAt))
829  for (const [key, r] of newestFirst) {
830    const since = new Date(Date.parse(r.resetsAt) - (SPAN_MS[r.kind] ?? 0)).toISOString()
831    for (const [pct, b] of Object.entries(r.byPct))
832      for (const isMin of [true, false]) {
833        if ((isMin ? b.minX : b.maxX) !== undefined) continue
834        const at = isMin ? b.minAt : b.maxAt
835        const spec = `${since},${r.resetsAt},${new Date(at).toISOString()}`
836        let name = names.get(spec)
837        if (name === undefined) {
838          if (names.size >= BACKFILL_MAX_SPECS) return { sides, names }
839          name = `bf${names.size}`
840          names.set(spec, name)
841        }
842        sides.push({ key, pct, isMin, at, usd: isMin ? b.minUsd : b.maxUsd, name })
843      }
844  }
845  return { sides, names }
846}
847
848/* The window with one side's per-feature dollars as record() stores them: new keys
849   appended in sorted order, values in units of 1e-6. */
850function withSideFeatures(r: StoredReading, pct: string, isMin: boolean, x: Record<string, number>): StoredReading {
851  const b = r.byPct[pct]
852  if (!b) return r
853  const known = r.features ?? []
854  const features = [
855    ...known,
856    ...Object.keys(x)
857      .filter(f => !known.includes(f))
858      .sort(),
859  ]
860  const values = features.map(f => Math.round((x[f] ?? 0) * X_UNIT) / X_UNIT)
861  return { ...r, features, byPct: { ...r.byPct, [pct]: isMin ? { ...b, minX: values } : { ...b, maxX: values } } }
862}
863
864/* One helper call that rescans the dollars of sides stored without features. A side is
865   filled when its rescanned dollars match the stored ones; otherwise its window is marked
866   and not tried again. A failed call changes nothing; the next measure tries again. */
867async function backfillOnce(host: Host, context: MeterContext) {
868  const plan = backfillPlanOf(((await host.get(READINGS_KEY)) ?? {}) as StoredReadings, context)
869  if (plan.sides.length === 0) return
870  const extra = [...plan.names].flatMap(([spec, name]) => ['--window', `${name},${spec}`])
871  const result = await runHelper<WindowsOutput>(host, extra, BACKFILL_TIMEOUT_MS)
872  const out = result.out
873  if (!out?.windows) {
874    host.log(`usage-dollars: backfill: ${result.error ?? 'no windows in the helper output'}`)
875    return
876  }
877  if (subscriptionOf(out.org) !== context.subscription || out.pricesId !== context.pricesId) {
878    host.log('usage-dollars: backfill: the helper scanned another subscription or price table')
879    return
880  }
881  const tallies = out.windows
882  const now = await host.now()
883  await exclusively(async () => {
884    const readings = ((await host.get(READINGS_KEY)) ?? {}) as StoredReadings
885    const next = { ...readings }
886    let isChanged = false
887    for (const s of plan.sides) {
888      const r = next[s.key]
889      const b = r?.byPct[s.pct]
890      const x = tallies[s.name]
891      if (!r || !b || r.featuresUnverified || !x?.byFeature) continue
892      const isUnchanged = (s.isMin ? b.minAt : b.maxAt) === s.at && (s.isMin ? b.minUsd : b.maxUsd) === s.usd
893      if (!isUnchanged || (s.isMin ? b.minX : b.maxX) !== undefined) continue
894      next[s.key] =
895        Math.abs(x.usd - s.usd) <= toleranceOf(s.usd) ? withSideFeatures(r, s.pct, s.isMin, x.byFeature) : { ...r, featuresUnverified: true }
896      isChanged = true
897    }
898    if (isChanged) await host.set(READINGS_KEY, withinSize(next, now))
899  })
900}
901
902/* Closed windows of one kind in the subscription's current regime, as seen from it, that
903   hold readings, with their store keys. */
904function regimeWindowsOf(readings: StoredReadings, context: MeterContext, kind: Kind, startedAt: number, now: number) {
905  return Object.entries(readings)
906    .filter(
907      ([, r]) =>
908        r.org === context.subscription &&
909        r.pricesId === context.pricesId &&
910        r.kind === kind &&
911        Date.parse(r.resetsAt) <= now &&
912        Date.parse(r.resetsAt) >= startedAt,
913    )
914    .map(([key, r]) => ({ key, w: regimeView(r, startedAt) as StoredReading }))
915    .filter(({ w }) => Object.keys(w.byPct).length > 0)
916}
917
918/* What the model fit rests on, read from the store. */
919async function meterInputOf(host: Host, context: MeterContext) {
920  const now = await host.now()
921  const readings = ((await host.get(READINGS_KEY)) ?? {}) as StoredReadings
922  const regimes = ((await host.get(REGIMES_KEY)) ?? {}) as Regimes
923  const all = Object.values(readings).filter(r => r.pricesId === context.pricesId)
924  const resolution = resolutionOf(all)
925  const regimeStarts: Record<string, number> = {}
926  const closed: Record<string, { key: string; w: StoredReading }[]> = {}
927  for (const kind of KINDS) {
928    regimeStarts[kind] = regimeStart(regimes, context.subscription, kind)
929    closed[kind] = regimeWindowsOf(readings, context, kind, regimeStarts[kind] ?? 0, now)
930  }
931  const qualifying = (kind: Kind) => (closed[kind] ?? []).filter(({ w }) => isFeatureComplete(w))
932  return {
933    now,
934    resolution,
935    regimeStarts,
936    closed,
937    fiveHour: qualifying('five_hour'),
938    weekly: qualifying('seven_day'),
939    /* Closed windows of every subscription that may show the rounding rule, as the measure
940       takes them. */
941    forRounding: all.filter(r => Date.parse(r.resetsAt) <= now && !isStraddling(r, regimes)),
942  }
943}
944
945/* Scores the windows that qualify since the stored fit, under its weights for their kind
946   and under M0, before the refit; a kind's records are cleared when its regime or the
947   price table changed. */
948function prospectiveOf(was: MeterEntry | undefined, input: Awaited<ReturnType<typeof meterInputOf>>, pricesId: string | undefined) {
949  let records = [...(was?.prospective ?? [])]
950  if (!was) return records
951  for (const kind of KINDS) {
952    if (was.regimeStarts[kind] !== input.regimeStarts[kind] || was.pricesId !== pricesId) {
953      records = records.filter(p => p.kind !== kind)
954      continue
955    }
956    const fit = was.fits?.[kind]
957    if (!fit) continue
958    const seen = new Set(was.included?.[kind] ?? [])
959    const fresh = (kind === 'five_hour' ? input.fiveHour : input.weekly).filter(({ key }) => !seen.has(key)).map(({ w }) => w)
960    records.push(...prospectiveScore(fit, fresh, { resolution: input.resolution, rounding: was.rounding }))
961  }
962  return records.slice(-PROSPECTIVE_KEPT)
963}
964
965/* The stored model fit of the subscription, refitted when its fingerprint changed: model
966   selection on the 5-hour windows under the union, the rounding rule from the weighted
967   views it gives, selection again under that rule, then the transfer to the weeks. The
968   estimates do not use it. */
969async function refreshMeter(host: Host, context: MeterContext): Promise<MeterEntry | undefined> {
970  const input = await meterInputOf(host, context)
971  const fingerprint = fingerprintOf({
972    fiveHour: input.fiveHour,
973    weekly: input.weekly,
974    regimeStarts: input.regimeStarts,
975    pricesId: context.pricesId,
976    schema: SCHEMA,
977    stamp: HOOKS_STAMP,
978  })
979  const stored = ((await host.get(METER_KEY)) ?? {}) as StoredMeter
980  const was = stored[context.subscription]
981  if (was?.fingerprint === fingerprint) return was
982  const prospective = prospectiveOf(was, input, context.pricesId)
983  const { resolution } = input
984  const fiveHour = input.fiveHour.map(({ w }) => w)
985  const first = selectModel(fiveHour, { resolution, rounding: 'union' })
986  const views = input.forRounding.flatMap(r => weightedView(r, first.weights) ?? [])
987  const rounding = roundingEvidence(views, resolution).rule
988  const selection = rounding === 'union' ? first : selectModel(fiveHour, { resolution, rounding })
989  const transfer = transferCheck(input.weekly.map(({ w }) => w), selection.weights, { resolution, rounding })
990  const entry: MeterEntry = {
991    fingerprint,
992    included: { five_hour: input.fiveHour.map(({ key }) => key), seven_day: input.weekly.map(({ key }) => key) },
993    regimeStarts: input.regimeStarts,
994    ...(context.pricesId !== undefined ? { pricesId: context.pricesId } : {}),
995    rounding,
996    selection,
997    transfer,
998    fits: {
999      five_hour: {
1000        weights: selection.weights,
1001        omega: selection.fits[selection.selected]?.omega ?? UNFITTED_OMEGA,
1002        omegaM0: selection.fits.M0?.omega ?? UNFITTED_OMEGA,
1003      },
1004      seven_day: transfer.isRejected
1005        ? { weights: UNIT_WEIGHTS, omega: transfer.omega.M0, omegaM0: transfer.omega.M0 }
1006        : { weights: selection.weights, omega: transfer.omega.selected, omegaM0: transfer.omega.M0 },
1007    },
1008    prospective,
1009  }
1010  if (!isSame(entry, was)) await host.set(METER_KEY, { ...stored, [context.subscription]: entry })
1011  return entry
1012}
1013
1014/** The status line: what is left of each window's allowance. */
1015export function statusOf(summary: Pick<Summary, 'windows'>, isPlanUnseen: boolean) {
1016  return statusLine(
1017    summary.windows.map(s => ({ short: s.short, usedUsd: s.tally.usd, allowance: s.estimate?.allowance, left: s.estimate?.left })),
1018    isPlanUnseen,
1019  )
1020}
1021
1022/* One scan at a time, at most once a minute unless forced or fresh. A fresh call that
1023   meets a running scan is queued and runs, forced, once that scan settles. */
1024export function refresh(host: Host, limits?: readonly SessionRateLimit[], isForced = false, isFresh = false, receivedAt?: number) {
1025  if (running) {
1026    if (isFresh) pendingFresh = { host, limits, receivedAt }
1027    return running
1028  }
1029  if (!isForced && !isFresh && Date.now() - lastRunAt < MIN_GAP_MS) return Promise.resolve(last)
1030  lastRunAt = Date.now()
1031  running = measure(host, limits, isFresh, receivedAt)
1032    .then(summary => (last = summary ?? last))
1033    .catch(error => {
1034      host.log(`usage-dollars: ${String(error)}`)
1035      return last
1036    })
1037    .finally(() => {
1038      running = undefined
1039      const queued = pendingFresh
1040      pendingFresh = undefined
1041      if (queued) void refresh(queued.host, queued.limits, true, true, queued.receivedAt)
1042    })
1043  return running
1044}
1045
1046/** A forced measure that starts after any measure already running. */
1047export async function remeasure(host: Host) {
1048  if (running) await running
1049  return refresh(host, undefined, true)
1050}
1051
1052/* Past rate-limit rejections, each a window seen exactly full; rescanned every six hours. */
1053export async function refreshHistory(host: Host) {
1054  const subscription = await resolveSubscription(host)
1055  const now = await host.now()
1056  const kept = ((await host.get(HISTORY_KEY)) ?? {}) as History
1057  if (kept[subscription] && now - kept[subscription].scannedAt < HISTORY_REFRESH_MS) return
1058  const { out, error } = await runHelper<HelperBase & { observations?: Observation[] }>(
1059    host,
1060    ['--history', String(HISTORY_DAYS)],
1061    180_000,
1062  )
1063  if (!out?.observations) {
1064    host.log(`usage-dollars: history: ${error ?? 'no observations'}`)
1065    return
1066  }
1067  const stored = ((await host.get(HISTORY_KEY)) ?? {}) as History
1068  await host.set(HISTORY_KEY, { ...stored, [subscriptionOf(out.org)]: { scannedAt: now, observations: out.observations } })
1069  void refresh(host, undefined, true)
1070}
1071
1072/** Restarts the estimates of the session's subscription from now. */
1073export async function resetEstimates(host: Host) {
1074  const subscription = await resolveSubscription(host)
1075  const now = await host.now()
1076  const regimes = ((await host.get(REGIMES_KEY)) ?? {}) as Regimes
1077  await host.set(REGIMES_KEY, startOver(regimes, subscription, now))
1078  await remeasure(host)
1079}
1080
1081/** Undoes the latest reset when nothing observed has followed it. */
1082export async function undoReset(host: Host) {
1083  const subscription = await resolveSubscription(host)
1084  const regimes = ((await host.get(REGIMES_KEY)) ?? {}) as Regimes
1085  const result = undoStartOver(regimes, subscription)
1086  if (result.isUndone) await host.set(REGIMES_KEY, result.regimes)
1087  await remeasure(host)
1088  return result.isUndone
1089}
1090
1091/** Marks every queued notice seen: the card has been shown. */
1092export async function markNoticesSeen(host: Host) {
1093  const queue = ((await host.get(NOTICES_KEY)) ?? []) as Notice[]
1094  if (queue.every(n => n.isSeen)) return
1095  await host.set(NOTICES_KEY, queue.map(n => ({ ...n, isSeen: true })))
1096}
1097
1098/** The texts of this subscription's notices not toasted yet, marked toasted. */
1099export async function takeToasts(host: Host) {
1100  if (!lastSubscription) return []
1101  const queue = ((await host.get(NOTICES_KEY)) ?? []) as Notice[]
1102  const due = queue.filter(n => n.org === lastSubscription && !n.isToasted)
1103  if (due.length === 0) return []
1104  const ids = new Set(due.map(n => n.id))
1105  await host.set(NOTICES_KEY, queue.map(n => (ids.has(n.id) ? { ...n, isToasted: true } : n)))
1106  return due.map(n => n.text)
1107}
1108
1109export function toReport(summary: Summary, now: number): UsageReport {
1110  const windows: WindowReport[] = summary.windows.map(s => ({
1111    title: s.title,
1112    short: s.short,
1113    usedUsd: s.tally.usd,
1114    requests: s.tally.requests,
1115    resetLong: s.tally.resetLong ?? s.resetsAt,
1116    resetIn: s.tally.resetIn ?? '',
1117    left: s.estimate
1118      ? { value: Math.max(0, s.estimate.left.value), low: Math.max(0, s.estimate.left.low), high: Math.max(0, s.estimate.left.high) }
1119      : undefined,
1120    allowance: s.estimate?.allowance,
1121    confidence: s.estimate?.confidence,
1122    nextTick: s.estimate?.nextTick,
1123    pastWeight: s.estimate?.pastWeight,
1124    isPriorContradicted: s.estimate?.isPriorContradicted,
1125    isSpreadAssumed: s.estimate?.isSpreadAssumed,
1126    percent: s.percent,
1127    percentAgeMinutes: s.percentAt !== undefined ? Math.max(0, Math.round((now - s.percentAt) / MINUTE_MS)) : undefined,
1128    basis: basisOf(s.estimate, s.isUnpriced, s.sinceResetLabel),
1129    isCalibrated: s.calibration.isCalibrated,
1130  }))
1131  const widest = summary.windows[summary.windows.length - 1]
1132  const byModel: ModelSpend[] = Object.entries(widest?.tally.byModel ?? {})
1133    .map(([model, spend]) => ({ model, ...spend }))
1134    .sort((a, b) => b.usd - a.usd)
1135  return {
1136    type: 'windows',
1137    plan: summary.plan,
1138    notices: summary.notices,
1139    last24hUsd: summary.last24hUsd,
1140    sinceResetLabel: summary.sinceResetLabel,
1141    windows,
1142    byModel,
1143    byModelTitle: `By model · ${(widest?.title ?? '').toLowerCase()}`,
1144    notes: notesOf(widest?.tally),
1145    files: summary.files,
1146    ms: summary.ms,
1147  }
1148}
1149
1150function notesOf(t: Omit<WindowTally, 'byModel' | 'usd' | 'requests'> | undefined) {
1151  const notes: string[] = []
1152  if (t && t.otherSubscriptionsUsd > 0)
1153    notes.push(`Other subscriptions spent ${money(t.otherSubscriptionsUsd)} in this period; not counted here.`)
1154  if (t && t.unattributedUsd > 0)
1155    notes.push(`${money(t.unattributedUsd)} came from sessions with no subscription record; not counted here.`)
1156  if (t && t.unpricedRequests > 0)
1157    notes.push(`${t.unpricedRequests} requests to unpriced models (${t.unpricedModels.join(', ')}); not counted here.`)
1158  return notes
1159}
1160
1161/** Spending in a range: `range` is the helper's `--report` or `--report-local` argument pair. */
1162export async function spendReport(host: Host, range: readonly string[]): Promise<SpendReport | { error: string }> {
1163  const { out, error } = await runHelper<ReportOutput>(host, range, 180_000)
1164  if (!out) return { error: error ?? 'no report' }
1165  const notes = notesOf(out)
1166  if (out.transcriptsBeginLabel)
1167    notes.push(`Transcripts on this machine begin ${out.transcriptsBeginLabel}; earlier spending is not included.`)
1168  return {
1169    type: 'report',
1170    fromLabel: out.fromLabel,
1171    toLabel: out.toLabel,
1172    usedUsd: out.usd,
1173    requests: out.requests,
1174    byDay: out.byDay,
1175    byModel: Object.entries(out.byModel)
1176      .map(([model, spend]) => ({ model, ...spend }))
1177      .sort((a, b) => b.usd - a.usd),
1178    notes,
1179  }
1180}
1181
1182/** What this session has seen of other sessions and of its own readings. */
1183export const diagnosticsOf = (): Readonly<Diagnostics> => diagnostics
1184
1185type CheckSummary = { sessions: number; medianRatio: number | null; lowRatio: number | null; highRatio: number | null; error?: string }
1186
1187const NOT_RECORDED: Record<'unpriced' | 'unattributed', string> = {
1188  unpriced: 'too many of its requests go to unpriced models (see Prices)',
1189  unattributed: 'the subscription is a guess (see Subscription)',
1190}
1191
1192const titles = (list: readonly string[]) => list.join(' and ')
1193
1194function subscriptionItem(orgSource: OrgSource | null | undefined, hasOrg: boolean): CheckItem {
1195  const label = 'Subscription'
1196  if (orgSource === 'most recent')
1197    return {
1198      label,
1199      state: 'fail',
1200      text: 'Only guessed, from the most recently used one, so no readings are recorded. Sign in to Claude Code (/login).',
hooks/probe.ts 20 lines
1/* The check message: a real turn sent from the first-reading card, only when the person
2   presses its button, since only a main-conversation reply brings a usage reading in a
3   headless session. Pure: register.tsx sends it and keeps the in-flight flag. */
4
5import type { WaitingReport } from '../types'
6
7/* Says what it is in the transcript, and keeps the turn as short as the session's model
8   allows. Carries nothing from the session. */
9export const CHECK_PROMPT =
10  'usage-dollars check: this message only fetches a usage reading. Reply with the single word OK. Do not use any tools.'
11
12export const CHECK_LABEL = 'Send a short check message (uses one turn)'
13
14/** The first-reading card for `command`: a subscription with no check in flight may send
15    one; a sign-in without a subscription never gets a reading to wait for. */
16export function waitingReport(command: string, subscription: string, isCheckInFlight: boolean): WaitingReport {
17  if (subscription === 'none') return { type: 'waiting', command, canSend: false, isUnsubscribed: true }
18  return { type: 'waiting', command, canSend: !isCheckInFlight }
19}
20
hooks/estimate.ts 545 lines
1/* Estimates a rate-limit window's allowance in dollars from readings of (used dollars,
2   reported percent) and gives a 90% range.
3
4   Model, in natural logs. A is the dollars counted when the window reaches 100%, so the
5   window runs at D = A / 100 dollars per percent. Between windows log A ~ N(mu, tau²).
6   Within a window the cumulative rate U(s) / s read at share s differs from D with
7   variance omega² · (1/s − 1/100): an average of s one-percent steps against the average
8   of all 100, which vanishes as s → 100.
9
10   A percent p reported at resolution r means the true share lies in an interval set by
11   how the source rounds: [p − r/2, p + r/2) when it rounds, [p, p + r) when it truncates,
12   and their union while that is not known. The newest level gives the evidence: where the
13   level below it was also read, the tick was crossed between the two readings, at the
14   lower edge of p's interval; otherwise anywhere in p's interval. Past windows give a
15   prior on log A that the evidence is combined with by precision, unless the two
16   contradict each other. tau and omega start from assumed values and are shrunk toward
17   what closed windows show. */
18
19import type { Confidence } from '../types'
20
21/* minSlack and maxSlack: dollars of other sessions' requests close to that side's
22   reading, which its percent may not include yet. minX and maxX: that side's dollars per
23   feature, indexed by the window's features; a missing trailing index means 0. */
24export type Bucket = {
25  minUsd: number
26  minAt: number
27  maxUsd: number
28  maxAt: number
29  minSlack?: number
30  maxSlack?: number
31  minX?: number[]
32  maxX?: number[]
33}
34
35/* pricesId: the price table the dollars were computed with. features: the feature keys
36   of the buckets' minX and maxX, append-only. */
37export type WindowReadings = { kind: string; resetsAt: string; byPct: Record<string, Bucket>; pricesId?: string; features?: string[] }
38
39export type RangeEstimate = { value: number; low: number; high: number }
40
41export type Rounding = 'round' | 'truncate' | 'union'
42
43/** A past allowance in logs: a closed window's, at its reset, or a rejection's, at its time. */
44export type PastPoint = { logA: number; variance: number; at: number }
45
46/** A rate-limit rejection: the window was exactly full at `at`, with `usd` counted. */
47export type Rejection = { kind: string; resetsAt: string; at: string; usd: number }
48
49/** log A from one window's newest level `pct`, read at share `share`. shift: an error of
50    up to that much either way, not random, from not knowing the rounding rule.
51    crossingUsd: the dollars at the tick into that level, when it was seen. */
52export type Evidence = { logA: number; variance: number; shift: number; share: number; pct: number; crossingUsd?: number }
53
54/** The within-window spread omega, the age weight of the closed-window crossings behind
55    it, and the number of closed windows that gave a crossing. It counts as measured from
56    two windows on. */
57export type Spread = { omega: number; weight: number; windows: number; isAssumed: boolean }
58
59/** An allowance in logs: mean, variance, a non-random error of up to `shift` either way,
60    and the degrees of freedom of the interval. */
61export type LogEstimate = { mean: number; variance: number; shift: number; df: number }
62
63export type Estimate = {
64  allowance: RangeEstimate
65  /** The log allowance behind `allowance`, before any extra variance. */
66  log: LogEstimate
67  left: RangeEstimate
68  readings: number
69  pastWindows: number
70  pastWeight: number
71  /** The between-window spread is the assumed one: under 3 effective past windows. */
72  isSpreadAssumed: boolean
73  /** No closed window has measured the within-window spread yet. */
74  isWithinSpreadAssumed: boolean
75  isPriorContradicted: boolean
76  /** No level above 0 read in this window: the estimate is the prior alone. */
77  isPriorOnly: boolean
78  confidence: Confidence
79  nextTick?: RangeEstimate
80}
81
82export type EstimateOptions = {
83  resolution: number
84  rounding: Rounding
85  past: readonly PastPoint[]
86  kind: string
87  now: number
88  livePercent?: number
89  spread?: Spread
90  /** Added to the log variance before the interval; 0 by default. */
91  extraVariance?: number
92}
93
94const NU0 = 4
95const TAU0 = 0.1
96const OMEGA0 = 0.5
97const REJECTION_SD = 0.02
98const MIN_PAST_SHARE = 10
99const MIN_CROSSING_SHARE = 5
100const MIN_SPREAD_WINDOWS = 2
101export const MIN_ROUNDING_WINDOWS = 5
102const MINUTE_MS = 60 * 1000
103const HOUR_MS = 60 * MINUTE_MS
104const FIVE_HOUR_HALF_LIFE_MS = 24 * HOUR_MS
105const SEVEN_DAY_HALF_LIFE_MS = 14 * 24 * HOUR_MS
106
107export const ASSUMED_SPREAD: Spread = { omega: OMEGA0, weight: 0, windows: 0, isAssumed: true }
108
109export function resolutionOf(all: readonly WindowReadings[]) {
110  const isFine = all.some(w => Object.keys(w.byPct).some(p => !Number.isInteger(Number(p))))
111  return isFine ? 0.1 : 1
112}
113
114const X_UNIT = 1e6
115
116/* The window's features with x's new keys appended in sorted order. */
117function featuresWith(features: readonly string[] | undefined, x: Record<string, number>) {
118  const known = features ?? []
119  const added = Object.keys(x)
120    .filter(f => !known.includes(f))
121    .sort()
122  return [...known, ...added]
123}
124
125/* Within a window dollars only grow, so a tie keeps the later time: the most recent
126   reading that still supports the bound. Each side keeps its reading's slack, and its
127   per-feature dollars x, rounded to 1e-6, when the reading has them. */
128export function record(w: WindowReadings, pct: number, usd: number, at: number, slack = 0, x?: Record<string, number>): WindowReadings {
129  const key = String(pct)
130  const was = w.byPct[key]
131  const features = x ? featuresWith(w.features, x) : undefined
132  const xs = x && features ? features.map(f => Math.round((x[f] ?? 0) * X_UNIT) / X_UNIT) : undefined
133  let bucket: Bucket = { minUsd: usd, minAt: at, maxUsd: usd, maxAt: at, minSlack: slack, maxSlack: slack }
134  let minX = xs
135  let maxX = xs
136  if (was) {
137    const isMin = usd < was.minUsd || (usd === was.minUsd && at >= was.minAt)
138    const isMax = usd > was.maxUsd || (usd === was.maxUsd && at >= was.maxAt)
139    bucket = {
140      minUsd: isMin ? usd : was.minUsd,
141      minAt: isMin ? at : was.minAt,
142      maxUsd: isMax ? usd : was.maxUsd,
143      maxAt: isMax ? at : was.maxAt,
144      minSlack: isMin ? slack : (was.minSlack ?? 0),
145      maxSlack: isMax ? slack : (was.maxSlack ?? 0),
146    }
147    minX = isMin ? xs : was.minX
148    maxX = isMax ? xs : was.maxX
149  }
150  if (minX) bucket.minX = minX
151  if (maxX) bucket.maxX = maxX
152  const byPct = { ...w.byPct, [key]: bucket }
153  return features ? { ...w, features, byPct } : { ...w, byPct }
154}
155
156/* The window as seen from a regime that started at startedAt: readings taken before it
157   are dropped. A straddling bucket keeps only its max side. */
158export function regimeView(w: WindowReadings, startedAt: number): WindowReadings {
159  const byPct: Record<string, Bucket> = {}
160  for (const [key, b] of Object.entries(w.byPct)) {
161    if (b.maxAt < startedAt) continue
162    byPct[key] =
163      b.minAt < startedAt
164        ? {
165            minUsd: b.maxUsd,
166            minAt: b.maxAt,
167            maxUsd: b.maxUsd,
168            maxAt: b.maxAt,
169            minSlack: b.maxSlack,
170            maxSlack: b.maxSlack,
171            ...(b.maxX ? { minX: b.maxX, maxX: b.maxX } : {}),
172          }
173        : b
174  }
175  return { ...w, byPct }
176}
177
178function shareOf(pct: number, resolution: number, rounding: Rounding) {
179  if (rounding === 'round') return { lower: pct - resolution / 2, upper: pct + resolution / 2 }
180  if (rounding === 'truncate') return { lower: pct, upper: pct + resolution }
181  return { lower: pct - resolution / 2, upper: pct + resolution }
182}
183
184/* Where the share crosses into level p: one point, or for the union one of the two rules'
185   points, taken at their geometric center with `shift`, half the log distance between
186   them, as an error that is either rule's and not random. */
187export function crossingShareOf(pct: number, resolution: number, rounding: Rounding) {
188  if (rounding === 'round') return { s: pct - resolution / 2, variance: 0, shift: 0 }
189  if (rounding === 'truncate') return { s: pct, variance: 0, shift: 0 }
190  const lower = pct - resolution / 2
191  return lower > 0
192    ? { s: Math.sqrt(lower * pct), variance: 0, shift: Math.log(pct / lower) / 2 }
193    : { s: pct - resolution / 4, variance: (resolution / 4) ** 2, shift: 0 }
194}
195
196/* A share uniform over a level's interval, never below 0. */
197function levelShareOf(pct: number, resolution: number, rounding: Rounding) {
198  const { lower, upper } = shareOf(pct, resolution, rounding)
199  const from = Math.max(0, lower)
200  return { s: (from + upper) / 2, variance: (upper - from) ** 2 / 12, shift: 0 }
201}
202
203export function bounds(w: WindowReadings, resolution: number, rounding: Rounding) {
204  let low = 0
205  let high = Infinity
206  for (const [key, bucket] of Object.entries(w.byPct)) {
207    const { lower, upper } = shareOf(Number(key), resolution, rounding)
208    low = Math.max(low, bucket.maxUsd / (upper / 100))
209    if (lower > 0) high = Math.min(high, bucket.minUsd / (lower / 100))
210  }
211  return { low, high }
212}
213
214export type Level = { pct: number; bucket: Bucket }
215
216export const levelsOf = (w: WindowReadings): Level[] => Object.entries(w.byPct).map(([key, bucket]) => ({ pct: Number(key), bucket }))
217
218/* The dollars at which the share crossed into `level`, when the level one step below was
219   read before it: the midpoint of the gap less half the slack, uniform over the gap plus
220   the slack. Keys of fine levels are not exact, hence the tolerance. */
221export function crossingOf(levels: readonly Level[], level: Level, resolution: number) {
222  const lower = levels.find(l => Math.abs(l.pct - (level.pct - resolution)) < resolution / 1000)
223  if (!lower) return undefined
224  const gap = level.bucket.minUsd - lower.bucket.maxUsd
225  if (gap < 0) return undefined
226  const slack = Math.max(level.bucket.minSlack ?? 0, lower.bucket.maxSlack ?? 0)
227  return { usd: (lower.bucket.maxUsd + level.bucket.minUsd) / 2 - slack / 2, width: gap + slack }
228}
229
230/* Dollars uniform over usdWidth, the share at s with the given variance and shift. */
231function evidenceAt(pct: number, usd: number, usdWidth: number, share: { s: number; variance: number; shift: number }, omega: number) {
232  const { s } = share
233  if (!(s > 0) || !(usd > 0)) return undefined
234  const variance = share.variance / (s * s) + usdWidth ** 2 / (12 * usd * usd) + omega ** 2 * Math.max(0, 1 / s - 1 / 100)
235  return { logA: Math.log((100 * usd) / s), variance, shift: share.shift, share: s, pct }
236}
237
238/** log A and its variance from the newest level of a window, the level with the latest
239    reading. A level at or above 100 is used only through its crossing, since spending
240    can continue past the limit; without one the next newest level is used. Level 0 is
241    never used, since it bounds the share only from above. */
242export function evidenceOf(w: WindowReadings, resolution: number, rounding: Rounding, omega = 0): Evidence | undefined {
243  const levels = levelsOf(w)
244  const newest = [...levels].sort((a, b) => b.bucket.maxAt - a.bucket.maxAt)
245  for (const level of newest) {
246    const crossing = crossingOf(levels, level, resolution)
247    if (crossing) {
248      const e = evidenceAt(level.pct, crossing.usd, crossing.width, crossingShareOf(level.pct, resolution, rounding), omega)
249      return e && { ...e, crossingUsd: crossing.usd }
250    }
251    if (level.pct >= 100 || level.pct <= 0) continue
252    const slack = level.bucket.maxSlack ?? 0
253    return evidenceAt(level.pct, level.bucket.maxUsd - slack / 2, slack, levelShareOf(level.pct, resolution, rounding), omega)
254  }
255  return undefined
256}
257
258/** A closed window as a past allowance: its final evidence, with the within-window term
259    of where it stopped, once it reached 10%. */
260export function pastOf(w: WindowReadings, resolution: number, rounding: Rounding, omega: number): PastPoint | undefined {
261  const e = evidenceOf(w, resolution, rounding, omega)
262  if (!e || e.pct < MIN_PAST_SHARE) return undefined
263  return { logA: e.logA, variance: e.variance + e.shift ** 2, at: Date.parse(w.resetsAt) }
264}
265
266const minuteOf = (iso: string) => Math.round(Date.parse(iso) / MINUTE_MS)
267
268/** One past point per window of `kind`, keyed by its reset to the minute: a rejection
269    wins over the window's own readings, the earliest rejection over later ones. */
270export function pastPoints(
271  closed: readonly WindowReadings[],
272  rejections: readonly Rejection[],
273  kind: string,
274  resolution: number,
275  rounding: Rounding,
276  omega: number,
277): PastPoint[] {
278  const byWindow = new Map<number, PastPoint>()
279  for (const w of closed) {
280    if (w.kind !== kind) continue
281    const p = pastOf(w, resolution, rounding, omega)
282    if (p) byWindow.set(minuteOf(w.resetsAt), p)
283  }
284  const rejected = new Map<number, PastPoint>()
285  for (const r of rejections) {
286    if (r.kind !== kind || !(r.usd > 0)) continue
287    const key = minuteOf(r.resetsAt)
288    const at = Date.parse(r.at)
289    const was = rejected.get(key)
290    if (!was || at < was.at) rejected.set(key, { logA: Math.log(r.usd), variance: REJECTION_SD ** 2, at })
291  }
292  for (const [key, p] of rejected) byWindow.set(key, p)
293  return [...byWindow.values()]
294}
295
296export function weightOf(kind: string, ageMs: number) {
297  const halfLife = kind === 'seven_day' ? SEVEN_DAY_HALF_LIFE_MS : FIVE_HOUR_HALF_LIFE_MS
298  return 0.5 ** (Math.max(0, ageMs) / halfLife)
299}
300
301/** The weighted mean of past log allowances; tau², their spread beyond their own
302    measurement variance, shrunk toward the assumed TAU0 with NU0 degrees of freedom; and
303    the predictive variance of the next window's log allowance. A point weighs by its age
304    and by its information q = TAU0² / (TAU0² + v): one whose own variance v is large
305    beside the assumed tau² says little about the allowance or about tau. */
306export function prior(past: readonly PastPoint[], kind: string, now: number) {
307  const points = past.map(p => {
308    const q = TAU0 ** 2 / (TAU0 ** 2 + p.variance)
309    return { x: p.logA, v: p.variance, q, w: weightOf(kind, now - p.at) * q }
310  })
311  let sw = 0
312  let sw2 = 0
313  let swx = 0
314  let swq2 = 0
315  for (const p of points) {
316    sw += p.w
317    sw2 += p.w * p.w
318    swx += p.w * p.x
319    swq2 += p.w * p.q * p.q
320  }
321  const nEff = sw2 > 0 ? (sw * sw) / sw2 : 0
322  const mean = sw > 0 ? swx / sw : 0
323  let raw = 0
324  const denominator = sw > 0 ? sw - sw2 / sw : 0
325  if (denominator > 0) {
326    let ss = 0
327    let noise = 0
328    for (const p of points) {
329      ss += p.w * (p.x - mean) ** 2
330      noise += p.w * p.v * (1 - p.w / sw)
331    }
332    raw = (ss - noise) / denominator
333  }
334  const extra = sw > 0 ? Math.max(0, nEff - 1) * (swq2 / sw) : 0
335  const tau2 = (NU0 * TAU0 ** 2 + extra * Math.max(0, raw)) / (NU0 + extra)
336  let spread = 0
337  for (const p of points) spread += p.w * p.w * (tau2 + p.v)
338  const variance = sw > 0 ? tau2 + spread / (sw * sw) : Infinity
339  return { nEff, mean, tau2, variance, df: NU0 + extra, isUsable: nEff >= 1, isSpreadAssumed: 1 + extra < 3, points: past.length }
340}
341
342/** omega from closed windows that reached 10%: each tick crossed at share s in
343    [5, sEnd/2] gives e = log(U/s) − log(U_end/sEnd), with E[e²] = omega² · (1/s − 1/sEnd).
344    Age-weighted, and shrunk toward OMEGA0 with the weight of NU0 crossings. */
345export function calibrateOmega(
346  closed: readonly WindowReadings[],
347  kind: string,
348  now: number,
349  resolution: number,
350  rounding: Rounding,
351): Spread {
352  let sum = 0
353  let weight = 0
354  let windows = 0
355  for (const w of closed) {
356    const end = evidenceOf(w, resolution, rounding)
357    if (!end || end.pct < MIN_PAST_SHARE) continue
358    const age = weightOf(kind, now - Date.parse(w.resetsAt))
359    const levels = levelsOf(w)
360    let isCounted = false
361    for (const level of levels) {
362      const crossing = crossingOf(levels, level, resolution)
363      if (!crossing || !(crossing.usd > 0)) continue
364      const { s } = crossingShareOf(level.pct, resolution, rounding)
365      if (s < MIN_CROSSING_SHARE || s > end.share / 2) continue
366      const e = Math.log(crossing.usd / s) - (end.logA - Math.log(100))
367      sum += (age * e * e) / (1 / s - 1 / end.share)
368      weight += age
369      isCounted = true
370    }
371    if (isCounted) windows++
372  }
373  return { omega: Math.sqrt((NU0 * OMEGA0 ** 2 + sum) / (NU0 + weight)), weight, windows, isAssumed: windows < MIN_SPREAD_WINDOWS }
374}
375
376/** Student's t quantile by the Cornish-Fisher expansion in 1/df to third order. */
377export function tQuantile(p: number, df: number) {
378  const z = normalQuantile(p)
379  const z3 = z ** 3
380  const z5 = z ** 5
381  const z7 = z ** 7
382  const g1 = (z3 + z) / 4
383  const g2 = (5 * z5 + 16 * z3 + 3 * z) / 96
384  const g3 = (3 * z7 + 19 * z5 + 17 * z3 - 15 * z) / 384
385  return z + g1 / df + g2 / df ** 2 + g3 / df ** 3
386}
387
388/* Acklam's rational approximation; relative error under 1.2e-9. */
389function normalQuantile(p: number) {
390  const a = [-39.69683028665376, 220.9460984245205, -275.9285104469687, 138.357751867269, -30.66479806614716, 2.506628277459239]
391  const b = [-54.47609879822406, 161.5858368580409, -155.6989798598866, 66.80131188771972, -13.28068155288572]
392  const c = [-0.007784894002430293, -0.3223964580411365, -2.400758277161838, -2.549732539343734, 4.374664141464968, 2.938163982698783]
393  const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416]
394  const tail = (q: number) =>
395    (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
396  if (p < 0.02425) return tail(Math.sqrt(-2 * Math.log(p)))
397  if (p > 1 - 0.02425) return -tail(Math.sqrt(-2 * Math.log(1 - p)))
398  const q = p - 0.5
399  const r = q * q
400  return (
401    ((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) /
402    (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)
403  )
404}
405
406/* Which rounding the API uses, from closed windows of every subscription: a mode
407   contradicted in at most 10% of at least 5 windows while the other is contradicted in at
408   least half of them. The caller leaves out windows that straddle a regime start; a
409   window that is inconsistent even under the union is ignored here. */
410export function roundingEvidence(windows: readonly WindowReadings[], resolution: number) {
411  /* A reading exactly on a boundary makes low equal high, up to floating-point noise. */
412  const isEmpty = (b: { low: number; high: number }) => b.low > b.high * (1 + 1e-9)
413  let considered = 0
414  let roundConflicts = 0
415  let truncateConflicts = 0
416  for (const w of windows) {
417    if (Object.keys(w.byPct).length < 3) continue
418    const union = bounds(w, resolution, 'union')
419    if (isEmpty(union)) continue
420    considered++
421    const round = bounds(w, resolution, 'round')
422    const truncate = bounds(w, resolution, 'truncate')
423    if (isEmpty(round)) roundConflicts++
424    if (isEmpty(truncate)) truncateConflicts++
425  }
426  let rule: Rounding = 'union'
427  if (considered >= MIN_ROUNDING_WINDOWS) {
428    if (roundConflicts <= 0.1 * considered && truncateConflicts >= 0.5 * considered) rule = 'round'
429    else if (truncateConflicts <= 0.1 * considered && roundConflicts >= 0.5 * considered) rule = 'truncate'
430  }
431  return { considered, roundConflicts, truncateConflicts, rule }
432}
433
434export function inferRounding(windows: readonly WindowReadings[], resolution: number): Rounding {
435  return roundingEvidence(windows, resolution).rule
436}
437
438/** What has been measured for one window: the current window's levels and ticks, and
439    whether each of the within-window spread, the between-window spread and the rounding
440    rule rests on closed windows rather than on an assumption. */
441export function calibrationOf(input: {
442  current?: WindowReadings
443  resolution: number
444  spread: Spread
445  prior: ReturnType<typeof prior>
446  rounding: ReturnType<typeof roundingEvidence>
447}) {
448  const levels = input.current ? levelsOf(input.current) : []
449  const ticks = levels.filter(level => crossingOf(levels, level, input.resolution) !== undefined).length
450  const isWithinMeasured = !input.spread.isAssumed
451  const isBetweenMeasured = !input.prior.isSpreadAssumed
452  const isRoundingKnown = input.rounding.rule !== 'union'
453  const measured = [isWithinMeasured, isBetweenMeasured, isRoundingKnown].filter(Boolean).length
454  return {
455    levels: levels.length,
456    ticks,
457    closedForWithin: input.spread.windows,
458    isWithinMeasured,
459    pastPoints: input.prior.points,
460    pastWeight: Math.round(input.prior.nEff * 10) / 10,
461    isBetweenMeasured,
462    closedForRounding: input.rounding.considered,
463    isRoundingKnown,
464    measured,
465    isCalibrated: measured === 3,
466  }
467}
468
469export type Calibration = ReturnType<typeof calibrationOf>
470
471export function confidenceOf(r: RangeEstimate): Confidence {
472  const h = Math.sqrt(r.high / r.low) - 1
473  return h <= 0.1 ? 'good' : h <= 0.3 ? 'fair' : 'rough'
474}
475
476/* The spend until the reported percent next moves: one tick's dollars less what was spent
477   since the crossing into the current level, or without a crossing, up to one tick. */
478function nextTickOf(a: RangeEstimate, usedUsd: number, resolution: number, crossingUsd: number | undefined) {
479  const tick = (allowance: number) => (allowance / 100) * resolution
480  if (crossingUsd === undefined) return { value: tick(a.value) / 2, low: 0, high: tick(a.high) }
481  const at = (allowance: number) => Math.max(0, tick(allowance) - (usedUsd - crossingUsd))
482  return { value: at(a.value), low: at(a.low), high: at(a.high) }
483}
484
485/** The 90% range of exp(mean), with extraVariance added to the log variance, and no
486    value below floor. The union of the intervals either rounding rule gives. */
487export function rangeOf(log: LogEstimate, extraVariance: number, floor: number): RangeEstimate {
488  const { mean: m, shift, df } = log
489  const h = tQuantile(0.95, df) * Math.sqrt(log.variance + extraVariance) + shift
490  return {
491    value: Math.max(floor, Math.exp(m)),
492    low: Math.max(floor, Math.exp(m - h)),
493    high: Math.max(floor, Math.exp(m + h)),
494  }
495}
496
497export function estimate(w: WindowReadings, usedUsd: number, options: EstimateOptions): Estimate | undefined {
498  const { resolution, rounding, past, kind, now, livePercent } = options
499  const spread = options.spread ?? ASSUMED_SPREAD
500  const ev = evidenceOf(w, resolution, rounding, spread.omega)
501  const p = prior(past, kind, now)
502  const isAtLimit = livePercent !== undefined && livePercent >= 100
503  /* Only level 0 read: the prior alone stands in for the evidence. */
504  const isUnticked = Object.keys(w.byPct).every(key => Number(key) <= 0)
505  if (!ev && !(isUnticked && p.isUsable && !isAtLimit)) return undefined
506
507  let m = ev ? ev.logA : p.mean
508  let v = ev ? ev.variance : p.variance
509  let shift = ev ? ev.shift : 0
510  let df = ev ? NU0 + spread.weight : p.df
511  let isPriorContradicted = false
512  if (ev && p.isUsable && !isAtLimit) {
513    const z = Math.max(0, Math.abs(ev.logA - p.mean) - ev.shift) / Math.sqrt(ev.variance + p.variance)
514    isPriorContradicted = z > tQuantile(0.995, p.df)
515    if (!isPriorContradicted) {
516      v = 1 / (1 / p.variance + 1 / ev.variance)
517      m = v * (p.mean / p.variance + ev.logA / ev.variance)
518      shift = (ev.shift * v) / ev.variance
519      df = p.df
520    }
521  }
522  const log = { mean: m, variance: v, shift, df }
523  const floor = isAtLimit ? 0 : usedUsd
524  const allowance = rangeOf(log, options.extraVariance ?? 0, floor)
525  const left = isAtLimit
526    ? { value: 0, low: 0, high: 0 }
527    : { value: allowance.value - usedUsd, low: allowance.low - usedUsd, high: allowance.high - usedUsd }
528  const isLive = livePercent !== undefined && !isAtLimit
529  const isSameLevel = ev !== undefined && livePercent !== undefined && Math.abs(ev.pct - livePercent) < resolution / 1000
530  return {
531    allowance,
532    log,
533    left,
534    readings: Object.keys(w.byPct).length,
535    pastWindows: p.points,
536    pastWeight: Math.round(p.nEff * 10) / 10,
537    isSpreadAssumed: p.isSpreadAssumed,
538    isWithinSpreadAssumed: spread.isAssumed,
539    isPriorContradicted,
540    isPriorOnly: !ev,
541    confidence: confidenceOf(allowance),
542    nextTick: isLive ? nextTickOf(allowance, usedUsd, resolution, isSameLevel ? ev?.crossingUsd : undefined) : undefined,
543  }
544}
545
hooks/meter.ts 1011 lines
1/* Meter weights: whether the subscription meter counts each model's API dollars at the
2   API price ratio, fitted on closed 5-hour windows.
3
4   Per feature f (one priced token class of one model, or web searches) a window records
5   its dollars X_f at both sides of every bucket. The meter is taken to count weighted
6   dollars E = Σ w_f · X_f, with w_f = exp(θ_g) for f's group g and θ = 0 outside the free
7   groups. Between two tick crossings at least SEG_MIN_SHARE points apart, a segment's
8   y = log(w · ΔX / Δs) is its window's log dollars per percent, with variance ω² / Δs plus
9   the crossings' own gaps. θ and ω are fitted with each window's level profiled out and a
10   normal prior on θ; a blocked jackknife over windows gives θ's covariance. Models are
11   chosen by blocked cross-validation, and the weekly windows test whether the 5-hour
12   weights carry over to the week. */
13
14import type { Bucket, Estimate, PastPoint, RangeEstimate, Rejection, Rounding, Spread, WindowReadings } from './estimate.ts'
15import { calibrateOmega, crossingOf, crossingShareOf, estimate, levelsOf, pastPoints, rangeOf } from './estimate.ts'
16
17/* Segments and the outlier rule (S3). */
18const SEG_MIN_SHARE = 2
19const OUTLIER_RATE = 0.1
20/* Estimation (S4). */
21const SIGMA_THETA = 0.5
22const NM_TOLERANCE = 1e-6
23const NM_MAX_ITERATIONS = 500
24const OMEGA_START = 0.5
25const MIN_GROUP_SHARE = 0.02
26const MIN_WINDOWS = 4
27const MIN_SEGMENTS = 2
28/* Uncertainty and selection (S5, S6, S6b). */
29const JACKKNIFE_BLOCKS = 20
30const CV_FOLDS = 10
31const SELECT_MIN_DELTA = 2
32const SELECT_SE_MULTIPLE = 2
33const SELECT_MIN_Z = 2
34const TRANSFER_MIN_DAYS = 5
35const GRADIENT_STEP = 0.01
36const WEEKLY_FIT_MIN_WEEKS = 4
37/* Feature-complete windows (S2). */
38const FEATURE_TOLERANCE_RELATIVE = 1e-6
39const FEATURE_TOLERANCE_ABSOLUTE = 2e-4
40/* Nelder-Mead's initial step from the fixed start and from a warm start, and the simplex
41   size within which it stops once the objective has converged. */
42const NM_STEP = 0.25
43const NM_WARM_STEP = 0.05
44const NM_X_TOLERANCE = 1e-4
45/* ω is searched within these bounds; noise-free data would drive it to 0. */
46const OMEGA_MIN = 1e-4
47const OMEGA_MAX = 10
48/* Shares of fine levels are not exact. */
49const SHARE_EPSILON = 1e-9
50const MINUTE_MS = 60 * 1000
51const DAY_MS = 24 * 60 * MINUTE_MS
52
53const MODELS = ['M0', 'M1', 'M2'] as const
54
55export type Model = 'M0' | 'M1' | 'M2'
56
57/** The groups of one model. `reference` has θ = 0; `free` are the groups with a θ, in a
58    fixed order (sorted by key). Any group not in `free` (the reference, merged groups,
59    `web`, and groups never seen) has weight 1. */
60export type Grouping = { model: Model; reference: string; free: string[] }
61
62/** Grouping plus θ (aligned with `free`), the jackknife covariance Σ_J (free × free), and the
63    jackknife degrees of freedom K − 1. JSON-serializable. */
64export type Weights = Grouping & { theta: number[]; cov: number[][]; df: number }
65
66export const UNIT_WEIGHTS: Weights = { model: 'M0', reference: 'all', free: [], theta: [], cov: [], df: 1 }
67
68export type Segment = {
69  /** ΔX by feature. */
70  dX: Record<string, number>
71  /** Δs, percentage points. */
72  ds: number
73  /** Per-feature gap at the start crossing: level min side less lower max side. */
74  gapA: Record<string, number>
75  /** The same at the end crossing. */
76  gapB: Record<string, number>
77  /** Time of the end crossing (ms). */
78  at: number
79  /** The outlier rule of S3, evaluated at θ = 0. */
80  isExcluded: boolean
81}
82
83export type FitOptions = {
84  resolution: number
85  rounding: Rounding
86  /** Fixed grouping: skips both pruning steps. */
87  groups?: Grouping
88  /** Default true. */
89  isJackknifed?: boolean
90}
91
92export type FitResult = {
93  model: Model
94  groups: Grouping
95  /** Aligned with groups.free. */
96  theta: number[]
97  omega: number
98  /** Σ_J; zeros when not jackknifed. */
99  cov: number[][]
100  /** sqrt(diag Σ_J). */
101  se: number[]
102  /** K − 1 of the jackknife. */
103  df: number
104  /** I_g of S4, aligned with groups.free. */
105  information: number[]
106  /** Windows that entered the fit. */
107  windows: number
108  /** Non-excluded segments used. */
109  segments: number
110  excludedSegments: number
111  weights: Weights
112}
113
114export type Comparison = { from: Model; to: Model; delta: number; se: number; folds: number; isSelected: boolean }
115
116export type Selection = {
117  selected: Model
118  /** Of the selected model; UNIT_WEIGHTS for M0. */
119  weights: Weights
120  /** The rule it was run under. */
121  rounding: Rounding
122  fits: Partial<Record<Model, FitResult>>
123  /** M1 against M0, then M2 against the selected model. */
124  comparisons: Comparison[]
125  /** Reasons: 'not-feature-complete', 'too-few-segments', 'not-five-hour'. */
126  windows: { used: number; excluded: Record<string, number> }
127  segments: number
128  excludedSegments: number
129}
130
131export type Transfer = {
132  /** days ≥ TRANSFER_MIN_DAYS. */
133  isChecked: boolean
134  /** isChecked and delta < −max(2, 2 · se). */
135  isRejected: boolean
136  delta: number
137  se: number
138  days: number
139  /** Qualifying weekly windows. */
140  weeks: number
141  /** ω_week fitted with θ held fixed, per candidate. */
142  omega: { selected: number; M0: number }
143  /** Descriptive weekly-only M1 fit, from WEEKLY_FIT_MIN_WEEKS weeks. */
144  weeklyFit?: FitResult
145}
146
147export type StoredFit = { weights: Weights; omega: number; omegaM0: number }
148
149export type ProspectiveRecord = { resetsAt: string; kind: string; d: number }
150
151export type WeightedEstimateInput = {
152  kind: string
153  /** Closed windows of this kind and regime, already regimeView'd. */
154  closed: readonly WindowReadings[]
155  /** Already regimeView'd. */
156  current: WindowReadings | undefined
157  /** U of the current window (the tally's usd). */
158  usedUsd: number
159  /** The current tally's byFeature. */
160  usedX: Record<string, number>
161  /** The last7d tally's byFeature, for w̄ when U = 0. */
162  fallbackX?: Record<string, number>
163  weights: Weights
164  rejections: readonly Rejection[]
165  resolution: number
166  rounding: Rounding
167  now: number
168  livePercent?: number
169  /** Past points before it are dropped. */
170  startedAt: number
171}
172
173export type WeightedEstimate = {
174  /** In weighted dollars E, with extraVariance applied. */
175  estimate?: Estimate
176  /** In U dollars at the window's mix: E-values / w̄. */
177  display?: { allowance: RangeEstimate; left: RangeEstimate; nextTick?: RangeEstimate }
178  usedE: number
179  /** w̄_window. */
180  mixWeight: number
181  /** ∇ᵀ Σ_J ∇ added to the log variance. */
182  extraVariance: number
183  spread: Spread
184  past: PastPoint[]
185  /** Closed windows that could not be transformed. */
186  excludedClosed: number
187}
188
189const sumOf = (xs: readonly number[]) => xs.reduce((a, b) => a + b, 0)
190
191const zerosOf = (n: number) => new Array<number>(n).fill(0)
192
193const zeroMatrixOf = (n: number) => Array.from({ length: n }, () => zerosOf(n))
194
195const minuteOf = (iso: string) => Math.round(Date.parse(iso) / MINUTE_MS)
196
197/* Σ_i x_i · w_i over x's length; a missing trailing index of x is 0. */
198function dotOf(w: readonly number[], x: readonly number[] | undefined) {
199  let s = 0
200  if (x) for (let i = 0; i < x.length; i++) s += w[i] * x[i]
201  return s
202}
203
204const quadraticOf = (g: readonly number[], m: readonly (readonly number[])[]) => {
205  let s = 0
206  for (let a = 0; a < g.length; a++) for (let b = 0; b < g.length; b++) s += g[a] * (m[a]?.[b] ?? 0) * g[b]
207  return s
208}
209
210function sampleVarianceOf(xs: readonly number[]) {
211  if (xs.length < 2) return 0
212  const mean = sumOf(xs) / xs.length
213  return xs.reduce((s, x) => s + (x - mean) ** 2, 0) / (xs.length - 1)
214}
215
216function medianOf(xs: readonly number[]) {
217  const sorted = [...xs].sort((a, b) => a - b)
218  const middle = Math.floor(sorted.length / 2)
219  return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
220}
221
222/* priceKey and class of a feature key `<priceKey>[+fast]/<class>`. */
223function partsOf(feature: string) {
224  const slash = feature.lastIndexOf('/')
225  const head = slash < 0 ? feature : feature.slice(0, slash)
226  const cls = slash < 0 ? '' : feature.slice(slash + 1)
227  return { priceKey: head.endsWith('+fast') ? head.slice(0, -'+fast'.length) : head, cls }
228}
229
230/** Natural group of a feature: M0 → 'all'; M1 → priceKey (fast and normal together);
231    M2 → `${priceKey}/read` for class read, `${priceKey}/other` otherwise; `web` → 'web'
232    under every model. */
233export function groupOf(model: Model, feature: string): string {
234  if (feature === 'web') return 'web'
235  if (model === 'M0') return 'all'
236  const { priceKey, cls } = partsOf(feature)
237  if (model === 'M1') return priceKey
238  return `${priceKey}/${cls === 'read' ? 'read' : 'other'}`
239}
240
241/** Reference = group with the largest dollars (ties by key order; never 'web'; in M2 the
242    largest non-read group). Free = every other group except 'web', minus groups holding
243    under MIN_GROUP_SHARE of the total dollars, which merge into the reference. */
244export function groupsOf(model: Model, dollarsByFeature: Record<string, number>): Grouping {
245  if (model === 'M0') return { model, reference: 'all', free: [] }
246  const byGroup = new Map<string, number>()
247  let total = 0
248  for (const [feature, usd] of Object.entries(dollarsByFeature)) {
249    total += usd
250    const g = groupOf(model, feature)
251    if (g !== 'web') byGroup.set(g, (byGroup.get(g) ?? 0) + usd)
252  }
253  const keys = [...byGroup.keys()].sort()
254  const dollarsOf = (g: string) => byGroup.get(g) ?? 0
255  const largestOf = (gs: readonly string[]) => gs.reduce<string | undefined>((best, g) => (best === undefined || dollarsOf(g) > dollarsOf(best) ? g : best), undefined)
256  const nonRead = model === 'M2' ? keys.filter(g => !g.endsWith('/read')) : keys
257  const reference = largestOf(nonRead.length > 0 ? nonRead : keys) ?? 'all'
258  const free = keys.filter(g => g !== reference && total > 0 && dollarsOf(g) >= MIN_GROUP_SHARE * total)
259  return { model, reference, free }
260}
261
262export function weightsOf(groups: Grouping, theta: readonly number[], cov?: number[][], df?: number): Weights {
263  return {
264    model: groups.model,
265    reference: groups.reference,
266    free: [...groups.free],
267    theta: [...theta],
268    cov: cov ?? zeroMatrixOf(groups.free.length),
269    df: df ?? 1,
270  }
271}
272
273/** exp(θ_g) for the feature's group, or 1. */
274export function featureWeight(weights: Weights, feature: string): number {
275  const g = weights.free.indexOf(groupOf(weights.model, feature))
276  return g < 0 ? 1 : Math.exp(weights.theta[g])
277}
278
279/** w̄ = (w · x) / Σ x; 1 when Σ x is not above 0. */
280export function mixWeight(weights: Weights, x: Record<string, number>): number {
281  let sum = 0
282  let weighted = 0
283  for (const [feature, usd] of Object.entries(x)) {
284    sum += usd
285    weighted += featureWeight(weights, feature) * usd
286  }
287  return sum > 0 ? weighted / sum : 1
288}
289
290const isUnit = (weights: Weights) => weights.theta.every(t => t === 0)
291
292const toleranceOf = (usd: number) => Math.max(FEATURE_TOLERANCE_RELATIVE * Math.abs(usd), FEATURE_TOLERANCE_ABSOLUTE)
293
294const isSideComplete = (x: readonly number[] | undefined, usd: number, size: number) =>
295  x !== undefined && x.length <= size && Math.abs(sumOf(x) - usd) <= toleranceOf(usd)
296
297/** Every bucket has minX and maxX, and each array's sum equals its side's dollars within
298    max(1e-6 · usd, 2e-4). */
299export function isFeatureComplete(w: WindowReadings): boolean {
300  const size = w.features?.length ?? 0
301  return Object.values(w.byPct).every(b => isSideComplete(b.minX, b.minUsd, size) && isSideComplete(b.maxX, b.maxUsd, size))
302}
303
304/* The window in weighted dollars, from its features alone. */
305function transformed(w: WindowReadings, weights: Weights): WindowReadings {
306  const wf = (w.features ?? []).map(f => featureWeight(weights, f))
307  const byPct: Record<string, Bucket> = {}
308  for (const [key, b] of Object.entries(w.byPct)) {
309    const minUsd = dotOf(wf, b.minX)
310    const maxUsd = dotOf(wf, b.maxX)
311    const bucket: Bucket = { ...b, minUsd, maxUsd }
312    if (b.minSlack !== undefined) bucket.minSlack = b.minSlack * (b.minUsd > 0 ? minUsd / b.minUsd : 1)
313    if (b.maxSlack !== undefined) bucket.maxSlack = b.maxSlack * (b.maxUsd > 0 ? maxUsd / b.maxUsd : 1)
314    byPct[key] = bucket
315  }
316  return { ...w, byPct }
317}
318
319/** The window in weighted dollars E: minUsd/maxUsd become w · X at that side, slack is
320    scaled by that side's E / U (1 when U = 0). Returns `w` itself when every weight is 1;
321    `undefined` when the window is not feature-complete and some weight is not 1. */
322export function weightedView(w: WindowReadings, weights: Weights): WindowReadings | undefined {
323  if (isUnit(weights)) return w
324  return isFeatureComplete(w) ? transformed(w, weights) : undefined
325}
326
327type Crossing = { s: number; usd: number; x: number[]; gap: number[]; at: number }
328
329const recordOf = (features: readonly string[], values: readonly number[]) => Object.fromEntries(features.map((f, i) => [f, values[i]]))
330
331/** S3: crossings (gap ≥ 0, as crossingOf), then segments with SEG_MIN_SHARE = 2. A side
332    without features counts as 0 dollars in every feature. */
333export function segmentsOf(w: WindowReadings, resolution: number, rounding: Rounding): Segment[] {
334  const features = w.features ?? []
335  const sideOf = (x: readonly number[] | undefined) => features.map((_, i) => x?.[i] ?? 0)
336  const levels = levelsOf(w)
337  const crossings: Crossing[] = []
338  for (const level of levels) {
339    if (!crossingOf(levels, level, resolution)) continue
340    const lower = levels.find(l => Math.abs(l.pct - (level.pct - resolution)) < resolution / 1000)
341    if (!lower) continue
342    const from = sideOf(lower.bucket.maxX)
343    const to = sideOf(level.bucket.minX)
344    crossings.push({
345      s: crossingShareOf(level.pct, resolution, rounding).s,
346      usd: (lower.bucket.maxUsd + level.bucket.minUsd) / 2,
347      x: from.map((v, i) => (v + to[i]) / 2),
348      gap: to.map((v, i) => v - from[i]),
349      at: Math.max(level.bucket.minAt, lower.bucket.maxAt),
350    })
351  }
352  crossings.sort((a, b) => a.s - b.s || a.at - b.at)
353  const pairs: [Crossing, Crossing][] = []
354  let anchor = crossings[0]
355  for (const c of crossings.slice(1)) {
356    if (c.s - anchor.s < SEG_MIN_SHARE - SHARE_EPSILON) continue
357    pairs.push([anchor, c])
358    anchor = c
359  }
360  /* The rate at θ = 0 is in the window's own dollars U. */
361  const rates = pairs.map(([a, b]) => (b.usd - a.usd) / (b.s - a.s))
362  const median = rates.length > 0 ? medianOf(rates) : 0
363  return pairs.map(([a, b], k) => ({
364    dX: recordOf(features, b.x.map((v, i) => v - a.x[i])),
365    ds: b.s - a.s,
366    gapA: recordOf(features, a.gap),
367    gapB: recordOf(features, b.gap),
368    at: b.at,
369    isExcluded: rates[k] < OUTLIER_RATE * median,
370  }))
371}
372
373/* A window that qualifies for fitting: its usable segments, non-excluded with dollars, and
374   how many the outlier rule excluded. */
375type Prepared = { w: WindowReadings; usable: Segment[]; excluded: number }
376
377/* Feature-complete windows with at least MIN_SEGMENTS usable segments, in resetsAt order. */
378function qualify(windows: readonly WindowReadings[], resolution: number, rounding: Rounding) {
379  const excluded: Record<string, number> = { 'not-feature-complete': 0, 'too-few-segments': 0 }
380  const included: Prepared[] = []
381  let segments = 0
382  let excludedSegments = 0
383  for (const w of windows) {
384    if (!isFeatureComplete(w)) {
385      excluded['not-feature-complete']++
386      continue
387    }
388    const all = segmentsOf(w, resolution, rounding)
389    const usable = all.filter(s => !s.isExcluded && sumOf(Object.values(s.dX)) > 0)
390    if (usable.length < MIN_SEGMENTS) {
391      excluded['too-few-segments']++
392      continue
393    }
394    const out = all.filter(s => s.isExcluded).length
395    included.push({ w, usable, excluded: out })
396    segments += usable.length
397    excludedSegments += out
398  }
399  included.sort((a, b) => Date.parse(a.w.resetsAt) - Date.parse(b.w.resetsAt))
400  return { included, excluded, segments, excludedSegments }
401}
402
403function dollarsOf(prepared: readonly Prepared[]) {
404  const dollars: Record<string, number> = {}
405  for (const p of prepared) for (const s of p.usable) for (const [f, v] of Object.entries(s.dX)) dollars[f] = (dollars[f] ?? 0) + v
406  return dollars
407}
408
409/* One window's usable segments summed by group: slot 0 holds every group of weight 1, slot
410   g + 1 the free group g. offset centers y for precision; it cancels with α̂. */
411type WindowColumns = {
412  size: number
413  offset: number
414  logDs: number[]
415  invDs: number[]
416  dx: number[]
417  ga: number[]
418  gb: number[]
419  at: number[]
420}
421
422type Columns = { n: number; windows: WindowColumns[] }
423
424function columnsOf(prepared: readonly Prepared[], groups: Grouping): Columns {
425  const n = groups.free.length
426  const width = n + 1
427  const slots = new Map<string, number>()
428  const slotOf = (feature: string) => {
429    let slot = slots.get(feature)
430    if (slot === undefined) {
431      slot = groups.free.indexOf(groupOf(groups.model, feature)) + 1
432      slots.set(feature, slot)
433    }
434    return slot
435  }
436  const windows = prepared.map(p => {
437    const size = p.usable.length
438    const dx = zerosOf(size * width)
439    const ga = zerosOf(size * width)
440    const gb = zerosOf(size * width)
441    p.usable.forEach((s, k) => {
442      for (const [f, v] of Object.entries(s.dX)) dx[k * width + slotOf(f)] += v
443      for (const [f, v] of Object.entries(s.gapA)) ga[k * width + slotOf(f)] += v
444      for (const [f, v] of Object.entries(s.gapB)) gb[k * width + slotOf(f)] += v
445    })
446    const first = p.usable[0]
447    return {
448      size,
449      offset: Math.log(sumOf(Object.values(first.dX)) / first.ds),
450      logDs: p.usable.map(s => Math.log(s.ds)),
451      invDs: p.usable.map(s => 1 / s.ds),
452      dx,
453      ga,
454      gb,
455      at: p.usable.map(s => s.at),
456    }
457  })
458  return { n, windows }
459}
460
461const withoutBlock = (cols: Columns, [from, to]: readonly [number, number]): Columns => ({
462  n: cols.n,
463  windows: cols.windows.filter((_, i) => i < from || i >= to),
464})
465
466/* K contiguous blocks of `count` items, as [from, to) ranges. */
467const blocksOf = (count: number, k: number) =>
468  Array.from({ length: k }, (_, b) => [Math.floor((b * count) / k), Math.floor(((b + 1) * count) / k)] as [number, number])
469
470const logOmegaOf = (x: number) => Math.min(Math.log(OMEGA_MAX), Math.max(Math.log(OMEGA_MIN), x))
471
472const omegaOf = (x: number) => Math.exp(logOmegaOf(x))
473
474const expOf = (theta: readonly number[]) => [1, ...theta.map(t => Math.exp(t))]
475
476/* ½ Σ_i Σ_k [(y_ik − α̂_i)² / V_ik + log V_ik], α̂_i the precision-weighted mean of window
477   i's y; Infinity where some w · ΔX is not above 0. */
478function devianceOf(cols: Columns, theta: readonly number[], logOmega: number) {
479  const width = cols.n + 1
480  const e = expOf(theta)
481  const omega2 = omegaOf(logOmega) ** 2
482  let total = 0
483  for (const c of cols.windows) {
484    let s0 = 0
485    let s1 = 0
486    let s2 = 0
487    let sl = 0
488    for (let k = 0; k < c.size; k++) {
489      const base = k * width
490      let dot = 0
491      let a = 0
492      let b = 0
493      for (let j = 0; j < width; j++) {
494        dot += e[j] * c.dx[base + j]
495        a += e[j] * c.ga[base + j]
496        b += e[j] * c.gb[base + j]
497      }
498      if (!(dot > 0)) return Infinity
499      const y = Math.log(dot) - c.logDs[k] - c.offset
500      const v = omega2 * c.invDs[k] + (a * a + b * b) / (12 * dot * dot)
501      const p = 1 / v
502      s0 += p
503      s1 += p * y
504      s2 += p * y * y
505      sl += Math.log(v)
506    }
507    total += s2 - (s1 * s1) / s0 + sl
508  }
509  return total / 2
510}
511
512const penaltyOf = (theta: readonly number[]) => theta.reduce((s, t) => s + (t * t) / (2 * SIGMA_THETA ** 2), 0)
513
514/* Each segment's w · ΔX, y less the window's offset, and V; a segment whose w · ΔX is not
515   above 0 has V = Infinity, which leaves it out. */
516function responsesOf(c: WindowColumns, e: readonly number[], omega: number) {
517  const width = e.length
518  const dots: number[] = []
519  const ys: number[] = []
520  const vs: number[] = []
521  for (let k = 0; k < c.size; k++) {
522    const base = k * width
523    let dot = 0
524    let a = 0
525    let b = 0
526    for (let j = 0; j < width; j++) {
527      dot += e[j] * c.dx[base + j]
528      a += e[j] * c.ga[base + j]
529      b += e[j] * c.gb[base + j]
530    }
531    const isUsable = dot > 0
532    dots.push(dot)
533    ys.push(isUsable ? Math.log(dot) - c.logDs[k] - c.offset : 0)
534    vs.push(isUsable ? omega * omega * c.invDs[k] + (a * a + b * b) / (12 * dot * dot) : Infinity)
535  }
536  return { dots, ys, vs }
537}
538
539/* log N(y_k; α̂, V_k) of each segment of one window, α̂ profiled; 0 for a segment left out. */
540function densitiesOf(c: WindowColumns, theta: readonly number[], omega: number) {
541  const { ys, vs } = responsesOf(c, expOf(theta), omega)
542  let sp = 0
543  let spy = 0
544  ys.forEach((y, k) => {
545    sp += 1 / vs[k]
546    spy += y / vs[k]
547  })
548  const alpha = sp > 0 ? spy / sp : 0
549  return ys.map((y, k) => (Number.isFinite(vs[k]) ? -0.5 * (Math.log(2 * Math.PI * vs[k]) + (y - alpha) ** 2 / vs[k]) : 0))
550}
551
552/* I_g = Σ (d_ik − d̄_i)² / V_ik: d_ik is group g's share of the segment's w · ΔX, d̄_i its
553   precision-weighted window mean. */
554function informationOf(cols: Columns, theta: readonly number[], omega: number) {
555  const n = cols.n
556  const width = n + 1
557  const e = expOf(theta)
558  const information = zerosOf(n)
559  for (const c of cols.windows) {
560    const { dots, vs } = responsesOf(c, e, omega)
561    const sp = vs.reduce((s, v) => s + 1 / v, 0)
562    if (!(sp > 0)) continue
563    for (let g = 0; g < n; g++) {
564      const shares = dots.map((dot, k) => (dot > 0 ? (e[g + 1] * c.dx[k * width + g + 1]) / dot : 0))
565      const mean = shares.reduce((s, d, k) => s + d / vs[k], 0) / sp
566      information[g] += shares.reduce((s, d, k) => s + (d - mean) ** 2 / vs[k], 0)
567    }
568  }
569  return information
570}
571
572/* Minimizes f from `start` with a simplex of `step` along each axis, with the standard
573   coefficients. Stops when the simplex's values lie within NM_TOLERANCE and its points
574   within NM_X_TOLERANCE of the best, or after NM_MAX_ITERATIONS. */
575function nelderMead(f: (x: number[]) => number, start: readonly number[], step: number): number[] {
576  const d = start.length
577  const valueOf = (x: number[]) => {
578    const v = f(x)
579    return Number.isNaN(v) ? Infinity : v
580  }
581  let points = [start.slice(), ...start.map((_, i) => start.map((v, j) => (i === j ? v + step : v)))]
582  let values = points.map(valueOf)
583  const order = () => {
584    const index = points.map((_, i) => i).sort((a, b) => (values[a] < values[b] ? -1 : values[a] > values[b] ? 1 : a - b))
585    points = index.map(i => points[i])
586    values = index.map(i => values[i])
587  }
588  const replace = (x: number[], v: number) => {
589    points[d] = x
590    values[d] = v
591  }
592  for (let iteration = 0; iteration < NM_MAX_ITERATIONS; iteration++) {
593    order()
594    let size = 0
595    for (const p of points) for (let i = 0; i < d; i++) size = Math.max(size, Math.abs(p[i] - points[0][i]))
596    if (values[d] - values[0] <= NM_TOLERANCE && size <= NM_X_TOLERANCE) break
597    const centroid = start.map((_, i) => {
598      let s = 0
599      for (let j = 0; j < d; j++) s += points[j][i]
600      return s / d
601    })
602    const toward = (t: number) => centroid.map((c, i) => c + t * (points[d][i] - c))
603    const reflected = toward(-1)
604    const fr = valueOf(reflected)
605    if (fr < values[0]) {
606      const expanded = toward(-2)
607      const fe = valueOf(expanded)
608      if (fe < fr) replace(expanded, fe)
609      else replace(reflected, fr)
610    } else if (fr < values[d - 1]) {
611      replace(reflected, fr)
612    } else {
613      const isOutside = fr < values[d]
614      const contracted = toward(isOutside ? -0.5 : 0.5)
615      const fc = valueOf(contracted)
616      if (isOutside ? fc <= fr : fc < values[d]) replace(contracted, fc)
617      else
618        for (let j = 1; j <= d; j++) {
619          points[j] = points[j].map((v, i) => points[0][i] + (v - points[0][i]) / 2)
620          values[j] = valueOf(points[j])
621        }
622    }
623  }
624  order()
625  return points[0]
626}
627
628const startOf = (n: number) => [...zerosOf(n), Math.log(OMEGA_START)]
629
630/* (θ, log ω) minimizing the penalized objective Q of S4. */
631function optimize(cols: Columns, start: readonly number[], step: number) {
632  const n = cols.n
633  return nelderMead(x => {
634    const theta = x.slice(0, n)
635    return devianceOf(cols, theta, x[n]) + penaltyOf(theta)
636  }, start, step)
637}
638
639/* ω with θ held fixed. */
640function omegaFitOf(cols: Columns, theta: readonly number[]) {
641  if (cols.windows.length === 0) return OMEGA_START
642  return omegaOf(nelderMead(x => devianceOf(cols, theta, x[0]), [Math.log(OMEGA_START)], NM_STEP)[0])
643}
644
645/* S5 on prepared columns: K = min(G, JACKKNIFE_BLOCKS) contiguous blocks, each left out in
646   turn, refitting from x. */
647function jackknifeOf(cols: Columns, x: readonly number[]) {
648  const n = cols.n
649  const k = Math.min(cols.windows.length, JACKKNIFE_BLOCKS)
650  const df = Math.max(0, k - 1)
651  if (n === 0 || k < 2) return { cov: zeroMatrixOf(n), se: zerosOf(n), df }
652  const thetas = blocksOf(cols.windows.length, k).map(block => optimize(withoutBlock(cols, block), x, NM_WARM_STEP).slice(0, n))
653  const mean = zerosOf(n).map((_, g) => sumOf(thetas.map(t => t[g])) / k)
654  const cov = zeroMatrixOf(n).map((row, a) => row.map((_, b) => ((k - 1) / k) * sumOf(thetas.map(t => (t[a] - mean[a]) * (t[b] - mean[b])))))
655  return { cov, se: cov.map((row, g) => Math.sqrt(row[g])), df }
656}
657
658type Fitted = { result: FitResult; cols: Columns; x: number[] }
659
660/* S4 on qualifying windows, in resetsAt order. */
661function fitPrepared(model: Model, prepared: readonly Prepared[], options: FitOptions): Fitted | undefined {
662  if (prepared.length < MIN_WINDOWS) return undefined
663  let groups = options.groups ?? groupsOf(model, dollarsOf(prepared))
664  let cols = columnsOf(prepared, groups)
665  let x = optimize(cols, startOf(groups.free.length), NM_STEP)
666  if (!options.groups && groups.free.length > 0) {
667    const information = informationOf(cols, x.slice(0, cols.n), omegaOf(x[cols.n]))
668    const free = groups.free.filter((_, g) => information[g] >= 1 / SIGMA_THETA ** 2)
669    if (free.length < groups.free.length) {
670      groups = { ...groups, free }
671      cols = columnsOf(prepared, groups)
672      x = optimize(cols, startOf(free.length), NM_STEP)
673    }
674  }
675  const n = cols.n
676  const theta = x.slice(0, n)
677  const omega = omegaOf(x[n])
678  const k = Math.min(prepared.length, JACKKNIFE_BLOCKS)
679  const jk = options.isJackknifed === false ? { cov: zeroMatrixOf(n), se: zerosOf(n), df: k - 1 } : jackknifeOf(cols, x)
680  const result: FitResult = {
681    model,
682    groups: { model: groups.model, reference: groups.reference, free: [...groups.free] },
683    theta,
684    omega,
685    cov: jk.cov,
686    se: jk.se,
687    df: jk.df,
688    information: informationOf(cols, theta, omega),
689    windows: prepared.length,
690    segments: sumOf(prepared.map(p => p.usable.length)),
691    excludedSegments: sumOf(prepared.map(p => p.excluded)),
692    weights: weightsOf(groups, theta, jk.cov, jk.df),
693  }
694  return { result, cols, x }
695}
696
697/** S4. Throws if any window's kind is not 'five_hour'. Filters to feature-complete windows
698    with ≥ 2 non-excluded segments; returns undefined below MIN_WINDOWS such windows. Group
699    pruning (2% share, then information < 1/SIGMA_THETA²) unless `groups` is given; the
700    dollars for the 2% rule are Σ ΔX over the non-excluded segments. */
701export function fit(model: Model, windows: readonly WindowReadings[], options: FitOptions): FitResult | undefined {
702  const other = windows.find(w => w.kind !== 'five_hour')
703  if (other) throw new Error(`The meter weights are fitted on five_hour windows only, not ${other.kind}.`)
704  return fitPrepared(model, qualify(windows, options.resolution, options.rounding).included, options)?.result
705}
706
707/** S5: blocked jackknife with K = min(G, 20) contiguous blocks in resetsAt order, refitting
708    with the grouping held fixed, from θ and the ω fitted at it. */
709export function jackknife(
710  model: Model,
711  windows: readonly WindowReadings[],
712  groups: Grouping,
713  theta: readonly number[],
714  options: FitOptions,
715): { cov: number[][]; se: number[]; df: number } {
716  const cols = columnsOf(qualify(windows, options.resolution, options.rounding).included, { ...groups, model })
717  return jackknifeOf(cols, [...theta, Math.log(omegaFitOf(cols, theta))])
718}
719
720/** Score of one window under fixed weights and ω: Σ_k log N(y_k; α̂, V_k), α̂ profiled as
721    the precision-weighted mean. Undefined when the window is not feature-complete or has
722    fewer than 2 usable segments. */
723export function scoreWindow(w: WindowReadings, weights: Weights, omega: number, resolution: number, rounding: Rounding): number | undefined {
724  const [prepared] = qualify([w], resolution, rounding).included
725  if (!prepared) return undefined
726  const [c] = columnsOf([prepared], weights).windows
727  return sumOf(densitiesOf(c, weights.theta, omega))
728}
729
730/* Held-out score per fold: each fold's windows scored under the fit on the other folds. */
731function crossValidated(fitted: Fitted, folds: readonly [number, number][]) {
732  const { cols, x } = fitted
733  const n = cols.n
734  return folds.map(block => {
735    const fx = optimize(withoutBlock(cols, block), x, NM_WARM_STEP)
736    const theta = fx.slice(0, n)
737    const omega = omegaOf(fx[n])
738    let score = 0
739    for (let i = block[0]; i < block[1]; i++) score += sumOf(densitiesOf(cols.windows[i], theta, omega))
740    return score
741  })
742}
743
744/** S6: blocked K-fold CV, K = min(G, 10), contiguous blocks; grouping held fixed per
745    candidate (from its full fit). Rule: Δ > max(2, 2·SE_Δ), some |θ̂|/SE_J ≥ 2, ≥ 4 windows.
746    Under 4 qualifying windows: selected 'M0' with no fits. */
747export function selectModel(fiveHourWindows: readonly WindowReadings[], options: { resolution: number; rounding: Rounding }): Selection {
748  const { resolution, rounding } = options
749  const fiveHour = fiveHourWindows.filter(w => w.kind === 'five_hour')
750  const q = qualify(fiveHour, resolution, rounding)
751  const summary = {
752    rounding,
753    windows: { used: q.included.length, excluded: { ...q.excluded, 'not-five-hour': fiveHourWindows.length - fiveHour.length } },
754    segments: q.segments,
755    excludedSegments: q.excludedSegments,
756  }
757  const fitted: Partial<Record<Model, Fitted>> = {}
758  const fits: Partial<Record<Model, FitResult>> = {}
759  for (const model of MODELS) {
760    const f = fitPrepared(model, q.included, { resolution, rounding })
761    if (!f) continue
762    fitted[model] = f
763    fits[model] = f.result
764  }
765  if (!fitted.M0) return { selected: 'M0', weights: UNIT_WEIGHTS, fits, comparisons: [], ...summary }
766  const folds = blocksOf(q.included.length, Math.min(q.included.length, CV_FOLDS))
767  const scores = new Map<Model, number[]>()
768  const scoresOf = (model: Model) => {
769    let s = scores.get(model)
770    if (!s) {
771      s = crossValidated(fitted[model]!, folds)
772      scores.set(model, s)
773    }
774    return s
775  }
776  const compare = (from: Model, to: Model): Comparison => {
777    const target = fitted[to]?.result
778    if (!target || !fitted[from] || target.groups.free.length === 0) return { from, to, delta: 0, se: 0, folds: 0, isSelected: false }
779    const base = scoresOf(from)
780    const d = scoresOf(to).map((s, k) => s - base[k])
781    const delta = sumOf(d)
782    const se = Math.sqrt(d.length * sampleVarianceOf(d))
783    const isClear = target.theta.some((t, g) => target.se[g] > 0 && Math.abs(t) / target.se[g] >= SELECT_MIN_Z)
784    return { from, to, delta, se, folds: d.length, isSelected: delta > Math.max(SELECT_MIN_DELTA, SELECT_SE_MULTIPLE * se) && isClear }
785  }
786  const first = compare('M0', 'M1')
787  let selected: Model = first.isSelected ? 'M1' : 'M0'
788  const second = compare(selected, 'M2')
789  if (second.isSelected) selected = 'M2'
790  const weights = selected === 'M0' ? UNIT_WEIGHTS : fits[selected]!.weights
791  return { selected, weights, fits, comparisons: [first, second], ...summary }
792}
793
794/** S6b on qualifying weekly windows: ω_week fitted per candidate with θ held fixed, α
795    profiled under each; d_day sums the segments' log-density differences by the UTC day of
796    their end crossing. Under UNIT_WEIGHTS: unchecked, with both ω fitted under M0. */
797export function transferCheck(weeklyWindows: readonly WindowReadings[], weights: Weights, options: { resolution: number; rounding: Rounding }): Transfer {
798  const { resolution, rounding } = options
799  const prepared = qualify(weeklyWindows, resolution, rounding).included
800  const cols = columnsOf(prepared, weights)
801  const zero = zerosOf(cols.n)
802  const omegaM0 = omegaFitOf(cols, zero)
803  const weeklyFit = prepared.length >= WEEKLY_FIT_MIN_WEEKS ? fitPrepared('M1', prepared, { resolution, rounding })?.result : undefined
804  const reported = { weeks: prepared.length, ...(weeklyFit ? { weeklyFit } : {}) }
805  if (isUnit(weights)) return { isChecked: false, isRejected: false, delta: 0, se: 0, days: 0, omega: { selected: omegaM0, M0: omegaM0 }, ...reported }
806  const omega = omegaFitOf(cols, weights.theta)
807  const byDay = new Map<number, number>()
808  for (const c of cols.windows) {
809    const selected = densitiesOf(c, weights.theta, omega)
810    const plain = densitiesOf(c, zero, omegaM0)
811    c.at.forEach((at, k) => {
812      const day = Math.floor(at / DAY_MS)
813      byDay.set(day, (byDay.get(day) ?? 0) + selected[k] - plain[k])
814    })
815  }
816  const d = [...byDay.values()]
817  const delta = sumOf(d)
818  const se = Math.sqrt(d.length * sampleVarianceOf(d))
819  const isChecked = d.length >= TRANSFER_MIN_DAYS
820  return {
821    isChecked,
822    isRejected: isChecked && delta < -Math.max(SELECT_MIN_DELTA, SELECT_SE_MULTIPLE * se),
823    delta,
824    se,
825    days: d.length,
826    omega: { selected: omega, M0: omegaM0 },
827    ...reported,
828  }
829}
830
831/** S7: one record per new window that scores under both the stored weights and M0, with
832    d = score_selected − score_M0; [] when the stored weights are M0's. */
833export function prospectiveScore(
834  stored: StoredFit,
835  newWindows: readonly WindowReadings[],
836  options: { resolution: number; rounding: Rounding },
837): ProspectiveRecord[] {
838  if (isUnit(stored.weights)) return []
839  const records: ProspectiveRecord[] = []
840  for (const w of newWindows) {
841    const selected = scoreWindow(w, stored.weights, stored.omega, options.resolution, options.rounding)
842    const plain = scoreWindow(w, UNIT_WEIGHTS, stored.omegaM0, options.resolution, options.rounding)
843    if (selected === undefined || plain === undefined) continue
844    records.push({ resetsAt: w.resetsAt, kind: w.kind, d: selected - plain })
845  }
846  return records
847}
848
849/** Deterministic string over the inputs listed in S7. Each window as (window key, bucket
850    count, latest maxAt), sorted by key. */
851export function fingerprintOf(input: {
852  fiveHour: readonly { key: string; w: WindowReadings }[]
853  weekly: readonly { key: string; w: WindowReadings }[]
854  regimeStarts: Record<string, number>
855  pricesId?: string
856  schema: number
857  stamp: number
858}): string {
859  const listOf = (windows: readonly { key: string; w: WindowReadings }[]) =>
860    windows
861      .map(({ key, w }) => {
862        const buckets = Object.values(w.byPct)
863        return [key, buckets.length, buckets.reduce((latest, b) => Math.max(latest, b.maxAt), 0)] as const
864      })
865      .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
866  return JSON.stringify({
867    fiveHour: listOf(input.fiveHour),
868    weekly: listOf(input.weekly),
869    regimeStarts: Object.keys(input.regimeStarts)
870      .sort()
871      .map(key => [key, input.regimeStarts[key]]),
872    pricesId: input.pricesId ?? null,
873    schema: input.schema,
874    stamp: input.stamp,
875  })
876}
877
878/* Rejections in weighted dollars: each at the mix of the newest max side of the closed
879   window with the same reset; dropped without that window or its features. */
880function weightedRejections(closed: readonly WindowReadings[], rejections: readonly Rejection[], kind: string, weights: Weights) {
881  const weighted: Rejection[] = []
882  for (const r of rejections) {
883    if (r.kind !== kind) continue
884    const w = closed.find(c => c.kind === kind && minuteOf(c.resetsAt) === minuteOf(r.resetsAt))
885    if (!w || !isFeatureComplete(w)) continue
886    const newest = Object.values(w.byPct).reduce<Bucket | undefined>((a, b) => (!a || b.maxAt > a.maxAt ? b : a), undefined)
887    if (!newest) continue
888    const x = newest.maxX ?? []
889    const total = sumOf(x)
890    const wf = (w.features ?? []).map(f => featureWeight(weights, f))
891    weighted.push({ ...r, usd: r.usd * (total > 0 ? dotOf(wf, x) / total : 1) })
892  }
893  return weighted
894}
895
896type Run = { estimate?: Estimate; view?: WindowReadings; spread: Spread; past: PastPoint[]; mix: number; usedE: number; excluded: number }
897
898/* The pipeline in weighted dollars, through the features of every window. */
899function runAt(input: WeightedEstimateInput, weights: Weights): Run {
900  const { kind, closed, current, usedUsd, usedX, fallbackX, rejections, resolution, rounding, now, livePercent, startedAt } = input
901  const views = closed.filter(w => isFeatureComplete(w)).map(w => transformed(w, weights))
902  const view = current && isFeatureComplete(current) ? transformed(current, weights) : undefined
903  const mix =
904    usedUsd > 0 && sumOf(Object.values(usedX)) > 0
905      ? mixWeight(weights, usedX)
906      : fallbackX && sumOf(Object.values(fallbackX)) > 0
907        ? mixWeight(weights, fallbackX)
908        : 1
909  const usedE = usedUsd * mix
910  const spread = calibrateOmega(views, kind, now, resolution, rounding)
911  const past = pastPoints(views, weightedRejections(closed, rejections, kind, weights), kind, resolution, rounding, spread.omega).filter(
912    p => p.at >= startedAt,
913  )
914  const e = view ? estimate(view, usedE, { resolution, rounding, past, kind, now, livePercent, spread }) : undefined
915  return { estimate: e, view, spread, past, mix, usedE, excluded: closed.length - views.length }
916}
917
918const scaledBy = (r: RangeEstimate, f: number): RangeEstimate => ({ value: r.value * f, low: r.low * f, high: r.high * f })
919
920/** Weighted views of closed and current windows (closed ones that cannot be transformed are
921    dropped and counted), calibrateOmega, pastPoints (under non-unit weights a rejection's
922    usd is multiplied by the w̄ of the closed window with the same reset's newest max side
923    when that window is feature-complete, otherwise the rejection is dropped), estimate().
924    The displayed log quantity is L = e.log.mean − log w̄_window; its gradient by central
925    finite differences of GRADIENT_STEP per free group through the whole pipeline gives
926    extraVariance = ∇ᵀ Σ_J ∇, and estimate() is rerun with it. Under UNIT_WEIGHTS the result
927    is the plain pipeline's; with a zero cov, the weighted pipeline's without extra variance.
928    No estimate when the current window is not feature-complete under non-unit weights. */
929export function weightedEstimate(input: WeightedEstimateInput): WeightedEstimate {
930  const { kind, closed, current, usedUsd, weights, rejections, resolution, rounding, now, livePercent, startedAt } = input
931  if (isUnit(weights)) {
932    const spread = calibrateOmega(closed, kind, now, resolution, rounding)
933    const past = pastPoints(closed, rejections, kind, resolution, rounding, spread.omega).filter(p => p.at >= startedAt)
934    const e = current ? estimate(current, usedUsd, { resolution, rounding, past, kind, now, livePercent, spread }) : undefined
935    return {
936      estimate: e,
937      display: e && { allowance: e.allowance, left: e.left, nextTick: e.nextTick },
938      usedE: usedUsd,
939      mixWeight: 1,
940      extraVariance: 0,
941      spread,
942      past,
943      excludedClosed: 0,
944    }
945  }
946  const base = runAt(input, weights)
947  let e = base.estimate
948  let extraVariance = 0
949  const isCovZero = weights.cov.every(row => row.every(v => v === 0))
950  if (e && base.view && !isCovZero) {
951    const displayedOf = (run: Run) => (run.estimate ? run.estimate.log.mean - Math.log(run.mix) : undefined)
952    const at = (g: number, h: number) => displayedOf(runAt(input, { ...weights, theta: weights.theta.map((t, j) => (j === g ? t + h : t)) }))
953    const l0 = e.log.mean - Math.log(base.mix)
954    const gradient = weights.theta.map((_, g) => {
955      const up = at(g, GRADIENT_STEP)
956      const down = at(g, -GRADIENT_STEP)
957      if (up !== undefined && down !== undefined) return (up - down) / (2 * GRADIENT_STEP)
958      if (up !== undefined) return (up - l0) / GRADIENT_STEP
959      if (down !== undefined) return (l0 - down) / GRADIENT_STEP
960      return 0
961    })
962    extraVariance = quadraticOf(gradient, weights.cov)
963    if (extraVariance > 0) {
964      e = estimate(base.view, base.usedE, { resolution, rounding, past: base.past, kind, now, livePercent, spread: base.spread, extraVariance })
965    }
966  }
967  const toU = 1 / base.mix
968  return {
969    estimate: e,
970    display: e && { allowance: scaledBy(e.allowance, toU), left: scaledBy(e.left, toU), nextTick: e.nextTick && scaledBy(e.nextTick, toU) },
971    usedE: base.usedE,
972    mixWeight: base.mix,
973    extraVariance,
974    spread: base.spread,
975    past: base.past,
976    excludedClosed: base.excluded,
977  }
978}
979
980/** Per priceKey in the tally: w̄_m = Σ_{f∈m} w_f x_f / Σ_{f∈m} x_f, with a 90% interval
981    from ∂ log w̄_m / ∂θ_g (group g's share of model m's weighted dollars), Σ_J and
982    t(0.95, df). `web` is not a model. */
983export function modelConversion(weights: Weights, tally7d: Record<string, number>): Record<string, RangeEstimate> {
984  const byModel = new Map<string, string[]>()
985  for (const feature of Object.keys(tally7d).sort()) {
986    if (feature === 'web') continue
987    const { priceKey } = partsOf(feature)
988    byModel.set(priceKey, [...(byModel.get(priceKey) ?? []), feature])
989  }
990  const n = weights.free.length
991  const conversions: Record<string, RangeEstimate> = {}
992  for (const [priceKey, features] of byModel) {
993    let sum = 0
994    let weighted = 0
995    const byGroup = zerosOf(n)
996    for (const feature of features) {
997      const x = tally7d[feature]
998      const wx = featureWeight(weights, feature) * x
999      sum += x
1000      weighted += wx
1001      const g = weights.free.indexOf(groupOf(weights.model, feature))
1002      if (g >= 0) byGroup[g] += wx
1003    }
1004    const isPriced = sum > 0 && weighted > 0
1005    const gradient = isPriced ? byGroup.map(v => v / weighted) : zerosOf(n)
1006    const log = { mean: isPriced ? Math.log(weighted / sum) : 0, variance: quadraticOf(gradient, weights.cov), shift: 0, df: weights.df }
1007    conversions[priceKey] = rangeOf(log, 0, 0)
1008  }
1009  return conversions
1010}
1011
hooks/plan.ts 238 lines
1/* Plan tracking per subscription: a ledger of the plans the signed-in profile reported,
2   the promotions its cache listed, and the regimes (stretches of constant limits) that
3   decide which readings feed an estimate. Pure: no engine calls, every instant in epoch
4   milliseconds.
5
6   The profile describes only the subscription Claude Code is signed in to now, and is
7   refreshed on Claude Code's own schedule, so a plan change is known only as a range
8   between two profile fetches, and a profile for another subscription says nothing about
9   this one. */
10
11export type Kind = 'five_hour' | 'seven_day'
12
13export type ProfilePromotion = { limit: string | null; text: string; endsAt: string | null; endsLabel: string | null }
14
15/** The helper's `profile` block. */
16export type Profile = {
17  org: string
18  organizationType: string | null
19  rateLimitTier: string | null
20  userRateLimitTier: string | null
21  seatTier: string | null
22  billingType: string | null
23  subscriptionCreatedAt: string | null
24  fetchedAt: string | null
25  fetchedLabel: string | null
26  promotions: ProfilePromotion[]
27}
28
29export type PlanEntry = {
30  fingerprint: string
31  label: string
32  firstSeenAt: number
33  lastSeenAt: number
34  profileFetchedAt?: number
35}
36
37export type Ledger = Record<string, PlanEntry[]>
38
39export type PlanEvent =
40  | { kind: 'unknown'; reason: 'no-profile' | 'other-subscription'; lastKnown?: PlanEntry }
41  | { kind: 'first-seen' }
42  | { kind: 'same' }
43  | { kind: 'changed'; from: PlanEntry; to: PlanEntry; between: [number, number] }
44
45export type RegimeReason = 'first-seen' | 'plan' | 'promotion-start' | 'promotion-end' | 'manual'
46
47export type Regime = { startedAt: number; reason: RegimeReason; kinds?: Kind[]; isUndone?: boolean }
48
49export type Regimes = Record<string, Regime[]>
50
51export type Promotion = {
52  text: string
53  limit: string | null
54  endsAt: number | null
55  endsLabel: string | null
56  firstSeenAt: number
57  isEnded: boolean
58}
59
60export type Promotions = Record<string, Promotion[]>
61
62export type NoticeDraft = { id: string; kind: 'plan-changed' | 'promotion' | 'inferred'; text: string }
63
64const KEPT_ENTRIES = 20
65const KEPT_REGIMES = 50
66
67const timeOf = (iso: string | null) => {
68  const ms = iso ? Date.parse(iso) : NaN
69  return Number.isFinite(ms) ? ms : undefined
70}
71
72export function fingerprint(p: Profile) {
73  return [p.organizationType, p.rateLimitTier, p.userRateLimitTier, p.seatTier, p.subscriptionCreatedAt]
74    .map(v => v ?? '')
75    .join('|')
76}
77
78/* Display names for known values only; anything else is shown verbatim, never guessed. */
79export function planLabel(p: Profile) {
80  const tier = p.rateLimitTier
81  switch (p.organizationType) {
82    case 'claude_max':
83      if (tier && /_max_5x$/.test(tier)) return 'Max 5x'
84      if (tier && /_max_20x$/.test(tier)) return 'Max 20x'
85      return tier ? `Max (${tier})` : 'Max'
86    case 'claude_pro':
87      return 'Pro'
88    case 'claude_team':
89      return p.seatTier ? `Team · ${p.seatTier} seat` : 'Team'
90    case 'claude_enterprise':
91      return 'Enterprise'
92    case 'claude_free':
93      return 'Free'
94    default: {
95      const name = p.organizationType ?? 'unknown plan'
96      return tier ? `${name} (${tier})` : name
97    }
98  }
99}
100
101const capped = <T>(list: readonly T[], max: number) => list.slice(Math.max(0, list.length - max))
102
103export function observePlan(ledger: Ledger, profile: Profile | null | undefined, sessionOrg: string, now: number) {
104  const entries = ledger[sessionOrg] ?? []
105  const prev = entries[entries.length - 1]
106  if (!profile || profile.org !== sessionOrg) {
107    const event: PlanEvent = { kind: 'unknown', reason: profile ? 'other-subscription' : 'no-profile', lastKnown: prev }
108    return { ledger, event }
109  }
110
111  const fetchedAt = timeOf(profile.fetchedAt)
112  const entry: PlanEntry = {
113    fingerprint: fingerprint(profile),
114    label: planLabel(profile),
115    firstSeenAt: now,
116    lastSeenAt: now,
117    profileFetchedAt: fetchedAt,
118  }
119  if (!prev) {
120    const event: PlanEvent = { kind: 'first-seen' }
121    const regime: Regime = { startedAt: timeOf(profile.subscriptionCreatedAt) ?? 0, reason: 'first-seen' }
122    return { ledger: { ...ledger, [sessionOrg]: [entry] }, event, regime }
123  }
124  if (prev.fingerprint === entry.fingerprint) {
125    const raised = fetchedAt !== undefined && (prev.profileFetchedAt === undefined || fetchedAt > prev.profileFetchedAt)
126    const updated: PlanEntry = { ...prev, lastSeenAt: now, profileFetchedAt: raised ? fetchedAt : prev.profileFetchedAt }
127    const event: PlanEvent = { kind: 'same' }
128    return { ledger: { ...ledger, [sessionOrg]: [...entries.slice(0, -1), updated] }, event }
129  }
130
131  /* The last moment the server confirmed the old plan, and the first it reported the new. */
132  const isOrdered =
133    prev.profileFetchedAt !== undefined && fetchedAt !== undefined && prev.profileFetchedAt <= fetchedAt
134  const between: [number, number] = isOrdered ? [prev.profileFetchedAt!, fetchedAt!] : [prev.lastSeenAt, now]
135  const event: PlanEvent = { kind: 'changed', from: prev, to: entry, between }
136  const regime: Regime = { startedAt: between[1], reason: 'plan' }
137  return { ledger: { ...ledger, [sessionOrg]: capped([...entries, entry], KEPT_ENTRIES) }, event, regime }
138}
139
140export function addRegimes(regimes: Regimes, org: string, added: readonly Regime[]): Regimes {
141  if (added.length === 0) return regimes
142  return { ...regimes, [org]: capped([...(regimes[org] ?? []), ...added], KEPT_REGIMES) }
143}
144
145const appliesTo = (r: Regime, kind: Kind) => !r.isUndone && (!r.kinds || r.kinds.includes(kind))
146
147/** The regime in force for one window kind: the latest start that is not undone. */
148export function currentRegime(regimes: Regimes, org: string, kind: Kind) {
149  let found: Regime | undefined
150  for (const r of regimes[org] ?? []) if (appliesTo(r, kind) && (!found || r.startedAt > found.startedAt)) found = r
151  return found
152}
153
154export function regimeStart(regimes: Regimes, org: string, kind: Kind) {
155  return currentRegime(regimes, org, kind)?.startedAt ?? 0
156}
157
158export function startOver(regimes: Regimes, org: string, now: number) {
159  return addRegimes(regimes, org, [{ startedAt: now, reason: 'manual' }])
160}
161
162/* Only a reset that is still the latest regime can be undone: plan and promotion regimes
163   are observations, not choices. */
164export function undoStartOver(regimes: Regimes, org: string) {
165  const list = regimes[org] ?? []
166  let at = list.length - 1
167  while (at >= 0 && list[at]?.isUndone) at--
168  if (list[at]?.reason !== 'manual') return { regimes, isUndone: false }
169  const next = list.map((r, i) => (i === at ? { ...r, isUndone: true } : r))
170  return { regimes: { ...regimes, [org]: next }, isUndone: true }
171}
172
173const promoKinds = (limit: string | null): Kind[] | undefined =>
174  limit === 'five_hour' || limit === 'seven_day' ? [limit] : undefined
175
176const promoText = (p: { text: string; endsLabel: string | null }) =>
177  `Promotion in effect: ${p.text}${p.endsLabel ? ` — ends ${p.endsLabel}` : ''}.`
178
179export function observePromotions(stored: Promotions, profile: Profile | null | undefined, sessionOrg: string, now: number) {
180  const regimes: Regime[] = []
181  const notices: NoticeDraft[] = []
182  /* The cache belongs to whichever subscription is signed in. */
183  if (!profile || profile.org !== sessionOrg) return { stored, regimes, notices }
184
185  const cached = profile.promotions ?? []
186  const toPromotion = (p: ProfilePromotion): Promotion => ({
187    text: p.text,
188    limit: p.limit,
189    endsAt: timeOf(p.endsAt) ?? null,
190    endsLabel: p.endsLabel,
191    firstSeenAt: now,
192    isEnded: false,
193  })
194  const was = stored[sessionOrg]
195  if (!was) {
196    const list = cached.map(toPromotion)
197    for (const p of list) notices.push({ id: `promo:${sessionOrg}:${p.text}`, kind: 'promotion', text: promoText(p) })
198    return { stored: { ...stored, [sessionOrg]: list }, regimes, notices }
199  }
200
201  const next: Promotion[] = []
202  const texts = new Set(cached.map(p => p.text))
203  for (const p of was) {
204    let kept: Promotion | undefined = p
205    if (!p.isEnded && p.endsAt !== null && p.endsAt <= now) {
206      kept = { ...p, isEnded: true }
207      regimes.push({ startedAt: p.endsAt, reason: 'promotion-end', kinds: promoKinds(p.limit) })
208      notices.push({ id: `promo-end:${sessionOrg}:${p.text}`, kind: 'promotion', text: `Promotion ended: ${p.text}.` })
209    }
210    if (!texts.has(p.text)) {
211      /* Missing from the cache is no evidence that it ended: keep it until its end date. */
212      if (p.endsAt === null) {
213        kept = undefined
214        notices.push({
215          id: `promo-gone:${sessionOrg}:${p.text}`,
216          kind: 'promotion',
217          text: 'A promotion is no longer listed. If your limits changed, run /usage-dollars reset.',
218        })
219      } else if (kept!.isEnded) kept = undefined
220    }
221    if (kept) next.push(kept)
222  }
223  const known = new Set(was.map(p => p.text))
224  for (const c of cached) {
225    if (known.has(c.text)) continue
226    const p = toPromotion(c)
227    next.push(p)
228    regimes.push({ startedAt: now, reason: 'promotion-start', kinds: promoKinds(p.limit) })
229    notices.push({ id: `promo:${sessionOrg}:${p.text}`, kind: 'promotion', text: promoText(p) })
230  }
231  return { stored: { ...stored, [sessionOrg]: next }, regimes, notices }
232}
233
234/** The "in effect" lines for a subscription's stored promotions that have not ended. */
235export function activePromotions(stored: Promotions, org: string) {
236  return (stored[org] ?? []).filter(p => !p.isEnded).map(promoText)
237}
238
types/index.d.ts 217 lines
1export type ModelSpend = { model: string; usd: number; requests: number }
2
3export type RangeReport = { value: number; low: number; high: number }
4
5export type Confidence = 'good' | 'fair' | 'rough'
6
7export type WindowReport = {
8  title: string
9  short: string
10  usedUsd: number
11  requests: number
12  resetLong: string
13  resetIn: string
14  left?: RangeReport
15  allowance?: RangeReport
16  confidence?: Confidence
17  nextTick?: RangeReport
18  pastWeight?: number
19  isPriorContradicted?: boolean
20  /** The spread of allowances between windows is assumed: under 3 effective past windows. */
21  isSpreadAssumed?: boolean
22  /** The percent the limit reported, the freshest any session received. */
23  percent?: number
24  /** Minutes since that percent was received. */
25  percentAgeMinutes?: number
26  basis: string
27  /** Both spreads and the rounding rule rest on closed windows. */
28  isCalibrated?: boolean
29}
30
31export type PlanReport = {
32  label?: string
33  asOfLabel?: string
34  isStale: boolean
35  isUnknown: boolean
36  /** "Max 5x on Mon 5 Oct, 10:23": the plan last seen for this subscription. */
37  lastKnown?: string
38  /** Set only while the plan is unknown: whether any profile was found at all. */
39  unknownReason?: 'no-profile' | 'other-subscription'
40}
41
42export type UsageReport = {
43  type: 'windows'
44  plan: PlanReport
45  notices: string[]
46  last24hUsd?: number
47  sinceResetLabel?: string
48  windows: WindowReport[]
49  byModel: ModelSpend[]
50  byModelTitle: string
51  notes: string[]
52  files: number
53  ms: number
54}
55
56export type DaySpend = { date: string; label: string; usd: number; requests: number }
57
58export type SpendReport = {
59  type: 'report'
60  fromLabel: string
61  toLabel: string
62  usedUsd: number
63  requests: number
64  byDay: DaySpend[]
65  byModel: ModelSpend[]
66  notes: string[]
67}
68
69export type CheckItem = { label: string; state: 'ok' | 'fail' | 'info'; text: string }
70
71export type CheckReport = {
72  type: 'check'
73  items: CheckItem[]
74}
75
76/** What has been measured for one window. */
77export type CalibrationWindow = {
78  title: string
79  /** Percent levels read in the current window, and how many of them with a tick. */
80  levels: number
81  ticks: number
82  /** Closed windows of this kind, since the latest restart, that hold readings. */
83  closedWindows: number
84  /** Closed windows that gave the within-window spread a crossing; measured from 2. */
85  closedForWithin: number
86  isWithinMeasured: boolean
87  /** Past windows behind the prior, rejections included, and their effective weight. */
88  pastPoints: number
89  pastWeight: number
90  isBetweenMeasured: boolean
91  /** Closed windows of every subscription that could show the rounding rule. */
92  closedForRounding: number
93  roundingNeeded: number
94  isRoundingKnown: boolean
95  rounding: 'round' | 'truncate' | 'union'
96  /** Of the three above. */
97  measured: number
98  isCalibrated: boolean
99  /** Of the current 90% range, in proportion: 0.12 for ±12%. */
100  halfWidth?: number
101}
102
103export type CalibrationReport = {
104  type: 'calibration'
105  windows: CalibrationWindow[]
106}
107
108/** A candidate meter model: M0, the API price ratio; M1, a weight per model; M2, per model
109    for cache reads and for the rest. */
110export type MeterModel = 'M0' | 'M1' | 'M2'
111
112/** One free group of a fit: how the meter counts its API dollars against the reference
113    group's. */
114export type ModelsGroup = {
115  /** A price key under M1, `<priceKey>/read` or `<priceKey>/other` under M2. */
116  key: string
117  /** "Fable 5.1", "Fable 5.1 cache reads", "Fable 5.1 except cache reads". */
118  label: string
119  /** exp(θ), and its 90% interval exp(θ ± t(0.95, df) · se). */
120  weight: RangeReport
121  /** The windows' information on θ; the prior's is 4. */
122  information: number
123}
124
125/** One candidate model fitted on the 5-hour windows. */
126export type ModelsFit = {
127  model: MeterModel
128  /** The group at weight 1 that the others are measured against, and its label. */
129  reference: string
130  referenceLabel: string
131  /** Empty under M0, or when every other group merged into the reference. */
132  groups: ModelsGroup[]
133  /** Within-window spread ω of the fit. */
134  omega: number
135  windows: number
136  segments: number
137  /** Degrees of freedom of the intervals: jackknife blocks less 1. */
138  df: number
139}
140
141/** Cross-validated gain of `to` over `from`, in nats, with its SE; isSelected: `to` won. */
142export type ModelsComparison = { from: MeterModel; to: MeterModel; delta: number; se: number; folds: number; isSelected: boolean }
143
144/** Whether the 5-hour weights hold for the weeks. */
145export type ModelsTransfer = {
146  /** At least 5 days of weekly segments: until then the weeks use the weights unchecked. */
147  isChecked: boolean
148  /** The weeks fall back to M0. */
149  isRejected: boolean
150  days: number
151  /** Log-score gain of the weights over M0 on the weekly segments, in nats, with its SE. */
152  delta: number
153  se: number
154  /** Qualifying closed weeks. */
155  weeks: number
156  /** A weekly-only M1 fit from 4 closed weeks on, for comparison only. */
157  weeklyFit?: ModelsFit
158}
159
160/** calibrateOmega on closed windows of one kind: ω and the windows that measured it. */
161export type ModelsSpread = { omega: number; windows: number; isAssumed: boolean }
162
163export type ModelsOmega = { title: string; M0: ModelsSpread; selected: ModelsSpread }
164
165/** New windows scored before each refit: d is the window's log score under the stored
166    weights less under M0; n records, their sum and its SE. */
167export type ModelsProspective = { title: string; n: number; sum: number; se: number }
168
169/** The meter-weight study, as seen from this machine: summaries only. */
170export type ModelsReport = {
171  type: 'models'
172  /** At least `needed` qualifying 5-hour windows; otherwise no fit, and M0 holds. */
173  isFitted: boolean
174  qualifying: number
175  needed: number
176  /** 5-hour windows of the current regime used, and those left out by reason. */
177  windows: { used: number; excluded: { reason: string; count: number }[] }
178  segments: number
179  excludedSegments: number
180  /** M0, M1 and M2, those that could be fitted. */
181  fits: ModelsFit[]
182  /** M1 against M0, then M2 against the model selected so far. */
183  comparisons: ModelsComparison[]
184  selected: MeterModel
185  rounding: 'round' | 'truncate' | 'union'
186  transfer: ModelsTransfer
187  /** Per window kind. */
188  omegas: ModelsOmega[]
189  /** Per window kind. */
190  prospective: ModelsProspective[]
191}
192
193/** A guide: its title, and its Markdown in sections that each fit one Markdown element. */
194export type GuideReport = {
195  type: 'guide'
196  title: string
197  sections: string[]
198}
199
200/** No reading stored yet: what the first run explains, and the command to run again. */
201export type WaitingReport = {
202  type: 'waiting'
203  command: string
204  /** The card offers to send the check message: no check is in flight in this session. */
205  canSend: boolean
206  /** Signed in without a subscription: no reading will ever arrive. */
207  isUnsubscribed?: boolean
208}
209
210declare module 'claude-code' {
211  interface PluginState {
212    'usage-dollars': {
213      reports: Record<string, UsageReport | SpendReport | CheckReport | CalibrationReport | ModelsReport | GuideReport | WaitingReport>
214    }
215  }
216}
217