# Quota provider recipes

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

Worked `quota` configurations, one per provider, with the trap each one hides. The field reference
and the cost model are in [quota.md](quota.md).

## tokenharbor — one request, two buckets

The free-model allowance and the Pass allowance are measured separately but share one 7-day window,
so both buckets read the same `reset_at`.

```jsonc
{
  "providers": [{
    "name": "tokenharbor",
    "keys": [
      { "name": "primary", "value": "$TOKENHARBOR_API_KEY" },
      { "name": "backup",  "value": "$TOKENHARBOR_API_KEY_BACKUP" }
    ],
    "quota": {
      "from": "endpoint",
      "endpoint": { "url": "https://tokenharbor.ai/api/cli/free-tier" },
      "quotas": [
        { "id": "free", "primary": true, "unit": "percent",
          "usedPct": "used_pct", "resetAt": "reset_at", "exhausted": "exhausted" },
        { "id": "pass", "unit": "percent",
          "usedPct": "plan_used_pct", "resetAt": "reset_at", "exhausted": "plan_exhausted" }
      ],
      "status": "{{free.bar}} free {{free.usedPct}}% · pass {{pass.usedPct}}% · {{free.resetIn}}",
      "footer": true
    }
  }]
}
```

`used_pct` and `plan_used_pct` are whole-number percentages, so `unit` is `percent` and no `scale`
is needed; the endpoint reports percentages and never amounts, so a bar is the honest rendering.
`exhausted` and `plan_exhausted` are the provider's own verdicts — the percentage hitting 100 and
the flag turning true do not always happen on the same request. Nothing here sets `kind` because
both buckets are windows, which is the default.

The endpoint is read-only, costs nothing, counts against no rate limit, and its answer may be
cached for 15 seconds, so the default 60-second TTL already asks four times less often than the data
changes. `reset_at` is `null` until the first `:free` request opens the window; that reads as "no
reset instant yet" rather than as a failure.

## Anthropic (OAuth) — the endpoint

The subscription usage endpoint reports the same 5-hour and weekly windows the plan pages show.

```jsonc
{
  "providers": [{
    "name": "anthropic",
    "accounts": [
      { "name": "personal", "credential": "@~/.pi/accounts/anthropic-personal.json" }
    ],
    "strategy": "quota-first",
    "quota": {
      "from": "endpoint",
      "endpoint": {
        "url": "https://api.anthropic.com/api/oauth/usage",
        "authFrom": "oauth",
        "headers": {
          "anthropic-version": "2023-06-01",
          // Required. Without it the endpoint answers 401
          // "OAuth authentication is currently not supported".
          "anthropic-beta": "oauth-2025-04-20",
          "Accept": "application/json"
        }
      },
      "quotas": [
        { "id": "five_hour", "primary": true, "unit": "percent",
          "usedPct": "five_hour.utilization", "resetAt": "five_hour.resets_at" },
        { "id": "seven_day", "unit": "percent",
          "usedPct": "seven_day.utilization", "resetAt": "seven_day.resets_at" }
      ]
    }
  }]
}
```

`utilization` is a 0-100 percentage (`8.0` means 8% used), so `unit` is `percent` and there is no
`scale`. Only OAuth logins can call this: a workspace API key gets 401 here, and the token keyrouter
sends is the pool entry's own access token — for an account captured from Claude Code's login, the
same token Claude Code keeps in `~/.claude/.credentials.json` under `claudeAiOauth.accessToken`. The
`anthropic-beta` header above is required, not decoration: without it the endpoint answers 401
"OAuth authentication is currently not supported".

The per-model weekly buckets (`seven_day_opus`, `seven_day_sonnet`) come back `null` on plans that
do not have them. A `null` bucket produces no reading, which is exactly why a config may declare a
bucket that some plans never populate: the reading is simply absent until the plan grows one.

One caution about this endpoint. It is the endpoint Claude Code itself uses, and community clients cache
it for minutes rather than seconds, so a pool of logins should not be asking it often. A `quota-first`
pool reads every account once at session start — that one-time pass is what gives the ordering numbers
to compare — and only the entry in effect after that, so the steady cost is one request a minute. The
initialisation still spends one request per account, which is why `ttlMs` (300000 is a common choice)
is worth raising once a pool has more than a couple of logins.

## Anthropic (OAuth) — the headers, for free

Subscriptions already send their own usage headers on every response, so the same window costs
nothing at all:

```jsonc
{
  "providers": [{
    "name": "anthropic",
    "accounts": [
      { "name": "personal", "credential": "@~/.pi/accounts/anthropic-personal.json" }
    ],
    "quota": {
      "from": "headers",
      "headers": {
        "fiveHourUsed": "anthropic-ratelimit-unified-5h-utilization",
        "fiveHourReset": "anthropic-ratelimit-unified-5h-reset"
      },
      "quotas": [
        { "id": "five_hour", "primary": true, "unit": "ratio",
          "usedPct": "fiveHourUsed", "resetAt": "fiveHourReset" }
      ]
    }
  }]
}
```

The header is a 0-1 fraction, so `unit: "ratio"` scales it for display, while the endpoint's
`utilization` is already 0-100. `scale` belongs to the bucket, so one bucket cannot read both — a pool
that wants both readings declares one bucket per source. That is worth doing, because the two readings
merge bucket by bucket instead of replacing one another: a source updates only the buckets it
reported, a bucket the other source never carries survives with its own age and provenance, and the
header keeps its own id fresh as responses go by while the endpoint supplies the weekly windows the
headers do not carry. Where a header exists it is the better data: it describes the response that just
happened, so it is never up to a TTL behind.

