# Model authentication Provider profiles select an upstream and its credentials. Account identity and profile selection are separate: a profile can refer to a saved account, while environment accounts come from the process environment. See [models](models.md) and [quota](quota.md) for consumers of those choices. ## Credentials [`credential_store`](../src/albedo/harness/sdk/credential_store.gleam) owns `creds.json` under the Albedo home. Its `accounts` section holds provider accounts, `providers` holds profile API keys, and `mcp` holds MCP credentials. The file can contain secrets, but account records also contain metadata. Its default write uses a temporary file with mode `0600`, syncs it, and renames it into place. Mutations use the settings lock. `migrate` copies legacy account, MCP, and profile-key data into `creds.json` before retiring the old files to backups. An unreadable credential store causes migration to fail rather than overwrite it. The module merges saved profile keys into configuration on read. A nonempty key still in `config.json` takes precedence. ## Custom Anthropic gateways The [`anthropic-api` extension](../src/albedo/harness/extensions/anthropic_api/extension.gleam) uses bearer-token key accounts for custom Anthropic Messages gateways. It follows the OpenAI-compatible provider's profile selection and rotation rules. It does not use Claude Code OAuth, Claude Code identity headers, or the Anthropic Files API. The `claude` extension still owns Claude subscriptions and direct Console API keys. The endpoint is the API root that precedes `/messages`. Include `/v1` when the gateway requires it. Model discovery uses the same root followed by `/models`, as with OpenAI-compatible providers. Store the token as an `anthropic-api` key account through the login flow. This provider does not refresh gateway tokens. Discovery resolves credentials against the configured endpoint and does not follow HTTP redirects. It lists every model the endpoint lists, since Anthropic-style endpoints also serve other families. A Claude alias with a prefix or suffix (`anthropic/claude-…`, Bedrock's `us.anthropic.claude-…`, Vertex's `claude-…@date`) takes the catalog facts and thinking policy of the model it names (`thinking.claude_id`), and requests still send the alias. It never sends the gateway token as `x-api-key`. The [gateway thinking policy](../src/albedo/harness/extensions/anthropic_api/thinking.gleam) owns mode selection and the efforts advertised by discovery. A catalog effort alone does not establish a supported thinking mode. The primary Claude and gateway adapters share Messages streaming and [adaptive-thinking encoding](../src/albedo/anthropic_api/request.gleam). Claude-specific identity, tool aliases, uploads, hosted tools, and cache policy stay in the Claude adapter. Both replay a message's signed blocks through `request.native_blocks`, each only from details tagged with its own name and written by the same model, and only while those blocks still hold the transcript's text and calls. Anything else replays portably. Budgeted thinking rejects forced tool choices (`any` or a named tool) before transport; use automatic selection or no tools. Adaptive thinking retains its own tool-choice behavior. See [cache warming](cache-warming.md) for background eligibility, [model lists](models.md#model-lists), and [provider requests](provider-requests.md). ## Accounts [`auth_accounts`](../src/albedo/harness/sdk/auth_accounts.gleam) builds the account projection used by the auth API. It includes saved OAuth and key accounts and environment key accounts, together with profiles that select or rotate through them. The projection exposes account metadata, not the credential value. Environment accounts cannot be renamed through `rename_account`. A hand-edited key account without an ID, or without a label and a key that is a string or a list of byte values, is left out of the projection rather than failing it. A byte-list key keeps the label of its bytes. `put_key` checks the provider, UUIDv7 identity, endpoint, key, and label before saving a key account. The endpoint must be an HTTP or HTTPS URL with a host and without credentials, query, or fragment. Duplicate keys at the same provider and endpoint produce `key_exists`. Conflicting identity content produces `conflict`. ## Typed key accounts [`key_accounts.gleam`](../src/albedo/harness/sdk/key_accounts.gleam) selects profile-bound key accounts for OpenAI, Anthropic-compatible, Perplexity, and Mistral model requests. `Profile` supplies the home, credential store, and profile name. `select` returns an opaque `Account` snapshot with its identity, original endpoint, key, and label. Keep that snapshot beside the request client and pass it to `mark_limited` after a limit response. Do not rediscover the attempted account by its secret. `key_accounts.pool` pairs each account with its client; `upstream` retains that account's served label. Providers supply selection, client construction, and their wire send. Effective endpoint and key equality prevents repeating the same transport. Selection preserves inline profile keys, explicit account membership, and environment discovery. The shared `select` operation does not acquire saved sibling accounts for an unbound profile; provider-owned selection can have a different policy. Selection and affinity updates stay in the caller's process. Environment discovery reads the variables that the profile's account IDs name. OpenCode Go and Mistral also name their own variables. Other key stores ask a [`key_environment.KeyEnvironment`](../src/albedo/harness/sdk/key_environment.gleam) that the caller passes in. The [runtime](../src/albedo/harness/runtime.gleam) composes one from the `KeyEnvironmentPlugin` lookups of every declared extension, quarantined ones included, and `runtime.key_environment` returns it. The models extension contributes the variables its cached models.dev catalog names for the endpoint host. Discovery combines the catalog, self-named, and profile-referenced variables, then sorts and deduplicates them. Without the models extension, it finds only the self-named and profile-referenced ones. The value reaches each reader explicitly: - Providers read `ModelContext.keys` and pass it in `key_accounts.Profile`, `key_accounts.environment_keys`, and `credentials.candidates`. - Catalogs receive it as the third argument of `ModelCatalog.list`. - Quota sources receive it in `usage_feed.Source.accounts` and `profile`. - The daemon passes it to `auth_accounts.auth_snapshot`, `account_overview`, `rename_account`, `remove_account`, and the settings patch. Do not keep lookups in process-wide state. A reader without a runtime takes the value as an argument from its caller. `key_environment.empty()` is only for a caller that reads no store relying on catalog lookups, such as Claude search. The same module validates saved identity, key, and original endpoint under the settings lock before recording a limit. Deleted or replaced credentials are refused without marking the replacement. Renaming is allowed, and an in-flight request retains its captured label. A snapshot is not a revocation lease: it cannot prevent an already selected request from using a subsequently deleted key. Environment and inline limits use the process registry in [`accounts.gleam`](../src/albedo/harness/sdk/accounts.gleam) rather than credential persistence. Environment marking rechecks the captured variable, and inline marking rechecks the profile credential. Inline resolution reloads its noted cooldown. Registry limits remain scoped by store and account identity, and affinity remains scoped by store and session. Perplexity's [model account policy](../src/albedo/harness/extensions/perplexity/accounts.gleam) uses the account endpoint, profile endpoint, `PERPLEXITY_BASE_URL`, then the default endpoint. Its explicit `PERPLEXITY_API_KEY` fallback retains its captured identity and label, with transient limits. Environment values are never written to credentials. Search and catalog discovery use the typed discovery policy in the same module. Follow the shared [provider and retry rules](contributing.md#preserve-provider-and-retry-boundaries) when extending these APIs. Mistral keeps its plain-profile policy in [`mistral/accounts.gleam`](../src/albedo/harness/extensions/mistral/accounts.gleam): only endpoint-compatible saved keys are candidates, selected saved keys take precedence, and environment candidates follow. Explicit bindings use the shared selection path. Both paths carry the consumed snapshot for labels and limits. Zen's [account policy](../src/albedo/harness/extensions/opencode_zen/accounts.gleam) retains its endpoint aliases and environment precedence. It does not join a rotating key-account pool; free-lane selection remains request-owned. Malformed named profiles are refused rather than falling back to another credential source. ## Stored credentials and renewal [`credentials.gleam`](../src/albedo/harness/sdk/credentials.gleam) exposes opaque `Stored(a)` snapshots. Providers supply a decoder and retain their own credential types, identity rules, expiry policy, and HTTP protocol. Decoders use `lenient_text` for string fields that older stored credentials may hold as another type, and `/login` listings use `text` to read one string field from a raw credential. Both read a missing or non-string field as `""`. Account reads and binding do not establish session affinity. Ordering and affinity stay in the calling process. A separate read followed by binding is a snapshot, not a transaction across both operations. Login identity projections in [`claude/accounts`](../src/albedo/harness/extensions/claude/accounts.gleam), [`antigravity/accounts`](../src/albedo/harness/extensions/antigravity/accounts.gleam), and [`opencode_go/accounts`](../src/albedo/harness/extensions/opencode_go/accounts.gleam) can display incomplete legacy rows. A non-string refresh value is treated as empty for this projection. Claude retains a present account ID or email, and Antigravity uses its email or the empty-token fingerprint. OpenCode Go preserves field presence when choosing its token fallback. Listing a row does not make its credentials usable for a request or bypass renewal validation. `renew` rereads the captured public and provider identity under the existing per-home settings lock. Its callback runs in that same process and rechecks freshness before an exchange. The encoded patch merges into the current record, preserving unknown metadata and singleton or list storage. A failed write returns an error. Deleted or identity-replaced rows cannot be recreated by a renewal. The lock serializes this daemon's writers, not arbitrary external file editors. A concurrent successful refresh can replace both tokens. Provider callbacks accept a current fresh record with the same identity and refuse a changed refresh secret on a still-stale record. This does not distinguish a legitimate refresh from an external replacement that preserves the same identity and supplies a fresh token. A snapshot is not a revocation lease. Keep the returned snapshot beside the transport that consumes it. `mark` and `expire` require the captured identity and authentication material to still match. They do not mark a replacement credential. Inline and environment limits remain transient, with their source rechecked before recording a limit. Immutable labels and process-local served-account reporting survive the stream helper boundary. [`rotation.Pool`](../src/albedo/harness/sdk/rotation.gleam) owns retry budgets. Claude's one-time 401 renewal uses that owner without adding 429 hopping. [`google_oauth.gleam`](../src/albedo/harness/sdk/google_oauth.gleam) shares Google's token protocol between model and service accounts. Provider modules retain project provisioning, entitlement checks, cache policy, and request encoding. [Quota](quota.md) uses typed provider projections and the same renewal path, without session selection or sign-in. Failed renewal retains the account for a failed-authentication reading when its stored access token remains usable as an input to the feed. Antigravity's [account policy](../src/albedo/harness/extensions/antigravity/accounts.gleam) interprets Google limit responses and reconciles quota readings with cooldowns. Malformed details containers or exceptions during Unicode and duration conversion return not-a-limit without marking an account. Existing request retry handling still applies. Request marks use captured credential snapshots. Quota healing remains identity-based in its existing native transaction and does not gain snapshot replacement protection. A 403 whose details carry the reason `TOS_VIOLATION` means Google suspended the account. [`errors.suspension`](../src/albedo/harness/extensions/antigravity/errors.gleam) reads Google's message and an `https` appeal link, the extension shows both once, and `accounts.suspend` records a `suspended` object on the saved credential. Selection, discovery, quota reads, and limit advice skip suspended accounts; the failed request is not retried. A fresh `/login` of the account replaces the credential and clears the mark. Quota healing must not clear it. ## Sign-in [`oauth.gleam`](../src/albedo/harness/sdk/oauth.gleam) defines the sign-in declarations: `Login`, `Callback`, `DeviceFlow`, `Grant`, and `Keep`. Provider extensions own their token exchanges and account projection. [`oauth_flows.gleam`](../src/albedo/harness/sdk/oauth_flows.gleam) runs sign-ins. Its `Service` is an opaque handle to one owner process. The daemon starts it in [`server.main`](../src/albedo/daemon/server.gleam), linked to the daemon, and passes it in `registry.Config.oauth`. [`http_auth`](../src/albedo/daemon/http_auth.gleam) is its only caller. It calls `start_identified`, `get_identified`, `input_identified`, and `cancel_identified` with that handle. Nothing finds the owner by name. Pass the handle to any new caller instead of starting a second service, which would not see the first one's live flows. Extensions never receive it. They declare a `Login`, and the service runs that declaration's callbacks inside the flow process. The owner serializes admission, input, cancellation, and completion. It keeps durable records in `oauth-logins.json` under the settings lock. A record holds a keyed digest of the submitted intent and safe flow metadata, never submitted values. At most eight sign-ins are active at once. A flow waits five minutes for the browser or a pasted code, and a finished record stays readable for fifteen minutes. Each flow process owns the listening socket of its loopback callback listener, [`oauth_listener.gleam`](../src/albedo/harness/sdk/oauth_listener.gleam), a small HTTP/1.1 server over `gen_tcp`. A process linked to the flow accepts connections, and each connection is answered by its own process linked to that loop. A connection writes its whole page and closes before its query reaches the flow, so a callback that ends the flow cannot cut off the browser's page. The flow closes the listening socket before the code exchange. That stops accepting but lets accepted connections finish. A killed or crashed flow takes the accept loop and its connections with it. Do not give the listener process names or other per-start atoms; sign-ins can repeat without bound. A busy preferred port moves to an ephemeral one unless the `Callback` is `fixed`. Other bind failures fail the sign-in. The flow asks the owner to commit the credential and its completed record in one settings group. A restart keeps the records. A live sign-in from before the restart reads as failed with `daemon_restarted`. `exchange` receives the `Grant` with `issuer` set to the `iss` that the authorization response carried (RFC 9207), from either the browser callback or a pasted callback URL. `authorize` sees `None`. Mistral's [sign-in policy](../src/albedo/harness/extensions/mistral/sign_in.gleam) uses the custom `oauth.Device` callback rather than RFC 8628 `DeviceFlow`. It validates returned console URLs before polling or exchanging the token, keeps the PKCE verifier through exchange, and saves the minted key in the existing key-account format. Polls wait three seconds, with submitted input waking the wait early. A pending response resets the consecutive failure count; the third transport or non-success status failure ends the attempt. Terminal provider states and malformed success responses end it immediately. The initial future `expires_at` is converted from wall time to a monotonic duration. Missing, malformed, or past values use ten minutes. Expiry is checked before each wait, preserving a poll already admitted before the deadline. The deadline duration and waits use the same test timer scale. `oauth.wait_for_input` consumes one input wake in the completion worker. The sign-in service delivers input to the flow process itself, so the worker needs no handle to wait. The service terminates that worker on cancellation, including during waits and HTTP calls. Keep provider polling policy in the extension rather than adding another lifecycle owner. A `LoginResolverPlugin` names sign-ins at request time and supplies `keep`. [`http_auth`](../src/albedo/daemon/http_auth.gleam) resolves these through the installed extensions, enabled or not, and passes `keep` to `oauth_flows.start_identified`. The sign-in service then calls `keep` under the settings lock instead of storing a provider account. The sign-in's public id is its login's `store` key. Keep `keep` pure. MCP resource-bound OAuth and cloud signing/process authentication retain their separate owners. Ordinary credential snapshots do not replace their contracts. ### Terms warnings A provider whose terms forbid its sign-in outside its own apps sets `terms` on its `oauth.Login`: Claude, whose subscription sign-in passes as Claude Code, and Antigravity. `GET /auth` lists it on the sign-in with the notice id `terms:`; other sign-ins carry `null`. The copy lives in the provider extension, not in the clients. Clients show the warning before every sign-in to such a provider, with back and sign in anyway. They show it again before the first message on a profile that uses the sign-in, meaning a profile of that extension without an API key, and then never again: sending records the id in the ui group's `dismissed_notices`, which every client reads. Editing the message instead puts it back in the composer and records nothing. The terminal holds the message in [`terms.go`](../cli/internal/tui/terms.go) and [`app_terms.go`](../cli/internal/tui/app_terms.go); the web client in [`terms.svelte.ts`](../web/src/lib/terms.svelte.ts) and [`TermsDialog.svelte`](../web/src/lib/TermsDialog.svelte). Messages that agents, schedules or other non-human callers send are never held. ## Service and catalog reads [`credentials.gleam`](../src/albedo/harness/sdk/credentials.gleam) supplies typed read-only profile, stored-key, and service-section projections. Provider discovery does not establish session affinity. OAuth discovery can renew stored credentials or mint cached session tokens. Keep credential values out of diagnostics and public responses. OpenAI catalog discovery permits anonymous requests and tries matching inline, saved, then environment keys. Perplexity discovery tries the active matching profile first, other matching profiles, saved keys, then its environment key; Search uses that policy without an endpoint restriction. Mistral catalogs use endpoint-compatible selected saved keys, then its environment keys. These policies live in each provider's `accounts.gleam`, not in a universal resolver. Exa reads its `exa.apiKey` service section through `credentials.service`. [`http.gleam`](../src/albedo/harness/sdk/http.gleam) owns ordinary GET/JSON POST bindings with explicit request/connect timeouts. Streaming, provider status interpretation, and authentication policy remain with their existing owners. MCP credentials retain their stricter permission checks and resource-bound OAuth owner; ordinary service reads do not replace that contract. ## Related pages - [All topics](README.md) - [Change guidance](contributing.md) - [Models catalog](models.md) - [Persisted settings](settings.md)