# Quota

_See the [README](../README.md) for what pi-keyrouter is and how to install it._

keyrouter reacts to a 429 by rotating. Quota is the other half: knowing *before* the next request
which credential still has room, so entries can be ordered, a spent one skipped, and a bar shown.
Ready-made configs per provider: [provider-recipes.md](provider-recipes.md).

- **Advisory only.** A reading never fails, blocks or delays a request. Probes are fire-and-forget
  and only affect the *next* decision, and a failed probe keeps the previous reading and reports why.
- **Free when you do not use it.** Without a `quota` block nothing is fetched, allocated or
  scheduled — exactly today's behaviour, where the 429 is the first news of a limit. The one module
  that can reach a provider (`quota-probe.ts`) is not even loaded, there are no timers, and freshness
  is checked at pi's own moments (turn end, session start, model select).
- **A bench, until its own reset.** A reading can take *its own* entry out of selection, and only on
  the allowance the pool's `quota` block marks as primary. The rules are spelled out below, because
  exclusion is the one place a reading changes what keyrouter is allowed to do.
- **Nothing is written back.** Readings and benches live in the session; the config is never edited.

## The exclusion policy

Exclusion is deliberately narrow. These are the rules the code implements, and nothing else benches:

- **Only the primary bucket.** A spent secondary window — the weekly allowance, say — never benches an
  entry whose primary allowance still has room.
- **Only a DECLARED primary.** When the config marks a `primary` and the snapshot holds no reading
  for that bucket, nothing is claimed and nothing is benched. The fallback to another bucket is for
  *display* only (the footer and the table fall back to the first bucket with a reading); enforcement
  never borrows it. A pool that declares no `primary` at all is the one case where the first bucket is
  consulted. A bucket carried over from an earlier reading by the merge still counts — the cap below
  is what keeps that honest.
- **The provider's own verdict counts, but only with a reset.** A true `exhausted` path benches the
  entry until the reset instant it reported. Without a reset instant nothing is benched: an entry
  excluded with no way back is worse than a 429.
- **`unlimited` never benches — and is never spent.** A provider that reports a spent-looking number
  beside its `unlimited` flag is taken at its word: the flag outranks every numeric signal, so such a
  bucket is never read as spent even when it also reports `usedPct: 100` (GitHub Copilot's
  `premium_interactions` shape, whose full percentage sits beside the flag). The percentage is still
  carried and shown — the provider did report it — but it can neither bench the entry nor make the
  footer call the bucket exhausted.
- **`limit: 0` is not exhaustion.** A zero limit means "no cap configured" (providers without a budget
  commonly send `0` or `null`), so a limit is a denominator, never a verdict. A *spent reading* is the
  only derived verdict: `usedPct` at 100, or `remaining` at or below 0, and only when that number is
  actually there.
- **The bench is capped at 15 minutes** (`EXHAUSTION_CAP_MS`). A provider reporting a weekly reset
  benches the entry for a quarter hour at most, so the next reading gets to disagree with it — and
  every bench expires on its own, so none ever has to be cleared by hand.
- **A bench is a preference, not a lock.** It removes the entry from selection; when every entry is
  benched, rotation falls back to the one that becomes available soonest rather than refusing to pick.

## Where the numbers come from

| `from` | What it costs | Where it works |
|---|---|---|
| `"headers"` | **Nothing.** The numbers ride on responses keyrouter already receives through `after_provider_response`. | Providers that echo their own limits: Anthropic subscription logins (`anthropic-ratelimit-unified-*`), any OpenAI-compatible API (`x-ratelimit-*`), anything reporting a remaining or limit header. |
| `"endpoint"` | **One request per TTL for the pool** (60s by default), sent with the credential of the entry in effect — plus one request per entry on a `quota-first` pool's first pass. | Providers with a usage URL: tokenharbor, OpenRouter, DeepSeek, GitHub Copilot, Codex, Gemini. |

Both may be declared, and the readings are **merged bucket by bucket**, not chosen between. A reading
updates only the buckets it actually reported; a bucket only the *other* source knows survives as it
was, keeping its own age and its own `source`. That is the whole point of reading both: the header map
is fresh but narrow (only the allowances the provider chooses to put in headers), while the endpoint
is complete but can be minutes old. So a pool with both keeps a live number for the window the headers
carry *and* the buckets only the endpoint can see. Each bucket therefore records where it came from,
and the `[headers]` / `[endpoint]` marker on a line means "what we learned most recently" — not "where
every number on this line came from".

