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). Provider-specific role assignment (system /
6//! user / assistant / tool) is the renderer's job, not the kernel's.
7//!
8//! Content vocabulary is **Parts**: one
9//! logical message's mixed content commits as one block of ordered
10//! [`ContentPart`]s — the block is the fact atom (identity and envelope),
11//! and the part is the content
12//! atom (ordered, identity-free, shares the envelope). Media enters as
13//! a [`MediaRef`] — a cheap durable reference; bytes never enter facts,
14//! they appear only in resolved render payloads (provider side).
15//! Model-issued wire items the framework cannot read travel as
16//! [`SealedPart`]s, and the wire fields of a readable item ride in
17//! [`BlockMeta::wire`].
18
19use serde::{Deserialize, Serialize};
20
21use crate::context::ids::BlockId;
22use crate::context::tool_data::ToolResultPayload;
23
24/// Envelope provenance. Fields are serde-additive so older records
25/// without them still deserialize.
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
27#[non_exhaustive]
28pub struct BlockMeta {
29 /// Provider-issued identifier (e.g. upstream call id).
30 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub provider_call_id: Option<String>,
32
33 /// Origin tag (e.g. "user", "provider:gpt-4o", "host"). Optional.
34 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub source: Option<String>,
36
37 /// What the provider's item carried beyond the facts in this block.
38 /// Written by the model door, read only by the protocol renderer whose
39 /// format matches; the kernel never interprets it.
40 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub wire: Option<WireMeta>,
42}
43impl BlockMeta {
44 /// Metadata naming only where the block came from, such as `"user"`.
45 pub fn from_source(source: impl Into<String>) -> Self {
46 Self {
47 source: Some(source.into()),
48 ..Self::default()
49 }
50 }
51
52 /// Sets the provider-issued call identifier.
53 pub fn with_provider_call_id(mut self, provider_call_id: impl Into<String>) -> Self {
54 self.provider_call_id = Some(provider_call_id.into());
55 self
56 }
57
58 /// Sets the origin tag.
59 pub fn with_source(mut self, source: impl Into<String>) -> Self {
60 self.source = Some(source.into());
61 self
62 }
63
64 /// Sets the wire-level residue of the item.
65 pub fn with_wire(mut self, wire: WireMeta) -> Self {
66 self.wire = Some(wire);
67 self
68 }
69}
70
71/// Wire-level residue of one provider item: every field the translator did
72/// not turn into block content, kept uninterpreted so a renderer of the same
73/// format can send the item back as returned.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[non_exhaustive]
76pub struct WireMeta {
77 /// Wire format the fields belong to (the protocol's stable name, for
78 /// example `openai_responses`).
79 pub format: String,
80 /// The item as returned, minus the fields the block's content holds.
81 pub fields: serde_json::Value,
82}
83impl WireMeta {
84 /// Wire residue in the named format.
85 pub fn new(format: impl Into<String>, fields: serde_json::Value) -> Self {
86 Self {
87 format: format.into(),
88 fields,
89 }
90 }
91}
92
93/// A single string of text. Serializes transparently as the inner string.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(transparent)]
96pub struct TextPayload(pub String);
97impl TextPayload {
98 /// Wrap any string-like value as a text payload.
99 pub fn new(s: impl Into<String>) -> Self {
100 Self(s.into())
101 }
102}
103
104/// A model-issued tool call. Its containing block ID is the declaration
105/// identity; provider-issued identifiers ride on BlockMeta::provider_call_id.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct ToolCallPayload {
109 /// Name of the invoked tool — the key the executor dispatches on.
110 pub tool_name: String,
111 /// The call's arguments as a JSON value.
112 pub arguments: serde_json::Value,
113}
114impl ToolCallPayload {
115 /// A declaration of one call.
116 pub fn new(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
117 Self {
118 tool_name: tool_name.into(),
119 arguments,
120 }
121 }
122}
123
124/// A typed fact. Three axes: identity, content, envelope provenance.
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub struct ContextBlock {
127 /// Identity axis: the UUID assigned to this fact block.
128 id: BlockId,
129 /// Content axis: the typed fact payload.
130 content: BlockContent,
131 /// Envelope provenance axis; serde-additive, defaulting when absent.
132 meta: BlockMeta,
133}
134
135impl ContextBlock {
136 /// Creates a context fact with an explicit identity, content, and metadata.
137 ///
138 /// Callers that change a block's content or metadata must supply a new
139 /// identity. Construction does not validate identity reuse against any
140 /// other block or context.
141 pub fn new(id: BlockId, content: BlockContent, meta: BlockMeta) -> Self {
142 Self { id, content, meta }
143 }
144
145 /// Returns this block's stable identity.
146 pub const fn id(&self) -> BlockId {
147 self.id
148 }
149
150 /// Returns this block's content by shared reference.
151 pub const fn content(&self) -> &BlockContent {
152 &self.content
153 }
154
155 /// Returns this block's metadata by shared reference.
156 pub const fn meta(&self) -> &BlockMeta {
157 &self.meta
158 }
159}
160
161/// A media fact: a cheap, durable reference. Bytes never enter facts —
162/// they appear only in resolved render payloads (provider side).
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[non_exhaustive]
165pub struct MediaRef {
166 /// IANA media type; only `image/*` renders to the wire, anything else
167 /// degrades to a deterministic text placeholder.
168 pub media_type: String,
169 /// Host-side asset reference (workspace asset id / content-addressed
170 /// hash). The kernel never interprets it; the host's resolver does.
171 pub reference: String,
172}
173
174impl MediaRef {
175 /// Wraps a media type and a host-side asset reference.
176 pub fn new(media_type: impl Into<String>, reference: impl Into<String>) -> Self {
177 Self {
178 media_type: media_type.into(),
179 reference: reference.into(),
180 }
181 }
182}
183
184/// The content shape of a block. Three shapes: one message's ordered
185/// parts (any role), a tool call, a tool result.
186///
187/// Exhaustive on purpose: a renderer must handle every shape, so a new one is
188/// a breaking change that should stop downstream code from compiling.
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190#[serde(tag = "shape", content = "value", rename_all = "snake_case")]
191pub enum BlockContent {
192 /// One logical message's ordered content parts (text and media
193 /// references) — atomic at the block: identity, one
194 /// content identity; execution pairing is enforced by specialized append
195 /// operations rather than by importing arbitrary facts.
196 Parts(Vec<ContentPart>),
197 /// A model-issued tool invocation.
198 ToolCall(ToolCallPayload),
199 /// The recorded outcome of a prior call, paired by
200 /// `ToolResultPayload::call_block_id`.
201 ToolResult(ToolResultPayload),
202}
203
204/// One content atom inside a [`BlockContent::Parts`] block: ordered,
205/// identity-free, sharing the block's envelope. New modalities arrive
206/// as new variants (additive); media bytes stay out of facts forever.
207///
208/// Exhaustive on purpose, like [`BlockContent`]. A new part is additive only
209/// in the serde sense: stored material written before it still reads. In Rust
210/// it is a breaking change, because a wildcard arm in a renderer would drop
211/// the new part without a trace.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213#[serde(tag = "part", content = "value", rename_all = "snake_case")]
214pub enum ContentPart {
215 /// Plain text; provider role assignment stays the renderer's job.
216 Text(TextPayload),
217 /// A media reference; bytes never enter facts.
218 Media(MediaRef),
219 /// A model-issued wire item the kernel carries and never interprets.
220 Sealed(SealedPart),
221}
222
223/// A model-issued wire item carried as content the kernel cannot read.
224///
225/// Only a renderer of the matching `format` writes it back; every other
226/// renderer skips it.
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228#[non_exhaustive]
229pub struct SealedPart {
230 /// Wire format of `item`; interpreted only by the matching renderer.
231 pub format: String,
232 /// The item exactly as the provider returned it.
233 pub item: serde_json::Value,
234}
235impl SealedPart {
236 /// A sealed item in the named wire format.
237 pub fn new(format: impl Into<String>, item: serde_json::Value) -> Self {
238 Self {
239 format: format.into(),
240 item,
241 }
242 }
243}