# Commands

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

```
/keyrouter status [provider]    live pool state per provider (kind, active entry, install state, expiry)
/keyrouter reload     re-read ~/.pi/agent/pi-keyrouter.json
/keyrouter reset      hand providers back to pi's own credentials immediately
/keyrouter account <provider> [name|index]    pin a specific key or account
/keyrouter strategy <provider> [strategy]    show or set a pool's rotation strategy
/keyrouter quota [provider] [--all]    each entry's quota reading; --all probes every entry now
/keyrouter add <provider> [name]    add a key or an account to a pool, or update the named entry
/keyrouter remove <provider> <name|index>    remove a key or an account from a pool
/keyrouter notifications [all|quiet|silent]    show or set how much keyrouter notifies you
```

`/keyrouter` on its own — or `/keyrouter --help` — prints this list with every command's syntax, so
nothing has to be memorized or looked up.

`reset` also clears each pool's saved `active` position, so the next session starts at the first
entry rather than resuming onto the credential you just handed back.

The completion menu fills the rest in: the subcommands first, then the configured pools after
`status`, `quota`, `account`, `strategy`, `add` or `remove`, then that pool's entries for `account`,
`remove` and `add` — an existing name is an update target — or the strategy values valid for that
pool for `strategy`. After `notifications` it offers `all`, `quiet` and `silent`. Entry names
are matched case-insensitively, and the pool's current `active` entry is labelled as such.
Suggestions stop as soon as the command is complete, so `reload` never offers operands and `quota`
offers a pool name only — `--all` is typed by hand.

`account` switches a pool to a specific credential, and works for either pool kind. It accepts an
exact name, a case-insensitive name, or a 1-based index. With no name it reports the pool and the
available choices:

```
/keyrouter account cline         → cline (oauth) — active: work
                                   Choose one: /keyrouter account cline <work|home>
/keyrouter account cline home    → cline now using account home. Rotation continues from here.
/keyrouter account cline 1       → cline now using account work (pool default).
```

A pinned credential has its **cooldown cleared** — a manual pick is deliberate, so it must not be
one the automatic picker would immediately skip — and any pending retry is dropped. Rotation then
continues from the pinned position on the next failure, so this is a nudge rather than a lock.
Installs go through exactly the same path as automatic rotation, including capturing pi's rotated
blob before leaving the previous credential. The pin is also saved as the pool's `active`, so it
survives a restart.

`strategy` shows or changes how a pool picks its next entry at a turn boundary. With no arguments
it lists every pool; naming only the pool reports it; naming a pool and a value sets it:

```
/keyrouter strategy                  → strategies
                                         cline (oauth): stalest-first
                                         tokenharbor (keys): round-robin
                                       Set one: /keyrouter strategy <provider> <failover|round-robin|stalest-first|random|quota-first>
/keyrouter strategy cline             → cline (oauth) — strategy: stalest-first
                                       Choose one: /keyrouter strategy cline <failover|round-robin|stalest-first|random|quota-first>
/keyrouter strategy cline random     → cline strategy: stalest-first -> random (applies from the next turn boundary).
```

The change never rotates immediately — strategies act only at turn boundaries — and it is saved to
`~/.pi/agent/pi-keyrouter.json`, so it survives a reload and a restart. Setting `failover` removes the field
from the file (absent already means failover). On a `keys` pool, `stalest-first` is not even
offered: it orders by token expiry, which keys do not have, so it degrades to `round-robin` with a
warning — the command stores the effective value so a later reload does not warn again. `quota-first`
is likewise not offered for a pool whose config declares no `quota` block, since it would degrade to
`round-robin` for want of a reading. A strategy other than `failover` also shows up in
`/keyrouter status` next to the pool's `source`.

`add` and `remove` manage a pool's entries without hand-editing the file:

```
/keyrouter add tokenharbor backup      → prompts for the key, then:
                                         added backup to tokenharbor. It joins the pool on the next turn.
/keyrouter add tokenharbor              → the name defaults to key-3
/keyrouter add tokenharbor old         → "old" is already in the pool: prompts for the key, then:
                                         updated old in tokenharbor.
/keyrouter add cline                   → captures the account pi is holding (run /login first)
                                         added home to cline. It is now the active account.
/keyrouter remove tokenharbor backup    → confirms, then:
                                         removed backup from tokenharbor.
```

`add` asks for an API key in a prompt and writes it to `~/.pi/agent/pi-keyrouter.json` — keyrouter never
runs a login of its own. (pi's prompt is a plain text field, not a masked one, so the key is
visible while you type it.) For an `accounts` pool it captures the credential **pi** is holding right
now, so the flow stays pi's own: `/login` first, then `/keyrouter add <provider>`. If pi is already
holding one of the pool's accounts, the command says so — and tells you to `/login` another account
first — rather than adding the same credential twice. On an `accounts` pool the account that was just
captured becomes the pool's **active** account: you signed into it on purpose, so the reload that
follows leaves pi on that account instead of switching back to the previous one.

