Skip to main content

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; only `image/*` renders to the wire, anything else
196    /// degrades to a deterministic text placeholder.
197    pub media_type: String,
198    /// Host-side asset reference (workspace asset id / content-addressed
199    /// hash). The kernel never interprets it; the host's resolver does.
200    pub reference: String,
201}
202
203impl MediaRef {
204    /// Wraps a media type and a host-side asset reference.
205    pub fn new(media_type: impl Into<String>, reference: impl Into<String>) -> Self {
206        Self {
207            media_type: media_type.into(),
208            reference: reference.into(),
209        }
210    }
211}
212
213/// The content shape of a block. Four shapes: one message's ordered
214/// parts (any role), a tool call, a tool result, a change to the offered
215/// tools.
216///
217/// Exhaustive on purpose: a renderer must handle every shape, so a new one is
218/// a breaking change that should stop downstream code from compiling.
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
220#[serde(tag = "shape", content = "value", rename_all = "snake_case")]
221pub enum BlockContent {
222    /// One logical message's ordered content parts (text, media
223    /// references, or sealed wire items) and the role that produced them —
224    /// atomic at the block: one identity, one content identity; execution
225    /// pairing is enforced by specialized append operations rather than by
226    /// importing arbitrary facts.
227    Message {
228        /// Speaker role for this message.
229        role: Role,
230        /// Ordered content parts.
231        parts: Vec<ContentPart>,
232    },
233    /// A model-issued tool invocation.
234    ToolCall(ToolCallPayload),
235    /// The recorded outcome of a prior call, paired by
236    /// `ToolResultPayload::call_block_id`.
237    ToolResult(ToolResultPayload),
238    /// The tools offered to the model change from this position on. The
239    /// first one in a context declares the initial set.
240    ToolChange(ToolChange),
241}
242
243impl BlockContent {
244    /// Constructs a [`BlockContent::Message`] containing a single [`ContentPart::Text`].
245    pub fn text(role: Role, text: impl Into<String>) -> Self {
246        Self::Message {
247            role,
248            parts: vec![ContentPart::Text(TextPayload::new(text))],
249        }
250    }
251}
252
253/// One content atom inside a [`BlockContent::Message`] block: ordered,
254/// identity-free, sharing the block's envelope. New modalities arrive
255/// as new variants (additive); media bytes stay out of facts forever.
256///
257/// Exhaustive on purpose, like [`BlockContent`]. A new part is additive only
258/// in the serde sense: stored material written before it still reads. In Rust
259/// it is a breaking change, because a wildcard arm in a renderer would drop
260/// the new part without a trace.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(tag = "part", content = "value", rename_all = "snake_case")]
263pub enum ContentPart {
264    /// Plain text; provider role assignment stays the renderer's job.
265    Text(TextPayload),
266    /// A media reference; bytes never enter facts.
267    Media(MediaRef),
268    /// A model-issued wire item the kernel carries and never interprets.
269    Sealed(SealedPart),
270}
271
272/// A model-issued wire item carried as content the kernel cannot read.
273///
274/// Only a renderer of the matching `format` writes it back; every other
275/// renderer skips it.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277#[non_exhaustive]
278pub struct SealedPart {
279    /// Wire format of `item`; interpreted only by the matching renderer.
280    pub format: String,
281    /// The item exactly as the provider returned it.
282    pub item: serde_json::Value,
283}
284impl SealedPart {
285    /// A sealed item in the named wire format.
286    pub fn new(format: impl Into<String>, item: serde_json::Value) -> Self {
287        Self {
288            format: format.into(),
289            item,
290        }
291    }
292}