causa-provider 0.0.6

Causa — a minimal context kernel for Rust agents (facts, ports, adapters)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Gateway configuration and shared request preparation.

use super::config::{
    AnthropicGatewayConfig, KernelGatewayConfig, OpenAiChatGatewayConfig,
    OpenAiResponsesGatewayConfig,
};
use super::stream::{establish_stream, model_stream};
use crate::gateway_transport::{GatewayCore, check_control, finish_response, send_with_control};
use crate::media::MediaResolver;
use async_trait::async_trait;
use causa_kernel::{
    BlockContent, CallControl, ContentPart, MediaRef, ModelGateway, ModelInvokeError, ModelOutput,
    ModelRequest,
};
use causa_protocol::translation::media::{MediaKind, MediaSet, MediaSource};
use causa_protocol::translation::render_options::{
    AnthropicRenderOptions, ChatRenderOptions, ResponsesRenderOptions,
};
use causa_protocol::translation::streaming::{
    StreamDecoder, StreamLimits, configure_stream_request,
};
use reqwest::Client;
use std::sync::Arc;
use tracing::Instrument;

/// Inline media ceilings, one per [`MediaKind`], in decoded bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct InlineMediaCeilings {
    image: usize,
    document: usize,
}

impl Default for InlineMediaCeilings {
    fn default() -> Self {
        const DEFAULT_CEILING: usize = 5 * 1024 * 1024;
        Self {
            image: DEFAULT_CEILING,
            document: DEFAULT_CEILING,
        }
    }
}

impl InlineMediaCeilings {
    fn get(&self, kind: MediaKind) -> usize {
        match kind {
            MediaKind::Image => self.image,
            MediaKind::Document => self.document,
        }
    }

    fn set(&mut self, kind: MediaKind, max_bytes: usize) {
        match kind {
            MediaKind::Image => self.image = max_bytes,
            MediaKind::Document => self.document = max_bytes,
        }
    }
}

/// Generic kernel gateway: reqwest transport + the pure translation in
/// `causa_protocol::translation` composed with the shared error
/// mapping table and control-plane wiring from `crate::gateway_transport`.
///
/// Media: an optional host-injected [`MediaResolver`] turns the frame's
/// fact-level references into inline payloads right before rendering —
/// batch and stream share one resolution pass. Without a resolver, every
/// reference degrades to its text placeholder.
pub struct KernelHttpGateway<C: KernelGatewayConfig> {
    core: GatewayCore,
    api_key: String,
    config: C,
    media_resolver: Option<Arc<dyn MediaResolver>>,
    /// Inline media ceilings per kind, in decoded bytes (base64 is ~4/3 of
    /// this); payloads beyond their kind's ceiling degrade to placeholders
    /// like resolver misses. Default: 5 MiB for each kind, the documented
    /// per-image cap of the strictest of the three wires, also used for
    /// documents so one inline item never exceeds it.
    inline_media_ceilings: InlineMediaCeilings,
    stream_limits: StreamLimits,
}

impl<C: KernelGatewayConfig> std::fmt::Debug for KernelHttpGateway<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KernelHttpGateway")
            .field("protocol", &C::PROTOCOL.as_str())
            .field("path", &C::PATH)
            .field("media_resolver", &self.media_resolver.is_some())
            .field("inline_media_ceilings", &self.inline_media_ceilings)
            .field("stream_limits", &self.stream_limits)
            .finish_non_exhaustive()
    }
}

impl<C: KernelGatewayConfig> Clone for KernelHttpGateway<C> {
    fn clone(&self) -> Self {
        Self {
            core: self.core.clone(),
            api_key: self.api_key.clone(),
            config: self.config.clone(),
            media_resolver: self.media_resolver.clone(),
            inline_media_ceilings: self.inline_media_ceilings,
            stream_limits: self.stream_limits,
        }
    }
}

