# Provider keys and failover

| Concept | Meaning |
| --- | --- |
| List | One file per provider, `~/.openprogram/auth/<provider>/credentials.json`: `strategy` and the ordered `credentials`. An API key's secret is in [its company's file](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/auth/credential-model.html). Every change (`AuthStore.mutate`) holds the file's lock from the read to the write and applies to the file as it is then, so a key the CLI added or a token another process refreshed is never lost. Removing or replacing a key also drops the last good copy (`.bak`, `.bad-*`), so its secret leaves the disk (`models/auth/store.py`). |
| Use counts | `<provider>/usage.json`: each credential's uses, uses today, last use, and where `evenly` continues. A request writes only this file, never the secrets file. |
| Credential | `id`, `label`, `kind` (`api_key`, `oauth`, `device_code`, `import`, `token`, `credential_process`), `source` (`web`, `cli`, `import`, `env`), `identity`, `enabled`, `status`, cooldown, blocked models, last error, last use |
| Status | `ready`, `cooling`, `quota`, `invalid_key`, `needs_login` |
| Environment key | A set variable the provider reads (`login_method_registry.env_vars`) is a read-only row `env:<VAR>`, read from the environment at use; its place and state are kept, its value never. A variable several ways of a company read is a row on each of them ([One key, several ways](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/provider-management.html#shared-environment-keys)) |
| Sign in again | The same `account_id` or email renews its row in place: same id, name and place |

The name shown: the label, else the sign-in's email (the plan is shown beside it), else the variable, else `Key ····1234`. No listing carries a secret.

## Choosing a credential

1. **Pin** the conversation's chosen credential, if usable
2. **Binding** the credential the conversation last used
3. **Strategy** `in_order`, `evenly`, `least_used` (fewest uses today)

The binding and the pin live in the session's metadata (`credential_binding`, `credential_pin`); a call reads the conversation in its context before the cache key a `Runtime` sends (`op-…`), and a child session follows its `parent_session_id` up to the conversation, so programs, agent methods, sub-agents and Goal turns spend the conversation's pinned or bound key.

One `with_credential()` (`models/auth/selection.py`) wraps every adapter's stream; adapter SDKs do not retry on their own.

## What a failure does

| Failure | Credential | Request |
| --- | --- | --- |
| 429, Retry-After ≤ 5 s | unchanged | same credential once more |
| 429 | `cooling` for Retry-After, else 60 s doubling per strike to 15 min | next usable one |
| Quota or balance | `quota` until the reset the provider reports, else 24 h | next usable one |
| 401, or 403 naming the key | a sign-in is refreshed once (only here, not again in the adapter); then `invalid_key` or `needs_login` | same after refresh, else next; every key refused: [another way of the company](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/auth/credential-model.html#request) |
| Other 403 | a 403 about a model (verification, organization) blocks that model; one about a region or policy leaves the key alone | next usable one, or the error |
| Model refused | that model blocked for 24 h | next usable one |
| 5xx, network | unchanged | two backoff retries on the same credential |
| None usable | — | wait if one is back within 60 s, the one that just failed included (one key and a 429 waits out its cooldown); else the model fallback; else an error listing each credential's state |

A switch adds a muted notice to the reply (`EventRetry`, reason `credential`). A stored error message has the key, `Bearer` tokens and `?key=` values removed first. Once output has been shown, a failure is not retried on another credential.

## Interfaces

| Surface | Entry |
| --- | --- |
| REST | `/api/providers/{p}/credentials`: list, add, `PATCH` label or enabled, delete, `check`, `replace`, `reorder`, `strategy`. `/api/sessions/{sid}/credentials`: binding and pin. |
| Events | `provider.credentials.changed {provider}`, `session.credentials.changed {session_id, binding, pin}` |
| CLI | `openprogram providers keys <provider> list\|add\|replace\|rename\|move\|enable\|disable\|check\|remove\|strategy`; `providers login` is `keys add` |
| Usage | Each usage row records `credential_id`; quota is read per credential |

A pasted key is checked with `POST /api/providers/{p}/credentials/check-key`, which stores nothing; Add key or Replace key stores it with its name in one request and reuses that check. Adding a sign-in reuses `/api/providers/{p}/login/{start,poll,submit,cancel}`. Changes to the list go through `models/auth/manage.py`, which the routes and the CLI share.

## Carry-over

The first start on this layout carries the old per-account files over once (`models/auth/carry_over.py`):

1. Read every old account file: an object with a `credentials` list and the old account fields. Any other file is left alone; an unreadable one is logged by path.
2. Copy `auth/` once to `auth/.carry-over-backup`, inside the folder the sandbox never lets a tool read.
3. Flatten each provider's files into one list, in account order and then each account's credentials; a missing or repeated id gets a new one.
4. Keep every stored key. An old environment row that stored its key becomes a stored key with a new id, whatever the starting process's environment holds. A key a variable also holds is listed once at read time (`store.env_rows`). An environment row with no stored value is left out and logged.
5. Correct the rest: a key refused for a spent balance (HTTP 402, or OpenCode's 401 `CreditsError`) is out of quota for a day from when it was seen, ready when no time is recorded. A sign-in takes its email and plan from its `id_token`.
6. Check every row arrived, and only then remove that provider's old files.

A provider that fails keeps its old files without holding up the others. Running again adds nothing twice and makes no second backup.

An older OpenProgram installed elsewhere on the machine still writes an old file from the environment variable it reads, so the carry-over can run on any start. A key the list already holds is not added again, and rows that repeat a stored key keep only the earliest, which has the key's history.

A list an earlier carry-over wrote gets steps 4 and 5 once, on the next start (`carry_over.repair`, marked `.repaired` in the backup). It never changes a secret, so every `.bak` stays, and it reads a spent balance from the `.bak` when a later check wrote over it.

It also tidies: a lock file goes only while the repair holds that lock, empty folders go, and folders become 0700. A folder it cannot change stays as it is, and the repair is still marked done.

[Auth storage](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/auth/unified-auth-storage.html)
