small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs auth.md
12 kB · 214 lines
Markdown
at main

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 #

albedo_credentials 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.

Accounts #

albedo_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. Environment accounts cannot be renamed through rename_account.

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, 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.

The native adapter 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 existing process registry 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. 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, 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.

Sign-in #

oauth.gleam defines the sign-in interface. Provider extensions own their token exchanges and account projection. Native capabilities retain browser/device admission, cryptography, file caches, and process-owned resources.

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 existing OAuth owner terminates that worker on cancellation, including during waits and HTTP calls. Keep provider polling policy in the extension rather than adding another lifecycle owner.

MCP resource-bound OAuth and cloud signing/process authentication retain their separate owners. Ordinary credential snapshots do not replace their contracts.

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 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.