Skip to main content

causa_kernel/ports/
gateway.rs

1//! Logical model invocation contracts.
2//!
3//! `ModelGateway` port — the model-invocation seam drivers call into.
4//! Transport-free; concrete gateways live outside the kernel. The port is
5//! self-contained: its request parameters, result envelope, and transport
6//! error all live here. Fact vocabulary (`ModelResponse`, `ModelStopReason`,
7//! ids) comes from `crate::context`.
8
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11use std::time::Duration;
12
13use crate::context::ids::InvocationId;
14use crate::context::material::ContextFrame;
15use crate::context::model::{ModelResponse, ModelStopReason};
16use crate::ports::control::CallControl;
17use crate::ports::tool::ToolSurface;
18
19/// Opaque model identifier handed to the gateway. The kernel never parses
20/// it; resolution is the gateway's job.
21///
22/// Serializable for logs and tests; the serialized form is not part of the
23/// stable set and may change in any release.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ModelRef(pub String);
26impl ModelRef {
27    /// Wraps a raw model-id string.
28    pub fn new(s: impl Into<String>) -> Self {
29        Self(s.into())
30    }
31}
32
33/// Generation knobs a caller may pin for the invocation. `None` leaves the
34/// provider default in force.
35/// Protocol adapters reject options they cannot faithfully render. Hosts own
36/// model-specific capability validation, defaults, and aggregate budgets;
37/// `reasoning_effort` and `extra_body` are sent as given for that reason.
38///
39/// Serializable for logs and tests; the serialized form is not part of the
40/// stable set and may change in any release.
41#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
42#[non_exhaustive]
43pub struct GenerationOptions {
44    /// Sampling temperature; `None` leaves the provider default in force.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub temperature: Option<f32>,
47    /// Upper bound on generated tokens, including reasoning tokens where the
48    /// provider counts them. `None` leaves the limit unconstrained by the caller.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub max_tokens: Option<u32>,
51    /// Reasoning effort, written to the protocol's effort key exactly as
52    /// given: Chat `reasoning_effort`, Responses `reasoning.effort`, Anthropic
53    /// `output_config.effort`. `None` omits the key. The value is not checked
54    /// or mapped; which values a model accepts is the host's knowledge, and a
55    /// value the provider refuses comes back as the provider's error.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub reasoning_effort: Option<String>,
58    /// Further request fields, merged into the request body exactly as
59    /// given. This is where protocol- or model-specific settings go, such as
60    /// an Anthropic `thinking` object. Where the adapter wrote an object and
61    /// the same key here is an object too, the two are merged key by key, so
62    /// `{"reasoning": {"summary": "auto"}}` joins the effort the adapter
63    /// wrote. Any other value the adapter writes itself (`model`, the
64    /// messages, `tools`, the options above) is kept and the value given
65    /// here is dropped without an error. `output_schema` is kept whole: a
66    /// key beside the schema is merged, a key inside it is not. Every other
67    /// key is sent unchecked, a `null` included.
68    ///
69    /// "Kept" goes by the key the adapter wrote, not by meaning: a key the
70    /// protocol also understands under another name is sent beside the
71    /// adapter's own. An adapter may write further keys by default, and on a
72    /// streaming call it sets the keys that turn streaming on whatever is
73    /// given here; the adapter's documentation lists them. A field that
74    /// changes the shape of the response can make it unreadable to the
75    /// adapter.
76    ///
77    /// A serialized `null` reads as empty.
78    #[serde(
79        default,
80        deserialize_with = "null_as_empty",
81        skip_serializing_if = "serde_json::Map::is_empty"
82    )]
83    pub extra_body: serde_json::Map<String, serde_json::Value>,
84    /// JSON Schema the final response should satisfy, rendered natively
85    /// where the underlying protocol supports it. Schema validation and
86    /// corrective retry stay host-side. `None` omits it.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub output_schema: Option<serde_json::Value>,
89}
90
91impl GenerationOptions {
92    /// Sets the sampling temperature.
93    pub fn with_temperature(mut self, temperature: f32) -> Self {
94        self.temperature = Some(temperature);
95        self
96    }
97
98    /// Sets the upper bound on generated tokens.
99    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
100        self.max_tokens = Some(max_tokens);
101        self
102    }
103
104    /// Sets the reasoning effort.
105    pub fn with_reasoning_effort(mut self, reasoning_effort: impl Into<String>) -> Self {
106        self.reasoning_effort = Some(reasoning_effort.into());
107        self
108    }
109
110    /// Replaces the extra request body fields.
111    pub fn with_extra_body(
112        mut self,
113        extra_body: serde_json::Map<String, serde_json::Value>,
114    ) -> Self {
115        self.extra_body = extra_body;
116        self
117    }
118
119    /// Sets the JSON Schema the final response should satisfy.
120    pub fn with_output_schema(mut self, output_schema: serde_json::Value) -> Self {
121        self.output_schema = Some(output_schema);
122        self
123    }
124}
125
126fn null_as_empty<'de, D>(
127    deserializer: D,
128) -> Result<serde_json::Map<String, serde_json::Value>, D::Error>
129where
130    D: serde::Deserializer<'de>,
131{
132    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
133}
134
135/// Provider-reported token accounting for one model response.
136///
137/// Serializable for logs and tests; the serialized form is not part of the
138/// stable set and may change in any release.
139#[derive(Debug, Clone, Default, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct ModelUsage {
142    /// Tokens counted on the prompt side of the exchange.
143    pub input_tokens: usize,
144    /// Tokens counted on the generated side of the exchange.
145    pub output_tokens: usize,
146    /// Provider-reported prompt-cache read (hit) tokens, if disclosed.
147    #[serde(default)]
148    pub cache_read_tokens: Option<usize>,
149    /// Provider-reported prompt-cache write (population) tokens, if disclosed.
150    #[serde(default)]
151    pub cache_write_tokens: Option<usize>,
152    /// Provider-reported reasoning/thinking tokens, if disclosed.
153    #[serde(default)]
154    pub reasoning_tokens: Option<usize>,
155}
156impl ModelUsage {
157    /// Usage with the two counts every provider reports; the optional counts start undisclosed.
158    pub fn new(input_tokens: usize, output_tokens: usize) -> Self {
159        Self {
160            input_tokens,
161            output_tokens,
162            cache_read_tokens: None,
163            cache_write_tokens: None,
164            reasoning_tokens: None,
165        }
166    }
167}
168
169/// Structured reasoning content: the model's readable thinking text.
170/// Recorded as-is by callers; the kernel does not interpret or persist it.
171///
172/// Opaque provider items that must be echoed back on later turns are carried
173/// as context material (such as [`crate::ContentPart::Sealed`] parts). This
174/// observation is display-only.
175///
176/// Serializable for logs and tests; the serialized form is not part of the
177/// stable set and may change in any release.
178#[derive(Debug, Clone, Default, Serialize, Deserialize)]
179#[non_exhaustive]
180pub struct ReasoningPayload {
181    /// The model's thinking text.
182    pub text: String,
183}
184impl ReasoningPayload {
185    /// A payload holding the given thinking text.
186    pub fn new(text: impl Into<String>) -> Self {
187        Self { text: text.into() }
188    }
189}
190
191/// The gateway result envelope. Pure response conversion consumes neither
192/// this value nor its usage and reasoning; execution consumers retain them.
193///
194/// Serializable for logs and tests; the serialized form is not part of the
195/// stable set and may change in any release.
196#[derive(Debug, Clone, Serialize, Deserialize)]
197#[non_exhaustive]
198pub struct ModelOutput {
199    /// What the model said and asked: the [`ModelResponse`] fact.
200    pub response: ModelResponse,
201    /// Token accounting, when the provider disclosed it.
202    pub usage: Option<ModelUsage>,
203    /// Why generation ended: the [`ModelStopReason`] fact.
204    pub stop_reason: ModelStopReason,
205    /// The stop value exactly as the upstream provider or model sent it,
206    /// so a host can inspect what an unrecognized stop condition was. `None`
207    /// only for gateways with no wire value, such as test doubles.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub raw_stop_reason: Option<String>,
210    /// Structured reasoning payload, when the provider emitted one.
211    pub reasoning: Option<ReasoningPayload>,
212}
213impl ModelOutput {
214    /// An output with its response and stop reason; usage, the raw stop value and reasoning start absent.
215    pub fn new(response: ModelResponse, stop_reason: ModelStopReason) -> Self {
216        Self {
217            response,
218            stop_reason,
219            usage: None,
220            raw_stop_reason: None,
221            reasoning: None,
222        }
223    }
224}
225
226/// Classification of a logical model invocation failure.
227///
228/// More kinds may be added; a match needs a wildcard arm, and an unknown kind
229/// is best treated like [`Self::Permanent`]: not retried.
230///
231/// Serializable for logs and tests; the serialized form is not part of the
232/// stable set and may change in any release.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235#[non_exhaustive]
236pub enum ModelInvokeErrorKind {
237    /// Recoverable failure a retry policy may allow: transport hiccups,
238    /// rate limits, server-side errors.
239    Transient,
240    /// The request exceeded its deadline.
241    TimedOut,
242    /// The invocation was cancelled through its [`CallControl`], before send
243    /// or while in flight.
244    Cancelled,
245    /// Another attempt will not help. Usually the provider refused: a
246    /// rejected credential, an unknown model or path, or any other refusal
247    /// not classified below; such an error carries a status, or a code when
248    /// it arrived inside a successful response. Without either, the fault is
249    /// local: the transport could not build the request.
250    Permanent,
251    /// The provider answered and the adapter could not use the answer: a
252    /// success body or stream that is malformed or breaks the protocol's own
253    /// rules, or any response over a configured size limit. Not retryable. Unlike
254    /// [`Self::Permanent`], changing the credential, model or endpoint
255    /// setting is not the remedy; the adapter and the server disagree about
256    /// the wire.
257    Undecodable,
258    /// The request itself is malformed. Either the provider rejected it, or
259    /// the adapter refused it before anything was sent: options outside the
260    /// protocol's range, a body that is not an object, or a decoder used
261    /// against its contract.
262    InvalidRequest,
263    /// No observable outcome — e.g. a stream that ended without `Done`.
264    UnknownOutcome,
265}
266
267/// A model-invocation failure: a [`ModelInvokeErrorKind`] plus human-readable
268/// detail (provider text included where available).
269///
270/// `status` and `code` repeat, as data, what the message says in words, so a
271/// host can choose what to tell its user without parsing the message.
272///
273/// `retry_delay` carries a server-requested wait (an HTTP `retry-after` or
274/// `retry-after-ms` header) when the transport filled one. The kernel does
275/// not act on it; a caller-side retry policy decides whether to honor it.
276///
277/// `Display` prints the message alone; the kind is data, not prose.
278#[derive(Debug, Clone, thiserror::Error)]
279#[error("{message}")]
280#[non_exhaustive]
281pub struct ModelInvokeError {
282    /// The failure classification.
283    pub kind: ModelInvokeErrorKind,
284    /// Human-readable failure detail.
285    pub message: String,
286    /// The HTTP status of a non-success response. `None` when the failure
287    /// did not come from one: a transport fault, a local check, or an error
288    /// reported inside a successful response.
289    pub status: Option<u16>,
290    /// The provider's own error code or type, such as `rate_limit_error`.
291    /// `None` when the provider named none or the value was not a short
292    /// identifier.
293    pub code: Option<String>,
294    /// Server-requested delay before another attempt, when the provider sent
295    /// one. `None` when no usable delay was disclosed.
296    pub retry_delay: Option<Duration>,
297}
298impl ModelInvokeError {
299    /// Assembles an error from its kind and message, with no status, code or
300    /// retry delay.
301    pub fn new(kind: ModelInvokeErrorKind, message: impl Into<String>) -> Self {
302        Self {
303            kind,
304            message: message.into(),
305            status: None,
306            code: None,
307            retry_delay: None,
308        }
309    }
310    /// Records the HTTP status of the non-success response behind this error.
311    pub fn with_status(mut self, status: u16) -> Self {
312        self.status = Some(status);
313        self
314    }
315    /// Records the provider's error code or type. The caller passes only a
316    /// short identifier; the kernel stores it as given.
317    pub fn with_code(mut self, code: impl Into<String>) -> Self {
318        self.code = Some(code.into());
319        self
320    }
321    /// Sets the server-requested retry delay. A retry policy may wait this
322    /// long instead of using its own backoff.
323    pub fn with_retry_delay(mut self, delay: Duration) -> Self {
324        self.retry_delay = Some(delay);
325        self
326    }
327}
328
329/// Prompt-cache instruction carried on a [`ModelRequest`]. Adapters map this
330/// directive to protocol-specific cache mechanisms or treat it as a no-op where
331/// caching is automatic or unsupported.
332///
333/// Exhaustive on purpose: a renderer that marks cache anchors matches every
334/// directive, so a new one is a breaking change.
335///
336/// Serializable for logs and tests; the serialized form is not part of the
337/// stable set and may change in any release.
338#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "snake_case")]
340pub enum CacheDirective {
341    /// Mark no explicit cache breakpoints (the default).
342    #[default]
343    None,
344    /// Mark the stable-prefix anchors so provider caches cover the tool
345    /// surface, the system prefix, and the latest stable conversation
346    /// message.
347    StablePrefix,
348}
349
350/// Everything one logical invocation needs. All fields stay unchanged across
351/// internal retries; the gateway owns any attempt numbering and retry policy.
352#[derive(Debug, Clone)]
353#[non_exhaustive]
354pub struct ModelRequest {
355    /// Identifies the turn + round this logical invocation belongs to; the same id
356    /// recurs on every retry.
357    pub invocation_id: InvocationId,
358    /// The [`ContextFrame`] the gateway renders for the invocation.
359    pub frame: ContextFrame,
360    /// Which model to invoke.
361    pub model: ModelRef,
362    /// The [`ToolSurface`] offered alongside the frame.
363    pub tool_surface: ToolSurface,
364    /// The [`GenerationOptions`] governing sampling.
365    pub generation: GenerationOptions,
366    /// The prompt-cache instruction the translation face renders. Invariant
367    /// across retries like the rest of the request.
368    pub cache: CacheDirective,
369}
370impl ModelRequest {
371    /// A request with no tools, default generation options and no cache directive.
372    pub fn new(invocation_id: InvocationId, frame: ContextFrame, model: ModelRef) -> Self {
373        Self {
374            invocation_id,
375            frame,
376            model,
377            tool_surface: ToolSurface::empty(),
378            generation: GenerationOptions::default(),
379            cache: CacheDirective::None,
380        }
381    }
382}
383
384/// The model-invocation port: concrete gateways (provider adapters) live
385/// outside the kernel and translate [`ModelRequest`]s onto their transport,
386/// honoring the invocation's control plane.
387#[async_trait]
388pub trait ModelGateway: Send + Sync {
389    /// Runs one logical invocation, returning the
390    /// assembled [`ModelOutput`], or a classified [`ModelInvokeError`].
391    /// Cancellation and the deadline arrive through `control`.
392    async fn invoke(
393        &self,
394        request: &ModelRequest,
395        control: &CallControl,
396    ) -> Result<ModelOutput, ModelInvokeError>;
397
398    /// Streams one logical output. Once any delta has been yielded, transparent
399    /// retries are prohibited. The final Done alone supplies material for
400    /// submission. Default implementation: degenerates to a
401    /// single [`StreamDelta::Done`] after `invoke` — providers that never
402    /// implemented streaming keep working through the same port; streaming
403    /// providers override to expose real token increments.
404    async fn stream(
405        &self,
406        request: &ModelRequest,
407        control: &CallControl,
408    ) -> Result<ModelStream, ModelInvokeError> {
409        let output = self.invoke(request, control).await?;
410        Ok(completed_model_stream(output))
411    }
412}
413
414/// Bounded stream of provider deltas. Cancellation is observable through
415/// the same `CallControl` the `invoke` path uses — drivers race
416/// `next()` against the cancellation token, never poll.
417pub type ModelStream = std::pin::Pin<Box<dyn futures_core::Stream<Item = StreamDelta> + Send>>;
418
419struct OnceModelStream {
420    item: Option<ModelOutput>,
421}
422
423impl futures_core::Stream for OnceModelStream {
424    type Item = StreamDelta;
425
426    fn poll_next(
427        mut self: std::pin::Pin<&mut Self>,
428        _cx: &mut std::task::Context<'_>,
429    ) -> std::task::Poll<Option<Self::Item>> {
430        let delta = self
431            .item
432            .take()
433            .map(|final_output| StreamDelta::Done { final_output });
434        std::task::Poll::Ready(delta)
435    }
436}
437
438/// Wrap an already-complete output as a single-`Done` stream — the
439/// degenerate form the default `stream` implementation and tests use.
440pub fn completed_model_stream(output: ModelOutput) -> ModelStream {
441    Box::pin(OnceModelStream { item: Some(output) })
442}
443
444/// One incremental observation from a streaming provider.
445///
446/// Contract: `Done` MUST carry the fully-assembled [`ModelOutput`] (ordered
447/// items, tool-call drafts with stable ids, usage) — deltas are advisory
448/// observations for hosts, never the source of truth. A stream that ends
449/// without `Done` is an `UnknownOutcome`-shaped failure at the driver.
450#[derive(Debug, Clone)]
451#[non_exhaustive]
452pub enum StreamDelta {
453    /// An increment of assistant text.
454    TextDelta {
455        /// The new text fragment.
456        delta: String,
457    },
458    /// An increment of reasoning/thinking text.
459    ReasoningDelta {
460        /// The new reasoning fragment.
461        delta: String,
462    },
463    /// An increment of one streamed tool call, identified by its position
464    /// among the model's tool calls. A call seen here is an observation: the
465    /// calls to act on are the ones in `Done`, which leaves out a call the
466    /// response stopped in the middle of.
467    ToolCallDelta {
468        /// Position of this call among the model's tool-call drafts — how
469        /// deltas are matched to calls.
470        call_index: usize,
471        /// Provider-issued id retained verbatim when the gateway assembles
472        /// the complete tool declaration in `Done`.
473        provider_call_id: Option<String>,
474        /// Incremental fragment of the tool name, when the provider streams it.
475        name_delta: Option<String>,
476        /// Incremental fragment of the call's JSON arguments.
477        arguments_delta: Option<String>,
478    },
479    /// A mid-stream token-usage observation.
480    Usage(ModelUsage),
481    /// Terminal delta: generation ended. Carries the fully-assembled output —
482    /// the source of truth per this enum's contract, including its
483    /// [`ModelStopReason`].
484    Done {
485        /// The fully-assembled [`ModelOutput`] — the authoritative result.
486        final_output: ModelOutput,
487    },
488    /// In-stream failure observation carrying the gateway's own
489    /// [`ModelInvokeError`], so an error before any delta keeps its
490    /// classification and any server-requested retry delay.
491    Error {
492        /// The failure the gateway produced.
493        error: ModelInvokeError,
494    },
495}