**Adding knows who you are.** For an `accounts` pool the match is made on the account's *identity*
— the provider's `identityPath`, or the identity claims a token carries (see
[Attributing a refreshed credential](oauth.md#attributing-a-refreshed-credential)) — not on the bytes of
the credential: a token that was refreshed since the pool entry was written is still the same
account. When pi's current login matches an entry, `/keyrouter add` asks what to do: update that
entry, add the login as a new account, or cancel. If the match is ambiguous (two entries claim the
same identity), the command refuses and asks you to name the account or to set `identityPath` for
that provider.

**A name that already exists is an update.** `/keyrouter add <provider> <name>` where `<name>` is
already in the pool updates that entry **in place**, for both pool kinds. On a `keys` pool it
replaces the key value; on an `accounts` pool it replaces the stored credential with the one pi
holds right now. If the named entry holds a *different* account identity, keyrouter asks for
confirmation before replacing it. An entry whose value comes from an external source (`$ENV`,
`${ENV}` or `@file`) is **not** edited in place — the command points you at the environment variable
or the file instead, because that value is yours to maintain. A generated name that is already taken
gets a numbered suffix (`key-2`, `key-3`, …) and a note; a name you typed yourself is kept as typed.

**Names are matched case-insensitively**, because `Backup` and `backup` are the same name to you:
an update or a removal that names one of them finds the other too. If two entries in the pool
differ only in case, the command **refuses** instead of guessing which one you meant. On a `keys`
pool, a key the pool already holds is refused as well — adding it under a second name would make
the pool rotate onto one credential twice.

`remove` deletes the entry from the file after a confirmation, and forgets the pool's `active`
position when that was the entry removed. The pool itself keeps managing the provider, so pi keeps
using the pool's credential for it — only the removed entry is gone.

`status` prints, per provider: the pool kind, the active entry, whether keyrouter has installed
anything, pi's own `source` for the provider, and each entry's `uses`, `fails`, last status and
cooldown. Naming a provider — `/keyrouter status cline` — shows just that pool, in the same format.
Counters and cooldowns are per-session; only the active position carries over, via the
`active` field. For `accounts` pools it also shows how long the credential has left — never the
token:

```
cline (oauth, active: home, installed: yes, source: stored)
  → work  uses=4 fails=1 status=rate-limited (cooldown) expires=in 47m
    home  uses=2 fails=0 status=ok expires=in 12m
```

`quota` prints what each entry of every pool that declares a `quota` block currently reads — one row
per entry, in the shape `status` uses, with the active entry marked `▶`:

```
/keyrouter quota                  → 🔑 keyrouter: quota
                                    anthropic (oauth)
                                    ▶ personal █████████░░░░░  62%  seven_day 41%  resets in 3h12m  [headers]
                                      work     ██░░░░░░░░░░░░  14%  seven_day 9%  resets in 6d4h  [endpoint]
                                      spare    ERR: HTTP 401
                                    cached readings only — /keyrouter quota --all fetches fresh ones.
```

It is read-only: nothing is rotated, installed or probed, and a pool with a failed probe names the
reason on its own line. A cached row is shown exactly as the provider last reported it, with no age
marker — but only the entry in effect is kept fresh, so a non-active row can be hours old. That is the
number the ordering ranks on: a promoted entry can turn out emptier than its row said, which surfaces
as a 429 and rotates the pool, like any other limit. `[headers]` or `[endpoint]` says which source
produced the row's headline reading, which for a pool
reading both sources is the most recent one. Rows are listed best-first by reset time whenever at
least two of them carry a reading that can be ranked — soonest-resetting entry first, then by
fullness, then balances by size — and below that the table keeps the pool's own order, the one
`failover` rotates in. It is a ranking and not a prediction: the table cannot see cooldowns, overloads
or leases, and a tie keeps pool order. Because a row's place is a preference order and no longer a
position, it does not line up with the numbered `/keyrouter account <index>` operands, which still
count entries in config order; `▶` marks the entry in effect.
`--all` is the one form that spends requests: it probes
every entry of every pool that has an `endpoint` source — not only the pool you named, since the name
filters the output — and **waits** for the result, which is what to do before trusting an ordering
decision rather than a cached number. Naming a pool filters the output; a pool without a `quota` block,
or a name that matches none, is reported instead of
shown empty.

Rotations, overloads and exhaustion each notify one themeable line. **`notifications`** sets how much of
that reaches you — `"all"` (default), `"quiet"`, or `"silent"`:

| Event | `all` | `quiet` | `silent` |
|---|---|---|---|
| rotation for `rate-limited` — the entry cools down and rejoins on its own | shown | silent | silent |
| provider `overloaded` — no key change, pi retries on its own | shown | silent | silent |
| rotation for `unauthorized` / `quota` / `refresh-failed` — the credential needs you (replace the key, top up the account, re-login) | shown | shown | silent |
| pool exhausted — the request you are waiting on actually fails | shown | shown | shown |

Pool exhaustion is never silenced: hiding the one event where the request dies would only make the
provider's own error look unexplained. `/keyrouter status` names the active level whenever it is not
the default, and `/keyrouter notifications` shows it on its own: `/keyrouter notifications quiet`
sets the level, writes it to `~/.pi/agent/pi-keyrouter.json` and applies it to the running session right
away — no hand-editing of the file, and no `/reload` needed. In headless/print mode there is
no UI, so set `PI_KEYROUTER_TRACE=<file>` to log decisions (credential **names** only, never values) —
the trace records every decision regardless of the level:

```
2026-... bootstrap tokenharbor -> primary
2026-... rotate tokenharbor primary -> backup (429 rate-limited)
2026-... continue tokenharbor (retry with the rotated key, 1/3)
2026-... success tokenharbor key=backup (cooldown cleared)
2026-... clear tokenharbor (override removed)

2026-... oauth install cline -> work (2 account(s))
2026-... rotate cline work -> home (401 unauthorized)
2026-... continue cline (retry with the rotated key, 1/2)
2026-... oauth restore cline -> session-start credential
```
