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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub enum ToolResultStatus {
35    /// The tool returned an outcome.
36    Succeeded,
37    /// The tool ran but reported failure (including panic isolation).
38    Failed,
39    /// The call never ran — unknown tool, denied by a processor, or otherwise
40    /// refused before execution.
41    Rejected,
42    /// The invocation was cancelled before producing an outcome.
43    Cancelled,
44    /// The invocation exceeded its time budget before producing an outcome.
45    TimedOut,
46    /// No outcome was observed (e.g. the call-deadline backstop fired);
47    /// whether the turn continues is the harness's unknown-outcome
48    /// configuration, not tool vocabulary.
49    UnknownOutcome,
50}
51
52/// Optional observability sidecar on a tool output; never part of pairing.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct ToolOutputMeta {
55    /// Wall-clock duration of the execution, if measured.
56    pub duration_ms: Option<u64>,
57    /// Estimated token count of the output body before truncation, when known.
58    /// This does not include result notes or media.
59    pub original_tokens: Option<usize>,
60    /// Free-form JSON for tool- or driver-specific annotations.
61    pub extra: Option<serde_json::Value>,
62}
63
64/// Whether tool output content was shortened to fit the token limit.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum Truncation {
68    /// The content is the tool's full output.
69    None,
70    /// The content was replaced by head + notice + tail; the full output
71    /// spilled to an artifact when a store was available.
72    Middle,
73}
74
75/// What a tool returned, as recorded by the tool door.
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct ToolOutput {
78    /// The observation payload; after middle truncation this is a JSON
79    /// string (head + notice + tail) regardless of the original shape.
80    pub content: serde_json::Value,
81    /// Whether and how the content was shortened.
82    pub truncation: Truncation,
83    /// Optional observability metadata.
84    pub meta: Option<ToolOutputMeta>,
85    /// Reference to the full output in an artifact store, if spilled.
86    pub artifact: Option<ArtifactRef>,
87}
88impl ToolOutput {
89    /// Creates an output with no truncation, metadata, or artifact.
90    pub fn new(content: serde_json::Value) -> Self {
91        Self {
92            content,
93            truncation: Truncation::None,
94            meta: None,
95            artifact: None,
96        }
97    }
98    /// Returns whether the content was shortened (any marker other than
99    /// [`Truncation::None`]).
100    pub fn is_truncated(&self) -> bool {
101        !matches!(self.truncation, Truncation::None)
102    }
103}
104
105/// The result fact for one tool call: its declaration identity, terminal
106/// status, output, media, and ordered notes. Pairing is kernel-enforced.
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108pub struct ToolResultPayload {
109    /// The declaration block this result answers.
110    pub call_block_id: BlockId,
111    /// Terminal status of the invocation.
112    pub status: ToolResultStatus,
113    /// The tool's output, possibly truncated with an artifact spill.
114    pub output: ToolOutput,
115    /// Media artifacts attached to this result — references only; the
116    /// bytes live in the host's asset store, resolved provider-side at
117    /// render time. Serde-additive: absent media defaults to empty.
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub media: Vec<crate::context::block::MediaRef>,
120    /// Ordered result notes. `ToolBatch::resolve_at` places any pre-execution
121    /// context notes before notes returned by the tool; tool implementations
122    /// should return only notes they add.
123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
124    pub notes: Vec<crate::context::block::TextPayload>,
125}
126
127/// Pointer to a tool output persisted out-of-band (e.g. a spilled oversized
128/// observation), kept on the result instead of the full content.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct ArtifactRef {
131    /// Store-assigned handle for retrieving the artifact.
132    pub id: String,
133    /// Serialized size of the artifact in bytes.
134    pub size_bytes: usize,
135    /// What the artifact holds.
136    pub kind: ArtifactKind,
137    /// Whether the artifact is durably persisted in a store.
138    pub persisted: bool,
139}
140
141/// What an artifact holds.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143pub enum ArtifactKind {
144    /// The complete, untruncated tool output.
145    FullOutput,
146    /// Cached intermediate output (e.g. streamed pipe data).
147    PipeCache,
148    /// Raw binary payload.
149    Binary,
150}