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