Files
ai-kit/test
00b70757de feat(meter): read what is left at the vendor, off the call you already made (#47)
The obvious way to build a quota dashboard is to ask each provider how much is
left. That design is wrong, and it fails in the direction that hurts: it reports
a full tank during an outage.

Measured on one live key, within the same second:

  GET  /api/v1/key        →  limit_remaining: null,  usage_daily: 0
  POST /chat/completions  →  429, x-ratelimit-remaining: 0 of 50,
                             "Rate limit exceeded: free-models-per-day"

Both answers are OpenRouter's, about the same account, and the account was
locked out. The usage endpoint tracks money, free models cost nothing, and the
limit that actually binds is a REQUEST count that endpoint never reports.

So `complete()` now reads the rate-limit headers off every response and hands
them to `onQuota`. No extra request, no quota spent to discover how much quota
is left, and the number comes from the same exchange that either worked or did
not. It fires on 429s too, and those are the most valuable readings there are:
a refusal is the vendor correcting a local counter that had drifted optimistic.

Three refusals to guess, each a bug avoided rather than a feature declined:

- A vendor that sends no headers produces NO reading. Absent is a third state
  beside known and empty. Gemini sends nothing at all; inventing a zero there
  would invent an outage, and inventing a full tank repeats the bug above.
- The window is never guessed. `x-ratelimit-remaining-requests` counts a DAY at
  Groq and a MINUTE elsewhere, so it comes from a verified per-provider profile
  or from the header's own name, and is otherwise reported as unknown. A
  confident wrong window turns "900 requests left today" into "…this minute".
- A `size` 429 records nothing. That refusal means one prompt did not fit, not
  that the allowance is gone; recording it as empty would take a working vendor
  out of service for a day over a single oversized prompt.

Reset times arrive in three incompatible encodings and no vendor says which:
epoch milliseconds (OpenRouter), compound durations (Groq's "56m26.88s"), and
sub-second ones ("547ms"). They are told apart by magnitude, and anything
unparseable is null rather than a guess — a wrong reset tells the operator to
come back at the wrong hour.

`answersRemaining()` translates a token count into the unit a person thinks in.

The package still has no database: persisting is the app's job, which is why
this is a callback. A throwing sink cannot fail a good answer.

179 tests, up from 162.


Claude-Session: https://claude.ai/code/session_01CAfKwM1oUSA9tU9fgdhfdf

Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 12:52:50 -07:00
..