omp packages

@jeryjs/pi-keyrouter1.12.0

Credential pools for pi. Automatically rotate api keys and oauth credentials for built-in providers on 429 failovers in pi-coding-agent. No custom providers, no fetch hacks.

GitHub Actions Published 4 hours ago MIT ~2.8K downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

๐Ÿ”‘ pi-keyrouter

Credential pools for pi โ€” injected into providers you already have.

Multiple API keys or multiple OAuth logins per provider ยท automatic 429/401/403 failover ยท no custom providers, no fetch hacks.

Built for pi 1.0.0. Auth, retries, OAuth, refresh, storage and headers stay entirely inside pi; this extension only chooses which credential pi resolves.

Originally created by prevmaintainer. Forked, maintained, and substantially improved by jeryjs.

Release notes for every version, including the original 0.1.0 โ€“ 0.4.0 line, are in CHANGELOG.md.

pi install npm:@jeryjs/pi-keyrouter
# create ~/.pi/agent/pi-keyrouter.json with your keys or accounts
/reload

Want to stay on top of the latest changes? pi install git:github.com/jeryjs/pi-keyrouter works too.


What it does

~/.pi/agent/pi-keyrouter.json declares a pool per provider id. There are two kinds:

  • keys โ€” several API keys. keyrouter puts the active key into pi's runtime credential overlay, the same mechanism pi --api-key uses. The overlay wins over auth.json and environment variables, so every request for that provider carries your pooled key.
  • accounts โ€” several stored OAuth logins. keyrouter installs the active one into pi's credential store, because auth.json holds exactly one credential per provider id and pi has nowhere to keep the rest. pi still owns the OAuth flow, the refresh, and the headers.

When a request fails, keyrouter reads the error off the assistant message (message_end), marks the active credential bad, and installs the next one. pi's own retry then uses it โ€” and for error classes pi refuses to retry (401/403, quota), keyrouter asks for one extra request at pi's agent_before_settle boundary.

It never registers a provider. Pools point at provider ids that already exist โ€” built-ins like google or anthropic, ids from models.json, and ids owned by other extensions such as cx-providers. Nothing is shadowed, merged, or unregistered, so it cannot stomp on another extension's provider config.

user prompt
   โ†’ pi resolves auth for provider "tokenharbor"   โ†’ pool key A (runtime overlay)
   โ†’ provider answers 429
   โ†’ message_end: mark A bad, install pool key B  โ†’ overlay updated
   โ†’ pi's built-in retry                          โ†’ request uses B

user prompt
   โ†’ pi resolves auth for provider "cline"        โ†’ pool account #1 (credential store)
   โ†’ provider answers 401 (pi will not retry this)
   โ†’ message_end: capture pi's refreshed blob, install account #2
   โ†’ agent_before_settle: one extra request       โ†’ request uses account #2

Configuration

~/.pi/agent/pi-keyrouter.json only โ€” user-level, never project-scoped, because API keys are personal credentials that must not be overridable by a repo you clone. A config still at the old ~/.pi/keyrouter.json location is moved here on the first start.