**Cost.** `endpoint` is the only source that spends anything, and what it spends is now **1 request per
TTL for the pool**, not per entry. The old figure was N entries × (1 request / TTL): at the default 60s
TTL an 11-key pool made up to 11 requests a minute — 660 an hour — while that provider was in use, and
none while it was idle. Only the entry in effect is refreshed now, so an 11-entry `quota-first` pool
reads all 11 once (the initialisation below, which gives the ordering numbers to compare) and after
that one request a minute while it is in use: 11 + 60 in its first hour and 60 in each hour after,
instead of 660. A pool running any other strategy reads the entry in effect and nothing else, so it
costs that one request a minute from the start. An idle session reads nothing at all — there are no
timers, and a probe is only ever considered at pi's own moments. `/keyrouter quota --all` is the
on-demand full read: one request per entry, when you ask for it.

**What is read, and what ages.** Probing follows the provider in effect, and inside that pool the entry
in effect:

- only the pool of the provider **in effect** is probed at all — a pool that is serving no request has
  no use for a fresher number;
- within that pool only the entry **in effect** is refreshed, on the pool's TTL;
- a `quota-first` pool additionally reads each entry **once** while it has no reading. That is an
  initialisation, not a refresh: an ordering cannot rank an entry it has never read. After that pass a
  non-active entry is never re-read.

So a non-active entry's reading ages on purpose: ordering is as of the last time each entry was read,
not as of now. The worst case is bounded by the 429 path that has always existed — an entry promoted on
an old number can turn out emptier than the reading said, the request that proves it fails, and
keyrouter rotates off it and cools it down like any other rate limit. What you get for that trade is
the request not being made: a config with two providers spends the probe quota of the one you are
using, and a pool of eleven costs one request a minute rather than eleven. `/keyrouter quota --all` is
how you buy the full read back on demand.

**The TTL throttles attempts, not readings.** A probe that *fails* is retried on the same TTL, not on
the next turn or the next request, so a usage endpoint that is broken costs one request a minute
instead of one per turn. Nothing is polled: a probe is considered only at pi's own moments (turn end,
session start, model select), and `ttlMs: 0` — the one setting that means "ask every time" — is what
turns a failing endpoint back into a request at each of those moments. The moments are turn end,
session start, a provider switch, pinning an entry with `/keyrouter account`, and a strategy promotion
(`quota-first` moving to another entry refreshes the entry it just promoted) — each one a point where
you have either just chosen the pool or just finished using it, and never a timer. Note also which
reading counts as "already
have one": only an *endpoint* reading can cancel the endpoint probe. A fresh header reading never
does — headers keep arriving while a request is answered, so letting one veto the probe would mean a
`from: ["headers", "endpoint"]` pool never asks its endpoint at all.

## Configuring quota

`quota` sits on a provider, next to `strategy`:

| Field | Type | Default | Meaning |
|---|---|---|---|
| `from` | `"headers"` \| `"endpoint"` \| both | — | Which sources to read. Required. |
| `headers` | alias → header name | — | Required when `from` includes `headers`. Matched case-insensitively, so the config can name the header the way the provider documents it. Buckets then reference the *alias*: `"usedPct": "fiveHourUsed"`. |
| `endpoint` | object | — | Required when `from` includes `endpoint`. |
| `quotas` | bucket[] | — | The allowances. At least one. |
| `status` | template | adaptive (see below) | Footer template. Omitted, the default adapts to the primary bucket's shape. |
| `footer` | boolean | `false` | Render that line while this pool's provider is active. |

`endpoint`:

| Field | Default | Meaning |
|---|---|---|
| `url` | — | Full URL, required. Interpolates `{{env.NAME}}`, `{{key}}` and `{{credential.<path>}}`. |
| `method` | `"GET"` | `GET` or `POST`. |
| `authFrom` | `"key"` / `"oauth"` | Which credential to send: the entry's key, its OAuth access token, an env var (`"env"`, named by `authEnv`), or nothing (`"none"`). The default follows the pool kind, because sending the wrong one is a guaranteed 401. |
| `authHeader` | `"Authorization"` | Header the credential goes in. |
| `authPrefix` | `"Bearer "` | Prefix before the credential. `""` for a raw token, `"token "` for GitHub's scheme. |
| `headers` | — | Static headers, merged over the credential header. Values interpolate; this is where a provider's required version headers belong. |
| `body` | — | JSON body for a `POST`. Strings inside it may interpolate. |
| `timeoutMs` | `10000` | Hard cap on one attempt, so a hung provider cannot hold the slot. |
| `ttlMs` | `60000` | How long a reading stays fresh. Raising this is the cheapest way to cut cost. |

There is no field for *how much* of the pool a pass reads — `ttlMs` is about how often the entry in
effect is read again, not which entries are. A config that still carries the removed
`quota.endpoint.scope` loads, ignores it, and gets one warning naming it.

