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