Map: exarch / provider
provider.rs is the LLM facade over genai: it owns Provider and its live
or scripted Backend. The transcript owns
history; the provider only sends bytes and parses replies. Invariants are
local below the facade: provider/identity.rs owns selectable identity,
request.rs per-request ChatOptions and tuning (Tuning, the
EFFORT_LADDER rungs — the TUI keeps only the glyphs). Tuning::masked is the
shared capability mask for the picker and synod; Tuning::for_model resolves
synod’s effort choice and loads the catalog before masking. wire.rs is the one place
that turns the transcript’s ChatMessages into an owned genai::ChatRequest (below),
transport.rs credential binding and caching, stream.rs completion
execution, retry.rs recovery timing, usage.rs accounting,
error.rs fault classification, listing.rs model-list fetch
orchestration, tools.rs the tools a request may advertise (ToolSpec,
Toolset, wire definitions only; dispatch is agent::tools’), via.rs the
upstreams a routing service serves a model via (Via), and state.rs the
persisted choice. The public facade
re-exports their established types; sibling modules meet through narrow
methods on Pool and Transport, not visible fields. Pool
(provider/transport.rs) owns the shared async runtime and transport cache;
the agent’s ral Engine is a different lifetime and responsibility.
Services and accounts
Selectable identity is a product of two things, not a sum over provenance.
A Service is where bytes go — endpoint, wire adapter, billing, model list.
An Account is who is asking — an id, a credential, and a name for itself.
One service may own many accounts. Chatgpt and Grok distinguish returned
subjects, not emails or assumed workspaces. Codex distinguishes subject and
backend account/workspace id together; two people in one workspace cannot
overwrite one another. A key-bearing service owns exactly one account and
borrows the service’s name.
provider/identity.rs owns both, and the two newtypes that keep them apart:
ServiceNamehas two constructors, because its sources differ in trust: the built-in table is known good, a declaration is input.declaredrefuses an empty, colon-bearing, or control-bearing name, each with its own sentence. A declared name equal to a built-in’s is refused at load, naming it: an account id is a service name, so a shadow would be an identity collision, not a harmless override.AccountIdrenders a key-bearing account as its service’s name, and a login as"{service}:{issued}". Service names carry no colon, so the first colon separates the halves and the rendering is injective. Nothing ever parses one.state.json, the model cache, the record log, synod’s wire and--providerall compare a rendering against the renderings of the accounts actually present; there is nofrom_str, and adding one would reintroduce the ambiguity the type exists to prevent.
built_in_services() is the table — ten key-bearing services (Anthropic,
OpenAI, OpenRouter, DeepSeek, Gemini, opencode Zen, opencode Go, xAI, Qwen, Meta)
plus Login::ALL’s openai-chatgpt, openai-codex and xai-grok — as struct literals rather than a value enum. A declared
endpoint is the same struct parsed from a hand-written config.ral, with
the protocol mapped onto genai’s AdapterKind at decode time; provenance is
not a type. See provider-config-ral-script.
Service::routes is true for OpenRouter alone, and is what admits a Via, so
no code compares a service name against the string "openrouter".
Service::model_protocol is ModelProtocol::Fixed(adapter) or OpenAI’s
model-dependent Completions/Responses split; adapter selection never dispatches
on a service name. Service::hosted_search separately states whether the
service supplies native search or the external-access form Codex uses.
Declared endpoints advertise no hosted search merely by sharing a protocol.
Service::auth says how a service authenticates — Key(var), OAuth(Login),
or Keyless — and never the secret itself. A declared endpoint’s var is
identity::key_var’s {NAME}_API_KEY, never written in the declaration;
Keyless is the declaration’s key: `none, a fact about the server.
meta binds META_API_KEY to https://api.meta.ai/v1/ with fixed Responses
encoding, metered billing and no hosted search. Its authenticated model list
uses the same endpoint’s /models through genai; it adds no sign-in flow.
An account and its authentication have one home. CredentialStore owns
ordered AccountEntry values, each holding an account and AccountAuth: a
key’s environment/vault layers, an OAuth CredentialHandle, or keyless access.
A key resolves to the environment’s, else the vault’s; a retired login is
unavailable. available() derives the usable accounts; known() borrows all
of them. Roster snapshots bound account/credential pairs, retaining shared
OAuth owners, and exposes accounts by borrowed iteration. The model catalog,
listing, transport cache and picker name accounts by AccountId.
A handle is local; a label is set-relative
An Account::handle is derived from that account’s own credential alone: the
email, else the issued identity; Codex qualifies it with workspace or plan.
For a key-bearing service it is simply the service’s name. Admission needs
no set; refresh updates only that credential owner. exarch logout removes
the local record and attempts issuer revocation for Chatgpt/Grok. Codex
returns Revocation::LocalOnly; its refresh credential may remain usable.
Issuer acceptance does not promise immediate access-token invalidation.
identity::label(account, among) computes the set-relative name, and is
the one place in either product that names an account. It takes the set
because the answer depends on it, and it is never stored: a name that is a
function of the whole set cannot be cached in a single record, because there
is then no reconciliation path when a sibling arrives or leaves. The service
alone when the handle is the service’s name, the service and the handle both
otherwise, and the id to separate a tie — nothing is decorated, because how an
account bills is Billing’s business, not its name’s. The tie check also compares against the
other accounts’ id-qualified forms, so a handle that happens to spell one out
(the claims are issuer- and workspace-supplied) cannot impersonate a sibling’s
label.
anthropic
opencode-go
openai-chatgpt · alex@bristol.ac.uk
openai-codex · alex@bristol.ac.uk (workspace) · <issued id>
The honest limit: a live session’s status line keeps the handle it started with, because a mid-session refresh does not re-derive it. A changed email appears at the next launch.
The one place the log may hold a label is record.jsonl, where it is a
snapshot of what the account was called when the session began — which is
what a log is for.
One authority on metering
Service::billing is the sole authority on whether a turn costs money, and
Transport::metered is billing == Billing::Metered — the whole derivation.
The three login services and opencode Go are FlatRate; a subscription turn reports
tokens and never a cost. There is no second derivation to disagree with it;
one keyed on the login kind would report a future metered OAuth service as
free.
Service::meter answers a different question, and is deliberately not derived
from billing. Billing says does this turn cost money; Meter says does
this account publish what is left. The two are orthogonal and the table says
both: OpenRouter is Metered and publishes spending budgets, a declared local
endpoint is Metered and publishes nothing. openai-chatgpt and xai-grok
are FlatRate with Meter::Unpublished; ChatGPT token-sharing usage is in
Settings → Usage. openai-codex is FlatRate with Meter::Codex, reading
wham/usage windows and durations from the server (five hours and one week
are common, not fixed semantics). Meter::OpenRouterBudget reads /api/v1/key:
its effective_budget is authoritative, including workspace and guardrail
limits; otherwise the key’s spend is limit - limit_remaining. Lifetime
usage is comparable only to a non-resetting limit, with BYOK included when
that limit counts it. A resetting limit without a remaining amount fails
rather than guessing. An uncapped key reports lifetime usage and an unknown
account balance, never unlimited credit. Account-wide /credits requires a
management key and is not queried. See OpenRouter’s
current-key contract.
Every service states its meter explicitly; billing never implies a readout.
What a meter reports is one value type, provider/allowance.rs’s Allowance:
a quantity of entitlement, consumed against a bound. Scope distinguishes
server-defined windows (Duration, possibly undisclosed) from scoped budgets
with daily, weekly or monthly UTC resets; a calendar month is never a fixed
number of seconds. Labels derive from typed scopes and periods, never vendor
prose. Consumption keeps disclosed proportions and counts apart: a percentage
reads as 42% used, money retains spend, cap and remaining amount. A zero cap
is exhausted even at zero spend. Both warnings and presentation read this one
normalised value; the UI computes no independent budget arithmetic.
/limits has a neutral title and equally styled account sections, separated
by whitespace, with columns shared across the whole card. Its bars fill with
the consumed share, matching the number beside them.
Reading one mirrors ModelSource deliberately, so a reader who knows the model
path knows this one: MeterSource is the single seam the network sits behind,
LiveMeters its live implementation over a Roster, and Survey the
Fetches pump that reads every account concurrently — the same pump Listing
uses, unchanged. The one match from Meter to a request lives in
LiveMeters::read, and it is the whole extension point: another vendor is one
Meter variant, one arm, one allowance::meters module, and one meter
argument to the keyed builder. Nothing else moves. /limits keeps no cache
and no TTL: a ration is an instantaneous fact about a rolling window, and a
stale figure would be wrong in exactly the situation that prompted the
question.
What is known of each account’s allowance has one home, Rations
(provider/rations.rs), fed on the one road every model request travels.
The record is the third of the Holdings, beside the store and catalog —
exarch builds one, synod one for all its conversations — and keeps, per
account, the last meter reading, the user’s ration latches, and the instants
refusals said it is held until: the whole account for a spent allowance, one
model for a rate. Provider::complete is the only caller of
Pool::complete, so its live arm is where nothing can go around:
Rations::admit before the send refuses a held request with Refused and
nothing sent — only when the hold’s Refusal::recovery is Deferred, a
nearer one being waited out in place — else spawns a read of the account’s
meter when two minutes have passed, its reading landing straight in the
record; Rations::settle after it keeps a refusal’s resets_at, the later of
old and new, on the scope its Limit names. The read source rides the
provider: Bureau::build clones the roster out under one store lock, binds
the transport to its credential, and hands the roster to a LiveMeters in the
same Backend::Live, so the meter is exactly as fresh as the transport. The
latches are one per window, so a usage rung is told to the user once per
account, by whichever agent climbs it first (Rations::climb). Rations
holds no store and takes no lock but its own leaf one. /limits
(Bureau::survey_allowances) reads every account fresh and Survey::settle
lands each reading in the record before drawing its card, so no frontend can
survey without feeding it; the agent’s ration gauge
(agent) only climbs Provider::allowances, the record’s
last reading, at Allowance::percent — the same consumed share represented
by the card’s percentages or exact budget figures. Success responses carry usage too, but genai does not expose
their headers; when it does, they are one more input to settle.
On disk the login store is persisted through OwnDir::store with
Visibility::Secret (provider/oauth/mod.rs): the file is replaced whole and
atomically, and born owner-private whatever was there before. The Unix arm
creates it mode 0600; the Windows arm gives it an owner-only,
inheritance-protected DACL at creation, so at no instant does the token file wear
the parent directory’s inherited ACL. A store that cannot be read is never
written over: a failed read aborts the write and returns its error. The document
holds the host id and service-qualified AccountId entries. StoredToken
stays flat; conversion checks grant-specific required fields and key agreement.
Unknown services (including old chatgpt), invalid semantic fields and key
mismatches drop only that entry with a non-secret warning. Invalid JSON or
structurally undecodable required fields make the whole store unreadable.
Queries do not rewrite it; successful writes omit rejected entries. Upserts
compare the full account id, never bare issued identity across services.
Credential rotation
oauth/session.rs owns one canonical CredentialHandle per store/account and
one process-lived refresh executor. Exarch and Synod share Exarch’s oauth.json;
product-specific vaults, configuration, logs and model caches remain separate.
StoreLeasecombines an asynchronous process gate with a stableoauth.lockfile. Refresh, read-and-attach, login commit, host-id creation and removal all use it. The predecessor is reread under the lease, which spans issuer exchange and commit. Only the lease can attach, publish or retire an owner. The synchronoustransactionwrapper panics on an async worker instead of risking deadlock.Stateseparates pending subscribers fromCredentialState: aLivecredential (ready, uncertain, or an unsaved predecessor/successor pair) or a retired one. Exhaustive, pure reconciliation returns onlyLive: it retains unresolved outcomes while disk still names their predecessor and adopts a changed credential otherwise, so preparation never meetsRetiredafter it. Login and removal publish before returning;login_flowreturns the committed handle, not a token for delayed admission to overwrite.- Retirement refuses preparation while disk lacks the account. A login committed by another process revives the same canonical owner at the next preparation or credential load; a pre-removal snapshot cannot recreate it.
oauth::credentials()returns the store or lease failure rather than an empty list;resolve_and_scrubwarns on stderr and offers no logins, so a lease timeout at startup is never a silent absence of accounts.- A caller may cancel its wait; the owner retains a submitted exchange through persistence. The caller’s 30-second deadline bounds lease acquisition and the decision to submit (once passed, nothing is marked or sent); a submitted exchange runs under its own fixed 30-second budget, so lock contention cannot shorten it. Snapshots take only a short mutex, never a network or file-lock wait.
- A refresh fails as a
RefreshError, typed by whether the issuer may have rotated the token:NotSubmitted(client build, connect, DNS or TLS failure: provably unsent),Rejected(the issuer answered a 4xx) orAmbiguous(sent with an unknown outcome: a timeout, a dropped connection, a 5xx that may follow a committed rotation, an unreadable or unusable success body). The credential isUncertainwhile the exchange is in flight; onlyAmbiguous, or exhausting the exchange budget, leaves it so. The other two restoreReadywith the same token, and the error says a retry is safe. - Within the owning process, an ambiguous exchange is not replayed. A failed write retains the fresh live token and its disk predecessor; a later preparation can retry that exact write. A changed or removed disk account wins. Uncertain and unsaved outcomes are process-local: a peer can still read the persisted predecessor after the lease is released. Signing in again may be necessary after ambiguity, failed persistence or process death; rotation is not crash-atomic with the issuer.
- Shared recovery names an escaped service-qualified account, not a product
command.
Transport::preparereturnsBeforeRequestcancellation or terminalOtherfailure; refresh does not spend the model retry budget or invent usage.
The sign-in
Login::{Chatgpt, Codex, Grok} determines service and supported Method:
Chatgpt browser, Codex browser/device, Grok device. Login::title is the one
name a person reads (“ChatGPT”, “OpenAI Codex”, “xAI Grok”); Service::name is
the one configuration and logs use. SignIn::New(login, method)
adds an account; SignIn::Renew(token, method) refuses a different identity.
OAuthToken has common credentials and Grant-specific data. Chatgpt/Grok
use nonempty subject as issued identity; Codex uses the injective
base64url(sub):base64url(chatgpt_account_id) composite, retaining the raw
backend id separately for headers. Naming metadata does not participate in keys.
Issuer refresh functions send through the shared submit_refresh and return
RefreshUpdate<M> with typed naming/token metadata, or a RefreshError. The dispatcher matches the grant once and preserves issued identity,
Chatgpt client id and Codex backend id when applying the update. The flat disk
schema remains separate so semantic errors reject only the affected entry.
Chatgpt preserves dynamic registration, host id, issued client, nonce, scope
and ID-token-hint behavior. Codex reuses the Codex CLI public client and
Grok pi’s xAI client; reuse is not issuer approval. Grok’s initial ID-token
subject and bearer compatibility with Xai inference and /v1/models remain
live-unverified. See sign-in-with-chatgpt-token-sharing
for policy and deferred acceptance, including no migration of chatgpt:*.
The /login overlay chooses accounts or one new-account row per login, then
only supported methods. LoginPhase distinguishes browser URL, device
code/URL/expiry and code exchange. Choosing bounds its account viewport;
running/failed phases collapse the roster so instructions remain visible.
Esc closes immediately and signals cancellation; sliced waits observe it
within a tick, while in-flight HTTP remains bounded by its timeout.
Browser callbacks share oauth/loopback.rs’s nonblocking worker and callback
path constant. Only a matching-state callback settles a flow; stray,
malformed and duplicate-field requests close or reject that connection only.
The worker holds at most eight connections, each with a 16 KiB request-line
limit and an absolute two-second read deadline, beneath one fifteen-minute
flow deadline. Accept/read work is bounded per iteration; cancellation is
polled at most every 50 ms. Responses have a 100 ms deadline clipped to the
flow’s; failed delivery cannot undo a validated callback. Cancellation and
flow expiry close pending sockets without flushing. The browser acknowledges
callback receipt, not the subsequent token exchange or durable sign-in.
Connection::advance takes its time explicitly and reads/writes through its
stream; expiry is tested with forced backpressure, independently of socket
buffer capacity or scheduler timing. Socket round-trip tests leave a full
second for responses; peer closure may report either a reset or an abort.
Two layers for a key, the environment’s on top
Environment resolution is exarch’s own story: CredentialStore::resolve_and_scrub
sweeps every Auth::Key service’s variable once, at single-threaded startup,
into the store’s environment layer, and scrubs what it found (see
a-grant-never-reaches-its-own-key)
so neither a child of a tool call nor the session itself can read a live key
back. The sweep is therefore un-repeatable by
construction, and that layer never changes after it.
The other layer is the computer’s own credential manager. synod
was built for it; exarch reads it too, at startup in lib.rs through
CredentialStore::read_vault, an ordinary second call that scrubs nothing,
and writes it through the shared Wallet (below). The environment’s key
outranks the vault’s, in both products: a variable set for one run is the
narrower, more deliberate act, and a vault key beneath one is kept and shown,
not discarded. A vaulted key, unlike a scrubbed variable, is somewhere a child
could ask for it: a confined child cannot, since the macOS profile admits no
securityd and the Linux envelope binds no session bus unless a grant reads
/run/user, but an unconfined session can, like any process of the user’s.
Each launch reads the vault once per key-bearing account:
provider/keychain.rs—Keychain::for_app(App)reaches the macOS Keychain, the Windows Credential Manager, or a Linux desktop’s Secret Service through onekeyringentry named(app, account-id), so two products’ keys are two entries exactly as their config directories are two directories. Only key-bearing accounts reach the vault, and their ids are their service names, so an entry name stays short printable ASCII and no login account id ever becomes a Credential Manager target.Entry::store_status()is asked first; a computer with no credential manager falls back to an owner-only file beside the app’s configuration, andvault()answers where secrets actually land in a sentence a window prints verbatim rather than implying a protection that is not there. A blank or control-bearing entry reads as no key, the rulecredential.rsalready applies to a key read from the environment.provider::credential_files— every file on the computer holding one of our credentials: each app inapp::APPScontributing its keychain fallback path plusoauth::token_path.policy::for_invocationdenies all of them to every grant that attenuates the filesystem at all, since the base profiles read the`xdg-config/`xdg-stateplaces wholesale and would otherwise hand the agent the key that pays for its own turn — see a-grant-never-reaches-its-own-key.- the OAuth token store and that fallback file are both written through
ral_core::own’sOwnDir::storewithVisibility::Secret: one implementation of the owner-only promise, in the walk, instead of two copies.
The store’s mid-session mutators exist for an accounts screen: known (every
account, bound or not, since one with no key is precisely the one a user has
come to give a key to), declare (a declared endpoint’s arrival),
save_key/forget_key (the vault layer only; the environment’s is fixed),
and retire (drop an account entirely: a withdrawn declaration, a signed-out
login). from_environment and from_vault read the two layers apart, so a
screen can say which key is in force and which lies beneath it without asking
the vault again. See
synod-keeps-its-own-accounts,
whose order this reverses.
provider/accounts.rs holds the rest of what an accounts screen needs:
declared_endpoints, declare_endpoint, withdrawable, checked_key, a
find that resolves by AccountId alone, and the plain Entry/Source row
derivation (entries) both products draw from: the source in force
(Environment, Vault, Keyless, SignedIn, or None), the last four of
its key, the last four of a vault key the environment’s outranks
(shadowed), and the variable a key is read from. wallet.rs, above both
config and provider, holds Wallet { keychain, declarations, label }:
the one route through which a product changes its keys and declarations
(set_key, forget_key, add_endpoint, forget_endpoint), each checking
everything before writing anything, touching the vault with the store
unlocked, and applying the change live through Holdings::change.
Wallet::of(app, declarations, label) builds Keychain::for_app(app) and
the declarations UserFile in that app’s config home. Wallet::prepare
loads declarations, resolves and scrubs environment keys, then reads the vault;
both products call it while startup is still single-threaded. /providers
uses exarch’s wallet; synod’s accounts::wallet() builds its own through of.
An OAuth login is no wallet’s: the token store is exarch’s whichever
product signed in. Holdings::sign_out removes the token and retires the local
account; the caller runs oauth::revoke_blocking off its UI thread and reports
issuer acceptance, local-only removal or revocation failure without conflating them.
config.rs is likewise generalised: load_declared(path, label) reads either
product’s file, and save_declared writes the same .ral source back — a
file a program wrote and a person can still edit, which is the whole reason
declarations are .ral and not an opaque blob. A declaration is an address,
a protocol, and at most key: `none; anything else under key is refused
without being echoed, since what was written there may be the key itself. A
label or address carrying a quote is refused with a question rather than
escaped.
Building the transport
provider/transport.rs::build_client binds the resolved Credential to a
genai Client:
- An API key keeps the provider’s native adapter (it fixes the wire
format, so an Anthropic provider speaks Anthropic even at a custom base URL).
A custom
endpointredirects the service target through aServiceTargetResolver; with no endpoint the native default target is used, gated by anAuthResolverthat hands the key only to that adapter. genai’s unknown-name fallback to local Ollama is overridden — the provider is the authority, so a misspelled model fails at its provider rather than silently hittinglocalhost. - An OAuth login branches to
build_oauth_client, using its service’s adapter (OpenAIRespfor Chatgpt/Codex,Xaifor Grok). The resolver readsOAuthToken::auth_datafrom the shared owner’s current snapshot. Chatgpt/Grok supply the bearer; Codex supplies a backend Responses URL override andrequest_headers, including the raw backend account id, beta, originator and user-agent headers. Other grants never receive Codex headers.CredentialHandle::prepareis shared by inference, catalogs and Codex allowance reads. Each inference attempt prepares after its retry wait, before manufacturing the request; preparation failure sends no model request. Issued identity, Chatgpt client id and Codex raw backend id stay pinned; naming metadata may change.
One owner for construction
Provider::build(backend, &account, selected) constructs a client holding its backend,
account and immutable Selected stamp. The bureau builds a live transport using its
Pool and credentials; the client retains no construction authority.
Minting a second selection has nothing to work from unless the pool and the application’s
Holdings — credential store, model catalog, allowance record, whose lock
discipline is stated once on the type — are reachable together.
provider/bureau.rs names them once: Bureau::Live { engine, holdings }, or
Bureau::Scripted for a session that mints nothing (Pool::new primes the
pricing catalog over the network, so no unit test may build one). It mirrors
Provider’s own Backend::{Live, Scripted} split rather than inventing a
second idiom.
Bureau::build is the live constructor of Provider; the scripted
constructor uses the same stamp-bearing Provider::build inside provider.
available, admit (a /login’s admission) and with_catalog are the rest of the surface. The two halves are shared
(Arc<Mutex<_>>) rather than owned, so two hosts compose: exarch builds one
bureau over its own pair in run(), while synod keeps the same pair as
application-wide window state and mints a provider pool per conversation. They are
two mutexes and not one so that a credential read never queues behind a
catalog fold, which writes the disk cache under its lock.
Lock discipline, synod’s own rule inherited: locked briefly, never across
a network call, a picker frame, or a machine boot; and the converse, that a UI
thread never holds either while waiting on an agent thread. Bureau::admit is
the one call that takes both at once, store first. The /model overlay’s
drive therefore takes the catalog per fold — to open the Listing,
to pump it, to record endpoints, to clone the fetch seam — and never around
the fetch itself; Bureau carries Arc<Bureau> on LaunchConfig and from
there on the fleet’s Launch, the one place a run’s host settings live,
beside factory.
Model catalogs
An account’s own listing is the authority on what it serves. The picker
offers only listed models, --model alone resolves to the one account whose
listing names it, and Bureau::build refuses any other choice, so no account is
ever asked for a model it does not list. ModelCatalog memoises and
disk-caches both paths:
-
Roles (
provider/roles.rs) are the one way a spawned agent gets a model other than its parent’s, and the human binds them.--role NAME=MODEL(repeatable) resolves MODEL exactly as--modeldoes throughstate::named— to the one account whose listing names it, or to the account--role-provider NAME=ACCOUNTgives (ACCOUNT as--provideraccepts it), the tie-breaker the ambiguity error asks for;--role-via NAME=TAGSgives the upstreams that serve it (TAGS as--viatakes them). Each of the three flags refuses a name given twice, and the latter two a name no--rolebinds.Roles::mintbuilds eachChoicethroughBureau::buildonce, at launch, with the launch’sTuning(Tuning::initialplus--effort) and--max-tokens; a later/modelchanges only the switching agent’s own provider. Roles are flags only, never persisted, and absent by default: with none, every child inherits and the system prompt says nothing of roles.RolesridesLaunchConfigintoLaunch; the desk’schild_providerresolves`role <name>against it, and theRolesprompt section (data/roles.mdplus onename: modelline per role) is taught only to an agent that spawns. The agent never lists models or names an account: the catalog is not an ambient authority. -
Anthropic, DeepSeek and Gemini list through exarch’s own
GET /models(paged to the end for Anthropic and Gemini), because each reports a context window genai discards; other API-key providers list through genai’sall_model_names. Each of the three is oneNativerow inmodels/native.rs— base URL, how the key is presented, paging, page parser — andNative::ofis the only place an adapter picks one. Every listing isVec<Listed { id, context_window }>, and the picker sees only the names. Native parsers refuse malformed catalog envelopes, model IDs and pagination metadata; repeated cursors fail instead of revisiting a page. A legitimate empty array remains an empty catalog, not a parse failure; Gemini’s omitted or null fields retain their ProtoJSON default semantics. -
models::list_logindispatches after the shared stale-token check.plan_modelspreserves server order,visibility == "list"and context windows for Chatgpt’shttps://api.openai.com/v1/modelsand Codex’s backend catalog. Codex sends its raw-account headers andclient_version, pinned to0.164.0unlessEXARCH_CODEX_CLIENT_VERSIONoverrides it. Grok lists through genai’s Xai adapter. Its OAuth/v1/modelsacceptance remains live-unverified. -
Bureau::buildis the one place a selection passes, and takes aChoice: an account, one of its models, and theViait is served through, if any. It refuses a via on a service that does not route, or one naming an upstream the model’s endpoints do not list; a via’s window is the least its upstreams hold, an upstream listing none holding the model’s. A plan account (Service::shares_a_plan) gets a selection carrying reasoning effort alone: the token-sharing route refusestemperature,top_pandmax_output_tokens, so none rides one. It reads the serving account’s listing once (models::listing_of: the cache, else one fetch made with the catalog unlocked), refuses a model the listing does not name, and resolves the context window from it: the listing’s own figure, else the OpenRouter catalog, else unknown. The bureau stamps the result inSelectedwith the label snapshot, model, account, service, via, accepted tuning and token cap. The immutable client carries it; installation records it inControl::SessionStarted,SessionResumedorModelChanged. Agent code reads the cell’sModel, not the client stamp, thereafter; the view folds the same records without a catalog. Unknown window is?. -
/loginadmits an account mid-session throughprovider::admit_login, which runsCredentialStore::add_logininsideHoldings::change: every change to the store goes through that one route, which hands the catalog the store’s freshRoster(ModelCatalog::set_roster), so a key saved, a key forgotten and an endpoint withdrawn reach the listing as a login does. Re-login commits to the shared owner before admission; attaching that owner cannot restore an earlier token. A login that has learnt its email is renamed where it stands, its identity being the account id throughout. -
OpenRouter serving endpoints remain a separate request per model; the
/modeloverlay makes it for whichever OpenRouter model is highlighted, andBureau::buildfor a model minted with a via.ProviderEndpoint::tagkeeps the full endpoint tag, including variant or region suffixes. AViais an ordered, non-empty, duplicate-free list of those tags, most preferred first, sent asprovider.orderwithallow_fallbacks: false: every request is served by an upstream the via names, or by none.--via,--role-viaand the picker’s via row (one tag) choose one; without one, OpenRouter chooses per request. The picker shows the suffixes and keeps one row per distinct tag, in server order: selection resolves by tag, so repeated tags would trap navigation. -
listing.rsstates the picker-side orchestration once for every front-end (the/modeloverlay and synod’s window alike): theFetchStatevocabulary, a keyed background-fetch pump (Fetches), and the per-providerListingthat seeds from the catalog’s cache and fills misses in as they land. -
state.rsremembers the choice — account, model and via — as the project’sstate.json; tuning is never replayed: a remembered effort can be one the new model rejects, and the flags and the picker set it. A restored via is rechecked against the model’s endpoints like any other.opening(flags, saved, available, listing)decides what a launch opens on (Opening::Namedfrom the flags,Restoredfrom the saved choice, elseChoose— the picker); a refused restore opens the picker instead of ending the launch or, headless, fails.
The streaming path
complete(request, on_delta, cancel), aRequest { system, transcript, tools, search }— streams one assistant reply, callingon_deltawith aDelta::Sayper text chunk, aDelta::Thinkper reasoning chunk, and aDelta::Retry(&ProviderError)when an attempt failed and is being re-issued (the deltas before it belong to the failed attempt, the ones after to the new), and projects theStreamEndinto aStepOut(assistant message, tool calls,Usage,StopReason). One callback rather than two because the order of the two kinds is the caller’s whole interest: a reasoning run ends exactly where the prose after it begins, and two independent callbacks cannot say so.step_out_from_endpreserves captured structured content as authoritative: signed reasoning keeps its exact signature bytes, order and pairing, including equal text signed differently. Aggregate reasoning is appended only whencontains_reasoning_content()is false, not compared or deduplicated by text. This is the model-facing content; display commits are authored from deltas. The stream-event match is exhaustive: any tool chunk and any nonempty signature, reasoning or text chunk are generated-work evidence (heard), but only non-whitespace answer text setsspoke. Start, heartbeat and empty string deltas prove no generated work. Tool/signature content is admitted whole fromEnd, never reconstructed from incomplete chunks (X10).- Liveness is one byte-level clock, owned by genai.
complete_optionssetsstream_header_timeout(STREAM_HEADER_TIMEOUT, 3 min) andstream_read_timeout(STREAM_READ_TIMEOUT, 10 min, per raw body chunk, SSE comments included) on every request, and the stream loop races only the cancel scope againstnext(); aHeartbeatevent adds nothing there. The bound is patient because HTTP/2 PING and TCP keepalives (provider/tls.rs) evict a dead peer in about 45 s, so it only judges a live server gone quiet. reqwest’sREAD_TIMEOUTstays as the backstop for every client sharing it, held 30 s above the read bound so genai’s namedStreamTimeoutwins;Faultclassifies itTransient. This lands the slice of provider-heartbeats-and-retry-boundaries that fits genai as released: no fork, no semantic clock. - Streaming is the only completion path the pool runs. There is no second, non-streamed path: bounding the window is `Agent::force_eviction`‘s job and it makes no provider call at all (context-rollover).
cancel: &ral_core::process::Scopeis the exchange-local cancellation view, passed explicitly byAgent::deliberatethrough streaming, credential preparation and retry waits. Each child has its own exchange under its life ancestry; there is no exarch token or reset.wait_for_cancelpolls the scope, so its polling period bounds sampling latency, not arbitrary in-flight waits (an-agent-is-a-thread, agent).
Retry driver
Streaming in provider/stream.rs runs on a tokio runtime through one retry
driver, provider/retry.rs::retry_with_backoff, over an Attempt<T> (Done
/ Failed):
- The streaming-specific rule rides on
Done: only answer text survives into the transcript, so once prose has flowed toon_deltaa re-issue would double it. A failure then commits asstalled_step_out, aCutShort::StalledStepOutreturned asAttempt::Done, only ifProviderError::retryable(the driver’s own verdict,retry.rs::budget) says it would be retried; any other error surfaces as itself. A failure before any prose, reasoning alone included, goes to the ordinary retry loop. No third “don’t retry” variant is needed.CutShortlives inprovider/error.rsbesideProviderError, whoseTruncatedcarries it: one type says why a turn was cut short, and each arm carries its own remedy (provider-fault-recovery). Provider::completepasses a record-independentbefore_attemptcallback.before_requestinvokes it after retry evidence and beforetransport.prepareor HTTP; scripted completion invokes it before consuming a reply. Failure becomes nonretryableProviderError::Unavailable. The agent’s outer sync precedesRations::admitand preserves the original recording failure before cancellation classification.- Each attempt is handed the failure it replaces (
Nonefirst), which the stream emits asDelta::Retry { cause, lost }before the new attempt’s deltas (lost: the usage of an attempt that streamed output the provider never reported): the commit producer seals the failed attempt’s lanes there anddeliberaterecords the lost usage and aForensic::Retried, the log’s alone, drawn by no renderer.heardyields one unknown delta per generated attempt actually retried, not per chunk. The record seam meters that delta once; replay folds the same fact. A successfulEnduses its report, or one missing-report fallback, without also chargingheard. Terminal failure and cancellation do not acquire new accounting here. - Rate limits get a larger budget and a higher backoff ceiling than transient
failures, and a named wait is honoured. A
Refusedwhose reset lies past that ceiling (Recovery::Deferred) surfaces on its first attempt, and the agent resumes it by a wakeup at the reset (provider-fault-recovery).
Transport retry lives here, so the nudge rules cover only model-behaviour outcomes, not transport.
Structural error classification
ProviderError::from_genai (provider/error.rs) reads retryability from
genai’s typed variants, not from its Display string. A single structural walk, Fault::of, descends
each error to one of three leaves — Response (a provider error with an optional HTTP status), Transport
(a reqwest fault with no status), or Terminal (no recoverable leaf) — recovering
the StatusCode, the response HeaderMap, and the parsed JSON body across the four
paths a non-2xx reaches us by: HttpError, WebModelCall(ResponseFailedStatus),
the HttpError boxed inside a streaming WebStream (recursion), and a mid-stream
ChatResponse frame whose numeric status, when present, lives in
body["error"]["code"] / body["code"]. A string code or absent status
still retains the complete body and becomes a terminal Api error, subject
to the same overflow classification as HTTP errors.
The status drives the split: refused reads a 429 as a spent quota (Api) or
else a Refused stated whole — its Limit, reset and receipt — taking the
first two from provider/reset.rs, which reads every header and body
convention providers name one by, and leaving recovery to Refusal::recovery;
a 5xx is Transient, any other 4xx Api.
The _ => Terminal floor makes the walk total — a contract breach (a non-JSON
2xx) or an unrecognised shape surfaces raw rather than being retried on a
Display-string guess. The full
tutorial is provider-fault-recovery
(transcript-admission).
A 4xx whose text matches a known overflow phrasing (vLLM, OpenAI/OpenRouter,
Anthropic, Gemini), or whose type/code is context_length_exceeded, is
Overflow rather than Api: it carries the sent and limit token counts
when stated, and is never retried by retry.rs. Provider::complete passes
it through unchanged. Agent::relieve stamps its listed window from the
cell’s Model and calls Txn::narrow, recording Control::WindowNarrowed
only if that model is still in force and the limit tightens its window.
Clients have no mutable window: two agents sharing a client learn separately.
The owner sheds context and retries once. Reopen retains a learned narrowing
only for the same model name, bounded by the new catalog window; a via starts
at the least window its upstreams hold.
Retryable and 4xx variants retain portable typed causes, including original
response bodies. ProviderError::body derives the parsed view;
record::fault::body_fields keeps type and code distinct, with message
last. Core’s ServiceFailure response helpers
(core/src/fact/error/host/response.rs) share relay extraction, one-line
normalization and capped snippets between live summaries and typed failure
messages. Helper settlements carry typed evidence, not a pre-rendered summary;
their notices derive concise text without dumping the retained response.
Credential readouts distinguish safe retry from uncertain rotation and
reauthentication. The chrome lives in cards /
frontend.
reset.rs’s last-resort text scrape, parse_retry_after, slices the
lowercased copy it searches, never indexing the original with an offset taken
from it, so a length-changing lowercase (İ) cannot land mid-character and
panic (X8).
Usage, pricing, and the token formatter
humanize_tokensis the one rule every token readout shares — the usage line, the startup banner’s context/limit fields, and the per-agent token tallies — so the plainDisplayand the styled TUI renderers cannot drift on what a turn cost (X9).Usage::parts(UsageParts) is the single content/layout source for the usage line:Displayjoins the pieces as text and the TUI styles them. Positive known dollars always render to four decimals.unmeteredORs subscription participation across turns and agents independently of dollars: a mixed total reads$0.0364 + subscription, a pure reported subscriptionsubscription. Metered zero/unknown-rate cost remains—; absent cache counts remain absent, not reported zeroes.Usage::unreportedcounts attempts whose usage the provider never sent (a retried generated attempt, a stalled stream, anEndwithout usage). It adds like every other field, a total with any is incomplete, and the cost slot says so ($0.0364 + ?for metered usage,subscription (usage unknown)or$0.0364 + subscription (usage unknown)when subscription participates). Unknown subscription usage does not prove an additional cash charge.Usage::measured_input()is the one reading ofinputas a context measurement and isNonefor such a usage, so neither the pressure gauge’sMeasurenor the view’slast_inputis ever overwritten by a zero. Headlesstotal_cost_usdisnullandusage.unreported_turnsis set likewise.provider/pricing.rsfetches OpenRouter’s/api/v1/modelscatalog once per process and caches it;ModelPricing::dollarsstrips the cache counts out ofinputand bills uncached/cache-creation/cache-read/output each at its rate, falling back to the base input rate when no separate cache rate is published. Native DeepSeek models use the local rate table — DeepSeek’s own first-party card, doubling inside its weekday UTC peak windows, where the catalog would price a third-party OpenRouter host — before any OpenRouter alias; other providers use the catalog. The catalog also suppliesModelCaps(supported request parameters, and the context window only as the fallback when the serving account’s listing reports none) for startup and picker decisions. Offline starts degrade to—.
New completions preserve canonical content; resume does not infer repairs to
historical malformed signed messages. Those messages remain until withdrawn.
The Usage schema is unchanged: existing mixed-dollar records gain the honest
shared presentation on replay, but historically omitted retry deltas cannot be
reconstructed or backfilled.
The wire request
provider/wire.rs is the one place an owned genai::ChatRequest is built —
the-transcript-is-a-value is the
ADR, session-record covers the persistent
render_messages projection it consumes. Sealed(ChatRequest) wraps the result and is
deliberately not Clone, so a built request cannot be kept alive and cloned
for a later retry; manufacture(adapter, system, transcript: &[ChatMessage], tools) is called fresh inside each retry attempt in stream.rs’s
Pool::complete, and is the only place a request is built.
manufacture marks cache_control: ephemeral breakpoints on the system
prompt and the last two messages, for Anthropic alone: two anchors of
different depths, so a diverging tail (retry, fork, a self-nudge) still lands on
a cached prefix. The marks land on manufacture’s own fresh clone of the
transcript’s shared messages, never on the shared segments themselves. On
OpenAI the same marks would select the metered explicit prompt cache, which
the ChatGPT plan route rejects outright (rust-genai #273),
so every other adapter carries its system prompt in the request’s own
system field — where the Responses adapter’s instructions string wants it
anyway — and leans on the per-process prompt_cache_key alone, which genai
reads as intent for the free implicit cache. tool_defs receives the selected
service’s HostedSearch policy through its transport. The policy admits
search; the OpenAIResp, Anthropic and Gemini adapter whitelist only
constrains its encoding. Codex receives external_web_access: true on
Responses; Chatgpt uses the native form. Declared endpoints and services
without hosted search send no search tool. The request bit is
agent’s search.