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 pub duration_ms: Option<u64>,
61 /// Estimated token count of the output body before truncation, when known.
62 /// This does not include result notes or media.
63 pub original_tokens: Option<usize>,
64 /// Free-form JSON for tool- or driver-specific annotations.
65 pub extra: Option<serde_json::Value>,
66}
67
68/// Whether tool output content was shortened to fit the token limit.
69///
70/// Exhaustive on purpose: content was shortened or it was not.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(rename_all = "snake_case")]
73pub enum Truncation {
74 /// The content is the tool's full output.
75 None,
76 /// The content was replaced by head + notice + tail; the full output
77 /// spilled to an artifact when a store was available.
78 Middle,
79}
80
81/// What a tool returned, as recorded by the tool door.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83#[non_exhaustive]
84pub struct ToolOutput {
85 /// The observation payload; after middle truncation this is a JSON
86 /// string (head + notice + tail) regardless of the original shape.
87 pub content: serde_json::Value,
88 /// Whether and how the content was shortened.
89 pub truncation: Truncation,
90 /// Optional observability metadata.
91 pub meta: Option<ToolOutputMeta>,
92 /// Reference to the full output in an artifact store, if spilled.
93 pub artifact: Option<ArtifactRef>,
94}
95impl ToolOutput {
96 /// Creates an output with no truncation, metadata, or artifact.
97 pub fn new(content: serde_json::Value) -> Self {
98 Self {
99 content,
100 truncation: Truncation::None,
101 meta: None,
102 artifact: None,
103 }
104 }
105 /// Returns whether the content was shortened (any marker other than
106 /// [`Truncation::None`]).
107 pub fn is_truncated(&self) -> bool {
108 !matches!(self.truncation, Truncation::None)
109 }
110}
111
112/// The result fact for one tool call: its declaration identity, terminal
113/// status, output, media, and ordered notes. Pairing is kernel-enforced.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct ToolResultPayload {
117 /// The declaration block this result answers.
118 pub call_block_id: BlockId,
119 /// Terminal status of the invocation.
120 pub status: ToolResultStatus,
121 /// The tool's output, possibly truncated with an artifact spill.
122 pub output: ToolOutput,
123 /// Media artifacts attached to this result — references only; the
124 /// bytes live in the host's asset store, resolved provider-side at
125 /// render time. Serde-additive: absent media defaults to empty.
126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
127 pub media: Vec<crate::context::block::MediaRef>,
128 /// Ordered result notes. `ToolBatch::resolve_at` places any pre-execution
129 /// context notes before notes returned by the tool; tool implementations
130 /// should return only notes they add.
131 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub notes: Vec<crate::context::block::TextPayload>,
133}
134impl ToolResultPayload {
135 /// A result for one declaration, with no media and no notes.
136 pub fn new(call_block_id: BlockId, status: ToolResultStatus, output: ToolOutput) -> Self {
137 Self {
138 call_block_id,
139 status,
140 output,
141 media: Vec::new(),
142 notes: Vec::new(),
143 }
144 }
145
146 /// Replaces the media artifacts attached to this result.
147 pub fn with_media(mut self, media: Vec<crate::context::block::MediaRef>) -> Self {
148 self.media = media;
149 self
150 }
151
152 /// Replaces the ordered result notes.
153 pub fn with_notes(mut self, notes: Vec<crate::context::block::TextPayload>) -> Self {
154 self.notes = notes;
155 self
156 }
157}
158
159/// Pointer to a tool output persisted out-of-band (e.g. a spilled oversized
160/// observation), kept on the result instead of the full content.
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[non_exhaustive]
163pub struct ArtifactRef {
164 /// Store-assigned handle for retrieving the artifact.
165 pub id: String,
166 /// Serialized size of the artifact in bytes.
167 pub size_bytes: usize,
168 /// What the artifact holds.
169 pub kind: ArtifactKind,
170 /// Whether the artifact is durably persisted in a store.
171 pub persisted: bool,
172}
173impl ArtifactRef {
174 /// A reference to one stored artifact.
175 pub fn new(
176 id: impl Into<String>,
177 size_bytes: usize,
178 kind: ArtifactKind,
179 persisted: bool,
180 ) -> Self {
181 Self {
182 id: id.into(),
183 size_bytes,
184 kind,
185 persisted,
186 }
187 }
188}
189
190/// What an artifact holds. A label for the host; nothing in the library
191/// decides by it, so further kinds may be added.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194#[non_exhaustive]
195pub enum ArtifactKind {
196 /// The complete, untruncated tool output.
197 FullOutput,
198 /// Cached intermediate output (e.g. streamed pipe data).
199 PipeCache,
200 /// Raw binary payload.
201 Binary,
202}