{
  "$schema": "https://raw.githubusercontent.com/jeryjs/pi-monorepo/refs/heads/main/packages/pi-keyrouter/schema.json", // optional: editor completion + validation
  "providers": [
    {
      "name": "tokenharbor",     // provider id pi knows: a built-in, a models.json id, or another extension's
      "keys": [
        { "name": "primary", "value": "$TOKENHARBOR_API_KEY" }, // env ref โ€” prefer this
        { "name": "backup",  "value": "thk_live_..." }          // literal works, but keeps the secret on disk
      ],
      "takeoverOAuth": false,    // inject pooled keys even when pi holds a stored OAuth login
      "strategy": "failover",    // failover | round-robin | stalest-first | random | quota-first
      "rotationTriggers": { "quota": ["insufficient_credits"] }, // extra error patterns that rotate (regex)
      "active": "backup"         // written by keyrouter: the entry the last session ended on
    },
    {
      "name": "anthropic",
      "accounts": [
        { "name": "personal", "credential": "@~/.pi/accounts/anthropic-personal.json" }, // file ref
        { "name": "work",     "credential": "$ANTHROPIC_WORK_CREDENTIAL" }              // env ref
      ],
      "strategy": "quota-first", // spend the window that resets soonest, keep fresh quota
      "rotateOnQuota": true,     // accounts pools rotate on account-level quota/billing errors
      "sweepRefresh": false,     // refresh idle accounts at session start
      "identityPath": "access:email", // where this account's identity lives inside its credential
      "leases": true,            // one credential per concurrent pi process
      "quota": {
        "from": "headers",       // free: the numbers ride on responses keyrouter already sees
        "headers": { "fiveHourUsed": "anthropic-ratelimit-unified-5h-utilization", "fiveHourReset": "anthropic-ratelimit-unified-5h-reset" },
        // The header carries a 0-1 fraction, hence `unit: "ratio"`. The OAuth usage endpoint
        // reports the same window as `utilization` on a 0-100 scale, where `unit` is `percent`.
        // Any other bucket key is a display value: "requests": "req_used" renders as {{five_hour.requests}}.
        "quotas": [{ "id": "five_hour", "primary": true, "unit": "ratio", "usedPct": "fiveHourUsed", "resetAt": "fiveHourReset" }]
      }
    }
  ],
  "maxRetries": 3,               // rotations per provider before giving up
  "cooldownMs": 60000,           // how long a failed key stays bad
  "overloadedCooldownMs": 30000, // provider-wide pause on "overloaded"/529
  "notifications": "all"         // "all" | "quiet" | "silent"
}

$NAME / ${NAME} expand from the environment at load time. A key whose variable is missing is dropped; if that empties the pool, the provider is skipped with a warning. A provider takes either keys (API keys) or accounts (OAuth logins), never both. $schema is optional โ€” keyrouter ignores it at runtime, preserves it when writing the file back, and never adds it. PI_KEYROUTER_CONFIG=/path/to/file overrides the config path (the test suite relies on it).

Every field, default and caveat: docs/configuration.md. Real quota blocks, one per provider: docs/provider-recipes.md.

Strategies

Set strategy per provider. All act only at turn boundaries and never pick a cooled-down entry.

strategy Use it when
"failover" (default) Stay on the current entry until it fails.
"round-robin" Spread the load, and keep every account exercised and refreshed.
"stalest-first" Serve the account whose token expires soonest (accounts pools only).
"random" No fixed pattern at all.
"quota-first" Spend the allowance that is about to expire first, keeping fresh quota. Needs a quota block, reads each entry once so the ordering has numbers to compare, and from then on refreshes only the entry in effect.

Commands

Command What it does
/keyrouter status [provider] Live pool state: active entry, install state, usage, cooldowns, expiries.
/keyrouter account <provider> [name|index] Pin one credential; with no operand, list the choices.
/keyrouter strategy <provider> [value] Show or set how the next entry is picked.
/keyrouter quota [provider] [--all] What each entry has left, listed best-first by reset time when at least two rows can be ranked (pool order otherwise); --all fetches fresh numbers for every entry.
/keyrouter reload Re-read ~/.pi/agent/pi-keyrouter.json.

/keyrouter alone prints every command's syntax. The rest โ€” add, remove, reset, notifications โ€” is in docs/commands.md.

Documentation

File What is in it
docs/configuration.md Every provider field, rotation rules, rotationTriggers, leases, compatibility.
docs/quota.md Quota: both sources and their cost, every field, templates, quota-first, known limitations.
docs/provider-recipes.md Copy-paste quota configs per provider, with the traps.
docs/oauth.md Rotating OAuth logins, refresh attribution, resuming across sessions.
docs/commands.md The full command reference.
docs/development.md Tests and publishing.
CHANGELOG.md Release notes.

License

MIT