causa_kernel/context/model/value.rs
1//! Fact vocabulary of the model door — what the fact machine validates and
2//! records. The gateway envelope (`ModelOutput`), the transport error, and
3//! request parameters (`ModelRef`, `GenerationOptions`, `ToolSurface`) are
4//! port vocabulary and live in `crate::ports::gateway`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::context::block::{ContentPart, TextPayload, WireMeta};
9
10/// A tool call as the model proposed it, before the caller assigns its declaration `BlockId`. Exactly what the gateway parsed off the wire.
11///
12/// Serializable for logs and tests; the serialized form is not part of the
13/// stable set and may change in any release.
14#[derive(Debug, Clone, Default, Serialize, Deserialize)]
15#[non_exhaustive]
16pub struct ToolCallDraft {
17 /// Name of the tool the model asked to invoke.
18 pub tool_name: String,
19 /// Tool arguments as a JSON object; validated by the kernel before commit.
20 pub arguments: serde_json::Value,
21 /// Provider-issued identifier for this tool call, if the upstream model
22 /// API assigned one. The kernel records it verbatim (on the envelope
23 /// `BlockMeta`) and pairs tool results by the declaration `BlockId`, never by this field.
24 /// `ToolCallId` remains a borrowed content key for concurrent deduplication.
25 #[serde(default)]
26 pub provider_call_id: Option<String>,
27}
28impl ToolCallDraft {
29 /// A draft call with no provider call id.
30 pub fn new(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
31 Self {
32 tool_name: tool_name.into(),
33 arguments,
34 provider_call_id: None,
35 }
36 }
37
38 /// Sets the provider-issued identifier for this tool call.
39 pub fn with_provider_call_id(mut self, provider_call_id: impl Into<String>) -> Self {
40 self.provider_call_id = Some(provider_call_id.into());
41 self
42 }
43}
44
45/// Why the model stopped producing output for this round, as reported by
46/// the gateway. The kernel validates only the EndTurn/ToolUse structural
47/// pairing; interpreting terminal reasons is driver policy.
48///
49/// Exhaustive on purpose: the runtime decides what a turn does next from this value, so a new one is a breaking change.
50///
51/// Serializable for logs and tests; the serialized form is not part of the
52/// stable set and may change in any release.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub enum ModelStopReason {
56 /// The model ended its turn without requesting tools; `tool_calls` must
57 /// be empty.
58 EndTurn,
59 /// The model requested tool invocations; `tool_calls` must be non-empty.
60 ToolUse,
61 /// Output was cut off at the token limit.
62 MaxTokens,
63 /// The model (or a provider content filter) refused to produce output.
64 Refusal,
65 /// The provider stopped because the context window was exhausted. The
66 /// output was not committed; the runner reports it as an interruption.
67 ContextWindowExceeded,
68 /// The provider reported a stop value this kernel has no meaning for. The
69 /// output was not committed and the wire value is preserved on
70 /// `ModelOutput::raw_stop_reason`.
71 Unrecognized,
72}
73
74/// The model door's fact shape: what the model produced, as an ordered list
75/// of items. One item becomes one block on commit, in item order. Named for
76/// the participant, not for any wire role.
77///
78/// Serializable for logs and tests; the serialized form is not part of the
79/// stable set and may change in any release.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct ModelResponse {
82 /// What the model said and asked, in the order the provider returned it.
83 pub items: Vec<ModelItem>,
84}
85
86impl ModelResponse {
87 /// The tool calls the model asked for, in item order; ids are assigned
88 /// at commit.
89 pub fn tool_calls(&self) -> impl Iterator<Item = &ToolCallDraft> {
90 self.items.iter().filter_map(|item| match &item.content {
91 ModelItemContent::ToolCall(call) => Some(call),
92 ModelItemContent::Parts(_) => None,
93 })
94 }
95
96 /// Every text part of every readable item, concatenated in order with no
97 /// separator. Media and sealed parts contribute nothing.
98 pub fn text(&self) -> String {
99 let mut text = String::new();
100 for item in &self.items {
101 if let ModelItemContent::Parts(parts) = &item.content {
102 for part in parts {
103 if let ContentPart::Text(t) = part {
104 text.push_str(&t.0);
105 }
106 }
107 }
108 }
109 text
110 }
111}
112
113/// One item the model produced: its content plus the wire fields that
114/// content does not hold.
115///
116/// Serializable for logs and tests; the serialized form is not part of the
117/// stable set and may change in any release.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[non_exhaustive]
120pub struct ModelItem {
121 /// What the item says or asks.
122 pub content: ModelItemContent,
123 /// What the provider's item carried beyond `content`; copied to
124 /// [`BlockMeta::wire`](crate::BlockMeta::wire) on commit. The kernel
125 /// never reads it.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub wire: Option<WireMeta>,
128}
129impl ModelItem {
130 /// An item with no wire residue.
131 pub fn new(content: ModelItemContent) -> Self {
132 Self {
133 content,
134 wire: None,
135 }
136 }
137}
138
139impl ModelItem {
140 /// An item of one text part and no wire fields.
141 pub fn text(text: impl Into<String>) -> Self {
142 Self {
143 content: ModelItemContent::Parts(vec![ContentPart::Text(TextPayload::new(text))]),
144 wire: None,
145 }
146 }
147
148 /// A tool-call item with no wire fields.
149 pub fn tool_call(call: ToolCallDraft) -> Self {
150 Self {
151 content: ModelItemContent::ToolCall(call),
152 wire: None,
153 }
154 }
155}
156
157/// The content of a [`ModelItem`].
158///
159/// Exhaustive on purpose: conversion to blocks handles every shape, so a new one is a breaking change.
160///
161/// Serializable for logs and tests; the serialized form is not part of the
162/// stable set and may change in any release.
163#[derive(Debug, Clone, Serialize, Deserialize)]
164#[serde(rename_all = "snake_case")]
165pub enum ModelItemContent {
166 /// Ordered content parts (text and sealed items) that commit as one
167 /// `Parts` block.
168 Parts(Vec<ContentPart>),
169 /// A tool call that commits as one `ToolCall` block.
170 ToolCall(ToolCallDraft),
171}