Skip to main content

causa_kernel/ports/
tool.rs

1//! Tool behavior — the `Tool` trait and the `ArtifactStore` port, plus the
2//! execution vocabulary they share with drivers: definitions and call
3//! context. Recorded facts (results, outputs, artifacts) live in
4//! `crate::context::tool_data`; batch dispatch lives in `causa-runtime`'s
5//! executor. A tool returns its recorded result and nothing else —
6//! handling unknown outcomes and retaining output belong to execution
7//! consumers, not tool declarations.
8
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11
12use crate::context::block::{TextPayload, ToolCallPayload};
13use crate::context::ids::BlockId;
14use crate::context::tool_data::{ArtifactKind, ArtifactRef, ToolResultPayload};
15use crate::ports::control::CallControl;
16
17/// The model-facing description of one callable tool; renderers map it onto
18/// the protocol's tool entries (name, description, parameter schema).
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct ToolDefinition {
22    /// The name the model uses to invoke the tool.
23    pub name: String,
24    /// Short summary of what the tool does, shown to the model.
25    pub description: String,
26    /// Schema of the arguments the tool accepts, embedded verbatim in the
27    /// rendered request.
28    pub parameters: serde_json::Value,
29}
30impl ToolDefinition {
31    /// A definition from its name, description and JSON Schema parameters.
32    pub fn new(
33        name: impl Into<String>,
34        description: impl Into<String>,
35        parameters: serde_json::Value,
36    ) -> Self {
37        Self {
38            name: name.into(),
39            description: description.into(),
40            parameters,
41        }
42    }
43}
44
45/// The tool definitions offered to the model for one invocation; renderers
46/// turn this into the protocol's `tools` array.
47#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
48#[non_exhaustive]
49pub struct ToolSurface {
50    /// Model-facing [`ToolDefinition`]s, in offer order.
51    pub definitions: Vec<ToolDefinition>,
52}
53
54impl ToolSurface {
55    /// A surface offering no tools.
56    pub fn empty() -> Self {
57        Self {
58            definitions: Vec::new(),
59        }
60    }
61
62    /// Builds a surface from the given definitions.
63    pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
64        Self { definitions }
65    }
66}
67
68/// Identity of one tool dispatch, handed to [`Tool::execute`].
69#[derive(Debug, Clone)]
70#[non_exhaustive]
71pub struct ToolCallContext {
72    /// The declaration block whose result this dispatch produces.
73    pub call_block_id: BlockId,
74    /// The effective input after any pre-processing edits.
75    pub input: ToolCallPayload,
76    /// Notes added before execution. `ToolBatch::resolve_at` prepends these
77    /// to the returned result's notes; tool implementations should return
78    /// only notes they add and must not copy this field into the result.
79    pub result_notes: Vec<TextPayload>,
80}
81impl ToolCallContext {
82    /// A call context with no result notes.
83    pub fn new(call_block_id: BlockId, input: ToolCallPayload) -> Self {
84        Self {
85            call_block_id,
86            input,
87            result_notes: Vec::new(),
88        }
89    }
90}
91
92impl ToolCallContext {
93    /// Builds execution material from a committed declaration.
94    pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
95        Self {
96            call_block_id,
97            input: declaration.clone(),
98            result_notes: Vec::new(),
99        }
100    }
101}
102
103/// Provenance a caller attaches to bytes handed to [`ArtifactStore::persist`],
104/// so the store can label what it receives.
105#[non_exhaustive]
106pub struct ArtifactHint {
107    /// The tool whose output produced the bytes.
108    pub tool_name: String,
109    /// The tool call the bytes belong to.
110    pub call_block_id: BlockId,
111    /// The [`ArtifactKind`] classification of the bytes.
112    pub kind: ArtifactKind,
113}
114impl ArtifactHint {
115    /// A hint for the artifact one call produced.
116    pub fn new(tool_name: impl Into<String>, call_block_id: BlockId, kind: ArtifactKind) -> Self {
117        Self {
118            tool_name: tool_name.into(),
119            call_block_id,
120            kind,
121        }
122    }
123}
124
125/// Error surface of the [`ArtifactStore`] port.
126#[derive(Debug, thiserror::Error)]
127#[non_exhaustive]
128pub enum StoreError {
129    /// Persisting the artifact failed; carries the human-readable cause.
130    #[error("persist failed: {0}")]
131    Persist(String),
132    /// Reading an artifact back failed; carries the human-readable cause.
133    #[error("read failed: {0}")]
134    Read(String),
135}
136
137/// Persistence port for tool artifacts — where oversized tool outputs are
138/// spilled and read back. Callers persist raw bytes plus an [`ArtifactHint`]
139/// and receive an [`ArtifactRef`] to embed in the result; concrete stores
140/// are host concerns.
141#[async_trait]
142pub trait ArtifactStore: Send + Sync {
143    /// Stores `data`, tagged with `hint`, and returns the [`ArtifactRef`]
144    /// describing the persisted artifact.
145    async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
146    /// Reads back the bytes stored under `id`; an optional byte range bounds
147    /// the read.
148    async fn read(
149        &self,
150        id: &str,
151        range: Option<std::ops::Range<u64>>,
152    ) -> Result<Vec<u8>, StoreError>;
153}
154
155/// The tool port: one callable tool the model can invoke. Implementations
156/// live outside the kernel; the driver's executor dispatches them. A tool
157/// returns only its recorded result. Handling unknown outcomes and retaining
158/// output belong to the execution consumer, not tool declarations.
159#[async_trait]
160pub trait Tool: Send + Sync {
161    /// The model-facing [`ToolDefinition`] for this tool.
162    fn definition(&self) -> ToolDefinition;
163    /// Runs one call under the call's [`CallControl`], returning the
164    /// recorded result. `store` is the host's [`ArtifactStore`] when one is
165    /// configured: a tool that produces media or oversized output persists
166    /// the bytes there and returns a reference; a tool that does not need
167    /// storage ignores it.
168    async fn execute(
169        &self,
170        ctx: &ToolCallContext,
171        control: &CallControl,
172        store: Option<&dyn ArtifactStore>,
173    ) -> ToolResultPayload;
174}