Skip to main content

causa_kernel/ports/gateway/
contract.rs

1//! `ModelGateway` port — the model-invocation seam drivers call into.
2//! Transport-free; concrete gateways live outside the kernel. The port is
3//! self-contained: its request parameters, result envelope, and transport
4//! error all live here. Fact vocabulary (`ModelResponse`, `ModelStopReason`,
5//! ids) comes from `crate::context`.
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::context::ids::InvocationId;
11use crate::context::material::ContextFrame;
12use crate::context::model::{ModelResponse, ModelStopReason};
13use crate::ports::control::CallControl;
14use crate::ports::tool::ToolDefinition;
15
16/// Opaque model identifier, rendered verbatim into the provider request's
17/// `model` field. The kernel never parses it; resolution is the gateway's job.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ModelRef(pub String);
20impl ModelRef {
21    /// Wraps a raw model-id string.
22    pub fn new(s: impl Into<String>) -> Self {
23        Self(s.into())
24    }
25}
26
27/// Sampling knobs a caller may pin for the invocation. `None` means
28/// "unspecified": renderers omit the knob and the provider default applies.
29#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
30pub struct GenerationOptions {
31    /// Sampling temperature; `None` leaves the provider default in force.
32    pub temperature: Option<f32>,
33    /// Upper bound on generated tokens; `None` omits the limit from the
34    /// request.
35    pub max_tokens: Option<u32>,
36    /// JSON Schema the final response should satisfy, rendered natively
37    /// where the provider supports it (Chat `response_format`, Responses
38    /// `text.format`; Anthropic has no native mapping — schema validation
39    /// and corrective retry stay host-side). `None` omits the knob.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub output_schema: Option<serde_json::Value>,
42}
43
44/// The tool definitions offered to the model for one invocation; renderers
45/// turn this into the protocol's `tools` array.
46#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
47pub struct ToolSurface {
48    /// Model-facing [`ToolDefinition`]s, in offer order.
49    pub definitions: Vec<ToolDefinition>,
50}
51impl ToolSurface {
52    /// A surface offering no tools.
53    pub fn empty() -> Self {
54        Self {
55            definitions: Vec::new(),
56        }
57    }
58    /// Builds a surface from the given definitions.
59    pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
60        Self { definitions }
61    }
62}
63
64/// Provider-reported token accounting for one model response.
65#[derive(Debug, Clone, Default, Serialize, Deserialize)]
66pub struct ModelUsage {
67    /// Tokens counted on the prompt side of the exchange.
68    pub input_tokens: usize,
69    /// Tokens counted on the generated side of the exchange.
70    pub output_tokens: usize,
71    /// Provider-reported prompt-cache read (hit) tokens, if disclosed.
72    #[serde(default)]
73    pub cache_read_tokens: Option<usize>,
74    /// Provider-reported prompt-cache write (population) tokens, if disclosed.
75    #[serde(default)]
76    pub cache_write_tokens: Option<usize>,
77    /// Provider-reported reasoning/thinking tokens, if disclosed.
78    #[serde(default)]
79    pub reasoning_tokens: Option<usize>,
80}
81
82/// Structured reasoning content: the model's thinking text plus the optional
83/// provider signature some APIs attach so it can be replayed on later turns.
84/// Recorded as-is by callers; the kernel does not interpret or persist it.
85#[derive(Debug, Clone, Default, Serialize, Deserialize)]
86pub struct ReasoningPayload {
87    /// The model's thinking text.
88    pub text: String,
89    /// Provider signature that lets the reasoning be replayed on later turns,
90    /// when the provider issues one.
91    #[serde(default)]
92    pub signature: Option<String>,
93}
94
95/// The gateway result envelope. Pure response conversion consumes neither
96/// this value nor its usage and reasoning; execution consumers retain them.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ModelOutput {
99    /// What the model said and asked: the [`ModelResponse`] fact.
100    pub response: ModelResponse,
101    /// Token accounting, when the provider disclosed it.
102    pub usage: Option<ModelUsage>,
103    /// Why generation ended: the [`ModelStopReason`] fact.
104    pub stop_reason: ModelStopReason,
105    /// Structured reasoning payload, when the provider emitted one.
106    pub reasoning: Option<ReasoningPayload>,
107}
108
109/// Classification of a logical model invocation failure.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub enum ModelInvokeErrorKind {
112    /// Recoverable failure a retry policy may allow: transport hiccups,
113    /// rate limits, server-side errors.
114    Transient,
115    /// The request exceeded its deadline.
116    TimedOut,
117    /// The invocation was cancelled through its [`CallControl`], before send
118    /// or while in flight.
119    Cancelled,
120    /// Non-retryable failure: auth, unusable provider responses, parse
121    /// failures, and everything else not classified transient.
122    Permanent,
123    /// The provider rejected the request itself as malformed.
124    InvalidRequest,
125    /// No observable outcome — e.g. a stream that ended without `Done`.
126    UnknownOutcome,
127}
128
129/// A model-invocation failure: a [`ModelInvokeErrorKind`] plus human-readable
130/// detail (provider text included where available).
131#[derive(Debug)]
132pub struct ModelInvokeError {
133    /// The failure classification.
134    pub kind: ModelInvokeErrorKind,
135    /// Human-readable failure detail.
136    pub message: String,
137}
138impl ModelInvokeError {
139    /// Assembles an error from its kind and message.
140    pub fn new(kind: ModelInvokeErrorKind, message: impl Into<String>) -> Self {
141        Self {
142            kind,
143            message: message.into(),
144        }
145    }
146    /// The failure classification.
147    pub fn kind(&self) -> &ModelInvokeErrorKind {
148        &self.kind
149    }
150}
151impl std::fmt::Display for ModelInvokeError {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        write!(f, "{:?}: {}", self.kind, self.message)
154    }
155}
156impl std::error::Error for ModelInvokeError {}
157
158/// Prompt-cache instruction carried on a [`ModelRequest`]. The Anthropic
159/// translation face renders explicit `cache_control` breakpoints at the
160/// stable-prefix anchors; OpenAI-family providers cache server-side and
161/// accept the directive as a documented no-op.
162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(rename_all = "snake_case")]
164pub enum CacheDirective {
165    /// Mark no cache breakpoints (the default; OpenAI server-side caching
166    /// applies regardless).
167    #[default]
168    None,
169    /// Mark the stable-prefix anchors so provider caches cover the tool
170    /// surface, the system prefix, and the latest stable conversation
171    /// message.
172    StablePrefix,
173}
174
175/// Everything one logical invocation needs. All fields stay unchanged across
176/// internal retries; the gateway owns any attempt numbering and retry policy.
177#[derive(Debug, Clone)]
178pub struct ModelRequest {
179    /// Identifies the turn + round this logical invocation belongs to; the same id
180    /// recurs on every retry.
181    pub invocation_id: InvocationId,
182    /// The [`ContextFrame`] the gateway renders into provider messages.
183    pub frame: ContextFrame,
184    /// Which model to invoke.
185    pub model: ModelRef,
186    /// The [`ToolSurface`] offered alongside the frame.
187    pub tool_surface: ToolSurface,
188    /// The [`GenerationOptions`] governing sampling.
189    pub generation: GenerationOptions,
190    /// The prompt-cache instruction the translation face renders. Invariant
191    /// across retries like the rest of the request.
192    pub cache: CacheDirective,
193}
194
195/// The model-invocation port: concrete gateways (provider adapters) live
196/// outside the kernel and translate [`ModelRequest`]s onto their transport,
197/// honoring the invocation's control plane.
198#[async_trait]
199pub trait ModelGateway: Send + Sync {
200    /// Runs one logical invocation, returning the
201    /// assembled [`ModelOutput`], or a classified [`ModelInvokeError`].
202    /// Cancellation and the deadline arrive through `control`.
203    async fn invoke(
204        &self,
205        request: &ModelRequest,
206        control: &CallControl,
207    ) -> Result<ModelOutput, ModelInvokeError>;
208
209    /// Streams one logical output. Once any delta has been yielded, transparent
210    /// retries are prohibited. The final Done alone supplies material for
211    /// submission. Default implementation: degenerates to a
212    /// single [`StreamDelta::Done`] after `invoke` — providers that never
213    /// implemented streaming keep working through the same port; streaming
214    /// providers override to expose real token increments.
215    async fn stream(
216        &self,
217        request: &ModelRequest,
218        control: &CallControl,
219    ) -> Result<ModelStream, ModelInvokeError> {
220        let output = self.invoke(request, control).await?;
221        Ok(completed_model_stream(output))
222    }
223}
224
225/// Bounded stream of provider deltas. Cancellation is observable through
226/// the same `CallControl` the `invoke` path uses — drivers race
227/// `next()` against the cancellation token, never poll.
228pub type ModelStream = std::pin::Pin<Box<dyn futures_util::Stream<Item = StreamDelta> + Send>>;
229
230/// Wrap an already-complete output as a single-`Done` stream — the
231/// degenerate form the default `stream` implementation and tests use.
232pub fn completed_model_stream(output: ModelOutput) -> ModelStream {
233    let stop_reason = output.stop_reason;
234    Box::pin(futures_util::stream::once(async move {
235        StreamDelta::Done {
236            stop_reason,
237            final_output: output,
238        }
239    }))
240}
241
242/// One incremental observation from a streaming provider.
243///
244/// Contract: `Done` MUST carry the fully-assembled [`ModelOutput`] (text,
245/// tool-call drafts with stable ids, usage) — deltas are advisory
246/// observations for hosts, never the source of truth. A stream that ends
247/// without `Done` is an `UnknownOutcome`-shaped failure at the driver.
248#[derive(Debug, Clone)]
249pub enum StreamDelta {
250    /// An increment of assistant text.
251    TextDelta {
252        /// The new text fragment.
253        delta: String,
254    },
255    /// An increment of reasoning/thinking text.
256    ReasoningDelta {
257        /// The new reasoning fragment.
258        delta: String,
259    },
260    /// An increment of one streamed tool call, identified by its position
261    /// among the model's tool calls.
262    ToolCallDelta {
263        /// Position of this call among the model's tool-call drafts — how
264        /// deltas are matched to calls.
265        call_index: usize,
266        /// Provider-issued id retained verbatim when the gateway assembles
267        /// the complete tool declaration in `Done`.
268        provider_call_id: Option<String>,
269        /// Incremental fragment of the tool name, when the provider streams it.
270        name_delta: Option<String>,
271        /// Incremental fragment of the call's JSON arguments.
272        arguments_delta: Option<String>,
273    },
274    /// A mid-stream token-usage observation.
275    Usage(ModelUsage),
276    /// Terminal delta: generation ended. Carries the fully-assembled output —
277    /// the source of truth per this enum's contract.
278    Done {
279        /// The terminal [`ModelStopReason`].
280        stop_reason: ModelStopReason,
281        /// The fully-assembled [`ModelOutput`] — the authoritative result.
282        final_output: ModelOutput,
283    },
284    /// In-stream failure observation, shaped like [`ModelInvokeError`].
285    Error {
286        /// The failure classification.
287        kind: ModelInvokeErrorKind,
288        /// Human-readable failure detail.
289        message: String,
290    },
291}