# Configuration

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

Every provider field, the rotation rules they feed, and the per-provider options. A minimal config
is in the [README](../README.md#configuration).

## Provider fields

A pool is **one kind or the other**, and `keys` versus `accounts` is what decides it — the schema marks
every field accordingly. `keys` and `takeoverOAuth` mean something only on an API-key pool; `accounts`,
`rotateOnQuota`, `identityPath` and `sweepRefresh` only on an OAuth pool (`identityPath` and
`sweepRefresh` say so with a warning when they land on a `keys` pool, and are ignored); `name`, `match`,
`strategy`, `rotationTriggers`, `leases`, `active` and `quota` apply to both. Two *values* are kind-bound
too: `strategy: "stalest-first"` orders accounts by OAuth token expiry, so a `keys` pool warns and behaves
as `"round-robin"`; and `quota.endpoint.authFrom` defaults to `"key"` on a `keys` pool and `"oauth"` on
an `accounts` pool, because `"oauth"` cannot resolve on a pool of API keys and `"key"` cannot resolve on
a pool of logins — the wrong one refuses the probe rather than sending it with no credential.

| Field | Default | Meaning |
|---|---|---|
| `name` | — | Provider id as pi knows it: a built-in (`google`), a `models.json` id, or another extension's id. Matched case-insensitively. |
| `keys` | `[]` | API keys for this pool. Mutually exclusive with `accounts`; an empty list is allowed so `/keyrouter add` can fill it later. |
| `accounts` | `[]` | OAuth logins for this pool. Mutually exclusive with `keys`. |
| `match` | — | Deprecated and ignored: rotation is keyed by provider id, not by URL. |
| `strategy` | `"failover"` | Which healthy entry serves each turn — see [Strategies](#strategies). |
| `takeoverOAuth` | `false` | `keys` pool only: inject pooled keys even when pi already holds a stored OAuth login, which a runtime key would otherwise shadow. |
| `rotateOnQuota` | `true` | `accounts` pool only: rotate on account-level quota or billing errors. Ignored for `keys` pools. |
| `rotationTriggers` | — | Extra error patterns that make this pool rotate — see [Provider-specific triggers](#provider-specific-triggers). |
| `identityPath` | — | Where an account's identity lives inside a credential — see [oauth.md](oauth.md#attributing-a-refreshed-credential). |
| `sweepRefresh` | `false` | `accounts` pool only: refresh idle accounts at session start — see [oauth.md](oauth.md#2-rotating-between-several-oauth-logins-accounts-pools). |
| `leases` | `true` | Coordinate with other pi processes by claiming one entry per process — see [Leases](#leases--one-credential-per-concurrent-worker). |
| `active` | — | Written by keyrouter: the entry the last session ended on. Leave it out. |
| `quota` | — | Where this provider's usage numbers live — see [quota.md](quota.md). |

Top level: `providers` (required), plus `maxRetries` (`3`), `cooldownMs` (`60000`),
`overloadedCooldownMs` (`30000`), `notifications` (`"all"`) and the optional `$schema`.

## The config file

An annotated config with every provider option is in the [README](../README.md#configuration).

## Rotation rules

The classification is deliberate, because pi only *retries* some failures.

| Signal | Detected from | `keys` pool | `accounts` pool |
|---|---|---|---|
| `429` / "rate limit" / "too many requests" | assistant error message | cooldown, **rotate** | cooldown, **rotate** |
| `401` / `403` / "unauthorized" / "forbidden" | assistant error message | cooldown, **rotate** | cooldown, **rotate** |
| "quota exceeded" / "insufficient_quota" / billing | assistant error message | **ignored** | **rotate** (if `rotateOnQuota`) |
| "OAuth refresh failed" / `invalid_grant` | assistant error message | n/a | cooldown, **rotate** |
| `529` / "overloaded" | assistant error message | provider-wide cooldown, **no rotation** | same |
| `500` / `502` / `503` | assistant error message | **ignored** — pi retries the same key | same |
| any 2xx | `after_provider_response` | entry marked ok, its cooldown cleared |
| provider-specific `rotationTriggers` | assistant error message | cooldown, **rotate** | cooldown, **rotate** |

The differing quota row is the point: an API key for an account that has hit its limit cannot help,
whereas a different OAuth account is a different subscription — so the same error wording
**rotates** one pool kind and is **ignored** by the other.

Two consequences of pi's retry policy worth knowing:

- **401/403 and quota errors are not in pi's retryable set.** pi stops immediately. To keep
  rotation useful for those, keyrouter uses `agent_before_settle` — pi's actionable boundary that
  may add exactly one more request — and appends a hidden message so the continuation is valid.
  The extra request then runs with the rotated key or account. Capped at `maxRetries` per provider
  until that provider succeeds again, so an all-bad pool cannot loop. (429 *is* retryable, so that
  leg needs no continuation.)
- **Failed requests are not visible to `after_provider_response`.** The OpenAI SDK throws on non-2xx,
  so pi's response hook never fires. That is why errors are read from `message_end`.

## Provider-specific triggers

Use `rotationTriggers` on a provider to extend keyrouter's built-in failure rules. Each key is an
existing rotation reason (`rate-limited`, `unauthorized`, or `quota`) mapped to an array of regular
expressions. Patterns are matched case-insensitively against the full assistant error message.

```jsonc
{
  "providers": [{
    "name": "my-provider",
    "keys": [
      { "name": "primary", "value": "$MY_PROVIDER_KEY" },
      { "name": "backup",  "value": "$MY_PROVIDER_KEY_BACKUP" }
    ],
    "rotationTriggers": {
      "quota": ["insufficient_credits", "Insufficient balance"]
    }
  }]
}
```

A custom trigger is explicit opt-in, so it rotates a `keys` pool even when the built-in quota
rules would ignore the error. Use that only when another key in the pool can succeed after the
first one fails. An invalid regular expression is ignored with a warning; the rest of the pool keeps
working.

## Strategies

By default a pool is a **failover** pool: keyrouter stays on the current entry until it fails,
and only an error moves the pool on. Set `strategy` per provider to change *which entry serves each
turn* — rotation on failure is unaffected and still applies on top of every strategy. It can
also be changed live with `/keyrouter strategy` (see [commands.md](commands.md)).

| `strategy` | Behavior |
|---|---|
| `"failover"` (default) | Stay on the current entry until it fails. The original behavior. |
| `"round-robin"` | Advance to the next entry at every turn boundary. Spreads load across the pool, and keeps every OAuth account exercised — and therefore refreshed through the normal capture machinery. |
| `"stalest-first"` | Serve the turn with the available account whose token expires soonest: the account most in need of a refresh gets picked first. Under steady traffic it degenerates to round-robin. `accounts` pools only — on a `keys` pool it warns and behaves as `"round-robin"`. |
| `"random"` | A uniformly random available entry other than the current one, for when a fixed rotation pattern is unwanted. |
| `"quota-first"` | Serve the entry whose quota is most urgent to spend: the window that resets soonest, or the largest balance. Needs a `quota` block — without one it warns and behaves as `"round-robin"`, as it does while it has no reading to order by. It reads each entry once while it has no reading, so the ordering has numbers to compare, and only the entry in effect after that, so a non-active entry's number ages until something promotes it. See [quota.md](quota.md). |

Two rules that hold for every strategy:

- **Advancement happens only at turn boundaries, never mid-turn.** A turn is one logical unit of
  work, so every request in it goes out on the entry that was installed when the turn started.
- **Cooldowns still bind.** A strategy spreads load; it never selects an entry that is known to be
  bad. And failure rotation wins: while a rotated-in replacement is still waiting for its retry
  turn, the strategy does not move away from it.

Strategy advancement is silent by design — the pool is doing what you asked, not reporting an
event. It is visible in the trace (`PI_KEYROUTER_TRACE`), e.g.
`advance cline home -> work (round-robin)`.

## Leases — one credential per concurrent worker

A pool is shared by every pi process on the machine: a subagent, a second window, a `pi` running in
another directory. Left alone they all install the same first entry and then hit the same 429 at
the same time. A **lease** is the coordination: an exclusive claim on one entry of a pool.

The claim is a file under `~/.pi/agent/extensions/.pi-keyrouter-leases/`, created with an exclusive create, so the
filesystem — not a lock protocol — decides the winner. The claim is taken on the **entry**, not on
its position in the pool, so removing or reordering entries cannot detach it from the credential it
was taken for. The first process to install an entry holds the claim; another process sees it and
picks a different entry. The claim is released when the entry is replaced, when the pools are handed
back (`reset`, `reload`), and at shutdown. A claim whose owner process is gone is stale and is taken
over.

Within one process, a request holds its entry for the duration of that request, so a rotation never
walks onto a credential that is already serving one. A lease is a **preference, never a lock**: when
every entry is leased, the busy one is reused rather than leaving the request with no credential at
all.

`/keyrouter status` shows who holds each entry:

```
tokenharbor (keys, active: primary, installed: yes, source: runtime)
  → primary  uses=4 fails=0 status=ok lease=this-session
    backup   uses=2 fails=0 status=ok lease=pid 48213
    spare    uses=0 fails=0 status=ok
```

A manual `/keyrouter account` pin overrides the lease: you asked for that credential explicitly,
so the pool installs it even when another process holds the claim.

**OAuth pools do not use entry leases.** pi's credential store holds exactly one credential per provider
id — `~/.pi/agent/auth.json` is `{ [providerId]: credential }` — and every process reads the same
file, so two processes cannot hold two different accounts for one provider: there is no slot to
lease. Spreading OAuth accounts across concurrent processes needs a distinct provider id per
account, which is the architecture keyrouter deliberately does not use (it never registers
providers). Run those processes against different provider ids, or give them separate agent homes,
when they need different accounts.

An OAuth pool does take the provider-wide **sweep claim** while it refreshes idle accounts, so two
sessions never exchange the same rotating refresh token.

**Disabling leases per provider.** Add `"leases": false` to a provider entry. That provider then
neither reads nor writes lease files: it does not claim an entry, it does not skip an entry another
process has claimed, and its OAuth sweep skips the sweep claim. Use it when several processes must
deliberately share the same credential (the lease would otherwise spread them off it), or when the
lease directory is not writable. The trade-off is exactly what the lease prevents: concurrent
processes can pile onto one credential and hit the same rate limit together.

## Compatibility

Versions before 0.80.8 of pi exposed `ModelRegistry.authStorage`. pi 1.0.0 removed it: the
`ModelRegistry` given to extensions is a read-oriented facade over the internal `ModelRuntime`, and
its credential writers (`setRuntimeApiKey`, `login`, …) are not part of that facade.

Two internals are reached through that facade, each behind its own capability check and each
verified against pi 1.0.0's shipped bundle:

1. **The runtime overlay** (`runtime`, for `keys` pools), once the facade's `runtime` field — a
   plain property that survives bundling. It also awaits the now-async setters, where 0.78.x was
   synchronous.
2. **The credential store** (`runtime.credentials`, for `accounts` pools), whose `modify()` writes
   through pi's own `AuthStorage` so the file lock, the shared `readState` cache and the revision
   counter all stay coherent. Writing `auth.json` directly would risk clobbering a concurrent
   `/login`.

If a future pi hides either one, that pool kind reports once and stays inert — **`keys` pools and
`accounts` pools degrade independently**, so neither can take the other down. `test/verify-runtime-credentials.mjs`
is the executable record of the behaviour both depend on; run it first when bumping pi.