Each bucket:

| Field | Default | Meaning |
|---|---|---|
| `id` | — | Stable name, required. Referenced by `primary` and by templates. |
| `primary` | `false` | The bucket used for ordering, the footer and exhaustion checks. The first bucket wins when none is marked. |
| `kind` | `"window"` | `"window"`, `"balance"` or `"count"`. See below. |
| `unit` | `"percent"` / `"usd"` | `percent`, `ratio`, `requests`, `tokens`, `usd`, `credits`, `count`. Defaults to `percent`, or `usd` for a `balance`. |
| `used` / `limit` / `remaining` | — | Paths to the raw numbers. `limit` together with `used` or `remaining` derives a percentage; a single number is reported as an amount. |
| `usedPct` | — | Path to an already-computed percentage or ratio. Takes precedence over a derived one. |
| `resetAt` | — | Path to the instant the window refills. Ignored for a `balance`. |
| `resetFormat` | `"auto"` | `auto`, `iso`, `epochSec`, `epochMs`, `duration`, `date`. |
| `scale` | from `unit` | `ratio` (0-1, ×100 for display) or `percent` (0-100, clamped). |
| `unlimited` | — | Path that resolves truthy when the plan has no cap. |
| `exhausted` | — | Path that resolves truthy when the provider itself says the allowance is spent. |
| `pick` | — | For a path that resolves to an array: keep the element whose properties equal these values. |

**`kind` decides whether a reset exists.** A `window` refills, so its reset instant is meaningful to
order by. A `balance` — money or credits — only ever decreases: nothing refills, so `resetAt` is
ignored for it and no config can invent a reset the provider does not have. A `count` is a plain call
counter, such as a daily free-request allowance. `kind` is independent of `unit`: OpenRouter's budget
is a `window` in `usd`, DeepSeek's balance is a `balance` in `usd`.

**A `QuotaPath` is a string or a list of strings.** A list is tried in order, first hit wins — that is
how one bucket reads either source: `["five_hour.resets_at", "fiveHourReset"]`. A path that does not
resolve is a miss, never an error and never a zero, so a header map without the rate-limit headers —
or a bucket this plan does not have — produces no reading for that bucket rather than "0% used".
A `null` in the middle of a path is a miss too.

**`resetFormat`** is where the provider zoo collapses into one number. `"duration"` is the one that
surprises people: `6m0s` is a **delta** — "in six minutes" — so it is added to now instead of being
parsed as an instant. `auto` tries the formats most-specific-first: a number over `1e11` is epoch
milliseconds, anything smaller (or a string) is epoch seconds, and a bare date means local midnight
and is tried before ISO, so a day can never be mistaken for a timestamp.

**`pick`** narrows a path that resolves to an array down to one element, by property equality and
nothing else: `pick: { "currency": "USD" }` reads DeepSeek's USD balance. A value the array does not
contain is "no reading", not zero.

### Custom fields

A bucket key the loader does not read itself is **not a typo** — it is a display value read from the
provider's own document, carried along with the reading and rendered by name as `{{<bucketId>.<name>}}`,
or `{{primary.<name>}}` for the primary bucket. The recognised keys are `id`, `primary`, `kind`,
`unit`, `used`, `limit`, `remaining`, `usedPct`, `resetAt`, `resetFormat`, `scale`, `unlimited`,
`exhausted` and `pick`; every other key is a custom field. That is the whole boundary — there is no
list of allowed field names, and nothing between the declaration and the token is provider-aware. So a
bucket that reports a request counter and a model list beside its percentage shows both, without a new
built-in token existing for either:

```jsonc
{ "id": "free", "primary": true, "usedPct": "used_pct", "resetAt": "reset_at", "exhausted": "exhausted",
  "requests": "req_used", "models": "models" }
```

Here `{{free.requests}}` and `{{free.models}}` — or `{{primary.requests}}`, since `free` is primary —
print the request count and the model list from the endpoint's own answer. The loader never learns the
words `requests` or `models`: it knows only which keys it reads itself, and every other key is a path.

A custom field's path follows the same grammar as a metric's (one string, or a list tried in order),
and the same rule covers a miss: a path the provider does not report leaves the token absent, not zero.
But a custom field is display only — nothing orders, benches or merges by it, and it can never turn a
bucket that read nothing into a reading.

Thirteen names can never be custom fields, for the same reason: a token has to mean exactly one
thing, and with a `usedPct` field allowed `{{primary.usedPct}}` would be a metric on one pool and a
provider number on another, and neither you nor the ordering code could tell which it was.

