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/// Reports four non-overlapping raw counts with the same meaning across all
137/// wire protocols. Any reasoning or thinking tokens are included in
138/// [`Self::output_tokens`].
139///
140/// Serializable for logs and tests; the serialized form is not part of the
141/// stable set and may change in any release.
142#[derive(Debug, Clone, Default, Serialize, Deserialize)]
143#[non_exhaustive]
144pub struct ModelUsage {
145 /// Input tokens that neither hit nor were written to the prompt cache
146 /// (uncached input).
147 ///
148 /// The meaning is the same across all wire protocols. This count does not
149 /// overlap with [`Self::cache_read_tokens`], [`Self::cache_write_tokens`],
150 /// or [`Self::output_tokens`].
151 pub input_tokens: usize,
152 /// All tokens generated by the model on the output side of the exchange,
153 /// including any reasoning or thinking tokens.
154 ///
155 /// The meaning is the same across all wire protocols. This count does not
156 /// overlap with [`Self::input_tokens`], [`Self::cache_read_tokens`], or
157 /// [`Self::cache_write_tokens`].
158 pub output_tokens: usize,
159 /// Tokens read from the prompt cache, if disclosed by the endpoint.
160 ///
161 /// The meaning is the same across all wire protocols. `None` indicates the
162 /// endpoint did not report it (never fabricated as 0). This count does
163 /// not overlap with [`Self::input_tokens`], [`Self::cache_write_tokens`],
164 /// or [`Self::output_tokens`].
165 #[serde(default)]
166 pub cache_read_tokens: Option<usize>,
167 /// Tokens written to the prompt cache, if disclosed by the endpoint.
168 ///
169 /// The meaning is the same across all wire protocols. `None` indicates the
170 /// endpoint did not report it (never fabricated as 0). This count does not
171 /// overlap with [`Self::input_tokens`], [`Self::cache_read_tokens`], or
172 /// [`Self::output_tokens`].
173 #[serde(default)]
174 pub cache_write_tokens: Option<usize>,
175 /// Reasoning or thinking tokens generated by the model, if disclosed by
176 /// the endpoint.
177 ///
178 /// The meaning is the same across all wire protocols. `None` indicates the
179 /// endpoint did not report it. When present, this count is a subset of
180 /// [`Self::output_tokens`]; hosts must not add it to output or total
181 /// sums.
182 #[serde(default)]
183 pub reasoning_tokens: Option<usize>,
184}
185impl ModelUsage {
186 /// Usage with the two counts every provider reports (uncached input tokens
187 /// and total output tokens); the optional counts start undisclosed (`None`).
188 pub fn new(input_tokens: usize, output_tokens: usize) -> Self {
189 Self {
190 input_tokens,
191 output_tokens,
192 cache_read_tokens: None,
193 cache_write_tokens: None,
194 reasoning_tokens: None,
195 }
196 }
197}
198
199/// Structured reasoning content: the model's readable thinking text.
200/// Recorded as-is by callers; the kernel does not interpret or persist it.
201///
202/// Opaque provider items that must be echoed back on later turns are carried
203/// as context material (such as [`crate::ContentPart::Sealed`] parts). This
204/// observation is display-only.
205///
206/// Serializable for logs and tests; the serialized form is not part of the
207/// stable set and may change in any release.
208#[derive(Debug, Clone, Default, Serialize, Deserialize)]
209#[non_exhaustive]
210pub struct ReasoningPayload {
211 /// The model's thinking text.
212 pub text: String,
213}
214impl ReasoningPayload {
215 /// A payload holding the given thinking text.
216 pub fn new(text: impl Into<String>) -> Self {
217 Self { text: text.into() }
218 }
219}
220
221/// The gateway result envelope. Pure response conversion consumes neither
222/// this value nor its usage and reasoning; execution consumers retain them.
223///
224/// Serializable for logs and tests; the serialized form is not part of the
225/// stable set and may change in any release.
226#[derive(Debug, Clone, Serialize, Deserialize)]
227#[non_exhaustive]
228pub struct ModelOutput {
229 /// What the model said and asked: the [`ModelResponse`] fact.
230 pub response: ModelResponse,
231 /// Token accounting, when the provider disclosed it.
232 pub usage: Option<ModelUsage>,
233 /// Why generation ended: the [`ModelStopReason`] fact.
234 pub stop_reason: ModelStopReason,
235 /// The stop value exactly as the upstream provider or model sent it,
236 /// so a host can inspect what an unrecognized stop condition was. `None`
237 /// only for gateways with no wire value, such as test doubles.
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub raw_stop_reason: Option<String>,
240 /// Structured reasoning payload, when the provider emitted one.
241 pub reasoning: Option<ReasoningPayload>,
242}
243impl ModelOutput {
244 /// An output with its response and stop reason; usage, the raw stop value and reasoning start absent.
245 pub fn new(response: ModelResponse, stop_reason: ModelStopReason) -> Self {
246 Self {
247 response,
248 stop_reason,
249 usage: None,
250 raw_stop_reason: None,
251 reasoning: None,
252 }
253 }
254}
255
256/// Classification of a logical model invocation failure.
257///
258/// More kinds may be added; a match needs a wildcard arm, and an unknown kind
259/// is best treated like [`Self::Permanent`]: not retried.
260///
261/// Serializable for logs and tests; the serialized form is not part of the
262/// stable set and may change in any release.
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(rename_all = "snake_case")]
265#[non_exhaustive]
266pub enum ModelInvokeErrorKind {
267 /// Recoverable failure a retry policy may allow: transport hiccups,
268 /// rate limits, server-side errors.
269 Transient,
270 /// The request exceeded its deadline.
271 TimedOut,
272 /// The invocation was cancelled through its [`CallControl`], before send
273 /// or while in flight.
274 Cancelled,
275 /// Another attempt will not help. Usually the provider refused: a
276 /// rejected credential, an unknown model or path, or any other refusal
277 /// not classified below; such an error carries a status, or a code when
278 /// it arrived inside a successful response. Without either, the fault is
279 /// local: the transport could not build the request.
280 Permanent,
281 /// The provider answered and the adapter could not use the answer: a
282 /// success body or stream that is malformed or breaks the protocol's own
283 /// rules, or any response over a configured size limit. Not retryable. Unlike
284 /// [`Self::Permanent`], changing the credential, model or endpoint
285 /// setting is not the remedy; the adapter and the server disagree about
286 /// the wire.
287 Undecodable,
288 /// The request itself is malformed. Either the provider rejected it, or
289 /// the adapter refused it before anything was sent: options outside the
290 /// protocol's range, a body that is not an object, or a decoder used
291 /// against its contract.
292 InvalidRequest,
293 /// No observable outcome — e.g. a stream that ended without `Done`.
294 UnknownOutcome,
295}
296
297/// A model-invocation failure: a [`ModelInvokeErrorKind`] plus human-readable
298/// detail (provider text included where available).
299///
300/// `status` and `code` repeat, as data, what the message says in words, so a
301/// host can choose what to tell its user without parsing the message.
302///
303/// `retry_delay` carries a server-requested wait (an HTTP `retry-after` or
304/// `retry-after-ms` header) when the transport filled one. The kernel does
305/// not act on it; a caller-side retry policy decides whether to honor it.
306///
307/// `Display` prints the message alone; the kind is data, not prose.
308#[derive(Debug, Clone, thiserror::Error)]
309#[error("{message}")]
310#[non_exhaustive]
311pub struct ModelInvokeError {
312 /// The failure classification.
313 pub kind: ModelInvokeErrorKind,
314 /// Human-readable failure detail.
315 pub message: String,
316 /// The HTTP status of a non-success response. `None` when the failure
317 /// did not come from one: a transport fault, a local check, or an error
318 /// reported inside a successful response.
319 pub status: Option<u16>,
320 /// The provider's own error code or type, such as `rate_limit_error`.
321 /// `None` when the provider named none or the value was not a short
322 /// identifier.
323 pub code: Option<String>,
324 /// Server-requested delay before another attempt, when the provider sent
325 /// one. `None` when no usable delay was disclosed.
326 pub retry_delay: Option<Duration>,
327}
328impl ModelInvokeError {
329 /// Assembles an error from its kind and message, with no status, code or
330 /// retry delay.
331 pub fn new(kind: ModelInvokeErrorKind, message: impl Into<String>) -> Self {
332 Self {
333 kind,
334 message: message.into(),
335 status: None,
336 code: None,
337 retry_delay: None,
338 }
339 }
340 /// Records the HTTP status of the non-success response behind this error.
341 pub fn with_status(mut self, status: u16) -> Self {
342 self.status = Some(status);
343 self
344 }
345 /// Records the provider's error code or type. The caller passes only a
346 /// short identifier; the kernel stores it as given.
347 pub fn with_code(mut self, code: impl Into<String>) -> Self {
348 self.code = Some(code.into());
349 self
350 }
351 /// Sets the server-requested retry delay. A retry policy may wait this
352 /// long instead of using its own backoff.
353 pub fn with_retry_delay(mut self, delay: Duration) -> Self {
354 self.retry_delay = Some(delay);
355 self
356 }
357}
358
359/// Prompt-cache instruction carried on a [`ModelRequest`]. Adapters map this
360/// directive to protocol-specific cache mechanisms or treat it as a no-op where
361/// caching is automatic or unsupported.
362///
363/// Exhaustive on purpose: a renderer that marks cache anchors matches every
364/// directive, so a new one is a breaking change.
365///
366/// Serializable for logs and tests; the serialized form is not part of the
367/// stable set and may change in any release.
368#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "snake_case")]
370pub enum CacheDirective {
371 /// Mark no explicit cache breakpoints (the default).
372 #[default]
373 None,
374 /// Mark the stable-prefix anchors so provider caches cover the tool
375 /// surface, the system prefix, and the latest stable conversation
376 /// message.
377 StablePrefix,
378}
379
380/// Everything one logical invocation needs. All fields stay unchanged across
381/// internal retries; the gateway owns any attempt numbering and retry policy.
382#[derive(Debug, Clone)]
383#[non_exhaustive]
384pub struct ModelRequest {
385 /// Identifies the turn + round this logical invocation belongs to; the same id
386 /// recurs on every retry.
387 pub invocation_id: InvocationId,
388 /// The [`ContextFrame`] the gateway renders for the invocation.
389 pub frame: ContextFrame,
390 /// Which model to invoke.
391 pub model: ModelRef,
392 /// The [`GenerationOptions`] governing sampling.
393 pub generation: GenerationOptions,
394 /// The prompt-cache instruction the translation face renders. Invariant
395 /// across retries like the rest of the request.
396 pub cache: CacheDirective,
397}
398impl ModelRequest {
399 /// A request with default generation options and no cache directive. The
400 /// tools offered are the frame's [`crate::ToolChange`] blocks.
401 pub fn new(invocation_id: InvocationId, frame: ContextFrame, model: ModelRef) -> Self {
402 Self {
403 invocation_id,
404 frame,
405 model,
406 generation: GenerationOptions::default(),
407 cache: CacheDirective::None,
408 }
409 }
410}
411
412/// The model-invocation port: concrete gateways (provider adapters) live
413/// outside the kernel and translate [`ModelRequest`]s onto their transport,
414/// honoring the invocation's control plane.
415#[async_trait]
416pub trait ModelGateway: Send + Sync {
417 /// Runs one logical invocation, returning the
418 /// assembled [`ModelOutput`], or a classified [`ModelInvokeError`].
419 /// Cancellation and the deadline arrive through `control`.
420 async fn invoke(
421 &self,
422 request: &ModelRequest,
423 control: &CallControl,
424 ) -> Result<ModelOutput, ModelInvokeError>;
425
426 /// Streams one logical output. Once any delta has been yielded, transparent
427 /// retries are prohibited. The final Done alone supplies material for
428 /// submission. Default implementation: degenerates to a
429 /// single [`StreamDelta::Done`] after `invoke` — providers that never
430 /// implemented streaming keep working through the same port; streaming
431 /// providers override to expose real token increments.
432 async fn stream(
433 &self,
434 request: &ModelRequest,
435 control: &CallControl,
436 ) -> Result<ModelStream, ModelInvokeError> {
437 let output = self.invoke(request, control).await?;
438 Ok(completed_model_stream(output))
439 }
440}
441
442/// Bounded stream of provider deltas. Cancellation is observable through
443/// the same `CallControl` the `invoke` path uses — drivers race
444/// `next()` against the cancellation token, never poll.
445pub type ModelStream = std::pin::Pin<Box<dyn futures_core::Stream<Item = StreamDelta> + Send>>;
446
447struct OnceModelStream {
448 item: Option<ModelOutput>,
449}
450
451impl futures_core::Stream for OnceModelStream {
452 type Item = StreamDelta;
453
454 fn poll_next(
455 mut self: std::pin::Pin<&mut Self>,
456 _cx: &mut std::task::Context<'_>,
457 ) -> std::task::Poll<Option<Self::Item>> {
458 let delta = self
459 .item
460 .take()
461 .map(|final_output| StreamDelta::Done { final_output });
462 std::task::Poll::Ready(delta)
463 }
464}
465
466/// Wrap an already-complete output as a single-`Done` stream — the
467/// degenerate form the default `stream` implementation and tests use.
468pub fn completed_model_stream(output: ModelOutput) -> ModelStream {
469 Box::pin(OnceModelStream { item: Some(output) })
470}
471
472/// One incremental observation from a streaming provider.
473///
474/// Contract: `Done` MUST carry the fully-assembled [`ModelOutput`] (ordered
475/// items, tool-call drafts with stable ids, usage) — deltas are advisory
476/// observations for hosts, never the source of truth. A stream that ends
477/// without `Done` is an `UnknownOutcome`-shaped failure at the driver.
478#[derive(Debug, Clone)]
479#[non_exhaustive]
480pub enum StreamDelta {
481 /// An increment of assistant text.
482 TextDelta {
483 /// The new text fragment.
484 delta: String,
485 },
486 /// An increment of reasoning/thinking text.
487 ReasoningDelta {
488 /// The new reasoning fragment.
489 delta: String,
490 },
491 /// An increment of one streamed tool call, identified by its position
492 /// among the model's tool calls. A call seen here is an observation: the
493 /// calls to act on are the ones in `Done`, which leaves out a call the
494 /// response stopped in the middle of.
495 ToolCallDelta {
496 /// Position of this call among the model's tool-call drafts — how
497 /// deltas are matched to calls.
498 call_index: usize,
499 /// Provider-issued id retained verbatim when the gateway assembles
500 /// the complete tool declaration in `Done`.
501 provider_call_id: Option<String>,
502 /// Incremental fragment of the tool name, when the provider streams it.
503 name_delta: Option<String>,
504 /// Incremental fragment of the call's JSON arguments.
505 arguments_delta: Option<String>,
506 },
507 /// A mid-stream token-usage observation.
508 Usage(ModelUsage),
509 /// Terminal delta: generation ended. Carries the fully-assembled output —
510 /// the source of truth per this enum's contract, including its
511 /// [`ModelStopReason`].
512 Done {
513 /// The fully-assembled [`ModelOutput`] — the authoritative result.
514 final_output: ModelOutput,
515 },
516 /// In-stream failure observation carrying the gateway's own
517 /// [`ModelInvokeError`], so an error before any delta keeps its
518 /// classification and any server-requested retry delay.
519 Error {
520 /// The failure the gateway produced.
521 error: ModelInvokeError,
522 },
523}