## OpenRouter — a budget and a daily counter

Both live in the `data` wrapper of one response.

```jsonc
{
  "providers": [{
    "name": "openrouter",
    "keys": [{ "name": "main", "value": "$OPENROUTER_API_KEY" }],
    "quota": {
      "from": "endpoint",
      "endpoint": { "url": "https://openrouter.ai/api/v1/key" },
      "quotas": [
        // A spend cap that resets is a window measured in dollars, and it is the
        // bucket with a reset instant — the one quota-first can order by.
        { "id": "budget", "primary": true, "unit": "usd",
          "limit": "data.effective_budget.limit_usd",
          "remaining": "data.effective_budget.remaining_usd",
          "resetAt": "data.effective_budget.resets_at" },
        { "id": "free_daily", "kind": "count", "unit": "requests",
          "used": "data.free_model_daily_requests.used",
          "limit": "data.free_model_daily_requests.limit" }
      ]
    }
  }]
}
```

`limit` plus `remaining` is enough to derive the percentage, so no `used` path is needed.
`effective_budget` is `null` for a key with no cap; that bucket then has no reading and the pool
falls back to the daily counter for the footer. `free_model_daily_requests` resets at UTC midnight
but the response carries no field for that instant, so that bucket simply has no `resetAt` — invent
one and every reset countdown in the footer would be wrong.

## DeepSeek — a balance, and string numbers

```jsonc
{
  "providers": [{
    "name": "deepseek",
    "keys": [{ "name": "main", "value": "$DEEPSEEK_API_KEY" }],
    "quota": {
      "from": "endpoint",
      "endpoint": { "url": "https://api.deepseek.com/user/balance" },
      "quotas": [
        // balance_infos holds one entry per currency; pick reads the USD one.
        { "id": "balance", "primary": true, "kind": "balance", "unit": "usd",
          "remaining": "balance_infos.total_balance",
          "pick": { "currency": "USD" } }
      ]
    }
  }]
}
```

DeepSeek sends its amounts as strings (`"110.00"`); keyrouter coerces numeric strings, so no
transformation is needed. `kind: "balance"` tells keyrouter not to look for a reset at all: money
that is spent is spent, and a countdown on it would be fiction.

## GitHub Copilot — an undocumented endpoint with required editor headers

```jsonc
{
  "providers": [{
    "name": "github-copilot",
    "keys": [{ "name": "main", "value": "$GITHUB_COPILOT_TOKEN" }],
    "quota": {
      "from": "endpoint",
      "endpoint": {
        "url": "https://api.github.com/copilot_internal/user",
        // GitHub's own scheme, not Bearer.
        "authPrefix": "token ",
        "headers": {
          "Editor-Version": "vscode/1.96.2",
          "Editor-Plugin-Version": "copilot-chat/0.26.7",
          "User-Agent": "GitHubCopilotChat/0.26.7",
          "X-Github-Api-Version": "2025-04-01"
        },
        // The window is monthly, so a fresh reading every five minutes is plenty.
        "ttlMs": 300000
      },
      "quotas": [
        { "id": "premium", "primary": true, "unit": "percent",
          "remaining": "quota_snapshots.premium_interactions.percent_remaining",
          "resetAt": "quota_snapshots.premium_interactions.quota_reset_at",
          "unlimited": "quota_snapshots.premium_interactions.unlimited" }
      ]
    }
  }]
}
```

`percent_remaining` is a percentage of what is *left*, so it is read as `remaining` with
`unit: "percent"` (the footer shows "62%" left) rather than as `usedPct`, which would invert it.
`quota_reset_at` is epoch **seconds**; `auto` recognises that without being told. `unlimited` is a
boolean in the payload, and a truthy `unlimited` path means the bucket never looks spent.

This endpoint is undocumented. It answers 401/403 when the token needs refreshing, and it has been
seen returning `monthly_quotas`/`limited_user_quotas` instead of `quota_snapshots`. That drift is
the whole argument for a config-driven probe: it is fixed by editing JSON, not by waiting for a
release.

## Anything OpenAI-compatible — headers only

```jsonc
{
  "providers": [{
    "name": "my-gateway",
    "keys": [{ "name": "main", "value": "$MY_GATEWAY_KEY" }],
    "quota": {
      "from": "headers",
      "headers": {
        "requestLimit": "x-ratelimit-limit-requests",
        "requestRemaining": "x-ratelimit-remaining-requests",
        "requestReset": "x-ratelimit-reset-requests"
      },
      "quotas": [
        { "id": "requests", "primary": true, "kind": "window", "unit": "requests",
          "limit": "requestLimit", "remaining": "requestRemaining",
          "resetAt": "requestReset", "resetFormat": "duration" }
      ]
    }
  }]
}
```

`x-ratelimit-reset-requests: 6m0s` is a Go duration — a **delta**, meaning "in six minutes" — so
`resetFormat: "duration"` says to add it to now; `auto` would work it out too, and the explicit form
is there to make the intent readable. The token headers (`x-ratelimit-limit-tokens` and friends)
read the same way, as a second bucket. This is the free source: the numbers arrive on responses
keyrouter is already watching, so the pool gains a live quota bar without a single extra request.
