causa_kernel/context/block.rs
1//! Block facts -- the kernel-side vocabulary of a conversation.
2//!
3//! A ContextBlock is a typed fact with three orthogonal axes:
4//! identity (id), content (BlockContent), and envelope
5//! provenance (BlockMeta). Who produced a message (system, user or
6//! assistant) is a kernel fact recorded on message content as a [`Role`];
7//! `BlockMeta::source` is provenance only and does not affect rendering.
8//!
9//! Content vocabulary is **Message**: one
10//! logical message's mixed content commits as one block of ordered
11//! [`ContentPart`]s with its [`Role`] — the block is the fact atom (identity and envelope),
12//! and the part is the content
13//! atom (ordered, identity-free, shares the envelope). Media enters as
14//! a [`MediaRef`] — a cheap durable reference; bytes never enter facts,
15//! they appear only in resolved render payloads (provider side).
16//! Model-issued wire items the framework cannot read travel as
17//! [`SealedPart`]s, and the wire fields of a readable item ride in
18//! [`BlockMeta::wire`].
19
20use serde::{Deserialize, Serialize};
21
22use crate::context::ids::BlockId;
23use crate::context::tool_data::ToolResultPayload;
24use crate::context::tools::ToolChange;
25
26/// The speaker of a conversation message.
27///
28/// Exhaustive on purpose: a renderer must be total over the role vocabulary, so
29/// a new variant is a breaking change that should stop downstream code from
30/// compiling.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum Role {
34 /// Instructions or background context provided to the model.
35 System,
36 /// Input from the human user or external caller.
37 User,
38 /// Output produced by the model.
39 Assistant,
40}
41
42/// Envelope provenance. Fields are serde-additive so older records
43/// without them still deserialize.
44#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
45#[non_exhaustive]
46pub struct BlockMeta {
47 /// Provider-issued identifier (e.g. upstream call id).
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub provider_call_id: Option<String>,
50
51 /// Origin tag (e.g. "user", "provider:gpt-4o", "host"). Optional provenance
52 /// only: no renderer, validator, or runtime reads it and it does not affect
53 /// rendering.
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub source: Option<String>,
56
57 /// What the provider's item carried beyond the facts in this block.
58 /// Written by the model door, read only by the protocol renderer whose
59 /// format matches; the kernel never interprets it.
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub wire: Option<WireMeta>,
62}
63impl BlockMeta {
64 /// Metadata naming only where the block came from, such as `"user"`.
65 /// Provenance only: no renderer, validator, or runtime reads it and it does
66 /// not affect rendering.
67 pub fn from_source(source: impl Into<String>) -> Self {
68 Self {
69 source: Some(source.into()),
70 ..Self::default()
71 }
72 }
73
74 /// Sets the provider-issued call identifier.
75 pub fn with_provider_call_id(mut self, provider_call_id: impl Into<String>) -> Self {
76 self.provider_call_id = Some(provider_call_id.into());
77 self
78 }
79
80 /// Sets the origin tag. Provenance only: no renderer, validator, or runtime
81 /// reads it and it does not affect rendering.
82 pub fn with_source(mut self, source: impl Into<String>) -> Self {
83 self.source = Some(source.into());
84 self
85 }
86
87 /// Sets the wire-level residue of the item.
88 pub fn with_wire(mut self, wire: WireMeta) -> Self {
89 self.wire = Some(wire);
90 self
91 }
92}
93
94/// Wire-level residue of one provider item: every field the translator did
95/// not turn into block content, kept uninterpreted so a renderer of the same
96/// format can send the item back as returned.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98#[non_exhaustive]
99pub struct WireMeta {
100 /// Wire format the fields belong to (the protocol's stable name, for
101 /// example `openai_responses`).
102 pub format: String,
103 /// The item as returned, minus the fields the block's content holds.
104 pub fields: serde_json::Value,
105}
106impl WireMeta {
107 /// Wire residue in the named format.
108 pub fn new(format: impl Into<String>, fields: serde_json::Value) -> Self {
109 Self {
110 format: format.into(),
111 fields,
112 }
113 }
114}
115
116/// A single string of text. Serializes transparently as the inner string.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(transparent)]
119pub struct TextPayload(pub String);
120impl TextPayload {
121 /// Wrap any string-like value as a text payload.
122 pub fn new(s: impl Into<String>) -> Self {
123 Self(s.into())
124 }
125}
126
127/// A model-issued tool call. Its containing block ID is the declaration
128/// identity; provider-issued identifiers ride on BlockMeta::provider_call_id.
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[non_exhaustive]
131pub struct ToolCallPayload {
132 /// Name of the invoked tool — the key the executor dispatches on.
133 pub tool_name: String,
134 /// The call's arguments as a JSON value.
135 pub arguments: serde_json::Value,
136}
137impl ToolCallPayload {
138 /// A declaration of one call.
139 pub fn new(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
140 Self {
141 tool_name: tool_name.into(),
142 arguments,
143 }
144 }
145}
146
147/// A typed fact. Three axes: identity, content, envelope provenance.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149pub struct ContextBlock {
150 /// Identity axis: the UUID assigned to this fact block.
151 id: BlockId,
152 /// Content axis: the typed fact payload.
153 content: BlockContent,
154 /// Envelope provenance axis; serde-additive, defaulting when absent.
155 meta: BlockMeta,
156}
157
158impl ContextBlock {
159 /// Creates a context fact with an explicit identity, content, and metadata.
160 ///
161 /// Callers that change a block's content or metadata must supply a new
162 /// identity. Construction does not validate identity reuse against any
163 /// other block or context.
164 pub fn new(id: BlockId, content: BlockContent, meta: BlockMeta) -> Self {
165 Self { id, content, meta }
166 }
167
168 /// Constructs a text message block with the given identity, role, and text content,
169 /// using default metadata.
170 pub fn text(id: BlockId, role: Role, text: impl Into<String>) -> Self {
171 Self::new(id, BlockContent::text(role, text), BlockMeta::default())
172 }
173
174 /// Returns this block's stable identity.
175 pub const fn id(&self) -> BlockId {
176 self.id
177 }
178
179 /// Returns this block's content by shared reference.
180 pub const fn content(&self) -> &BlockContent {
181 &self.content
182 }
183
184 /// Returns this block's metadata by shared reference.
185 pub const fn meta(&self) -> &BlockMeta {
186 &self.meta
187 }
188}
189
190/// A media fact: a cheap, durable reference. Bytes never enter facts —
191/// they appear only in resolved render payloads (provider side).
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[non_exhaustive]
194pub struct MediaRef {
195 /// IANA media type. What renders to the wire depends on the media kind
196 /// and each protocol's rendering capabilities; any unsupported kind or
197 /// type degrades to a deterministic text placeholder.
198 pub media_type: String,
199 /// Host-side asset reference (workspace asset id / content-addressed
200 /// hash). The kernel never interprets it; the host's resolver does.
201 pub reference: String,
202 /// The model-visible file name; images do not use it; when `None` the
203 /// serialized form is the same as a [`MediaRef`] without the field.
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub name: Option<String>,
206}
207
208impl MediaRef {
209 /// Wraps a media type and a host-side asset reference.
210 pub fn new(media_type: impl Into<String>, reference: impl Into<String>) -> Self {
211 Self {
212 media_type: media_type.into(),
213 reference: reference.into(),
214 name: None,
215 }
216 }
217
218 /// Sets the model-visible file name.
219 pub fn with_name(mut self, name: impl Into<String>) -> Self {
220 self.name = Some(name.into());
221 self
222 }
223}
224
225/// The content shape of a block. Four shapes: one message's ordered
226/// parts (any role), a tool call, a tool result, a change to the offered
227/// tools.
228///
229/// Exhaustive on purpose: a renderer must handle every shape, so a new one is
230/// a breaking change that should stop downstream code from compiling.
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
232#[serde(tag = "shape", content = "value", rename_all = "snake_case")]
233pub enum BlockContent {
234 /// One logical message's ordered content parts (text, media
235 /// references, or sealed wire items) and the role that produced them —
236 /// atomic at the block: one identity, one content identity; execution
237 /// pairing is enforced by specialized append operations rather than by
238 /// importing arbitrary facts.
239 Message {
240 /// Speaker role for this message.
241 role: Role,
242 /// Ordered content parts.
243 parts: Vec<ContentPart>,
244 },
245 /// A model-issued tool invocation.
246 ToolCall(ToolCallPayload),
247 /// The recorded outcome of a prior call, paired by
248 /// `ToolResultPayload::call_block_id`.
249 ToolResult(ToolResultPayload),
250 /// The tools offered to the model change from this position on. The
251 /// first one in a context declares the initial set.
252 ToolChange(ToolChange),
253}
254
255impl BlockContent {
256 /// Constructs a [`BlockContent::Message`] containing a single [`ContentPart::Text`].
257 pub fn text(role: Role, text: impl Into<String>) -> Self {
258 Self::Message {
259 role,
260 parts: vec![ContentPart::Text(TextPayload::new(text))],
261 }
262 }
263}
264
265/// One content atom inside a [`BlockContent::Message`] block: ordered,
266/// identity-free, sharing the block's envelope. The axis for media modalities
267/// is [`MediaRef::media_type`], decided by the host's resolver and each
268/// protocol's rendering capabilities; new [`ContentPart`] variants are only
269/// for content that is not a run of bytes. Media bytes stay out of facts
270/// forever.
271///
272/// Exhaustive on purpose, like [`BlockContent`]. A new part is additive only
273/// in the serde sense: stored material written before it still reads. In Rust
274/// it is a breaking change, because a wildcard arm in a renderer would drop
275/// the new part without a trace.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277#[serde(tag = "part", content = "value", rename_all = "snake_case")]
278pub enum ContentPart {
279 /// Plain text; provider role assignment stays the renderer's job.
280 Text(TextPayload),
281 /// A media reference; bytes never enter facts.
282 Media(MediaRef),
283 /// A model-issued wire item the kernel carries and never interprets.
284 Sealed(SealedPart),
285}
286
287/// A model-issued wire item carried as content the kernel cannot read.
288///
289/// Only a renderer of the matching `format` writes it back; every other
290/// renderer skips it.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[non_exhaustive]
293pub struct SealedPart {
294 /// Wire format of `item`; interpreted only by the matching renderer.
295 pub format: String,
296 /// The item exactly as the provider returned it.
297 pub item: serde_json::Value,
298}
299impl SealedPart {
300 /// A sealed item in the named wire format.
301 pub fn new(format: impl Into<String>, item: serde_json::Value) -> Self {
302 Self {
303 format: format.into(),
304 item,
305 }
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use serde_json::json;
313
314 #[test]
315 fn named_media_ref_round_trips_through_serde() {
316 let media = MediaRef::new("application/pdf", "asset://doc").with_name("memo.pdf");
317 let serialized = serde_json::to_value(&media).expect("serialization succeeds");
318 assert_eq!(
319 serialized,
320 json!({
321 "media_type": "application/pdf",
322 "reference": "asset://doc",
323 "name": "memo.pdf",
324 })
325 );
326 let deserialized: MediaRef =
327 serde_json::from_value(serialized).expect("deserialization succeeds");
328 assert_eq!(deserialized, media);
329 assert_eq!(deserialized.name.as_deref(), Some("memo.pdf"));
330 }
331
332 #[test]
333 fn unnamed_media_ref_serializes_with_no_name_key() {
334 let media = MediaRef::new("image/png", "asset://img");
335 let serialized = serde_json::to_value(&media).expect("serialization succeeds");
336 assert_eq!(
337 serialized,
338 json!({
339 "media_type": "image/png",
340 "reference": "asset://img",
341 })
342 );
343 assert!(!serialized.as_object().unwrap().contains_key("name"));
344 let deserialized: MediaRef =
345 serde_json::from_value(serialized).expect("deserialization succeeds");
346 assert_eq!(deserialized, media);
347 assert_eq!(deserialized.name, None);
348 }
349}