Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Providers and streaming

This page defines how Robi reaches a model provider: the request it builds, the delta protocol a response becomes, and how it retries, times out, cancels, and reports failure. It is the design doc for M1 in the roadmap.

The first implementation is one OpenAI-compatible chat-completions client, wired to OpenCode Go. Read this page before writing code in crates/robi::agent::providers.

What this page does not cover

TopicWhere it belongs
The Model trait, the Delta enum, and the loop that consumes itagent-loop.md (M0)
The IPC encoding of a delta, and how the UI subscribesdocs/src/design/core/architecture.md (M2)
Where the API key lives, and the settings UI that produces itdocs/src/design/persistence/persistence.md (M2)
Token accounting and compaction triggersdocs/src/design/workspace/context-management.md (M3)

This page fixes the in-process provider boundary. The delta vocabulary is already fixed by M0; M1 adds emitters, not variants.

Problem

The M0 loop is frozen: it drives an async, cancellable Model and consumes a stream of deltas. M1 makes that real, and every hard part sits in the adapter:

  • A provider accepts one shape of transcript and no other. Robi’s transcript has no system role, and its tool-call ids are UUIDs the provider never issued. Both need a mapping rule, and the rules are load-bearing.
  • A stream can fail after it has already produced output. A retry that fires mid-stream renders a partially duplicated message. The retry boundary has to be a property of the design, not a hope.
  • The endpoint is a proxy in front of 33 models from different labs. The fields that carry reasoning are not in OpenAI’s schema, and a strict decoder drops them or fails the turn.
  • A cancelled turn must leave a resolvable transcript. Cancellation arrives while a socket is open, so the adapter owns part of that guarantee.

Scope

In scope. One provider family, OpenAI-compatible chat completions, and one instance of it, OpenCode Go. Streaming deltas, tool calling, reasoning traces, retries, cancellation, a model catalog, an SSE decoder, and the tests for each.

Out of scope. The Anthropic client, the OpenAI Responses API, embeddings, structured outputs, per-session model selection in a UI, and the settings and keychain layer. This milestone defines the seam that layer plugs into; it does not build it.

Provider facts

FactValue
Base URLhttps://opencode.ai/zen/go/v1
Chat endpointPOST {base}/chat/completions, SSE when streaming
Model listGET {base}/models
Model idConfig uses opencode-go/<model-id>; the provider receives <model-id> alone
AuthAuthorization: Bearer <api key>
Session headerx-opencode-session: <stable id per conversation>
User agentThe agent’s own name, robi/0.1
Catalog33 models, all with tool calling and reasoning

Sources: OpenCode Go, OpenCode providers, models.dev: opencode-go.

These facts come from vendor documentation, not from a live probe, and the vendor serves tool-less models elsewhere. The catalog lists only the tool-capable ones, so every entry above is one this loop can drive. The live tests in Testing are what would confirm the framing; they are not written yet.

Decisions

D1 — A hand-written adapter, not an OpenAI SDK