impl<C: KernelGatewayConfig> KernelHttpGateway<C> {
    /// Build a gateway with the protocol's default endpoint and configuration.
    /// Media resolution is absent until the host injects a resolver.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            core: GatewayCore::new(C::DEFAULT_ENDPOINT),
            api_key: api_key.into(),
            config: C::default(),
            media_resolver: None,
            inline_media_ceilings: InlineMediaCeilings::default(),
            stream_limits: StreamLimits::default(),
        }
    }

    /// Point at a non-default host (test doubles, gateways). `C::PATH`
    /// is appended to the given base URL, which must carry its own version
    /// segment: `https://api.anthropic.com/v1`, `https://api.openai.com/v1`,
    /// or `https://host/provider/v1` for a compatible provider. A base
    /// without a version segment is used as given.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.core = self.core.with_base_url(base_url, C::PATH);
        self
    }

    /// Full endpoint override (host + path).
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.core = self.core.with_endpoint(endpoint);
        self
    }

    /// Replace the HTTP client with one configured by the host.
    ///
    /// The default client disables redirects and retries, and configures a
    /// connect timeout and idle read timeout without a total timeout. A supplied
    /// client's transport policies remain host-owned: disable both for the same
    /// single-request guarantee. Note that a supplied client configured with its
    /// own `.timeout(...)` reintroduces a total request cap that cuts off long
    /// streaming or generation turns; total duration belongs to the
    /// [`CallControl`] deadline instead. Cancellation and deadlines remain
    /// enforced independently of the supplied client's timeout settings.
    pub fn with_http_client(mut self, http: Client) -> Self {
        self.core = self.core.with_http_client(http);
        self
    }

    /// Inject the media resolver: the host's asset table the gateway
    /// consults for every media reference in the frame.
    pub fn with_media_resolver(mut self, resolver: Arc<dyn MediaResolver>) -> Self {
        self.media_resolver = Some(resolver);
        self
    }

    /// Override the inline media ceiling for one [`MediaKind`], in decoded
    /// bytes. Each kind defaults to 5 MiB.
    ///
    /// The ceiling constrains inline payloads only ([`MediaSource::Inline`]);
    /// remote URLs ([`MediaSource::Url`]) are neither limited nor fetched. An
    /// inline payload over its kind's ceiling renders as the placeholder, like
    /// a resolver miss. The total size of a request is not checked; that is
    /// the provider's limit.
    pub fn with_max_inline_media_bytes(mut self, kind: MediaKind, max_bytes: usize) -> Self {
        self.inline_media_ceilings.set(kind, max_bytes);
        self
    }

    /// Override the pure decoder's framing, total-input, output and item budgets.
    /// Invalid limits are rejected before sending a streaming request.
    pub fn with_stream_limits(mut self, limits: StreamLimits) -> Self {
        self.stream_limits = limits;
        self
    }

    /// Shared media resolution and request validation for both call entrances.
    fn render_request(
        &self,
        request: &ModelRequest,
    ) -> Result<serde_json::Value, ModelInvokeError> {
        self.config.render(request, &self.resolve_media(request))
    }

    /// One resolution pass over the request's frame: every media
    /// reference (Message blocks and tool results) the injected resolver
    /// serves within the inline ceiling enters the table. Deterministic
    /// — the same frame and asset state produce the same table.
    fn resolve_media(&self, request: &ModelRequest) -> MediaSet {
        let mut set = MediaSet::new();
        let Some(resolver) = &self.media_resolver else {
            return set;
        };
        let mut refs: Vec<MediaRef> = Vec::new();
        let mut seen = std::collections::HashSet::new();
        for block in &request.frame.blocks {
            let collect = |r: &MediaRef,
                           refs: &mut Vec<MediaRef>,
                           seen: &mut std::collections::HashSet<String>| {
                if seen.insert(r.reference.clone()) {
                    refs.push(r.clone());
                }
            };
            match block.content() {
                BlockContent::Message { parts, .. } => {
                    for part in parts {
                        if let ContentPart::Media(r) = part {
                            collect(r, &mut refs, &mut seen);
                        }
                    }
                }
                BlockContent::ToolResult(result) => {
                    for r in &result.media {
                        collect(r, &mut refs, &mut seen);
                    }
                }
                BlockContent::ToolCall(_) | BlockContent::ToolChange(_) => {}
            }
        }
        for r in refs {
            if let Some(payload) = resolver.resolve(&r) {
                let within_ceiling = match &payload.source {
                    MediaSource::Inline { data_base64 } => {
                        match MediaKind::of(&payload.media_type) {
                            Some(kind) => {
                                let ceiling = self.inline_media_ceilings.get(kind);
                                data_base64.len() * 3 / 4 <= ceiling
                            }
                            // An unclassified type can only degrade, and the
                            // placeholder does not need the payload.
                            None => false,
                        }
                    }
                    // Only inline bytes count toward a ceiling: a URL (or any
                    // other non-inline source) is never fetched here, and
                    // whether it renders is the walk's decision.
                    MediaSource::Url(_) => true,
                    _ => true,
                };
                if within_ceiling {
                    set.insert(r.reference, payload);
                }
            }
        }
        set
    }
}

