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 and quota for consumers of those choices.
Credentials #
credential_store
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. Under the same lock it then runs the
step its caller passes:
credentials.migrate
passes
account_migration.run,
which turns saved profiles and keys into accounts once per home. 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
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 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.
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 for background eligibility,
model lists, and
provider requests.
Accounts #
auth_accounts
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. Each sign-in also carries the email and plan its login's
oauth.Account descriptor reports, null when unknown, and needs_sign_in:
the shared needsSignIn mark, an Antigravity suspension, or a descriptor's own
needs_sign_in. Keys never carry them. Descriptors report only what the
provider said; never guess an email or plan. 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.
remove_account signs an account out and never refuses a saved one: a profile
pinned to it by accountId goes back to automatic selection, and it leaves
every accountIds list, which is removed when it empties. Only environment
accounts are refused (account_external).
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
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. Session affinity is daemon-wide, as rotation
describes.
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
that the caller passes in. The
runtime 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.keysand pass it inkey_accounts.Profile,key_accounts.environment_keys, andcredentials.candidates. - Catalogs receive it as the third argument of
ModelCatalog.list. - Quota sources receive it in
usage_feed.Source.accountsandprofile. - 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 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
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 when extending these APIs.
Mistral keeps its plain-profile policy in
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 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
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; remember does. A separate
read followed by binding is a snapshot, not a transaction across both
operations.
Login identity projections in
claude/accounts,
antigravity/accounts,
and
opencode_go/accounts
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 owns
retry budgets. Claude's one-time 401 renewal uses that owner without adding 429
hopping.
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 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 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
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.
/auth reports a suspended account as needs_sign_in.
Rotation #
A profile's accountIds lists the accounts it uses, in order, and its
rotation says how. credential_store.binding reads both under the settings
lock and returns the bound accounts with a credential_store.Rotation;
credentials.bound keeps it on the snapshots and credentials.order passes it
to accounts.arrange_by. Key pools read it through key_accounts.select. A
profile with a pin, or with neither a pin nor a list, is Automatic: its one
account, the provider's selected or first one, ordered as before.
failover(the default, also for an absent, null or unknown value): a new session starts on the first ready account in list order.spread: a new session starts on the ready account that was given to a session longest ago, so sessions and agents take turns.first: only the list's first account is bound. A limit is waited out or fails, as for a pin.
In every mode a session keeps the account it was given for the daemon's
lifetime, so its prompt cache stays warm. It leaves the account only when the
account is limited or needs sign-in, then stays on the account it moved to.
Requests never rebalance a session. accounts.remember records the session's
account in a daemon-wide ETS table scoped by store and session, and stamps when
each account was last given to a session, which spread orders by. Deleting a
session or closing an agent calls accounts.forget_session, so the affinity
table holds at most one entry per store for each session that is neither deleted
nor closed; an unloaded idle session keeps its account. Signing an account out
calls accounts.forget_account with its public id and its login identity, so
the stamp table holds at most one entry per saved account and store. Limited
accounts follow the ready ones, soonest reset first. The selected flag is not
read for a list.
Every mode, Automatic included, leaves out an account that needs sign-in.
credentials.refuse sets needsSignIn on the captured saved credential, under
the settings lock, when the provider definitively refuses it:
credentials.refused is a 401 or a 400 invalid_grant from the token endpoint
on renewal (Claude, ChatGPT, and Google renewals through google_oauth), and a
ChatGPT 401 on a model request for a profile that names its accounts. Other
renewal failures never mark it. A credential replaced or removed since capture
is left alone. A fresh sign-in replaces the record, which clears the mark.
A Claude sign-in's limit comes from two places. The quota poller's
heal marks the account until the latest reset of a window reported at 100
percent, so new sessions pass over it before a request is refused; a report with
room never clears a mark. A 429 marks it from the response headers, which the
model stream's
HTTP pump
hands the wire as a RefusalHeaders event: claude/accounts.limit_until takes
the latest reset (epoch seconds) of the windows a rejected
anthropic-ratelimit-unified-status names
(anthropic-ratelimit-unified-5h-status / -7d-status with their -reset),
else anthropic-ratelimit-unified-reset, else retry-after, else one minute.
These header names come from Anthropic's rate-limit documentation, not from
captured responses. The request then moves to another ready account of the
profile, since the session would move there on its next turn and its prompt
cache is lost either way; a Claude 429 is never waited out.
Sign-in #
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
runs sign-ins. Its Service is an opaque handle to one owner process. The
daemon starts it in
server.main, linked to the
daemon, and passes it in registry.Config.oauth.
http_auth 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,
albedo_oauth/listener,
a small HTTP/1.1 server over gen_tcp that shows the pages oauth_flows passes
it. 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.
An RFC 8628 DeviceFlow runs through
albedo_oauth/device.
oauth.device_start encodes the request bodies and supplies the albedo parts:
requests go through
sdk/http, so the flow's
network route applies, and before each poll the flow reports the declared
progress text and waits its interval, unscaled, or until submitted input wakes
it. The provider's credential builds the account from the whole token
response, and each typed failure is worded in oauth.gleam.
A model sign-in that creates a new account joins its service in the same
settings group as the credential, through auth_accounts.joined. Each profile
of the extension with accountIds gains it at the end. Each with neither a pin,
a list, nor a saved key rotates through every saved sign-in of the store, in
file order. Pinned and keyed profiles are left alone. When no profile uses the
extension, the sign-in creates one named after it (name, name-2, ...) with
rotation: failover, and makes it the default when none is set. Its model is
the first one the extension's catalog lists, which is what clients pick, and its
protocol is the one the adapter takes. http_auth supplies that as
start_identified's first_profile, and the flow asks it outside the settings
lock only when no profile uses the extension; with no listed model no profile is
created.
A descriptor's id names the account, and signing in again replaces a saved
account only when the ids are equal: the credential is replaced and the account
keeps its public id, label, and place in every list. An account is a user in a
workspace or organization, never an email, since several accounts can share one:
a person can have a personal and a business ChatGPT workspace on one email, and
a workspace holds several people.
- ChatGPT names it
<user>@<workspace>: the token'schatgpt_user_id(else itssub, else the stored account user id) and itschatgpt_account_id. - Claude names it
<account UUID>:<organization UUID>from the account profile, read at sign-in. A sign-in from before this was named by a token fingerprint; its first request recordsaccountUuidandorganizationUuidon it (claude/accounts.record_subscription), which its descriptor then names it by, so a later sign-in to the same subscription replaces it in place. A legacy sign-in that has not recorded them is never matched, and signing in again adds a new account. - Google (Antigravity, Colab) names it by its email, which a Google account owns alone.
A new account is labelled with its email. When another account of the provider
already has that email, the label adds the first of the workspace or
organization name the descriptor reports (workspace; Claude reports its
organization name, also shown as its detail), the plan, or #N that no account
is labelled with. Existing accounts are never renamed, and a renamed account
keeps its label when signed in again.
Mistral's
sign-in policy
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 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:<provider>; 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 and
app_terms.go; the web client in
terms.svelte.ts and
TermsDialog.svelte. Messages that agents,
schedules or other non-human callers send are never held.
Service and catalog reads #
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 sends ordinary
GET and JSON POST requests with explicit request and connect timeouts, through
albedo_http/buffered
under the caller's route. 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.