causa_kernel/context/tool_data.rs
1//! Tool-domain fact vocabulary — call ids, results, outputs, artifacts.
2//!
3//! This module holds only recorded facts: what the tool door persists.
4//! Specialized append operations validate call/result pairing. Behavior and execution vocabulary
5//! (the `Tool` trait, the `ArtifactStore` port, definitions and dispatch
6//! context) live in `crate::ports::tool`. Execution policies belong to the
7//! runtime; this module does not depend on them.
8
9use crate::context::ids::BlockId;
10use serde::{Deserialize, Serialize};
11
12/// Borrowed content key for comparing tool calls within a caller-selected
13/// scope. Instance pairing always uses the declaration's [`BlockId`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub struct ToolCallId<'a> {
16 /// Tool name included in the complete content key.
17 pub tool_name: &'a str,
18 /// Arguments included with their `serde_json::Value` equality semantics.
19 pub arguments: &'a serde_json::Value,
20}
21impl<'a> ToolCallId<'a> {
22 /// Borrows the content key from a tool declaration.
23 pub const fn new(tool_name: &'a str, arguments: &'a serde_json::Value) -> Self {
24 Self {
25 tool_name,
26 arguments,
27 }
28 }
29}
30
31/// Terminal status of one tool invocation, recorded verbatim as a fact;
32/// mapping from execution errors is the driver's job, not the kernel's.
33///
34/// Exhaustive on purpose: renderers and the runtime decide by status, so a new one is a breaking change.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum ToolResultStatus {
38 /// The tool returned an outcome.
39 Succeeded,
40 /// The tool ran but reported failure (including panic isolation).
41 Failed,
42 /// The call never ran — unknown tool, denied by a processor, or otherwise
43 /// refused before execution.
44 Rejected,
45 /// The invocation was cancelled before producing an outcome.
46 Cancelled,
47 /// The invocation exceeded its time budget before producing an outcome.
48 TimedOut,
49 /// No outcome was observed (e.g. the call-deadline backstop fired);
50 /// whether the turn continues is the harness's unknown-outcome
51 /// configuration, not tool vocabulary.
52 UnknownOutcome,
53}
54
55/// Optional observability sidecar on a tool output; never part of pairing.
56#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
57#[non_exhaustive]
58pub struct ToolOutputMeta {
59 /// Wall-clock duration of the execution, if measured.
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub duration_ms: Option<u64>,
62 /// Estimated token count of the output body before truncation, when known.
63 /// This does not include result notes or media.
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub original_tokens: Option<usize>,
66 /// Free-form JSON for tool- or driver-specific annotations.
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub extra: Option<serde_json::Value>,
69}
70
71/// Whether tool output content was shortened to fit the token limit.
72///
73/// Exhaustive on purpose: content was shortened or it was not.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum Truncation {
77 /// The content is the tool's full output.
78 None,
79 /// The content was replaced by head + notice + tail; the full output
80 /// spilled to an artifact when a store was available.
81 Middle,
82}
83
84/// What a tool returned, as recorded by the tool door.
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86#[non_exhaustive]
87pub struct ToolOutput {
88 /// The observation payload; after middle truncation this is a JSON
89 /// string (head + notice + tail) regardless of the original shape.
90 pub content: serde_json::Value,
91 /// Whether and how the content was shortened.
92 pub truncation: Truncation,
93 /// Optional observability metadata.
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub meta: Option<ToolOutputMeta>,
96 /// Reference to the full output in an artifact store, if spilled.
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub artifact: Option<ArtifactRef>,
99}
100impl ToolOutput {
101 /// Creates an output with no truncation, metadata, or artifact.
102 pub fn new(content: serde_json::Value) -> Self {
103 Self {
104 content,
105 truncation: Truncation::None,
106 meta: None,
107 artifact: None,
108 }
109 }
110 /// Returns whether the content was shortened (any marker other than
111 /// [`Truncation::None`]).
112 pub fn is_truncated(&self) -> bool {
113 !matches!(self.truncation, Truncation::None)
114 }
115}
116
117/// The result fact for one tool call: its declaration identity, terminal
118/// status, output, media, and ordered notes. Pairing is kernel-enforced.
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct ToolResultPayload {
122 /// The declaration block this result answers.
123 pub call_block_id: BlockId,
124 /// Terminal status of the invocation.
125 pub status: ToolResultStatus,
126 /// The tool's output, possibly truncated with an artifact spill.
127 pub output: ToolOutput,
128 /// Media artifacts attached to this result — references only; the
129 /// bytes live in the host's asset store, resolved provider-side at
130 /// render time. Serde-additive: absent media defaults to empty.
131 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub media: Vec<crate::context::block::MediaRef>,
133 /// Ordered result notes. `ToolBatch::resolve_at` places any pre-execution
134 /// context notes before notes returned by the tool; tool implementations
135 /// should return only notes they add.
136 #[serde(default, skip_serializing_if = "Vec::is_empty")]
137 pub notes: Vec<crate::context::block::TextPayload>,
138}
139impl ToolResultPayload {
140 /// A result for one declaration, with no media and no notes.
141 pub fn new(call_block_id: BlockId, status: ToolResultStatus, output: ToolOutput) -> Self {
142 Self {
143 call_block_id,
144 status,
145 output,
146 media: Vec::new(),
147 notes: Vec::new(),
148 }
149 }
150
151 /// Replaces the media artifacts attached to this result.
152 pub fn with_media(mut self, media: Vec<crate::context::block::MediaRef>) -> Self {
153 self.media = media;
154 self
155 }
156
157 /// Replaces the ordered result notes.
158 pub fn with_notes(mut self, notes: Vec<crate::context::block::TextPayload>) -> Self {
159 self.notes = notes;
160 self
161 }
162}
163
164/// Pointer to a tool output persisted out-of-band (e.g. a spilled oversized
165/// observation), kept on the result instead of the full content.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167#[non_exhaustive]
168pub struct ArtifactRef {
169 /// Store-assigned handle for retrieving the artifact.
170 pub id: String,
171 /// Serialized size of the artifact in bytes.
172 pub size_bytes: usize,
173 /// What the artifact holds.
174 pub kind: ArtifactKind,
175 /// Whether the artifact is durably persisted in a store.
176 pub persisted: bool,
177}
178impl ArtifactRef {
179 /// A reference to one stored artifact.
180 pub fn new(
181 id: impl Into<String>,
182 size_bytes: usize,
183 kind: ArtifactKind,
184 persisted: bool,
185 ) -> Self {
186 Self {
187 id: id.into(),
188 size_bytes,
189 kind,
190 persisted,
191 }
192 }
193}
194
195/// What an artifact holds. A label for the host; nothing in the library
196/// decides by it, so further kinds may be added.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199#[non_exhaustive]
200pub enum ArtifactKind {
201 /// The complete, untruncated tool output.
202 FullOutput,
203 /// Cached intermediate output (e.g. streamed pipe data).
204 PipeCache,
205 /// Raw binary payload.
206 Binary,
207}