causa_provider/kernel_gateway/gateway.rs
1//! Gateway configuration and shared request preparation.
2
3use super::config::{
4 AnthropicGatewayConfig, KernelGatewayConfig, OpenAiChatGatewayConfig,
5 OpenAiResponsesGatewayConfig,
6};
7use super::stream::{establish_stream, model_stream};
8use crate::gateway_transport::{GatewayCore, check_control, finish_response, send_with_control};
9use crate::media::MediaResolver;
10use async_trait::async_trait;
11use causa_kernel::{
12 BlockContent, CallControl, ContentPart, MediaRef, ModelGateway, ModelInvokeError, ModelOutput,
13 ModelRequest,
14};
15use causa_protocol::translation::media::{MediaKind, MediaSet, MediaSource};
16use causa_protocol::translation::render_options::{
17 AnthropicRenderOptions, ChatMaxTokensField, ChatRenderOptions, ResponsesRenderOptions,
18};
19use causa_protocol::translation::streaming::{
20 StreamDecoder, StreamLimits, configure_stream_request,
21};
22use reqwest::Client;
23use std::sync::Arc;
24use tracing::Instrument;
25
26/// Inline media ceilings, one per [`MediaKind`], in decoded bytes.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28struct InlineMediaCeilings {
29 image: usize,
30 document: usize,
31}
32
33impl Default for InlineMediaCeilings {
34 fn default() -> Self {
35 const DEFAULT_CEILING: usize = 5 * 1024 * 1024;
36 Self {
37 image: DEFAULT_CEILING,
38 document: DEFAULT_CEILING,
39 }
40 }
41}
42
43impl InlineMediaCeilings {
44 fn get(&self, kind: MediaKind) -> usize {
45 match kind {
46 MediaKind::Image => self.image,
47 MediaKind::Document => self.document,
48 }
49 }
50
51 fn set(&mut self, kind: MediaKind, max_bytes: usize) {
52 match kind {
53 MediaKind::Image => self.image = max_bytes,
54 MediaKind::Document => self.document = max_bytes,
55 }
56 }
57}
58
59/// Generic kernel gateway: reqwest transport + the pure translation in
60/// `causa_protocol::translation` composed with the shared error
61/// mapping table and control-plane wiring from `crate::gateway_transport`.
62///
63/// Media: an optional host-injected [`MediaResolver`] turns the frame's
64/// fact-level references into inline payloads right before rendering —
65/// batch and stream share one resolution pass. Without a resolver, every
66/// reference degrades to its text placeholder.
67pub struct KernelHttpGateway<C: KernelGatewayConfig> {
68 core: GatewayCore,
69 api_key: String,
70 config: C,
71 media_resolver: Option<Arc<dyn MediaResolver>>,
72 /// Inline media ceilings per kind, in decoded bytes (base64 is ~4/3 of
73 /// this); payloads beyond their kind's ceiling degrade to placeholders
74 /// like resolver misses. Default: 5 MiB for each kind, the documented
75 /// per-image cap of the strictest of the three wires, also used for
76 /// documents so one inline item never exceeds it.
77 inline_media_ceilings: InlineMediaCeilings,
78 stream_limits: StreamLimits,
79}
80
81impl<C: KernelGatewayConfig> std::fmt::Debug for KernelHttpGateway<C> {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 f.debug_struct("KernelHttpGateway")
84 .field("protocol", &C::PROTOCOL.as_str())
85 .field("path", &C::PATH)
86 .field("media_resolver", &self.media_resolver.is_some())
87 .field("inline_media_ceilings", &self.inline_media_ceilings)
88 .field("stream_limits", &self.stream_limits)
89 .finish_non_exhaustive()
90 }
91}
92
93impl<C: KernelGatewayConfig> Clone for KernelHttpGateway<C> {
94 fn clone(&self) -> Self {
95 Self {
96 core: self.core.clone(),
97 api_key: self.api_key.clone(),
98 config: self.config.clone(),
99 media_resolver: self.media_resolver.clone(),
100 inline_media_ceilings: self.inline_media_ceilings,
101 stream_limits: self.stream_limits,
102 }
103 }
104}
105
106impl<C: KernelGatewayConfig> KernelHttpGateway<C> {
107 /// Build a gateway with the protocol's default endpoint and configuration.
108 /// Media resolution is absent until the host injects a resolver.
109 pub fn new(api_key: impl Into<String>) -> Self {
110 Self {
111 core: GatewayCore::new(C::DEFAULT_ENDPOINT),
112 api_key: api_key.into(),
113 config: C::default(),
114 media_resolver: None,
115 inline_media_ceilings: InlineMediaCeilings::default(),
116 stream_limits: StreamLimits::default(),
117 }
118 }
119
120 /// Point at a non-default host (test doubles, gateways). `C::PATH`
121 /// is appended to the given base URL, which must carry its own version
122 /// segment: `https://api.anthropic.com/v1`, `https://api.openai.com/v1`,
123 /// or `https://host/provider/v1` for a compatible provider. A base
124 /// without a version segment is used as given.
125 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
126 self.core = self.core.with_base_url(base_url, C::PATH);
127 self
128 }
129
130 /// Full endpoint override (host + path).
131 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
132 self.core = self.core.with_endpoint(endpoint);
133 self
134 }
135
136 /// Replace the HTTP client with one configured by the host.
137 ///
138 /// The default client disables redirects and retries, and configures a
139 /// connect timeout and idle read timeout without a total timeout. A supplied
140 /// client's transport policies remain host-owned: disable both for the same
141 /// single-request guarantee. Note that a supplied client configured with its
142 /// own `.timeout(...)` reintroduces a total request cap that cuts off long
143 /// streaming or generation turns; total duration belongs to the
144 /// [`CallControl`] deadline instead. Cancellation and deadlines remain
145 /// enforced independently of the supplied client's timeout settings.
146 pub fn with_http_client(mut self, http: Client) -> Self {
147 self.core = self.core.with_http_client(http);
148 self
149 }
150
151 /// Inject the media resolver: the host's asset table the gateway
152 /// consults for every media reference in the frame.
153 pub fn with_media_resolver(mut self, resolver: Arc<dyn MediaResolver>) -> Self {
154 self.media_resolver = Some(resolver);
155 self
156 }
157
158 /// Override the inline media ceiling for one [`MediaKind`], in decoded
159 /// bytes. Each kind defaults to 5 MiB.
160 ///
161 /// The ceiling constrains inline payloads only ([`MediaSource::Inline`]);
162 /// remote URLs ([`MediaSource::Url`]) are neither limited nor fetched. An
163 /// inline payload over its kind's ceiling renders as the placeholder, like
164 /// a resolver miss. The total size of a request is not checked; that is
165 /// the provider's limit.
166 pub fn with_max_inline_media_bytes(mut self, kind: MediaKind, max_bytes: usize) -> Self {
167 self.inline_media_ceilings.set(kind, max_bytes);
168 self
169 }
170
171 /// Override the pure decoder's framing, total-input, output and item budgets.
172 /// Invalid limits are rejected before sending a streaming request.
173 pub fn with_stream_limits(mut self, limits: StreamLimits) -> Self {
174 self.stream_limits = limits;
175 self
176 }
177
178 /// Shared media resolution and request validation for both call entrances.
179 fn render_request(
180 &self,
181 request: &ModelRequest,
182 ) -> Result<serde_json::Value, ModelInvokeError> {
183 self.config.render(request, &self.resolve_media(request))
184 }
185
186 /// One resolution pass over the request's frame: every media
187 /// reference (Message blocks and tool results) the injected resolver
188 /// serves within the inline ceiling enters the table. Deterministic
189 /// — the same frame and asset state produce the same table.
190 fn resolve_media(&self, request: &ModelRequest) -> MediaSet {
191 let mut set = MediaSet::new();
192 let Some(resolver) = &self.media_resolver else {
193 return set;
194 };
195 let mut refs: Vec<MediaRef> = Vec::new();
196 let mut seen = std::collections::HashSet::new();
197 for block in &request.frame.blocks {
198 let collect = |r: &MediaRef,
199 refs: &mut Vec<MediaRef>,
200 seen: &mut std::collections::HashSet<String>| {
201 if seen.insert(r.reference.clone()) {
202 refs.push(r.clone());
203 }
204 };
205 match block.content() {
206 BlockContent::Message { parts, .. } => {
207 for part in parts {
208 if let ContentPart::Media(r) = part {
209 collect(r, &mut refs, &mut seen);
210 }
211 }
212 }
213 BlockContent::ToolResult(result) => {
214 for r in &result.media {
215 collect(r, &mut refs, &mut seen);
216 }
217 }
218 BlockContent::ToolCall(_) | BlockContent::ToolChange(_) => {}
219 }
220 }
221 for r in refs {
222 if let Some(payload) = resolver.resolve(&r) {
223 let within_ceiling = match &payload.source {
224 MediaSource::Inline { data_base64 } => {
225 match MediaKind::of(&payload.media_type) {
226 Some(kind) => {
227 let ceiling = self.inline_media_ceilings.get(kind);
228 data_base64.len() * 3 / 4 <= ceiling
229 }
230 // An unclassified type can only degrade, and the
231 // placeholder does not need the payload.
232 None => false,
233 }
234 }
235 // Only inline bytes count toward a ceiling: a URL (or any
236 // other non-inline source) is never fetched here, and
237 // whether it renders is the walk's decision.
238 MediaSource::Url(_) => true,
239 _ => true,
240 };
241 if within_ceiling {
242 set.insert(r.reference, payload);
243 }
244 }
245 }
246 set
247 }
248}
249
250impl KernelHttpGateway<AnthropicGatewayConfig> {
251 /// Override the `anthropic-version` header (default `2023-06-01`).
252 pub fn with_anthropic_version(mut self, version: impl Into<String>) -> Self {
253 self.config.anthropic_version = version.into();
254 self
255 }
256
257 /// Append one extra `anthropic-beta` value for this gateway. Values are
258 /// sent as one comma-separated `anthropic-beta` header, in the order
259 /// listed, followed by the value an enabled option needs; nothing is
260 /// sent by default and no model table decides headers.
261 pub fn with_beta(mut self, value: impl Into<String>) -> Self {
262 self.config.beta.push(value.into());
263 self
264 }
265
266 /// Replace every render option at once, including any set earlier with
267 /// the per-option setters (a later call wins either way). Wire
268 /// consequences follow from the options: `native_tool_changes` still adds
269 /// `inline-tools-2026-09-15` to `anthropic-beta`. The value usually comes
270 /// from host configuration, as which servers and models support an option
271 /// is the host's to decide.
272 pub fn with_render_options(mut self, options: AnthropicRenderOptions) -> Self {
273 self.config.render_options = options;
274 self
275 }
276
277 /// Render tool changes in place (default `false`).
278 ///
279 /// `tools` stays at the context's first tool change and each later
280 /// change is sent at its position as `tool_removal` / `tool_addition`
281 /// blocks, so a changed tool listing keeps the cached prefix and earlier
282 /// thinking. The gateway adds the `inline-tools-2026-09-15` beta value
283 /// it needs. Off, every request carries the current tools in `tools`.
284 /// Enable only for a server known to support it: a server without support
285 /// may reject the request, or ignore the change so the model never sees
286 /// the added tool.
287 pub fn with_native_tool_changes(mut self, native: bool) -> Self {
288 self.config.render_options.native_tool_changes = native;
289 self
290 }
291}
292
293impl KernelHttpGateway<OpenAiChatGatewayConfig> {
294 /// Replace every render option at once, including any set earlier with
295 /// the per-option setters (a later call wins either way). Wire
296 /// consequences follow from the options. The value usually comes from host
297 /// configuration, as which servers and models support an option is the
298 /// host's to decide.
299 pub fn with_render_options(mut self, options: ChatRenderOptions) -> Self {
300 self.config.render_options = options;
301 self
302 }
303
304 /// Replay sealed `reasoning_content` message-level items (default `true`).
305 ///
306 /// DeepSeek requires `reasoning_content` back on every request that
307 /// carries `tools`; turning this off removes the key from the renderer's
308 /// own sealed items and changes nothing else. The choice is per gateway
309 /// value, not per request: a host that needs both holds two gateways.
310 pub fn with_reasoning_content_replay(mut self, replay: bool) -> Self {
311 self.config.render_options.replay_reasoning_content = replay;
312 self
313 }
314
315 /// Choose the request field that carries the output limit (default
316 /// [`ChatMaxTokensField::MaxCompletionTokens`]).
317 ///
318 /// Only the chosen field is sent. [`ChatMaxTokensField::MaxTokens`] is
319 /// for a server that reads only the older `max_tokens`; a server that
320 /// does not read the chosen field applies no limit and reports no error.
321 /// The choice is per gateway value, not per request.
322 pub fn with_max_tokens_field(mut self, field: ChatMaxTokensField) -> Self {
323 self.config.render_options.max_tokens_field = field;
324 self
325 }
326}
327
328impl KernelHttpGateway<OpenAiResponsesGatewayConfig> {
329 /// Replace every render option at once, including any set earlier with
330 /// the per-option setters (a later call wins either way). Wire
331 /// consequences follow from the options. The value usually comes from host
332 /// configuration, as which servers and models support an option is the
333 /// host's to decide.
334 pub fn with_render_options(mut self, options: ResponsesRenderOptions) -> Self {
335 self.config.render_options = options;
336 self
337 }
338
339 /// Send `include: ["reasoning.encrypted_content"]` (default `true`).
340 ///
341 /// Without it a reasoning item cannot be meaningfully replayed under
342 /// `store: false` or zero data retention. The choice is per gateway value,
343 /// not per request: a host that needs both holds two gateways.
344 pub fn with_encrypted_reasoning(mut self, include: bool) -> Self {
345 self.config.render_options.include_encrypted_reasoning = include;
346 self
347 }
348
349 /// Render `store`; `None` omits the field (default `Some(false)`, as Codex
350 /// and `pi-ai` send it). The host owns the data-retention choice. The
351 /// choice is per gateway value, not per request.
352 pub fn with_store(mut self, store: Option<bool>) -> Self {
353 self.config.render_options.store = store;
354 self
355 }
356
357 /// Send added tools as `additional_tools` input items (default `false`).
358 ///
359 /// `tools` stays at the context's first tool change and each later
360 /// addition is sent at its position, as Codex does, so the cached prefix
361 /// survives it. A context in which a later change removes a tool or
362 /// redefines one renders with the current tools in `tools`, as with this
363 /// off. Enable only for a server known to support it: a server without
364 /// support may reject the request, or ignore the change so the model never
365 /// sees the added tool.
366 pub fn with_additional_tools(mut self, additional_tools: bool) -> Self {
367 self.config.render_options.additional_tools = additional_tools;
368 self
369 }
370}
371
372#[async_trait]
373impl<C: KernelGatewayConfig> ModelGateway for KernelHttpGateway<C> {
374 async fn stream(
375 &self,
376 request: &ModelRequest,
377 control: &CallControl,
378 ) -> Result<causa_kernel::ModelStream, ModelInvokeError> {
379 let span = tracing::debug_span!(
380 "agent.http",
381 protocol = C::PROTOCOL.as_str(),
382 path = C::PATH
383 );
384 async {
385 check_control(control)?;
386 let decoder = StreamDecoder::new(C::PROTOCOL, self.stream_limits)?;
387 let mut body = self.render_request(request)?;
388 configure_stream_request(C::PROTOCOL, &mut body)?;
389 check_control(control)?;
390 let req = self
391 .config
392 .decorate_request(self.core.post(), &self.api_key)
393 .header(reqwest::header::ACCEPT, "text/event-stream")
394 .json(&body);
395 let response = establish_stream(req, control, C::PROTOCOL).await?;
396 Ok(model_stream(response, decoder, control.clone()))
397 }
398 .instrument(span)
399 .await
400 }
401
402 async fn invoke(
403 &self,
404 request: &ModelRequest,
405 control: &CallControl,
406 ) -> Result<ModelOutput, ModelInvokeError> {
407 // Observability baseline: ids and names only — never arguments,
408 // message bodies, or API keys. The span is entered per poll via
409 // `Instrument` so the boxed future stays `Send`.
410 let span = tracing::debug_span!(
411 "agent.http",
412 protocol = C::PROTOCOL.as_str(),
413 path = C::PATH
414 );
415 async {
416 // A frame the renderer rejects never reaches the wire. Media
417 // resolves first — the table feeds every renderer branch.
418 check_control(control)?;
419 let body = self.render_request(request)?;
420 check_control(control)?;
421 let req = self
422 .config
423 .decorate_request(self.core.post(), &self.api_key)
424 .json(&body);
425 let response = send_with_control(req, control).await?;
426 finish_response(response, C::PROTOCOL, |v| self.config.parse(v))
427 }
428 .instrument(span)
429 .await
430 }
431}