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