Take no OpenAI SDK. Write one adapter for one wire format, covering only the subset the transcript needs.

  • There is no official OpenAI Rust SDK. OpenAI ships Python, Node, .NET, Java, and Go; Rust is an open feature request (openai-go #628). “Use the SDK” therefore means a third-party crate, today async-openai.
  • An SDK does not remove the work that carries the risk. The delta vocabulary is Robi’s and frozen from M0. An SDK returns its own types, so the transcript mapping, delta mapping, tool-call assembly, cancellation path, timeouts, and error classification are written either way. The SDK replaces HTTP and SSE plumbing: three files of the module tree below.
  • A typed decoder drops exactly the fields this endpoint needs. reasoning_content is not in OpenAI’s schema. Reading it through async-openai means bypassing the typed stream with create_stream_byot and a custom chunk type, as in agent-driver-rs #2 on async-openai 0.41.1. That work comes with the dependency, not instead of it, and a strict decoder fails a turn on a line our decoder skips. A proxy fronting 33 models from different labs emits lines no one schema describes.
  • The costs are concrete. A large transitive tree, a version pin, and an MSRV that may exceed the workspace’s 1.75 pin.

Rejected: async-openai or a comparable crate. It supports a custom base URL, per-request headers, and SSE streaming, so it would work. This is a judgement call favouring tolerance and a small dependency tree, not a proven conclusion.

This decision is cheap to reverse. The adapter sits behind robi_core::Model, and wire.rs, sse.rs, and stream.rs stay separate. Swap the plumbing in one file. Re-open the decision when a second provider shows the plumbing duplicating, or when the provider count passes two.

D2 — The adapter injects the system prompt

robi_core::message::Role has User, Assistant, and Tool, and the transcript holds no system message. Build the request with {"role":"system","content": settings.system_prompt} prepended.

Rejected: adding Role::System to robi-core. That is a core change for a provider-shaped concern. robi-core::prompt renders ordered blocks. crates/robi::agent::prompt loads the sources, including the registered tools, and the model source stores the result on settings.system_prompt. See instructions.md.

Consequence, accepted: a session record cannot show what the model was told, because the system prompt never enters the transcript.

D3 — The provider’s tool-call id is the wire id; the UUID stays the loop’s identity

The chat format requires the id in an assistant tool_calls[] entry to equal the tool_call_id of the answering tool message. The provider mints its own id (call_abc123); Robi mints a UUID.

Store the provider’s id and send it back:

#![allow(unused)]
fn main() {
// crates/robi-core/src/message.rs
    /// The id the provider issued for this call, when it issued one.
    ///
    /// The wire id: a stateless request body must repeat what the provider handed
    /// out. Not identity — the loop keys on `id`, so a provider id that is reused,
    /// absent, or malformed cannot confuse approval or lookup.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_call_id: Option<String>,
}

Request building sends provider_call_id when present and the ToolCallId string otherwise. An OpenCode Go turn always provides one, so the fallback covers fixtures, a replayed transcript, and a server that omits the field.

Keep both ids, because they answer different questions. The wire needs the provider’s id to accept the request. The loop needs a stable local key: ToolCallId indexes Message::tool_call_id, Agent::approve, Agent::reject, and the pending-call scan. A provider id is an opaque string from an endpoint fronting 33 models, nothing guarantees it is unique across turns, and a duplicate would make two calls indistinguishable to approve.

A single ToolCallId -> wire id map, built by scanning the transcript’s assistant messages, resolves both the assistant entry and the matching tool result, so the two always agree. The lookup is needed either way, because a tool-result message carries only the local id.

Rejected: widening ToolCallId to Uuid | Opaque(String). It changes a type the loop compares and looks up, in serialization and at every construction site, to carry a string the loop never reads.

Rejected: an adapter-side ToolCallId -> provider id map. The adapter is stateless, and the transcript is the only state that survives a restart. After a restart the map is empty, so a resumed conversation sends a tool result whose id the provider no longer recognizes. That failure is silent and appears only on resume.

Why the change is small. The field is additive, so ToolCallId stays a UUID and #[serde(default)] keeps existing serialized transcripts deserializing. ToolCall has one construction site, ToolCall::new, and no struct-literal construction anywhere in the crate. The field follows the args_error precedent: an optional annotation an adapter sets.

What sets it. Delta::ToolCallStart does not change. The vocabulary is fixed from M0, and no consumer needs the provider’s internal id mid-stream. The adapter keeps the provider id in per-index assembly state and stamps it on the ToolCall inside the Finished message, which the loop appends as it is.

D4 — The session header is the loop’s SessionId, passed to the model

The vendor asks for a stable id per conversation in x-opencode-session, for routing and prompt caching. The loop already holds exactly that value: Agent carries a SessionId from MessageStore::create_session through every turn, and model_turn has it one line above its call to Model::generate. Pass it in and send it as the header. The adapter treats it as an opaque string.

That means one signature change to Model::generate:

#![allow(unused)]
fn main() {
async fn generate(
    &self,
    session: SessionId,
    transcript: &[Message],
    cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}

The id is minted once, when the store opens a session, and is persisted with it, so it is identical on every turn of a conversation and identical after a restart.

Send the header on POST /chat/completions and nowhere else: not on a model-list request, not on a catalog refresh, which is vendored (D9).

This is a deliberate change to a trait the M0 doc froze, and it is the right one. Three reasons:

  • It is not a new concept. The id already reaches the call site. Deriving the key from the transcript’s first message would invent a proxy for a value the loop is already holding.
  • The proxy is fragile. Compaction (M3) can drop the first message, which silently changes the key and loses the prompt cache the header exists to keep. A design whose own caveat is “the key may change” has the wrong key.
  • The trait was incomplete, not merely inconvenient. Per-session model selection (F1.4) needs a router mapping a session to a configured model, and a Model received only the transcript and the cancellation token. Without the session id in the signature that router cannot be written; it would have to re-derive the session from the transcript, which is the same fragile trick again.

agent-loop.md owns the Model trait, so it is updated in the same change, per the working rule that documentation ships with the behavior.

Rejected: deriving the header from the transcript’s first message. It works until compaction, and it makes the key an accident of transcript content rather than a fact about the conversation.

Rejected: an in-memory random id per session. It changes across a process restart, which defeats the caching it exists for.

Rejected: a ModelCallContext struct holding the session. One field today, and a struct added for a second field that may never arrive is speculative. When a second per-call input appears — a token budget, a retrieval hint — wrap the signature then and move the id into it.

D5 — ModelError stays two-variant

robi_core::error::ModelError has Provider(String) and StreamClosed. Retryability is decided inside the adapter, so the loop never needs it. The adapter encodes the HTTP status and a stable kind word in the message text, as in the provider is rate limiting requests (429): ....

The text after the colon is the provider’s own explanation, kept whole. An error body is the only place a provider says which quota ran out or which key it refused, so error_detail reads the JSON error.message and keeps its type and code beside it, as in insufficient_quota. A body that is not JSON is passed through as it arrived, with an HTML page reduced to its visible text. Nothing is cut before that sentence: the banner that shows it has room for a paragraph, and a 512-byte window used to end mid-sentence. A body that is empty falls back to the status reason.

Deferred: a structured ModelError::Http { status, retryable, body }, when the M2 UI must render a rate limit differently from a rejected key. Recording the deferral keeps the loop frozen at M1.

D6 — A hand-written SSE decoder

Decode SSE with about 60 lines over Response::bytes_stream(). That keeps exact control of the inter-chunk timeout and of cancellation, which a wrapper hides.

The decoder reads a byte stream, not lines, and handles what the spec requires:

  • Join multi-line data: fields into one payload, separated by \n.
  • Accept both CRLF and LF line endings.
  • Ignore : comment lines, and event:, id:, and retry: fields.
  • Dispatch the accumulated payload on a blank line.
  • Treat data: [DONE] as end of stream.

Rejected: reqwest-eventsource, async-sse, and eventsource-stream, which is effectively unmaintained.

D7 — Retry only before the first delta

Allow a retry only while the adapter has emitted nothing: a connect failure, a retryable status, a timeout waiting for response headers, or a failure before the first Delta. After the first delta, a failure is terminal and becomes Delta::Failed(ModelError::StreamClosed), so the loop ends the turn without appending.

That boundary is what stops a retry from duplicating a partially rendered message.

flowchart LR
  A[build request] --> B[send]
  B -- "retryable, nothing emitted" --> B
  B -- ok --> C[decode SSE]
  C --> D[emit deltas]
  D --> E[Finished, the loop appends]
  C -- "failure after the first delta" --> F[Failed, terminal]

Policy:

ResponseRetry
429Yes, after Retry-After when present, capped at 8 s
5xxYes
Connect failure, or timeout on response headersYes
400, 401, 403, 404, 422No
CancellationNo
Inter-chunk gap over chunk_timeoutNo
Anything after the first deltaNo

Backoff is exponential with full jitter, 500 ms base, 8 s cap, 3 attempts. Retry-After accepts both delta-seconds and an HTTP date, and a delay longer than 8 s waits 8 s. The wait for response headers is 45 s. The gap between chunks stays 5 min.

D8 — Credentials come from a factory, and the model never looks behind it

An OpenAiCompatibleModel takes a fully-constructed ProviderSettings and reads no environment variable, no file, and no keychain. SettingsModelSource reads the settings store when a session actor is built and passes the result to build_model. A later SettingsStore can keep secrets in the OS keychain. An actor that has already started keeps the model it was given; the next actor reads the store again.

providers::factory::build_model owns construction, so the model type stays a leaf and one place knows how a provider is assembled. It takes the ToolRegistry as well as the settings, because the request body carries the tool definitions and Model::generate is handed only the transcript. A live test builds the same way and reads the key from the environment itself, which keeps this boundary honest.

Switching is resolved when the actor is built, not inside generate. SettingsModelSource reads the session override, then the settings store, then the built-in default, and build_model returns one Arc<dyn Model>. Agent keeps holding that model and never learns that switching exists. A turn calls generate several times, so resolving again on each call would let a mid-turn change split one exchange across two models. The next actor, built when the session goes idle, reads the choice again. One reqwest::Client is still built per model; the actor’s lifetime is the cache.

Not by swapping the Arc<dyn Model> on the Agent. That produces a global switch rather than a per-session one, and it needs &mut self or interior mutability on an agent that several calls already drive concurrently.

Not by a ModelRouter that dispatches inside generate. The actor is already rebuilt per execution, which is the turn boundary. The picker writes model_config on the session; see persistence.md and chat-runtime.md.

D9 — The catalog is vendored, tool-capable models only, and owns the window

Keep a checked-in model table, generated from a models.dev snapshot, plus a loader for user overrides. Fetching at startup makes the app fail without connectivity, and a live desktop tool should not phone home to render a context meter.

Two rules:

  • List only models that call tools. A model that cannot call tools cannot drive this loop, so listing one only invites a session that fails. build_model validates the configured model against the catalog at construction and fails with an error naming the id, rather than discovering the problem on the first turn.
  • context_window is the model’s own advertised window, with no plan-tier arithmetic. The vendor’s tiered figures (Grok 4.7 at 200K, GPT 6 Luna at 272K) are pricing boundaries. They belong in the price table M2 uses for cost, never in the window M3’s meter reads.

M1 needs id, display_name, context_window, max_output, and supports_reasoning. Pricing rides along from the snapshot, unused until M2.

D10 — The transcript stores image references, never bytes

A user attaches images to a message. The transcript records only the reference — an id and a media type — not the bytes:

#![allow(unused)]
fn main() {
// crates/robi-core/src/message.rs
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageAttachment {
    pub id: String,          // the `chat_images` row id
    pub media_type: String,  // "image/png", "image/jpeg", "image/webp", "image/gif"
}

// Message gains:
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub images: Vec<ImageAttachment>,
}

#[serde(default)] keeps every stored transcript row deserializing, the same as the provider_call_id and subagent precedents. Only Role::User messages carry images.

Rejected: a data: URI (or the bytes) inside Message. The transcript is serialized into the chat_messages.body TEXT column, fanned out on the SSE event stream, and returned by every GET /messages. Base64 there bloats the database ~33% per image, ships megabytes on every transcript read, and leaks into the DTO and events. The wire needs the data URI; the transcript does not.

D11 — The adapter resolves bytes at send time, through a provider-side port

Model::generate receives only the transcript, and the adapter is stateless across restarts. So providers declares its own read port, and an ImageStore port that also accepts new rows:

#![allow(unused)]
fn main() {
// crates/robi/src/agent/providers/images.rs
#[async_trait]
pub trait ImageSource: Send + Sync {
    async fn image(&self, id: &str) -> Result<Option<(String, Vec<u8>)>, ProviderError>;
}

#[async_trait]
pub trait ImageStore: ImageSource {
    async fn store(&self, chat_session_id: &str, id: &str, media_type: &str,
                   bytes: Vec<u8>) -> Result<(), ProviderError>;
}
}

ImageSource is what the model’s request builder sees. ImageStore adds the write surface the ingestion handler uses, keeping it out of the read-only port the provider reaches. BlobImageStore implements both over the session blob file; factory::build_model and the web layer each take Arc<dyn ImageSource> or Arc<dyn ImageStore> as appropriate, wired the same way the ToolRegistry already is.

generate resolves every attachment id up front into a HashMap<String, (String, Vec<u8>)> and passes that into build_request, which stays pure and golden-testable.

Failure: a missing row fails the turn. image <id> is missing from the store reaches the loop as a ModelError::Provider. Never send a silently truncated message and never drop the part: the user attached it, and quiet loss is the one failure neither the model nor the user can detect.

D12 — Content parts on the wire; text-only bodies stay byte-identical

In wire.rs, ChatMessage.content: String becomes an untagged content enum:

#![allow(unused)]
fn main() {
// providers/openai/wire.rs
#[derive(Serialize)]
#[serde(untagged)]
pub enum WireContent {
    Text(String),          // a plain string, exactly as before
    Parts(Vec<ContentPart>),
}

#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    Text { text: String },
    ImageUrl { image_url: ImageUrl },   // { url: "data:<media_type>;base64,<b64>" }
}
}

Rules, each with a test:

  • Only a Role::User message with non-empty images uses Parts. Every other message — and a text-only user message — serializes byte-for-byte as before, so prompt-cache prefixes and golden tests are unchanged.
  • A user message with images always emits a text part first (its content, even when empty), then one image_url part per attachment in attach order.
  • Assistant, tool, and system messages stay strings. The provider does not need images echoed back beyond the turn that carried them, and chat-completions vision models accept the history either way; we send the parts each relevant turn so multi-turn image questions keep working.
  • The image_url is a data: URI built from the resolved bytes. No remote https URLs in the first cut — the desktop app has local files, not URLs.

D13 — Vision capability is catalogued, and gating happens in the adapter

ModelInfo gains supports_vision: bool. The vendored table sets it per row; where the models.dev snapshot does not state it, the default is permissive (true) so a capable model is never blocked by missing metadata — the provider’s own 400 is the honest fallback.

Gating happens inside generate at request build: images present and the configured model !supports_vision → the turn fails with ProviderError::NoVision naming the model (“visionless does not accept image input”). It surfaces as a failed turn the UI can show, not a submit-time refusal: the model choice can change between attach and send (D8), so the actor that builds the request is the only place that knows. A text-only turn never touches the flag or the store.

D14 — One multipart request ingests images; a side table stores the bytes

POST /api/v1/chat_sessions/{id}/messages accepts multipart/form-data: one instruction text field plus images file parts. The existing JSON body keeps working for text-only (the handler dispatches on content type). Limits, enforced at the handler:

LimitValueOn breach
Per image10 MiB413 naming the file
Per message8 images400
Media typesimage/png, image/jpeg, image/webp, image/gif415

The media type is validated by magic bytes (PNG/JPEG/WEBP/GIF signatures, a ~30-line matcher). No decode, no re-encode, no image crate: providers handle large images by tiling or rejecting, and the token cost comes back in Usage.

Bytes go in ~/.robi/sessions/<session_id>/blobs.redb (schema in persistence.md). They never enter chat_messages. Session delete removes that directory. A GET /chat_sessions/{id}/images/{image_id} route serves the bytes for the UI’s message bubbles.

Rejected: a separate upload endpoint returning an id. It needs orphan cleanup for images attached but never sent, and it splits one user action across two requests that can fail between them.

Anthropic (A1–A12)

M1 also adds Anthropic’s native Messages API as a second provider family. The constraints that shape it: Haiku 4.5 does not accept the effort parameter, the user never picks a provider (one flat model list), and every model id carries a provider prefix (ocg_ for OpenCode Go, ant_ for Anthropic).

A1 — A second hand-written adapter, not a shared abstraction

providers/anthropic/ has its own wire.rs, stream.rs, and mod.rs. Anthropic’s request shape (top-level system, required max_tokens, input_schema tools, content blocks) and its typed SSE event stream are different enough from chat-completions that a shared abstraction would be the lowest common denominator. The only piece promoted to a shared module is the SSE framing (providers/sse.rs): blank-line dispatch, CRLF, multi-line data:, and : comments are protocol-level, and each adapter decodes a payload its own way. D1’s revisit clause stands: the retry/pump/cancel skeleton is near-duplicated, and a providers/transport.rs extraction is the follow-up if it proves noisy.

A2 — Per-model effort gating lives in the catalog

ModelInfo gains supports_effort: bool. The Anthropic table sets it true for ant_claude-fable-5-1, ant_claude-opus-5-5, and ant_claude-sonnet-5-5, and false for ant_claude-haiku-4-5. Haiku rejects output_config with a 400 (“Extra inputs are not permitted”), so the adapter omits the field when the flag is false. A configured effort still builds the model: the setting is global, and switching the session to Haiku must not fail startup. OpenCode Go rides effort on reasoning_effort and is never gated, so its rows carry true.

A3 — Reasoning without an effort field is thinking, and the trace round-trips

Anthropic’s thinking blocks arrive as thinking_delta events and map to Delta::Reasoning. A tool continuation must echo the thinking block back, unmodified, with its signature, so Message gains an additive reasoning: Option<ReasoningTrace> (text + signature), set by the adapter at Finished and echoed in wire.rs for the assistant turn whose tool results are still pending. A trace with no signature is not echoed: the API rejects one. Old rows deserialize as None.

A4 — provider_call_id is the tool_use_id

Anthropic issues toolu_… ids in tool_use blocks; ToolCall.provider_call_id stores them, and the tool_result block is keyed by that same id. D3’s pattern, unchanged — no new core field.

A5 — max_tokens comes from the catalog’s max_output

The Messages API requires max_tokens. The adapter sends the configured model’s catalog max_output; no new setting, no per-request arithmetic.

A6 — No session header for Anthropic

There is no x-opencode-session equivalent. Model::generate still receives the loop’s SessionId (D4’s trait is unchanged); the Anthropic adapter simply does not send a session header. The x-api-key and anthropic-version: 2023-06-01 headers replace the bearer/session pair.

A7 — Stop reason mapping

message_delta.stop_reason: end_turn/stop_sequence → settled Finished; tool_use → settled with assembled tool calls; max_tokens → settled but logged at warn (the same known-gap treatment as finish_reason: "length"); refusal → Failed.

A8 — Cumulative usage

message_delta.usage is cumulative: it supersedes message_start’s counts. The assembler replaces rather than adds, so the final Usage delta is correct.

A9 — Error events mid-stream

An event: error inside a 200 stream becomes Delta::Failed, the same as the OpenAI {"error": …} object. overloaded_error is terminal once deltas have streamed — the retry boundary stays “before the first delta” (D7). 429/5xx and Retry-After classification is the shared retry.rs, unchanged.

A10 — Images

A Role::User message with images becomes image content blocks (source: { type: "base64", media_type, data }). The adapter reuses resolve_images (D11) unchanged, so vision gating (D13) and the missing-row failure are identical to OpenCode Go.

A11 — Model ids carry a provider prefix; the prefix resolves the provider

There is no provider picker. The dropdown is one flat list; the id itself names the provider. Each provider has an on/off setting (provider_opencode_go, provider_anthropic, provider_deepseek, default on). off drops that catalog from GET /api/v1/models and makes SettingsModelSource refuse a turn whose resolved id belongs to it. The prefix is still the dispatch.

  • Prefixed ids everywhere. OpenCode Go rows are ocg_glm-5.3, …; Anthropic rows are ant_claude-sonnet-5-5, …; DeepSeek rows are dsk_deepseek-flash and dsk_deepseek-v4-pro. The prefix is part of the id in the settings store, the session’s model_config, the /api/v1/models response, the dropdown, and the catalog keys.
  • The prefix is the dispatch. SettingsModelSource runs the existing resolution chain (session override → mode setting → MODEL → default), then reads the prefix: ant_ builds ProviderSettings::anthropic(...) and requires anthropic_api_key; ocg_ builds ProviderSettings::opencode_go(...) and requires opencode_go_api_key; dsk_ builds ProviderSettings::deepseek(...) and requires deepseek_api_key. DeepSeek uses the OpenAI-compatible adapter and its own base URL (deepseek_base_url, default https://api.deepseek.com). build_model dispatches the same way.
  • The wire gets the bare id. Both providers want their own id (claude-sonnet-5-5, glm-5.3), never the prefix. ModelId::wire_id strips it, golden-tested.
  • DEFAULT_MODEL is ocg_glm-5.3.
  • Legacy bare ids read as OpenCode Go. A settings or session row written before the prefix existed holds a bare id; ProviderKind::of treats an unknown prefix as OpenCode Go, build_model normalizes it to the prefixed form, and normalize_model rewrites it on store. No stored session breaks.
  • normalize_model validates the union of both catalogs.
  • GET /api/v1/models lists the enabled catalogs in one flat list. A provider set to off is omitted. The frontend picker is otherwise unchanged.
  • The key follows the provider. Switching a session to a Claude model makes the next actor read anthropic_api_key; a missing key is the existing “… is not set” refusal naming the key.
  • Catalog tests assert every id carries its provider’s prefix, the two tables are disjoint, and the free-text ids are unique across the union.

A12 — Effort on Anthropic maps to output_config, not budget_tokens

On the current lineup output_config: { effort } is a stable API field and controls all token spend, thinking included. Haiku rejects the field outright (A2). budget_tokens is not used: later models reject it. An unset effort sends no output_config.

Anthropic request mapping

TranscriptMessages request
settings.system_prompttop-level system (A1), omitted when empty
Role::User{ "role": "user", "content": msg.content }
Role::User with imagescontent: [{type:"text",…}, {type:"image",source:{type:"base64",…}}…] (A10)
Role::Assistantplain text when it made no tool call and has no thinking
Role::Assistant with a tool callcontent: [{type:"thinking",…}?, {type:"text",…}?, {type:"tool_use",id,name,input}…] (A3)
Role::Toola user message with one {type:"tool_result",tool_use_id,content} block (A4)
ToolRegistry::tools()tools: [{name, description, input_schema}], no function wrapper
settings.reasoning_effortoutput_config: {effort}, only when supports_effort (A2/A12)
—max_tokens: the catalog’s max_output (A5), stream: true
—headers: x-api-key, anthropic-version, User-Agent, Content-Type

Anthropic response mapping

SSE payload typeDelta
message_startseeds Usage from message.usage
content_block_start (text/thinking)nothing; the deltas carry the content
content_block_start (tool_use)ToolCallStart { index, id: <minted>, name }
content_block_delta text_deltaText
content_block_delta thinking_deltaReasoning
content_block_delta input_json_deltaToolCallArgs
content_block_delta signature_deltarecorded, not emitted
content_block_stopToolCallEnd for the open tool-use block
message_deltaUsage (cumulative, A8) and stop_reason
message_stopFinished(<assembled Message>)
error inside a 200 streamFailed
an unknown typeskipped (versioning)

The assembled assistant message carries the thinking trace as Message.reasoning (A3) and each call’s provider_call_id, which the next request echoes.

Modules

AGENTS.md puts providers in a module of crates/robi, not a crate of its own.

crates/robi-core/src/model.rs     # Model::generate takes the session id (D4)
crates/robi-core/src/agent.rs     # model_turn passes the id it already holds (D4)
crates/robi-core/src/message.rs   # + ToolCall.provider_call_id (D3), + Message.images (D10), + Message.reasoning (A3)
crates/robi/src/agent/providers/
  mod.rs          # re-exports, ProviderId, ProviderKind, ModelId, the prefixes
  config.rs       # ProviderSettings, redacting ApiKey, ModelId::wire_id, ProviderSettings::anthropic (A1)
  factory.rs      # build_model(settings, tools, images), dispatch on the model prefix (A11)
  error.rs        # ProviderError, and its mapping into ModelError
  images.rs       # ImageSource (read) and ImageStore (read + write) ports (D11)
  retry.rs        # RetryPolicy, backoff, classify
  sse.rs          # the shared SSE framing (A1)
  catalog/        # mod.rs, opencode_go.rs (ocg_*), anthropic.rs (ant_*); supports_effort (A2), all() (A11)
  openai/         # mod.rs (impl Model), wire.rs (WireContent, D12), stream.rs
  anthropic/      # mod.rs (impl Model), wire.rs, stream.rs (A1–A12)
crates/robi/src/adapters/chat_image_store.rs  # BlobImageStore (D11), MemoryImageStore (tests)
crates/robi/src/adapters/session_blobs.rs     # per-session redb file
crates/robi/src/web_api/chat_message.rs       # multipart ingestion + GET image route (D14)
crates/robi/tests/provider.rs  # the fake SSE server and its cases, both providers

M1 makes these edits to `robi-core`: the additive `provider_call_id` field (D3),
the `user_input_with_skills`/`Model::generate` signatures (D4), the new
cancellation point at the call site, the additive `Message.images` field with
`Message::user_with_images` (D10), and the additive `Message.reasoning` field with
`ReasoningTrace` (A3). All are recorded in
[agent-loop.md](../core/agent-loop.md), which owns the transcript types and the
`Model` trait. Everything else in the core stays as M0 left it: the turn state
machine, the approval path, the delta vocabulary, and the other three traits.

`docs/src/roadmap.md` F0.1 names `robi-providers` as the M1 crate. `AGENTS.md` is the
layout authority and says `crates/robi`; follow `AGENTS.md`, and fix the roadmap.

## Dependencies

Declare these in the root `[workspace.dependencies]` and reference them from
`crates/robi/Cargo.toml`. Run `cargo add` to resolve versions, and commit the
updated `Cargo.lock`.

| Dependency | Features | Why |
|---|---|---|
| `reqwest` | `json`, `stream`, `rustls-tls`, `default-features = false` | HTTP and streaming; rustls avoids an OpenSSL system dependency in a bundled app |
| `futures-util` | — | `StreamExt` over `bytes_stream()` |
| `bytes` | — | The SSE decoder's input |
| `http` | — | `StatusCode`, `HeaderName` |
| `tracing` | — | Request lifecycle logs, with the key redacted |

Already in the workspace: `async-trait`, `serde`, `serde_json`, `thiserror`,
`tokio` (add the `stream` feature), `tokio-util`, and `uuid`.

Dev only: `axum` for the fake server, and the `net` feature of `tokio` for the
listener.

`robi-core` gains no dependency. `cargo tree -p robi-core` stays short, and that
command is the audit.

## Interfaces

```rust
// crates/robi-core/src/message.rs — core change 1 of 2 (D3)
pub struct ToolCall {
    pub id: ToolCallId,
    // ...existing fields...
    pub provider_call_id: Option<String>,   // serde(default, skip_serializing_if)
}

// crates/robi-core/src/model.rs — core change 2 of 2 (D4)
#[async_trait]
pub trait Model: Send + Sync {
    async fn generate(
        &self,
        session: SessionId,        // new: the id the loop already holds
        transcript: &[Message],
        cancel: CancellationToken,
    ) -> Result<ModelStream, ModelError>;
}

// crates/robi-core/src/agent.rs — core change 3 of 3 (D7, cancellation)
// `model_turn` selects on the cancel token around `generate`, so a cancel before
// the response headers arrive is `Cancelled` rather than a transport failure:
let stream = tokio::select! {
    biased;
    () = cancel.cancelled() => return Err(TurnError::Cancelled),
    stream = self.model.generate(*session, &transcript, cancel.clone()) => stream?,
};

// providers/config.rs
#[derive(Clone)]
pub struct ProviderSettings {
    pub id: ProviderId,             // "opencode-go"
    pub base_url: String,
    pub api_key: ApiKey,            // Debug and Display print "<redacted>"
    pub model: ModelId,             // "glm-5.3"
    pub system_prompt: String,
    pub session_header: Option<HeaderName>, // Some("x-opencode-session")
    pub user_agent: String,         // "robi/0.1"
    pub header_timeout: Duration,   // 45 s
    pub chunk_timeout: Duration,    // 5 min
    pub retry: RetryPolicy,
    pub reasoning_effort: Option<ReasoningEffort>,
    pub session_key_override: Option<String>, // defaults to the SessionId the loop passes (D4)
}

// providers/factory.rs — the seam M2 fills
pub fn build_model(
    settings: ProviderSettings,
    tools: Arc<ToolRegistry>,   // the request carries the tool definitions, and
                                // `Model::generate` is not given them, so the
                                // adapter holds the registry
) -> Result<Arc<dyn Model>, ProviderError>;
// No env var, no file, no keychain behind this: the credential is already in `settings`.

// providers/retry.rs
pub struct RetryPolicy { pub max_attempts: u32, pub base: Duration, pub cap: Duration }
pub enum Retry { Yes { after: Option<Duration> }, No }
pub fn classify(status: StatusCode, headers: &HeaderMap) -> Retry;

// providers/openai/wire.rs
/// The id sent on the wire per call: the provider's own id when the transcript
/// carries one, else the `ToolCallId`.
pub fn wire_call_ids(transcript: &[Message]) -> HashMap<ToolCallId, String>;

// providers/openai/mod.rs
#[async_trait]
impl Model for OpenAiCompatibleModel {
    async fn generate(
        &self,
        session: SessionId,
        transcript: &[Message],
        cancel: CancellationToken,
    ) -> Result<ModelStream, ModelError>;
}

generate sends the request under header_timeout, then spawns one task that owns the response body and forwards deltas over an mpsc channel wrapped in ModelStream. The header wait and that task both select on cancel.cancelled(): around the request, around every chunk read, and around every delta send. The channel is bounded, so a bare send().await would ignore a stop until the loop drained the queue. A cancel drops the body and closes the connection instead of leaving a task parked in chunk().await or send().await. After a cancellation the task sends no Delta::Failed, because the loop already owns the cancelled outcome.

Request mapping

TranscriptChat-completions request
settings.system_promptprepended {"role":"system","content":…} (D2)
Role::User{"role":"user","content": msg.content}
Role::User with images{"role":"user","content": [{type:"text",text:…}, {type:"image_url",image_url:{url:"data:…"}}…]} (D12)
Role::Assistantcontent, plus tool_calls when the message has calls
Role::Assistant with callstool_calls: [{ id: wire_id(call), type: "function", function: { name, arguments } }]
Role::Tool{"role":"tool","tool_call_id": wire_id_for(msg.tool_call_id), "content": msg.content}
ToolRegistry::tools()tools: [{ type: "function", function: { name, description, parameters } }]
—stream: true, stream_options: {"include_usage": true}
settings.reasoning_effortreasoning_effort, only when set
—model: settings.model
—headers: Authorization, x-opencode-session, User-Agent, Content-Type

arguments is serde_json::to_string(&call.args). A call with args_error sends its stored raw text when the adapter kept it, and "{}" otherwise; the loop fails that call before execution either way, so the value exists only for the provider to accept the transcript.

ToolRegistry::tools() sorts by name, so the serialized tools array is byte-stable across runs. That matters twice: an unstable array breaks prompt caching, and it makes golden tests noisy.

Response mapping

SSE payloadDelta
choices[0].delta.contentText
delta.reasoning_content, or delta.reasoningReasoning
tool_calls[i] with an id and nameToolCallStart { index: i, id: <minted>, name }
tool_calls[i].function.argumentsToolCallArgs { index: i, fragment }
the array index advances, or finish_reason arrivesToolCallEnd { index: prev }
a chunk’s usageUsage
data: [DONE]Finished(<assembled Message>)
{"error": …} inside a 200 streamFailed

Read both spellings of the reasoning field, reasoning_content and reasoning. The field name is provider-specific, and which one arrives varies by model.

The assembled message reuses the ToolCallId minted at ToolCallStart, so the delta events and the transcript agree, as agent-loop.md requires. It carries the provider’s own id as provider_call_id, which is what the next request sends back (D3).

Quirks to handle, each with a test:

  • A chunk can split mid-JSON across two TCP reads.
  • A server can omit tool_calls[].index. Assume a single call then, and reject the turn when a second tool name appears.
  • A server can omit tool_calls[].id. provider_call_id stays None, and the request falls back to the UUID string.
  • Usage arrives on a chunk whose choices array is empty.
  • choices or delta.tool_calls may be JSON null. That is an empty list. DeepSeek sends "tool_calls": null on a text chunk.
  • finish_reason: "length" reports a truncated message. Message has nowhere to put that, so a truncated turn currently reads as Complete. See Known gaps.
  • A malformed line is skipped and logged at debug level. One bad keepalive must not kill a turn.

Failure modes

FailureHandlingRetry
401, 403Provider naming a rejected credential, then the provider’s own message. The key is never echoed from the requestNo
404, or a model absent from the catalogName the model idNo
A catalog model without tool supportRefused at build_model, naming the idNo
400, 422Surface the provider’s message; the body is deterministicNo
429Honour Retry-After up to the 8 s cap, else back off. The last attempt fails the turn with the provider’s messageYes, before the first delta
5xxBack off, then fail with the status and the bodyYes, before the first delta
Connect failure, or header timeoutTreat as transportYes, before the first delta
Inter-chunk gap over chunk_timeoutTerminal; a stalled stream is not recoverable in placeNo
Failure after the first deltaDelta::Failed(StreamClosed)No
Stream ends with no [DONE] and no finish_reasonStreamClosed; the message is not settledNo
Anthropic stream ends with no message_stop and no stop_reasonStreamClosed; the message is not settledNo
Anthropic event: error in a 200 streamDelta::Failed (A9)No
Configuring an effort on a model with supports_effort: falseProviderError::UnsupportedEffort naming the model, at build_model (A2)No
Malformed SSE lineSkip, log at debug—
Tool arguments that do not parseToolCall.args_error, never {} (agent-loop Deviation 3)—
A provider that omits a tool-call idprovider_call_id stays None; fall back to the UUID string—
Images on a non-vision modelProviderError::NoVision naming the model (D13)No
A transcript that references a missing image rowProviderError::MissingImage naming the id; the turn fails (D11)No
Cancellation before response headersReturn Err keyed off the token; the loop reports CancelledNo
Cancellation mid-streamDrop the body; send nothing furtherNo

A response whose status is success is logged at info with the model id and the status code. A finished stream is logged at info. A finish_reason of length is logged at warn when the message is settled, because that turn still completes. A stalled stream, a transport error, and a stream that fails to assemble are logged at warn. The API key never reaches a log, an error message, an event, or a test fixture. ApiKey’s Debug and Display both print <redacted>, and request building never formats a header map.

Testing

cargo test -p robi passes with no live network. A fake server binds 127.0.0.1:0 with axum, returns a scripted SSE body, and delays between chunks, so chunk splitting, timeouts, and cancellation are deterministic.

Link loopback access to run it inside the sandbox, or run the suite unsandboxed.

TestAsserts
Core field round tripprovider_call_id: None serializes without the field, and a transcript written before the field existed still deserializes
Core field is not identityapprove, reject, and the pending-call scan resolve by id; two calls sharing a provider_call_id stay distinct
Request bodyTranscript order, the injected system prompt, the tool array, and stream_options serialize as expected; two builds produce an identical tools array, so prompt caching and golden tests hold
Provider id on the wireThe stream’s provider ids are stored, and the next request carries them on both the assistant entry and the tool result
Provider id absentDeltas that omit tool_calls[].id leave provider_call_id None, and both halves of the request still agree on the local id
Session id reaches the modelA stub records the SessionId it was given, and it equals the session the turn ran in, across every turn of one conversation
Session headerEvery chat request carries x-opencode-session equal to that SessionId, plus the bearer credential and a robi/ user agent
Model validationbuild_model rejects an unknown id and a tool-less model, each naming the id
Image wire shapeA user message with images emits content parts — text first, then one image_url per attachment with a data: URI from the resolved bytes, in attach order
Text-only bytesA body without images serializes byte-identical with an empty resolution map, so prompt-cache prefixes hold
Missing image referenceA transcript referencing an unresolved id fails the build naming the id, rather than dropping the part
Vision gatingA non-vision model rejects the turn naming itself; a vision model resolves the bytes; a text-only turn skips both the store and the flag
VisionModelInfo.supports_vision is explicit on every vendored row
Text and reasoningChunks become Text and Reasoning deltas, both field spellings are read, and reasoning stays out of the message
Tool-call assemblyInterleaved fragments assemble in order, with ids that match the ToolCallStart deltas, and a second call at one index is refused rather than merged
SSE edge casesA chunk boundary inside a data: line, a split multi-byte character, CRLF endings, a : comment, multi-line data:, and a final event with no blank line all parse
Usage chunkA final chunk with an empty choices array yields Usage, reaches the finished message, and is not lost when it follows finish_reason
Malformed tool argsA truncated argument string sets args_error, not {}
Mid-stream errorAn {"error": …} object in a 200 stream becomes Failed, not a panic
RetryRetry-After is honoured; 429 then success sends two requests with exactly one Finished; 401 sends one; 500 sends max_attempts naming the status; backoff never exceeds its exponential ceiling (asserted directly, since full jitter is random)
No retry after a deltaA failure after the first delta sends no second request, and a stall past chunk_timeout ends the turn as Failed rather than being retried
CancelCancelling while the request is in flight and while awaiting a chunk both give Cancelled, and neither appends a message
End to endAgent::user_input with a real OpenAiCompatibleModel streams a turn, appends the assistant message, and completes
Live text, #[ignore]Not written. A real turn streams text; needs ROBI_LIVE_OPENCODE=1 and a key, read by the test
Live tool call, #[ignore]Not written. A real turn calls a tool, and the stored provider id round-trips and is accepted back

The last two are not written. Every pass above is against a server this repository controls, so the vendor’s exact framing stays an assumption until something talks to the real endpoint. Trying it by hand is the shorter route to that: run the example once with a real key, and check streaming, a tool call, and the approval pause in one run.

Known gap

Recorded rather than papered over:

  • No live turn has been run. The framing, the header names, and the model ids come from vendor documentation, not from a response. The fake server in tests/provider.rs encodes the same assumptions, so it cannot catch a wrong one.
  • No live image turn has been run either (D12–D14). The data: URI content part, the vision flag source, and which models genuinely accept images come from vendor documentation and models.dev, not from a response. The catalog defaults vision permissive where the snapshot is silent, so the provider’s own 400 is what actually reports a wrong flag.
  • A truncated message reads as Complete. finish_reason: "length" has nowhere to go in Message, so the transcript cannot distinguish a finished answer from one the output limit cut off. The adapter logs that finish at warn. Add a field to Message when a UI needs to show it.
  • The catalog’s figures are not verified against the endpoint. A window that is larger than the provider enforces means a context meter that under-reports.
  • The system prompt is invisible to a session record (D2).
  • A model switch applies to the next actor (D8). The one already running keeps the model it was built with, including an interrupt that only replaces the pending instruction.
  • A tool-call id can outlive the model that issued it. provider_call_id is recorded from whichever model answered, so after a switch a stored id was issued by a different model. A stateless endpoint only needs internal consistency, so this is normally fine; decide when the router lands whether to send the stored id anyway or fall back to the local UUID, since M1 has one provider.
  • One provider family had been wired. The OpenAI-compatible adapter generalizes to any chat-completions endpoint, but Kimi, DeepSeek, and OpenRouter need their own base URL, auth, and catalog entries. Anthropic now ships alongside it (A1–A12).
  • Anthropic’s framing is unverified too. The input_schema tool shape, the output_config gating, and the thinking-block round trip come from vendor documentation, not a live response; the fake server in tests/provider.rs encodes the same assumptions. Run the example with a real ANTHROPIC_API_KEY to confirm.

Where this landed

Built, in the order the plan called for:

  1. robi-core first, because everything compiles against it: the ToolCall.provider_call_id field (D3), the session parameter on Model::generate (D4), the cancellation select at the model_turn call site, the additive Message.images field (D10), the additive Message.reasoning field with ReasoningTrace (A3), and the StubModel update in testkit.rs. robi-core gained no dependency.
  2. crates/robi, with providers as its first module — config, error, retry, sse, catalog (opencode_go and anthropic), factory, and the openai adapter (wire, stream, and the Model impl). Dependencies stay off the core: reqwest with rustls-tls and no default features, plus futures-util, bytes, http, and tracing. Anthropic’s adapter added anthropic/ (wire, stream, and the Model impl) beside it (A1–A12).
  3. Tests — unit tests across robi (including agent::providers::anthropic) and 24 in crates/robi/tests/provider.rs against a scripted axum SSE server, covering both wire formats. cargo test --workspace runs offline.
  4. An entrypoint — crates/robi/examples/simple.rs, which drives the whole stack by hand and picks the provider from ROBI_MODEL’s prefix. See Trying it by hand.

To run the full check:

cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings

Next, in order: run one real turn against each provider with the entrypoint below. F1.4’s selection is the actor-start chain in D8.

Trying it by hand

cargo run -p robi --example simple builds a model and an agent, registers two tools, and runs a conversation. It is the smallest program that exercises the adapter, the transcript, the registry, and the approval path together, and it is the quickest way to check a change against a real endpoint.

export OPENCODE_GO_API_KEY=...
cargo run -p robi --example simple                  # the scripted two turns
cargo run -p robi --example simple -- "Add 40 and 2" # one prompt instead

# Anthropic: the prefix on ROBI_MODEL selects the provider and the key.
export ANTHROPIC_API_KEY=...
ROBI_MODEL=ant_claude-sonnet-5-5 cargo run -p robi --example simple
VariableRequiredDefaultMeaning
OPENCODE_GO_API_KEYfor an ocg_ model—The OpenCode Go bearer credential
ANTHROPIC_API_KEYfor an ant_ model—The Anthropic x-api-key credential
ROBI_MODELnoocg_glm-5.3Prefixed model id; the prefix picks the provider (A11)
ROBI_BASE_URLnothe vendor’sPoint at another endpoint, including a local fake
ROBI_EFFORTnounsetlow, medium, or high; refused on Haiku (A2)

The system prompt is fixed in the file rather than read from the environment, and it forbids mental arithmetic on purpose. A model that answers from memory produces a correct number without calling a tool, which leaves the tool path, the approval pause, and the provider’s tool-call id round trip all untested.

It runs two turns unless you pass a prompt:

  1. Add 2 and 3. — the tool needs no approval, so the turn completes on its own.
  2. Now multiply 454 by 543. — the tool needs approval, so the turn pauses. The pending call is printed, and y or n on the terminal approves or rejects it. Answering nothing, or closing stdin, counts as a rejection: a call that asked for a decision fails closed.

Then it prints the transcript, each call’s approval and execution status, and the token counts. Both answers are worth running: approving exercises approve + resume, and rejecting exercises the rejection the model reads.

What it found. The first run listed an addition call for approval that turn one had already run to completion. Agent::pending_tool_calls filtered on ApprovalStatus::Pending alone, and the loop records a decision only when a user makes one, so a call that needed no approval keeps Pending for its whole life. The filter now also requires needs_execution, which is the same predicate the rest of the loop already used. Two robi-core tests cover it.

Still open. An executed auto-approved call reads back as approval_status: Pending, which is now harmless but will render oddly in a UI. Decide in M3, when the first no-approval tools ship, whether the loop should mark an auto-approved call Approved at plan time instead.