Ten of them — `usedPct`, `used`, `limit`, `remaining`, `resetAt`, `id`, `unit`, `kind`, `exhausted`,
`unlimited` — are not refused because they are *bucket keys the loader reads itself*: writing one sets
that METRIC, exactly as it does with no custom field in play (`"remaining": "req_left"` changes
`remaining`, it does not create a field). The remaining three, `bar`, `resetIn` and `count`, exist only
as tokens, so declaring one is ignored with a warning and the built-in wins.
lesser refusals cost one field each, never the pool: a value that is not a path (a number or an object
where a string belongs) and a key with an empty name are both ignored with a warning.

Values render the way a status line can print them: a string or a boolean verbatim, an integer as it
is, a fraction rounded to two decimals, and an array joined with `, `, keeping the scalar elements it
has. An object, a `null` or a non-finite number is **dropped** rather than stringified, so no template
can dump raw JSON into the footer, and an array that held nothing printable at all is a miss, not an
empty list. A missing path leaves the token absent rather than printing a zero or an empty value.

## The `quota-first` strategy

Set `strategy: "quota-first"` on a pool with a `quota` block — the Anthropic endpoint recipe in
[provider-recipes.md](provider-recipes.md) is exactly this shape. It serves each turn from the
available entry whose allowance is most urgent to spend, because an allowance about to reset is about
to be discarded: spending it first wastes nothing, while the entry that just reset keeps a whole
window in reserve. Round-robin spreads evenly and lets everyone expire at 60%.

It is not `stalest-first`, though both pick something soonest: that one orders by OAuth token expiry
(a credential fact, about keeping logins refreshed), this one by the provider's own usage reset (a
billing fact, about spending an allowance).

- **Windows** rank by `resetAt` ascending. Equal resets drain the *fuller* window first — of two
  expiring together, the one with more left loses more if skipped. A window that reads as spent does
  not rank in front, however soon it resets.
- **Balances** never refill, so "soonest reset" says nothing about them: they rank by `remaining`
  descending, and behind every window that still has room, since a window's remainder expires and a
  balance's does not.
- **`/keyrouter quota` uses this order, whatever the strategy.** Whenever at least two rows carry a
  reading the comparison can rank, the table is sorted best-first — soonest-resetting window first,
  then windows by fullness, then balances by `remaining` descending, then anything spent or
  unrankable, then entries with no reading. It uses the same comparison the picker selects with, so
  the top row is the entry the strategy *prefers* among the ones it can rank. Below two rankable
  readings there is no order to show and the pool's own JSON order is kept, which is the order
  `failover` rotates in.

  It is a ranking, not a prediction. The table cannot see whether an entry is on cooldown, overloaded,
  leased by another process, or quota-benched, and on a tie it keeps pool order where the picker
  advances past the current entry — so the first row can still be an entry the next turn would skip or
  leave. Read it as "these are the entries, best-first on what the provider reported". And because a
  row's place is a preference order rather than a position, it no longer lines up with the numbered
  `/keyrouter account <index>` operands, which still count entries in config order; the `▶` marks the
  entry in effect.
- **Requirements.** A `quota` block. The strategy reads each entry once while it has no reading, so the
  first pass gives it something to compare; after that an entry still without a reading sorts last, and
  a pool with nothing rankable at all behaves as `round-robin`.
- **Degradation.** No reading, or a failed probe, changes nothing: ordering only ever sorts an entry
  later, it never excludes one. An entry with no reading is picked as `round-robin` would pick it — and
  an *aged* reading is still a reading, so it still orders until that entry is read again.

## `/keyrouter quota`, and the footer

```
/keyrouter quota                one line per entry, for every pool that declares quota
/keyrouter quota anthropic      just that pool
/keyrouter quota --all          probe every entry now instead of using the cached reading
```

Plain `quota` is read-only: it rotates nothing, installs nothing and probes nothing. `--all` awaits a
fresh sweep — one request per entry — for when you want to trust an ordering decision rather than a
cached number. An entry with no reading yet is reported, with that hint:

```
  cached readings only — /keyrouter quota --all fetches fresh ones.
```

```
▶ personal █████████░░░░░  62%  seven_day 41%  resets in 3h12m  [endpoint]
  work     ██░░░░░░░░░░░░  14%  resets in 6d4h  [endpoint]
  backup   ██████░░░░░░░░  41%  resets in 2d3h  [endpoint]
  spare    ERR: HTTP 401
```