impl KernelHttpGateway<AnthropicGatewayConfig> {
    /// Override the `anthropic-version` header (default `2023-06-01`).
    pub fn with_anthropic_version(mut self, version: impl Into<String>) -> Self {
        self.config.anthropic_version = version.into();
        self
    }

    /// Append one extra `anthropic-beta` value for this gateway. Values are
    /// sent as one comma-separated `anthropic-beta` header, in the order
    /// listed, followed by the value an enabled option needs; nothing is
    /// sent by default and no model table decides headers.
    pub fn with_beta(mut self, value: impl Into<String>) -> Self {
        self.config.beta.push(value.into());
        self
    }

    /// Replace every render option at once, including any set earlier with
    /// the per-option setters (a later call wins either way). Wire
    /// consequences follow from the options: `native_tool_changes` still adds
    /// `inline-tools-2026-09-15` to `anthropic-beta`. The value usually comes
    /// from host configuration, as which servers and models support an option
    /// is the host's to decide.
    pub fn with_render_options(mut self, options: AnthropicRenderOptions) -> Self {
        self.config.render_options = options;
        self
    }

    /// Render tool changes in place (default `false`).
    ///
    /// `tools` stays at the context's first tool change and each later
    /// change is sent at its position as `tool_removal` / `tool_addition`
    /// blocks, so a changed tool listing keeps the cached prefix and earlier
    /// thinking. The gateway adds the `inline-tools-2026-09-15` beta value
    /// it needs. Off, every request carries the current tools in `tools`.
    /// Enable only for a server known to support it: a server without support
    /// may reject the request, or ignore the change so the model never sees
    /// the added tool.
    pub fn with_native_tool_changes(mut self, native: bool) -> Self {
        self.config.render_options.native_tool_changes = native;
        self
    }
}

impl KernelHttpGateway<OpenAiChatGatewayConfig> {
    /// Replace every render option at once, including any set earlier with
    /// the per-option setters (a later call wins either way). Wire
    /// consequences follow from the options. The value usually comes from host
    /// configuration, as which servers and models support an option is the
    /// host's to decide.
    pub fn with_render_options(mut self, options: ChatRenderOptions) -> Self {
        self.config.render_options = options;
        self
    }

    /// Replay sealed `reasoning_content` message-level items (default `true`).
    ///
    /// DeepSeek requires `reasoning_content` back on every request that
    /// carries `tools`; turning this off removes the key from the renderer's
    /// own sealed items and changes nothing else. The choice is per gateway
    /// value, not per request: a host that needs both holds two gateways.
    pub fn with_reasoning_content_replay(mut self, replay: bool) -> Self {
        self.config.render_options.replay_reasoning_content = replay;
        self
    }
}

