Files
ai-agent/docs/usage-calibration.md
gabrielvidalandClaude Opus 5.5 bb3f49d80d feat(plugins): usage.read / usage.calibrate bridges; Plan usage moves to the plan-usage plugin
- backend: plugins/usagedata.py + hub/usage/overview and hub/usage/calibrate
  (owner-only, operator-approved caps); usage/ and /api/usage/* stay core.
- frontend: drop PlanUsage.tsx + planViz.tsx (ArcGauge moved to its own file
  for Home's strip), their hooks/fetchers, viz Columns, unused billing/planUsage
  helpers; /dashboards/plan redirects to /plugins/plan-usage/board (else
  /dashboards); nav/drawer/telemetry entries updated.
- docs: plugins.md, usage-calibration.md, CLAUDE.md; openapi + orval regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:28:27 +01:00

327 lines
19 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# What 1 % of a Claude plan window is worth
Claude Code's `/usage` shows how full the subscription's windows are (rolling
5 h, 7-day week), as whole percentages. The transcripts show what was spent, in
tokens. `scripts/usage-calibration.py` lines the two up and fits the exchange
rate, so a dollar figure on the dashboard can be read as "% of my week", and
the plan's ceiling can be expressed in tokens.
```bash
uv run scripts/usage-calibration.py # personal seat, last 9 days
uv run scripts/usage-calibration.py --since 2026-09-13 --json /tmp/cal.json
uv run scripts/usage-calibration.py --account work --prefix sensor.claude_work_usage
```
## Inputs
- **Usage %**: Home Assistant long-term statistics (hourly min/max) of the
sensors that the homelab's `claude-usage-notifier` pushes (`<prefix>_5h`,
`_week`, `_fable`). The script reads the recorder SQLite db read-only, so it
goes back to the sensors' creation, beyond the 10-day state history.
- **Tokens**: the account's conversations listed by `/api/conversations?account=`
(the backend resolves each conversation's account), parsed from the archive,
subagents included. Records are de-duplicated on (message id, request id) and
priced at **list price** (the script's own table; see "Pricing" below).
## Method
The data is binned by hour. A window's % only rises between resets, so each
bin's increase is the usage spent in it. Bins that contain a reset are dropped,
and so are 5 h bins above 100 % (overage). The fit is `Δ% = k·cost + c`, by
non-negative least squares. `c` soaks up usage the archive can't see
(claude.ai, the desktop app, a Mac that isn't paired as a worker). It came out
at ≈ 0 once both Macs were paired.
Unweighted list-price dollars leave a drift. Through a Fable-heavy week the
cumulative $/% climbed from $13.5 to $20 as the mix moved to Opus. A **Fable
multiplier** removes it. It is chosen by grid search on the combined R² of the
5 h and week fits, and with it the cumulative ratio stays flat at $21–23/%.
Other weightings were tested and lost: cache reads free, cache reads at 0.1×
input, cache reads at 1× input, Opus 5.5 priced as Opus 5, and raw token
counts.
Use 1 h bins. With 3 h bins most 5 h resets fall inside a bin, which then gets
dropped, and the 5 h fit collapses.
## Calibration — personal Max plan (€200/month), 2026-10-12
Window: 2026-10-04 18:00 → 2026-10-12 (Opus 5.5 / Fable 5.1 era), 1 h bins.
Intervals are 90 % CIs from a 300-draw day-block bootstrap.
| | API $ at list price | tokens at the real Opus 5.5 mix¹ |
|---|---|---|
| 1 % of the **5 h** window | **$5.6** [5.4–6.8] | ≈ 17 Mtok |
| 1 % of the **week** | **$22.1** [21.1–24.6] | ≈ 68 Mtok |
| Fable multiplier | **×1.75** [1.6–2.5]: 1 % week ≈ $13 of Fable 5.1 | ≈ 14 Mtok of Fable¹ |
| full 5 h window | ≈ $560 ≈ 25 % of a week | |
| full week | ≈ $2,200 | ≈ 6.8 Gtok |
| 100 % of every week for a month (×4.35) | ≈ $9,600 (≈ $5,700 if all Fable) | ≈ 30 Gtok |
¹ Agentic Claude Code traffic is 98 % cache reads by tokens. On Opus 5.5 they
are about 61 % of the dollars, cache writes 32 % and output 8 %. The same 1 % of
the week buys ≈ 1.1 M Opus 5.5 output tokens, or 5.5 M fresh input, or 110 M
cache reads.
- **No separate Fable bucket.** The `seven_day_<model>` key never appeared in
the status line's `rate_limits` from 2026-07-17 to 2026-10-12, despite heavy
Fable 5 and Fable 5.1 use. Fable draws on the same 5 h and week windows, about
1.75× faster per list-price dollar than Opus 5.5.
- **The week binds, not the 5 h window.** A full 5 h window is ≈ 25 % of the
week, and a week has 33.6 of them.
- **Earlier eras differ.** In Jul–Aug (Opus 4.8 / Opus 5 / Fable 5), unweighted
fits gave ≈ $30 per 1 % of the week. Limits and prices move with model
launches, so re-run the script after one.
## Plan units: what the limits actually count
Re-fitting the whole history (Jul → Oct 2026) per model version shows the
*token* allowance never moved — only its list-price value did. When every new
model is metered **at its predecessor's price** (Opus 5.5 as Opus 5, Fable 5.1
as Fable 5, Sonnet 5.5 as Sonnet 5, Haiku 5.5 as Haiku 4.5) and Fable/Mythos
tokens weigh **×1.75**, one constant explains July, August and October alike:
≈ 42–52 *plan units* per 1 % of the personal week, ≈ 8–12 per 1 % of 5 h. That
is `pricing.plan_units`. Effort changes how many tokens a turn spends, not the
rate (the per-effort fits all overlap). The work seat meters the same way with
smaller buckets: ≈ 24 units per 1 % of its week (½ the personal), ≈ 4 per 1 %
of its 5 h (⅓).
| version | used | list $ per 1 % week | list $ per 1 % 5h | Mtok per 1 % week |
|---|---|---|---|---|
| Opus 4.8 | Jul | 35 | 6.8 | 46 |
| Opus 5 | Jul–Oct | 42 | 9.1 | 59 |
| Opus 5.5 | Sep → | 22 | 5.6 | 69 |
| Fable 5 | Jul–Aug | 26 | 5.2 | 16 |
| Fable 5.1 | Sep → | 14 | 3.6 | 16 |
| Sonnet 5 | Jul–Oct | 36 | 6.9 | 123 |
## In the app (since 2026-10-12)
- **Exact prices.** Each provider plugin keeps a per-version price book (its
`pricing.models`, read through `conversations/pricing.py`; the newest
`bookDate` is stamped on every summary as `priceBook`):
each model's own cache-read rate, 5 m / 1 h cache writes, fast mode ×2, Haiku
5.5's >100K-prompt tier. Unknown ids price as the newest of their family.
- **One usage per API call.** Claude Code writes an assistant message as one
record per content block, each repeating the call's full `usage`; the parser
used to sum them all (tokens ≈ 1.93× too high). It now prices a call once,
keyed on (message id, request id), and re-homes that charge onto the tool the
call drove. With the old family prices on top, the dashboard used to read
≈ 3.7× list price.
- **Per conversation**: `planUnits`, `planPct` (`{week, h5}` — the units over
the account's calibration in force), `byModel` (per model id: turns, tokens,
list $, plan units, usage, and the same per `--effort` level), `meterBins`
(epoch hour → [list $, plan units]), `fastCalls`.
- **The official % is recorded by the backend** (`backend/usage/`): every change
of each account's `rate-limits.json` (mounted read-only from
`~/.claude{,-work}/usage-state`, `USAGE_STATE_DIRS`), plus a 30 min
heartbeat, kept forever in `usage_limits`. History before that came from HA:
`scripts/usage-backfill-ha.py` posts HA's hourly statistics to
`/api/usage/import` (idempotent).
- **Daily recalibration** (`usage/calibrate.py`): `Δ% = units/k + c` over the
last 14 days, hourly; a fit becomes the rate in force only when it is
*trusted* (≥ 24 busy hours, R² ≥ 0.5, within ×3 of the seed rate — usage on an
unpaired machine in the same hours as lab work fits cleanly at a rate 10×
off). A trusted move of more than 20 % pushes a notification (a model launch
or a limits change). `POST /api/usage/calibrate {"backfill": true}` adds the
weekly fits over the whole history (the *$ per 1 % over time* chart).
- **Untracked usage**: per day, the observed rise minus what the archived spend
predicts — claude.ai, the desktop app, a machine that isn't paired.
- **Where it shows**: the conversation card chip (`≈0.4% wk`), the Details
drawer's *Plan usage* card (per-model / per-effort table), the Conversations
dashboard (spend by model version, $ per 1 % over time), the *Plan usage*
dashboard (the `plan-usage` live plugin, `/plugins/plan-usage/board` —
`/dashboards/plan` redirects there: gauges, history, observed vs predicted,
calibration, recalibrate), and the notifications: the notify CLI's own
`Claude Code · $x · N tokens · 8m` line is restated by the hub with the run's
exact list price (subagents included), and a `--final` push adds the plan
share (`Claude Code · $35.46 · ≈1.5% wk · 76.3M tokens · 2h 3m`).
`scripts/usage-calibration.py` stays as the offline cross-check (pandas/scipy,
per-version fits, bootstrap).
## One calibration per plan (since 2026-10-31)
The % per plan unit belongs to a **plan**, not to an account: a tier change
(Max 5× → Max 20× holds 4× the units per 1 %) or a change of the limit windows
(the personal Max lost its 5-hour window on 2026-10-31 at 04:40 UTC) makes the
old rate wrong. So the backend tracks the plan itself (`usage/plans.py`):
- **What it reads.** The tier comes from the login: the sidecar's `/accounts`
row carries `plan` (`claude_accounts._plan_info`: `userRateLimitTier` /
`organizationRateLimitTier` and `planDisplayName` from the CLI's cached
profile in `.claude.json`, `rateLimitTier` from `.credentials.json` as the
fallback — never a token). The windows are the ones the account's fresh
`rate-limits.json` reports. Both are read after every usage poll
(`service.track_plans`).
- **Segments.** `usage_plans` holds one row per plan the account has been on.
A change must hold `CONFIRM_S` (1 h) and is dated from when it was first seen;
an unknown reading (sidecar down, stale snapshot) never changes anything.
The first reading backfills the past as one `assumed` segment from the first
recorded % point on the current tier, split where a window it no longer
reports went quiet. `POST /api/usage/plans` corrects the history by hand
(`{account, since, tier?, windows?}` or `{…, delete: true}`).
- **Fitted independently.** `calibrate.fit` never reaches before the start of
the segment in force; a fit is stamped with its `plan`. Fits from before the
tracking belong to the segment their data window began in. A segment's rate
is its own latest trusted fit; until it has one (≥ 24 busy hours), its seed
is the previous segment's last trusted fit (`carried`) × the tiers'
multipliers (`scaled`, Max N× = N × Pro) — or the account's `DEFAULTS`,
stamped with the tier they were measured on. A move between segments is not
a "rate shift": the plan change pushes its own notification
(`📏 Personal plan: Max 5× → Max 20×`; `USAGE_NOTIFY_PLAN_CHANGE=0` mutes it).
- **Where it shows.** `/api/usage/limits` → `plan`, `/api/usage/history` →
`plans`, `/api/accounts` → `planWindows` (the live plan's), `planLabel`,
`planTier`. The Plan usage dashboard has a *Which plan* panel (segments, each
with its own rate). Settings → Claude accounts → *Plan* follows the tier
(`lib/planFollow`): the first sight only fills an unset plan; a later tier
change moves the plan, scales the monthly price by the list prices (keeps
your currency and VAT) and files the old plan in `pastPlans`, so *paid so
far* charges each period its own price.
## What is left of the week (`ai-agent budget`, since 2026-11-01)
`GET /api/usage/budget?account=` (`backend/usage/budget.py`) turns the rate in
force into a forecast for the rest of the week:
- **left** = (100 − week %) × units per 1 %;
- **due** before the reset: every enabled cron job billing that account (its
last run's account, else its worker's, else its frontmatter's), times its
firings until the reset, at the median of its last 8 runs; plus each
*Send later* conversation due before it, at the median single-prompt run of
its model family;
- **free** = left − due, also in list $ and in tokens per family (the family's
own tokens per plan unit over the last 14 days: on the personal seat in
2026-10, 1 % ≈ 86 Mtok of Opus 5.5, 19 Mtok of Fable 5.1, 146 Mtok of
Sonnet 5.5);
- **pace**: the week % rise over the last 6 h (else 24 h) projected to the
reset, against the pace that uses every free % by then; **streams** = how
many nonstop runs of a family that is (a family's units per hour = the
median of its single-prompt runs of ≥ 20 min — Opus 5.5 xhigh ≈ 33 u/h,
i.e. ≈ 0.6 % of the week per hour).
The cron agents themselves are noise on that scale: radar, mail-secretary,
lab-digest and co. cost ≈ 0.2–0.7 units a run, 0.14 % of the week together.
`ai-agent budget [--account A] [--json]` prints it; the homelab's `week-burn`
agent reads it to keep just enough runs going near the end of a week.
## The billing cycle (since 2026-11-14)
Anthropic's API has no next-charge date: `/api/oauth/profile` (and the CLI's
cached copy, `.claude.json` → `oauthAccount`) carries only
`subscriptionCreatedAt` — `2026-03-09T13:43:40Z` for the personal Max — plus
`billingType: stripe_subscription` and `subscription_status`.
`backend/usage/billing.py` takes the monthly Stripe renewal on that day and
time (the month's last day when shorter), so the date is an **estimate** — an
upgrade that reset the billing day or an annual plan would move it; claude.ai →
Settings → Billing is authoritative. The sidecar already passes the date in
`/accounts` → `plan`; the plan tracker stores it with each segment (the
fallback when no live row is in).
`/api/usage/limits` → `billing` (Claude accounts in the totals only — the work
seat's bill is Orus's): `nextBillingAt`, `periodStart`, `previousPeriodStart`,
and each `seven_day` window ending in this cycle or the previous one with its
peak %. Shown as the **Billing cycle** panel on Plan usage — the weeks' peaks
against where Pro / Max 5× caps sit on this plan's scale (Max 5× = 25 % of a
Max 20× week), i.e. whether a smaller plan would have held them — and a
**Renews** tile on the home strip (hold to bench it). Asked by Gabriel while
weighing a downgrade; his Oct–Nov weeks peaked 64–100 % of Max 20×.
## The ChatGPT seat (opencode harness, since 2026-10-18)
The Orus ChatGPT Enterprise seat (`chatgpt-work`) has a **weekly window only**.
opencode never reads it, so the sidecar hosting the account reads ChatGPT's
own usage endpoint (`wham/usage`, what Codex CLI's `/status` shows) every
5 minutes and writes the same `rate-limits.json`; the hub records it like a
Claude seat (from the worker's `/opencode/usage` when the account lives on a
worker). Its plan units are plain GPT list $ (`pricing.plan_units`) and only the
week is fitted (`calibrate.windows`); the seed is a guess (1 % ≈ $5 of list
price) until the first trusted fit. A push fires once per crossing of 95 %
(`limitAlerts`).
## The week target (since 2026-11-06)
The personal Max is meant to be **maxed out every week**. Its account
declares `weekTarget: {goal: 100, behindAlert: 20}` (`backend/accounts`),
served on `/api/usage/limits` as `weekTarget`. The target is a straight line,
0 % when the week opens (7 days before `resets_at`) to `goal` % at the reset
(`usage/target.py`, mirrored by `frontend/src/lib/weekTarget.ts`):
- the home usage strip's week gauge carries a **tick** at the target and a
`target N%` line under the reset countdown (no ahead/behind figure);
- the poller pushes **🎯 Personal week behind its target** once each time the
week falls more than 20 points under the line — where it is, where the line
is, and how many nonstop Opus runs would still use the rest (`budget`'s
streams). Catching up re-arms it; the heartbeat points (every 30 min) are
what catch an idle week drifting behind.
## How fresh the % is (checked 2026-11-09)
Anthropic reports **whole percentages** everywhere: the status line's
`rate_limits`, the `anthropic-ratelimit-unified-*-utilization` reply headers and
`GET /api/oauth/usage` all give integers (`usage_limits` has never held a
fractional point). The figure itself is current on every API reply. What
lags is the lab's copy of it, `<config dir>/usage-state/rate-limits.json`,
which is rewritten:
- on every status-line render of an **interactive** Claude Code terminal on
the lab, i.e. every turn;
- every **10 minutes** by the host cron's `refresh-rate-limits.sh` (one line
per account; it boots a throwaway `claude`, no model turn, no tokens);
- for worker runs, on every reply the Claude proxy streams (`observe`).
Hub-launched headless runs render no status line, so they never refresh it.
The hub reads the file every 20 s (`POLL_S`) and stores a point when it moves,
plus a 30 min heartbeat; `claude-usage-notifier` pushes it to HA every 15 s;
both flag a snapshot older than 30 min as stale. With no terminal open the
lag is therefore ≤ 10 min.
Over 2026-10-26 → 11-09 the personal week rose **1 point at a time** (157 of
161 rises), one rise every ~70 min (median; p10 15 min, p90 5 h): at ≈ $31–37
of list price per point, spending is what sets the pace. The work seat's 5 h
window (≈ $2.3 per point) rose every 10 min, often by 2–6 points at once. That
is the cron cadence showing. A sub-minute feed would have to poll
`/api/oauth/usage` (see the sidecar's `claude_usage.py`) instead of the cron.
## Sonnet vs Opus (re-checked 2026-11-09)
**Prices first.** Sonnet 5.5 is half of Opus 5.5 on every token type: $2 /
$10 input / output, $2.50 / $4 cache writes (5 min / 1 h) and **$0.10 cache
reads**, against Opus 5.5's $4 / $20, $5 / $8 and $0.20. Both models' cache
reads are 0.05× input (Anthropic's pricing page and models.dev agree). Until
price book `2026-11-09` (parser v43) the hub priced Sonnet 5.5 cache reads at
Sonnet 5's $0.20. Sonnet traffic is 95 % cache reads by tokens, so its dollars
read ≈ 1.4–1.6× too high: $197 for $123 on the personal seat over these
40 days, $39 for $28 on the work seat.
Per-family fit of the recorded % against each family's list $ (correct
prices) over the last 40 days (`Δ% = Σ k_f·$_f + c`, NNLS), plus a scan of the
Sonnet weight with Opus = 1 and Fable = 2.1. Eight datasets: personal week
before and after 10-31 (6 h and 24 h bins), the work 5 h window (1 h and 2 h
bins) and the work week (6 h and 24 h bins).
- **Per list-price dollar, Sonnet weighs ≈ ×1.5–2 what Opus does.** Only the
work 5 h window resolves it: ≈ 1 % per $2.3 there, with Sonnet worth about
10–20 points of it. Its hourly fit bottoms at ×2. ×1 is ≈ 2 σ worse and ×0
(free) far worse. The free fits give ×2.1 (work 5 h, 1 h bins), ×2.4 (2 h
bins) and ×1.5 (personal October, 6 h). The week datasets are flat between
×0 and ×3: at ≈ $33 per point, $123 of Sonnet is too little to move them.
Treat it as a rough answer.
- **So a Sonnet 5.5 token weighs about what an Opus 5.5 token does**, though
it lists at half. Measured mixes: Opus 3.0 M tokens per list $, Sonnet
4.3 M. Sonnet's runs are shorter, with more cache writes and output per
token. At ≈ $33 per 1 % of the personal week that is **≈ 100 Mtok of Opus
5.5 against ≈ 70–95 Mtok of Sonnet 5.5**, and ≈ 17 Mtok of Fable 5.1
(×2.1). Switching a long agentic run from Opus to Sonnet does not stretch
the week; the plan seems to meter Sonnet 5.5 well above its list price
(Sonnet 5's $0.20 cache reads alone would make it ×1.6).
- `pricing.plan_units` meters Opus 5.5 at Opus 5's prices (≈ ×1.9 its list $
at the agentic mix) and Sonnet 5.5 at Sonnet 5's (≈ ×1.6 at its mix). That
is Sonnet ≈ ×0.85 of Opus per list $, about half what the data shows. So
`ai-agent budget`'s ≈ 158 Mtok of Sonnet per 1 % is ≈ 2× too generous:
70–95 Mtok is nearer.
- **A Fable-scoped weekly limit exists now.** `GET /api/oauth/usage` lists a
`weekly_scoped` limit for Fable (`allowance_percent_of_weekly: 50`, inactive
at 0 %) on both seats: Fable draws on the shared week, which it may fill
only halfway. `seven_day_opus` and `seven_day_sonnet` are `null`: Opus and
Sonnet have no bucket of their own and share the one week.