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

API Integration

Provider code formats requests and parses responses in core. The host carries them out asynchronously: the Zellij adapter uses its web-request API, while Montana implements the component’s HTTP import with a native client and sends the completion back as a host event. Provider logic does not depend on a terminal or Zellij panes. Proxy routing, credentials and network policy still depend on the deployment.

Source: crates/core/src/provider/.

Providers

Six providers implement the LlmProvider trait, selected by ProviderType:

  • ClaudeProvider (Anthropic Messages API)
  • OpenAIProvider (Chat Completions / Responses API)
  • CodexProvider (ChatGPT subscription Responses API with SSE)
  • OpenRouterProvider
  • VercelProvider (Vercel AI Gateway, Chat Completions)
  • OllamaProvider (local, keyless)

The LlmProvider trait

The trait does not perform transport I/O. It only serializes requests and deserializes responses:

#![allow(unused)]
fn main() {
pub trait LlmProvider {
    fn name(&self) -> &str;

    fn format_request(
        &self,
        messages: &[Message],
        tools: &[Tool],
        system: &str,
    ) -> (String, BTreeMap<String, String>, Vec<u8>);

    fn parse_response(&self, body: &[u8]) -> Result<LlmResponse, ProviderError>;
    fn parse_error(&self, status: u16, body: &[u8]) -> ProviderError;

    fn set_model(&mut self, model: &str);
    fn api_key(&self) -> &str;
}
}

The request flow is:

  1. format_request() produces (url, headers, body).
  2. Core requests HTTP through its host interface.
  3. The host delivers the correlated HTTP result: a Zellij event or, through Montana, a WIT host event mapped back into core.
  4. parse_response() (on HTTP 200) or parse_error() (otherwise) interprets it.

set_model() supports switching the model at runtime (the /model command).

Credentials

In the managed credential-proxy deployment (services.cowboy.secretsProxy.enable), the agent sends placeholder keys and the proxy injects the real credentials on the wire based on per-domain mappings. Codex is the same pattern: its rotating ChatGPT subscription token is injected outside the agent. Local and ordinary Docker launches hold credentials. See Security Model. For keyless providers (Ollama) api_key() is empty.

Provider defaults

Every main-model request carries an output cap of 32768 tokens, reasoning included. The max_output_tokens launch key changes it; a managed agent sets it with maxOutputTokens. A reasoning model that spends the whole cap thinking returns neither text nor a tool call, and a one-shot turn then ends as if the agent had finished. Summarization, compaction and the judge keep their own smaller caps.

ClaudeProvider targets https://api.anthropic.com/v1/messages; there is no base-URL override, so no Bedrock or Vertex route. Its defaults: model claude-sonnet-5, max_tokens 32768, thinking on. The model id decides how thinking is spelled, because the shapes are not interchangeable:

Model idThinking onThinking off
Claude 3.x, 4.0–4.5{"type":"enabled","budget_tokens":4096}field omitted
Opus 4.6–5, Sonnet 4.6–5{"type":"adaptive", …}{"type":"disabled"}
Opus 5.5 and later, Fable, Mythos, unrecognized ids{"type":"adaptive", …}field omitted

A budget is rejected by current models, and disabled is rejected by models that always think; an unrecognized id is treated as one of those. Adaptive thinking is sent with block_binding.prefix_mismatch_behavior: "drop_block" under the thinking-binding-controls-2026-08-01 beta: Cowboy edits earlier turns (microcompacted tool results), and where the API binds a thinking block to the conversation before it, the stale block is dropped instead of the request failing. By default the context packet (a plan no longer shown by an update_plan_state result, abandoned tool processes) is not such an edit: it joins the conversation where its content changes and stays there, so a plan update leaves earlier turns byte-identical. The experiment-only plan_packet=rewrite launch setting instead removes the superseded packet, which is such an edit. temperature is sent only to models that accept sampling parameters (before 4.7, not Fable or Mythos); the utility path (summaries, the idle judge) is the only caller that sets it.

Every Messages request asks for prompt caching: the system prompt goes as one text block carrying a cache_control breakpoint (tools render ahead of it, so it caches both), and a top-level cache_control puts an automatic breakpoint on the conversation’s last block. The cache fields of the response’s usage are logged on the LLM usage: line.

OpenAIProvider defaults to gpt-4o and auto-selects the Responses API for reasoning models (o-series, gpt-5, codex) to capture reasoning summaries, which are mapped onto thinking content blocks. On that path, and on Codex, the session id is sent as prompt_cache_key, so one session’s requests share a prompt cache.

With openai_base_url (or the managed openaiBaseUrl option), the same provider targets an arbitrary OpenAI-compatible endpoint. Cowboy strips trailing slashes, appends /chat/completions, and sends the configured model name unchanged. Custom endpoints always use Chat Completions—even for names such as gpt-5-*—and use the broadly supported max_tokens request field. They may be keyless; when an OpenAI key is configured Cowboy adds bearer authorization, otherwise it omits the Authorization header. The endpoint is also retained for summarization, compaction, judge, delegated vision, and sub-agent requests.

Message model

Messages carry a string role and a vector of ContentBlocks, matching the Claude API’s native content-block model. A block’s block_type is one of text, tool_use, tool_result, image, thinking, redacted_thinking, or reasoning.

Reasoning replay

Some reasoning has to go back to the provider that produced it, unchanged:

  • Anthropic thinking blocks (text and signature; the text may be empty) and redacted_thinking blocks (data). The signature covers the block, and on some models the conversation before it.
  • Codex reasoning items. Codex runs stateless (store: false), so each request asks for include: ["reasoning.encrypted_content"], and the item (less its id) is sent back as an input item ahead of the function call that followed it.

A provider stamps its reasoning with a replay key when it parses the response (claude; codex/<model>, since encrypted reasoning is readable only by the model that wrote it). The assistant turn in the transcript keeps those blocks in reasoning, each anchored ahead of the turn’s text, ahead of a tool call, or after the rest, and the view puts them back in place. A provider sends only blocks carrying its own key and complete enough to replay (a thinking block needs its signature); other providers never see them. The display text stays in thinking and is never sent.

The session log writes reasoning only when its secret redaction would leave every block byte-identical, since a rewritten block fails its signature on every later request. Codex encrypted_content is opaque ciphertext, so redaction leaves it alone: random base64url often contains a run that reads like a key. A turn that quotes a credential in its thinking therefore replays that thinking live but not after a resume. Session files written before this field existed load and replay no reasoning. Compaction replaces the transcript, so no block bound to the old history is replayed after it.

Errors and retries

ProviderError includes ParseError, ApiError, NetworkError, RateLimited, Timeout, InvalidRequest, AuthenticationError, and Overloaded. is_retryable() marks rate limits (429), network errors, server errors (5xx), and timeouts as retryable; auth and other 4xx errors are not. Automatic retry is wired in: a RetryState with exponential backoff drives a bounded retry of failed LLM calls from the ranch handlers (crates/core/src/handlers.rs, schedule_llm_retry) — a retryable error schedules a backed-off retry until max_attempts is exhausted, after which the failure surfaces as an error message.

Bridges

Bridge services (Discord, email) do not use the provider layer. They reach the agent through the pub/sub message system: inbound messages are polled and processed as user input, and replies flow back out the same way. See Approvals & Outbox.