impl KernelHttpGateway<OpenAiResponsesGatewayConfig> {
    /// Replace every render option at once, including any set earlier with
    /// the per-option setters (a later call wins either way). Wire
    /// consequences follow from the options. The value usually comes from host
    /// configuration, as which servers and models support an option is the
    /// host's to decide.
    pub fn with_render_options(mut self, options: ResponsesRenderOptions) -> Self {
        self.config.render_options = options;
        self
    }

    /// Send `include: ["reasoning.encrypted_content"]` (default `true`).
    ///
    /// Without it a reasoning item cannot be meaningfully replayed under
    /// `store: false` or zero data retention. The choice is per gateway value,
    /// not per request: a host that needs both holds two gateways.
    pub fn with_encrypted_reasoning(mut self, include: bool) -> Self {
        self.config.render_options.include_encrypted_reasoning = include;
        self
    }

    /// Render `store`; `None` omits the field (default `Some(false)`, as Codex
    /// and `pi-ai` send it). The host owns the data-retention choice. The
    /// choice is per gateway value, not per request.
    pub fn with_store(mut self, store: Option<bool>) -> Self {
        self.config.render_options.store = store;
        self
    }

    /// Send added tools as `additional_tools` input items (default `false`).
    ///
    /// `tools` stays at the context's first tool change and each later
    /// addition is sent at its position, as Codex does, so the cached prefix
    /// survives it. A context in which a later change removes a tool or
    /// redefines one renders with the current tools in `tools`, as with this
    /// off. Enable only for a server known to support it: a server without
    /// support may reject the request, or ignore the change so the model never
    /// sees the added tool.
    pub fn with_additional_tools(mut self, additional_tools: bool) -> Self {
        self.config.render_options.additional_tools = additional_tools;
        self
    }
}

#[async_trait]
impl<C: KernelGatewayConfig> ModelGateway for KernelHttpGateway<C> {
    async fn stream(
        &self,
        request: &ModelRequest,
        control: &CallControl,
    ) -> Result<causa_kernel::ModelStream, ModelInvokeError> {
        let span = tracing::debug_span!(
            "agent.http",
            protocol = C::PROTOCOL.as_str(),
            path = C::PATH
        );
        async {
            check_control(control)?;
            let decoder = StreamDecoder::new(C::PROTOCOL, self.stream_limits)?;
            let mut body = self.render_request(request)?;
            configure_stream_request(C::PROTOCOL, &mut body)?;
            check_control(control)?;
            let req = self
                .config
                .decorate_request(self.core.post(), &self.api_key)
                .header(reqwest::header::ACCEPT, "text/event-stream")
                .json(&body);
            let response = establish_stream(req, control, C::PROTOCOL).await?;
            Ok(model_stream(response, decoder, control.clone()))
        }
        .instrument(span)
        .await
    }

    async fn invoke(
        &self,
        request: &ModelRequest,
        control: &CallControl,
    ) -> Result<ModelOutput, ModelInvokeError> {
        // Observability baseline: ids and names only — never arguments,
        // message bodies, or API keys. The span is entered per poll via
        // `Instrument` so the boxed future stays `Send`.
        let span = tracing::debug_span!(
            "agent.http",
            protocol = C::PROTOCOL.as_str(),
            path = C::PATH
        );
        async {
            // A frame the renderer rejects never reaches the wire. Media
            // resolves first — the table feeds every renderer branch.
            check_control(control)?;
            let body = self.render_request(request)?;
            check_control(control)?;
            let req = self
                .config
                .decorate_request(self.core.post(), &self.api_key)
                .json(&body);
            let response = send_with_control(req, control).await?;
            finish_response(response, C::PROTOCOL, |v| self.config.parse(v))
        }
        .instrument(span)
        .await
    }
}