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 and
4//! what the pairing invariant validates. Behavior and execution vocabulary
5//! (the `Tool` trait, the `ArtifactStore` port, definitions, limits, outcome
6//! policies, dispatch context) live in `crate::ports::tool`; canonical
7//! modules must depend on this module, never on the executor-sized behavior
8//! module.
9
10use serde::{Deserialize, Serialize};
11
12/// Canonical causal key pairing a tool call with its result. Kernel-generated
13/// (see `generate`), unique within a single turn context; never the
14/// provider-issued call id, which rides on the envelope metadata.
15#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
16pub struct ToolCallId(pub String);
17impl ToolCallId {
18    /// Wraps an arbitrary string as a tool call id.
19    pub fn new(s: impl Into<String>) -> Self {
20        Self(s.into())
21    }
22    /// `tool_name + blake3(round_id + tool_name + arguments_json)[..8] + position`。
23    /// `round_id` enters the hash preimage so the same `(tool, arguments,
24    /// position)` yields a different id in every ModelRound — a model re-sending
25    /// the same call in a later round (the legitimate dedup-recovery path) must
26    /// not collide with a historical call_id. Uniqueness scope is a single
27    /// TurnContext.
28    pub fn generate(
29        round_id: crate::context::ids::RoundId,
30        tool_name: &str,
31        arguments: &serde_json::Value,
32        position: usize,
33    ) -> Self {
34        let json = serde_json::to_string(arguments)
35            .unwrap_or_else(|_| "<unserializable-arguments>".to_string());
36        let preimage = format!("{}|{}|{}", round_id.0, tool_name, json);
37        let hash = blake3::hash(preimage.as_bytes());
38        let hex = hash.to_hex();
39        Self(format!("{}:{}:{}", tool_name, &hex[..8], position))
40    }
41}
42
43/// Terminal status of one tool invocation, recorded verbatim as a fact;
44/// mapping from execution errors is the driver's job, not the kernel's.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub enum ToolResultStatus {
47    /// The tool returned an outcome.
48    Succeeded,
49    /// The tool ran but reported failure (including panic isolation).
50    Failed,
51    /// The call never ran — unknown tool, denied by a filter, or otherwise
52    /// refused before execution.
53    Rejected,
54    /// The invocation was cancelled before producing an outcome.
55    Cancelled,
56    /// The invocation exceeded its time budget before producing an outcome.
57    TimedOut,
58    /// No outcome was observed (e.g. the call-deadline backstop fired);
59    /// whether the turn continues is the harness's unknown-outcome
60    /// configuration, not tool vocabulary.
61    UnknownOutcome,
62}
63
64/// Optional observability sidecar on a tool output; never part of pairing.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct ToolOutputMeta {
67    /// Wall-clock duration of the execution, if measured.
68    pub duration_ms: Option<u64>,
69    /// Estimated token count of the output before truncation, when known.
70    pub original_tokens: Option<usize>,
71    /// Free-form JSON for tool- or driver-specific annotations.
72    pub extra: Option<serde_json::Value>,
73}
74
75/// Whether tool output content was shortened to fit the token limit.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum Truncation {
79    /// The content is the tool's full output.
80    None,
81    /// The content was replaced by head + notice + tail; the full output
82    /// spilled to an artifact when a store was available.
83    Middle,
84}
85
86/// What a tool returned, as recorded by the tool door.
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub struct ToolOutput {
89    /// The observation payload; after middle truncation this is a JSON
90    /// string (head + notice + tail) regardless of the original shape.
91    pub content: serde_json::Value,
92    /// Whether and how the content was shortened.
93    pub truncation: Truncation,
94    /// Optional observability metadata.
95    pub meta: Option<ToolOutputMeta>,
96    /// Reference to the full output in an artifact store, if spilled.
97    pub artifact: Option<ArtifactRef>,
98}
99impl ToolOutput {
100    /// Creates an output with no truncation, metadata, or artifact.
101    pub fn new(content: serde_json::Value) -> Self {
102        Self {
103            content,
104            truncation: Truncation::None,
105            meta: None,
106            artifact: None,
107        }
108    }
109    /// Returns whether the content was shortened (any marker other than
110    /// [`Truncation::None`]).
111    pub fn is_truncated(&self) -> bool {
112        !matches!(self.truncation, Truncation::None)
113    }
114}
115
116/// The result fact for one tool call: the paired call id, terminal status,
117/// and the output. Committed through the tool door; pairing against the
118/// committed call block is kernel-enforced.
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120pub struct ToolResultPayload {
121    /// The kernel-generated id of the call this result answers.
122    pub call_id: ToolCallId,
123    /// Terminal status of the invocation.
124    pub status: ToolResultStatus,
125    /// The tool's output, possibly truncated with an artifact spill.
126    pub output: ToolOutput,
127    /// Media artifacts attached to this result — references only; the
128    /// bytes live in the host's asset store, resolved provider-side at
129    /// render time. Serde-additive: absent media defaults to empty.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub media: Vec<crate::context::block::MediaRef>,
132}
133
134/// Pointer to a tool output persisted out-of-band (e.g. a spilled oversized
135/// observation), kept on the result instead of the full content.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct ArtifactRef {
138    /// Store-assigned handle for retrieving the artifact.
139    pub id: String,
140    /// Serialized size of the artifact in bytes.
141    pub size_bytes: usize,
142    /// What the artifact holds.
143    pub kind: ArtifactKind,
144    /// Whether the artifact is durably persisted in a store.
145    pub persisted: bool,
146}
147
148/// What an artifact holds.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150pub enum ArtifactKind {
151    /// The complete, untruncated tool output.
152    FullOutput,
153    /// Cached intermediate output (e.g. streamed pipe data).
154    PipeCache,
155    /// Raw binary payload.
156    Binary,
157}