Skip to main content

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/// The boundary between these statuses is whether a result was reported or
35/// observed, not whether the call could have had an effect:
36///
37/// - [`Succeeded`](Self::Succeeded), [`Failed`](Self::Failed),
38///   [`Cancelled`](Self::Cancelled) and [`TimedOut`](Self::TimedOut) are
39///   results for the call. `Cancelled` and `TimedOut` are the tool's own
40///   report of a terminal state; they may carry partial output and do not
41///   prove that nothing happened.
42/// - [`Rejected`](Self::Rejected) records a call that never ran: an unknown
43///   tool, a denying processor or another refusal stopped it before
44///   execution, so no tool reported a result.
45/// - [`UnknownOutcome`](Self::UnknownOutcome) is a placeholder synthesized by
46///   the executor or a tool-source bridge when no result was observed — for
47///   example, a call stopped before its first poll or one that did not
48///   return.
49///
50/// Exhaustive on purpose: renderers and the runtime decide by status, so a new one is a breaking change.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum ToolResultStatus {
54    /// The tool returned a successful result.
55    Succeeded,
56    /// The tool ran and reported failure (including panic isolation).
57    Failed,
58    /// The call never ran — unknown tool, denied by a processor, or otherwise
59    /// refused before execution.
60    Rejected,
61    /// The tool reported that the invocation was cancelled before completing.
62    /// The result may carry partial output, and it does not prove that no
63    /// side effect happened.
64    Cancelled,
65    /// The tool reported that the invocation exceeded its time budget. The
66    /// result may carry partial output, and it does not prove that no side
67    /// effect happened.
68    TimedOut,
69    /// No result was observed: the executor recorded it for a call stopped
70    /// before the first poll or one that did not return, or a tool-source
71    /// bridge recorded it for a source that reported an unobserved timeout or
72    /// cancellation. It does not mean the tool failed or had no effect.
73    UnknownOutcome,
74}
75
76/// Optional observability sidecar on a tool output; never part of pairing.
77#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct ToolOutputMeta {
80    /// Wall-clock duration of the execution, if measured.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub duration_ms: Option<u64>,
83    /// Estimated token count of the output body before truncation, when known.
84    /// This does not include result notes or media.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub original_tokens: Option<usize>,
87    /// Free-form JSON for tool- or driver-specific annotations.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub extra: Option<serde_json::Value>,
90}
91
92/// Whether tool output content was shortened to fit the token limit.
93///
94/// Exhaustive on purpose: content was shortened or it was not.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "snake_case")]
97pub enum Truncation {
98    /// The content is the tool's full output.
99    None,
100    /// The content was replaced by head + notice + tail; the full output
101    /// spilled to an artifact when a store was available.
102    Middle,
103}
104
105/// What a tool returned, as recorded by the tool door.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct ToolOutput {
109    /// The observation payload; after middle truncation this is a JSON
110    /// string (head + notice + tail) regardless of the original shape.
111    pub content: serde_json::Value,
112    /// Whether and how the content was shortened.
113    pub truncation: Truncation,
114    /// Optional observability metadata.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub meta: Option<ToolOutputMeta>,
117    /// Reference to the full output in an artifact store, if spilled.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub artifact: Option<ArtifactRef>,
120}
121impl ToolOutput {
122    /// Creates an output with no truncation, metadata, or artifact.
123    pub fn new(content: serde_json::Value) -> Self {
124        Self {
125            content,
126            truncation: Truncation::None,
127            meta: None,
128            artifact: None,
129        }
130    }
131    /// Returns whether the content was shortened (any marker other than
132    /// [`Truncation::None`]).
133    pub fn is_truncated(&self) -> bool {
134        !matches!(self.truncation, Truncation::None)
135    }
136}
137
138/// The result fact for one tool call: its declaration identity, terminal
139/// status, output, media, and ordered notes. Pairing is kernel-enforced.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[non_exhaustive]
142pub struct ToolResultPayload {
143    /// The declaration block this result answers.
144    pub call_block_id: BlockId,
145    /// Terminal status of the invocation.
146    pub status: ToolResultStatus,
147    /// The tool's output, possibly truncated with an artifact spill.
148    pub output: ToolOutput,
149    /// Media artifacts attached to this result — references only; the
150    /// bytes live in the host's asset store, resolved provider-side at
151    /// render time. Serde-additive: absent media defaults to empty.
152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
153    pub media: Vec<crate::context::block::MediaRef>,
154    /// Ordered result notes. `ToolBatch::resolve_at` places any pre-execution
155    /// context notes before notes returned by the tool; tool implementations
156    /// should return only notes they add.
157    #[serde(default, skip_serializing_if = "Vec::is_empty")]
158    pub notes: Vec<crate::context::block::TextPayload>,
159}
160impl ToolResultPayload {
161    /// A result for one declaration, with no media and no notes.
162    pub fn new(call_block_id: BlockId, status: ToolResultStatus, output: ToolOutput) -> Self {
163        Self {
164            call_block_id,
165            status,
166            output,
167            media: Vec::new(),
168            notes: Vec::new(),
169        }
170    }
171
172    /// Replaces the media artifacts attached to this result.
173    pub fn with_media(mut self, media: Vec<crate::context::block::MediaRef>) -> Self {
174        self.media = media;
175        self
176    }
177
178    /// Replaces the ordered result notes.
179    pub fn with_notes(mut self, notes: Vec<crate::context::block::TextPayload>) -> Self {
180        self.notes = notes;
181        self
182    }
183}
184
185/// Pointer to a tool output persisted out-of-band (e.g. a spilled oversized
186/// observation), kept on the result instead of the full content.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[non_exhaustive]
189pub struct ArtifactRef {
190    /// Store-assigned handle for retrieving the artifact.
191    pub id: String,
192    /// Serialized size of the artifact in bytes.
193    pub size_bytes: usize,
194    /// What the artifact holds.
195    pub kind: ArtifactKind,
196    /// Whether the artifact is durably persisted in a store.
197    pub persisted: bool,
198}
199impl ArtifactRef {
200    /// A reference to one stored artifact.
201    pub fn new(
202        id: impl Into<String>,
203        size_bytes: usize,
204        kind: ArtifactKind,
205        persisted: bool,
206    ) -> Self {
207        Self {
208            id: id.into(),
209            size_bytes,
210            kind,
211            persisted,
212        }
213    }
214}
215
216/// What an artifact holds. A label for the host; nothing in the library
217/// decides by it, so further kinds may be added.
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
219#[serde(rename_all = "snake_case")]
220#[non_exhaustive]
221pub enum ArtifactKind {
222    /// The complete, untruncated tool output.
223    FullOutput,
224    /// Cached intermediate output (e.g. streamed pipe data).
225    PipeCache,
226    /// Raw binary payload.
227    Binary,
228}