Skip to main content

causa_provider/
lib.rs

1//! Concrete provider adapters for the context kernel's `ModelGateway`
2//! seam — `AnthropicMessagesGateway`, `OpenAiChatCompletionsGateway`,
3//! and `OpenAiResponsesGateway` compose the kernel-native translation in
4//! `causa-protocol::translation` with reqwest transport, the shared
5//! error mapping table, and read-only `CallControl` wiring.
6//!
7//! This crate is the transport + adapter layer: it owns reqwest HTTP
8//! plumbing and the adapter implementations. Wire-protocol translation
9//! and the `Protocol` discriminator live in `causa-protocol`.
10//!
11//! Media: the host injects a [`MediaResolver`] so the gateway can turn
12//! fact-level references into render payloads (inline bytes or remote URLs);
13//! the kernel never touches bytes. What renders to the wire depends on each
14//! protocol's capability table: Anthropic emits images and PDF documents (in
15//! user messages and tool results, inline or URL); Chat and Responses emit
16//! images only. Anything else degrades to a deterministic text placeholder.
17//! Inline payloads are bounded by per-kind ceilings configured via
18//! [`KernelHttpGateway::with_max_inline_media_bytes`], defaulting to 5 MiB each
19//! for images and documents, measured on decoded bytes. Unclassified inline
20//! payloads are dropped before rendering. Remote URLs are never fetched or
21//! limited by the gateway, and total request size is not checked here (that
22//! remains the provider's limit).
23//!
24//! # Generation options
25//!
26//! [`causa_kernel::GenerationOptions`] carries explicit sampling, output-token
27//! limits, an optional reasoning effort and extra request fields. Both call
28//! entrances render the same options. The adapter's own options are never
29//! dropped; an `extra_body` value under a key the adapter wrote is dropped
30//! without an error.
31//!
32//! The reasoning effort is a string sent as given: Chat `reasoning_effort`,
33//! Responses `reasoning.effort`, Anthropic `output_config.effort`.
34//! `extra_body` is merged into the request, beside what the adapter wrote
35//! and never in place of it, which is how
36//! a host sends an Anthropic `thinking` object or any setting only one
37//! server knows. Neither is checked here. The keys the adapter writes are
38//! the model, the messages or input, the system content, the tools and the
39//! options above under each protocol's own names; Responses also writes
40//! `include` and `store` unless its render options turn them off. `stream`
41//! and Chat `stream_options.include_usage` are written on `stream` only, so
42//! on `invoke` an `extra_body` value for either is sent as given. A value the provider refuses comes
43//! back as its error, with its message, status and code.
44//!
45//! Anthropic requires `max_tokens`: a missing limit is rejected before HTTP,
46//! never defaulted, and `output_schema` remains unsupported by the Anthropic
47//! adapter. Reasoning state replays as sealed context material: the
48//! Anthropic and Responses parsers keep provider reasoning items whole and the
49//! Chat renderer replays sealed `reasoning_content`. Which effort values,
50//! sampling settings and tools a model accepts is the host's knowledge;
51//! model identifiers remain opaque to Causa.
52//!
53//! # Render options
54//!
55//! The renderer-specific choices live in
56//! [`causa_protocol::translation::render_options`] and are hosted by the
57//! matching gateway configuration:
58//! [`KernelHttpGateway::with_native_tool_changes`] for Anthropic,
59//! [`KernelHttpGateway::with_encrypted_reasoning`],
60//! [`KernelHttpGateway::with_store`] and
61//! [`KernelHttpGateway::with_additional_tools`] for Responses, and
62//! [`KernelHttpGateway::with_reasoning_content_replay`] and
63//! [`KernelHttpGateway::with_max_tokens_field`] for Chat. They can
64//! also be replaced at once with [`KernelHttpGateway::with_render_options`].
65//! They apply to the gateway value, not to one request; the defaults are
66//! documented on each option type.
67//!
68//! # Streaming
69//!
70//! All built-in gateways implement real SSE through
71//! [`causa_kernel::ModelGateway::stream`]. Observations are provisional; only
72//! [`causa_kernel::StreamDelta::Done`] carries the authoritative complete
73//! output. Invalid/truncated streams fail without producing partial material.
74//! [`StreamLimits`] bounds wire, event and retained-output budgets; configure
75//! it with [`KernelHttpGateway::with_stream_limits`].
76//!
77//! Consumption drives reads, with no detached reader or automatic fallback.
78//! Cancellation and deadlines apply during establishment and body processing;
79//! parsing one complete JSON event is synchronous. Dropping the stream or
80//! accepting a terminal releases the local HTTP response. Default clients
81//! configure a 10-second connect timeout and a 300-second idle read timeout
82//! that resets after each successful read, without a total request timeout:
83//! long turns continue uninterrupted while stalled connections time out, and
84//! total duration is governed by the [`causa_kernel::CallControl`] deadline.
85//! Default clients disable retries and redirects; host-injected clients retain
86//! their policies. Session history, event delivery, display and persistence
87//! remain host-owned.
88//!
89//! # Retries
90//!
91//! Every non-2xx response is classified: 408, 409, 429 and 5xx are
92//! `Transient`, 400 and 422 are `InvalidRequest`, and the rest
93//! `Permanent`. A response the adapter cannot read is `Undecodable`, which
94//! is not retried either: a 2xx body or stream it cannot parse, or a body of
95//! any status over the size cap. A failure before any response arrived,
96//! including a connection the peer closed, is `Transient`; the request may
97//! have reached the server. An `x-should-retry` response header overrides
98//! the status rule when it is `true` or `false`. A `retry-after-ms` or `retry-after`
99//! value (seconds or an HTTP date) fills
100//! [`causa_kernel::ModelInvokeError::retry_delay`]. The adapters never retry
101//! themselves — default clients disable transport retries — so bounded
102//! retries stay a caller-side choice, such as the runtime's
103//! `RetryingGateway`. See the shared transport module for the full table.
104//!
105//! # Error bodies
106//!
107//! Non-2xx responses from both `invoke` and `stream` follow one rule: when the
108//! response body contains the documented error envelope (`{"error": {"message": "..."}}`),
109//! the error message is formatted as `"{protocol} error {status}: {error.message}"`,
110//! with `error.message` truncated to 200 characters (appended with `…` if longer).
111//! When the body is not that envelope, there is no fallback to raw body text and
112//! the message contains the protocol name and status only: `"{protocol} error {status}"`.
113//!
114//! The status is also in [`causa_kernel::ModelInvokeError::status`], and the
115//! envelope's `code` (or `type`) in [`causa_kernel::ModelInvokeError::code`]
116//! when it is a short identifier, so a host can tell a rejected credential
117//! from an unknown model without parsing the message.
118//!
119//! An error inside a successful response (a stream event, or a 2xx body
120//! that is an error envelope) is read by the same rule and formatted as
121//! `"provider error ({code}): {error.message}"`; it has a code and no
122//! status, and its kind comes from the envelope's `code` and `type`. Provider text is always one line: control characters
123//! are replaced by spaces.
124
125#![deny(unsafe_code)]
126#![deny(missing_docs)]
127
128mod gateway_transport;
129mod kernel_gateway;
130pub mod media;
131
132pub use kernel_gateway::{
133    AnthropicGatewayConfig, AnthropicMessagesGateway, KernelGatewayConfig, KernelHttpGateway,
134    OpenAiChatCompletionsGateway, OpenAiChatGatewayConfig, OpenAiResponsesGateway,
135    OpenAiResponsesGatewayConfig,
136};
137pub use media::MediaResolver;
138
139/// Per-protocol render options for gateway configuration.
140pub use causa_protocol::translation::render_options::{
141    AnthropicRenderOptions, ChatMaxTokensField, ChatRenderOptions, ResponsesRenderOptions,
142};
143
144/// Resource limits for the transport-free streaming decoder.
145pub use causa_protocol::translation::streaming::StreamLimits;
146
147/// Media vocabulary a [`MediaResolver`] answers with, and the kind an
148/// inline ceiling applies to.
149pub use causa_protocol::translation::media::{MediaKind, MediaPayload, MediaSource};