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///
20/// Serializable for logs and tests; the serialized form is not part of the
21/// stable set and may change in any release.
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23#[non_exhaustive]
24pub struct ToolDefinition {
25 /// The name the model uses to invoke the tool.
26 pub name: String,
27 /// Short summary of what the tool does, shown to the model.
28 pub description: String,
29 /// Schema of the arguments the tool accepts, embedded verbatim in the
30 /// rendered request.
31 pub parameters: serde_json::Value,
32}
33impl ToolDefinition {
34 /// A definition from its name, description and JSON Schema parameters.
35 pub fn new(
36 name: impl Into<String>,
37 description: impl Into<String>,
38 parameters: serde_json::Value,
39 ) -> Self {
40 Self {
41 name: name.into(),
42 description: description.into(),
43 parameters,
44 }
45 }
46}
47
48/// The tool definitions offered to the model for one invocation; renderers
49/// turn this into the protocol's `tools` array.
50///
51/// Serializable for logs and tests; the serialized form is not part of the
52/// stable set and may change in any release.
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[non_exhaustive]
55pub struct ToolSurface {
56 /// Model-facing [`ToolDefinition`]s, in offer order.
57 pub definitions: Vec<ToolDefinition>,
58}
59
60impl ToolSurface {
61 /// A surface offering no tools.
62 pub fn empty() -> Self {
63 Self {
64 definitions: Vec::new(),
65 }
66 }
67
68 /// Builds a surface from the given definitions.
69 pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
70 Self { definitions }
71 }
72}
73
74/// Identity of one tool dispatch, handed to [`Tool::execute`].
75#[derive(Debug, Clone)]
76#[non_exhaustive]
77pub struct ToolCallContext {
78 /// The declaration block whose result this dispatch produces.
79 pub call_block_id: BlockId,
80 /// The effective input after any pre-processing edits.
81 pub input: ToolCallPayload,
82 /// Notes added before execution. `ToolBatch::resolve_at` prepends these
83 /// to the returned result's notes; tool implementations should return
84 /// only notes they add and must not copy this field into the result.
85 pub result_notes: Vec<TextPayload>,
86}
87impl ToolCallContext {
88 /// A call context with no result notes.
89 pub fn new(call_block_id: BlockId, input: ToolCallPayload) -> Self {
90 Self {
91 call_block_id,
92 input,
93 result_notes: Vec::new(),
94 }
95 }
96}
97
98impl ToolCallContext {
99 /// Builds execution material from a committed declaration.
100 pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
101 Self {
102 call_block_id,
103 input: declaration.clone(),
104 result_notes: Vec::new(),
105 }
106 }
107}
108
109/// Provenance a caller attaches to bytes handed to [`ArtifactStore::persist`],
110/// so the store can label what it receives.
111#[non_exhaustive]
112pub struct ArtifactHint {
113 /// The tool whose output produced the bytes.
114 pub tool_name: String,
115 /// The tool call the bytes belong to.
116 pub call_block_id: BlockId,
117 /// The [`ArtifactKind`] classification of the bytes.
118 pub kind: ArtifactKind,
119}
120impl ArtifactHint {
121 /// A hint for the artifact one call produced.
122 pub fn new(tool_name: impl Into<String>, call_block_id: BlockId, kind: ArtifactKind) -> Self {
123 Self {
124 tool_name: tool_name.into(),
125 call_block_id,
126 kind,
127 }
128 }
129}
130
131/// Error surface of the [`ArtifactStore`] port.
132#[derive(Debug, thiserror::Error)]
133#[non_exhaustive]
134pub enum StoreError {
135 /// Persisting the artifact failed; carries the human-readable cause.
136 #[error("persist failed: {0}")]
137 Persist(String),
138 /// Reading an artifact back failed; carries the human-readable cause.
139 #[error("read failed: {0}")]
140 Read(String),
141}
142
143/// Persistence port for tool artifacts — where oversized tool outputs are
144/// spilled and read back. Callers persist raw bytes plus an [`ArtifactHint`]
145/// and receive an [`ArtifactRef`] to embed in the result; concrete stores
146/// are host concerns.
147#[async_trait]
148pub trait ArtifactStore: Send + Sync {
149 /// Stores `data`, tagged with `hint`, and returns the [`ArtifactRef`]
150 /// describing the persisted artifact.
151 async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
152 /// Reads back the bytes stored under `id`; an optional byte range bounds
153 /// the read.
154 async fn read(
155 &self,
156 id: &str,
157 range: Option<std::ops::Range<u64>>,
158 ) -> Result<Vec<u8>, StoreError>;
159}
160
161/// The tool port: one callable tool the model can invoke. Implementations
162/// live outside the kernel; the driver's executor dispatches them. A tool
163/// returns only its recorded result. Handling unknown outcomes and retaining
164/// output belong to the execution consumer, not tool declarations.
165///
166/// # Requirements on `execute`
167///
168/// An executor may poll every call of one batch on a single task, with
169/// nothing spawned. An implementation therefore:
170///
171/// - must not block the thread. Blocking or CPU-heavy work runs on a
172/// blocking thread (for example `tokio::task::spawn_blocking`) and the
173/// tool awaits it;
174/// - must return promptly once its [`CallControl`] is cancelled or past its
175/// deadline.
176///
177/// For a tool that meets both, a stop takes effect at its next yield point.
178/// A tool that holds the thread also holds its sibling calls and the
179/// executor's own stop and timeout checks, so nothing is guaranteed for it:
180/// not cancellation, not the deadline, not a per-call timeout.
181///
182/// Calls of one batch are concurrent, not parallel, and their number is not
183/// bounded. A tool that needs a limit shares a semaphore across its calls.
184#[async_trait]
185pub trait Tool: Send + Sync {
186 /// The model-facing [`ToolDefinition`] for this tool.
187 fn definition(&self) -> ToolDefinition;
188 /// Runs one call under the call's [`CallControl`], returning the
189 /// recorded result. `store` is the host's [`ArtifactStore`] when one is
190 /// configured: a tool that produces media or oversized output persists
191 /// the bytes there and returns a reference; a tool that does not need
192 /// storage ignores it.
193 async fn execute(
194 &self,
195 ctx: &ToolCallContext,
196 control: &CallControl,
197 store: Option<&dyn ArtifactStore>,
198 ) -> ToolResultPayload;
199}