`▶` marks the active entry, as in `/keyrouter status`. Rows are listed best-first by reset time
whenever at least two of them carry a reading that can be ranked, and in the pool's own order below
that — the rules and what the order does and does not mean are under
[`quota-first`](#the-quota-first-strategy) above. Other buckets follow the primary reading, and
`[headers]` or `[endpoint]` says which source produced it (the most recent one, for a merged reading).
A cached row is shown exactly as it was read, with no age marker: after the first pass only the entry
in effect is kept current, so a non-active row can be hours old, and that number is what the ordering
ranks on until something promotes the entry. `--all` is how every row is made current at once. A failed
probe prints its reason instead of an empty row; the footer follows the same rule, showing no line
rather than a line of zeroes.

`footer: true` keeps a status line visible while that pool's provider is active, rendered from
`status` — a closed set of tokens, no expressions and no conditionals:

| Token | Renders |
|---|---|
| `{{primary.usedPct}}` | used percentage, rounded |
| `{{primary.bar}}` | a 14-cell progress bar |
| `{{primary.remaining}}`, `{{primary.limit}}`, `{{primary.used}}` | an amount with its unit (`$12.40`, `38`) |
| `{{primary.resetIn}}` | a countdown (`3h12m`, `45m`, `now`) |
| `{{primary.resetAt}}` | the reset instant, locally formatted |
| `{{primary.id}}`, `{{primary.unit}}`, `{{primary.kind}}` | which bucket this is |
| `{{primary.exhausted}}`, `{{primary.unlimited}}` | a note when the provider says so |
| `{{<bucketId>.<field>}}` | any bucket by id, e.g. `{{seven_day.resetIn}}` |
| `{{<bucketId>.<name>}}` | a [custom field](#custom-fields) the bucket declared, e.g. `{{primary.requests}}` |
| `{{count}}` | how many buckets produced a reading |

An unknown token renders as an empty string, and a template that renders nothing clears the line.

**A segment that renders nothing is dropped whole.** The template is split on `·`, and a segment left
empty is removed together with its separator — so `a · {{primary.requests}} · b` reads `a · b` when the
bucket declares no `requests`, never `a ·  · b`. That is why an optional token should be its own
segment, and why wrapping one in literals does **not** make it vanish: `({{primary.requests}})` renders
`()` when the field is missing, because the parentheses are the segment.

With no `status`, the default adapts to the shape of the primary bucket:

- A bucket that reports a percentage —
  `{{primary.bar}} {{primary.usedPct}}% · {{primary.requests}} · {{primary.resetIn}} · {{primary.exhausted}}`.
- A bucket that reports only `remaining` — a plain balance, or a provider with no cap —
  `{{primary.bar}} {{primary.remaining}} left · {{primary.resetIn}} · {{primary.exhausted}}`, because
  there is no percentage to show and `%` would dangle.

`exhausted` sits in a segment of its own in both shapes, and `requests` does too in the
percentage shape — the `remaining`-only default has no request token at all, so a balance pool never
shows one. A pool that declares no
`requests` field, or a bucket the provider does not call exhausted, loses that segment and nothing
else: the line gets shorter, it never breaks. An explicit `status` is never swapped for the adaptive
default: the tokens you wrote are the tokens rendered.

## Known limitations

The design is declarative on purpose — a bucket is a path into a JSON document plus a closed set of
enums, and nothing here executes code, so an undocumented endpoint is fixed by editing JSON. These are
the boundaries of that design, not defects: each one is a shape it cannot express, and knowing where
they are is how you avoid a config that silently reads nothing.

- **No inversion, and no arithmetic.** A provider that reports only a remaining *fraction* — Gemini's
  `buckets[].remainingFraction` — cannot be turned into a percentage. `scale` converts a number the
  provider already computed, and a percentage is derived from `used` + `limit` or `limit` +
  `remaining`, but a lone fraction carries no inverted cap to compute one from.
- **A `limit` cannot be a literal constant.** Every field is a path into the document, so the trick
  that would make that fraction usable — "pretend the cap is `1`" — has nowhere to be written.
- **`pick` requires an exact match.** There is no "whichever element is present" form, so
  `pick: { currency: "USD" }` against an account holding only CNY yields no reading rather than falling
  back to the currency that exists. Leave `pick` out when the array holds a single element.
- **`{{key}}` inside `endpoint.url` is accepted with no warning.** It is the author's choice, and
  keyrouter itself never logs the URL — the trace and the notifications carry status codes and
  provider ids, and a probe failure reports its status or the transport's own wording — but it places a
  credential where the headers are, and a URL is far likelier than a header value to end up in a log or
  on a screen.
- **An unbalanced `{{` is passed through literally**, in the footer template and in interpolated
  values alike. There is no escaping rule and no warning: `{{` with no matching `}}` is just text.
