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: the bound surface 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::context::tools::ToolDefinition;
16use crate::ports::control::CallControl;
17
18/// The tool definitions bound for one invocation: what the executor can
19/// dispatch this round. A driver records a difference from the context's
20/// tool state as a [`crate::ToolChange`] block, and renderers read the tools
21/// from the frame, never from this value.
22///
23/// Serializable for logs and tests; the serialized form is not part of the
24/// stable set and may change in any release.
25#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
26#[non_exhaustive]
27pub struct ToolSurface {
28    /// Model-facing [`ToolDefinition`]s, in offer order.
29    pub definitions: Vec<ToolDefinition>,
30}
31
32impl ToolSurface {
33    /// A surface offering no tools.
34    pub fn empty() -> Self {
35        Self {
36            definitions: Vec::new(),
37        }
38    }
39
40    /// Builds a surface from the given definitions.
41    pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
42        Self { definitions }
43    }
44}
45
46/// What a tool declares about its own effects, for the host's tool
47/// processors.
48///
49/// Each field is the tool's own claim and is not verified. `None` means the
50/// tool did not declare it: Causa fills in no default and never acts on a
51/// value, so a host decides how far to trust each one — for example by
52/// asking about every call of a tool that is not declared read-only. MCP
53/// servers declare the same four hints as tool annotations, and the MCP
54/// adapter in `causa-extension` carries them over one to one.
55///
56/// Hints sit beside the [`ToolDefinition`], not in it. They never reach the
57/// model or the context: a change in hints alone records no
58/// [`crate::ToolChange`] and leaves the rendered request as it was.
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct ToolHints {
62    /// The tool does not modify its environment.
63    pub read_only: Option<bool>,
64    /// The tool may overwrite or delete what exists, rather than only add
65    /// to it. Meaningful for a tool that is not read-only.
66    pub destructive: Option<bool>,
67    /// Repeating a call with the same arguments has no further effect.
68    /// Meaningful for a tool that is not read-only.
69    pub idempotent: Option<bool>,
70    /// The tool reaches entities outside a closed domain, such as the web.
71    pub open_world: Option<bool>,
72}
73
74impl ToolHints {
75    /// Declares whether the tool leaves its environment unchanged.
76    pub fn with_read_only(mut self, read_only: bool) -> Self {
77        self.read_only = Some(read_only);
78        self
79    }
80
81    /// Declares whether the tool may overwrite or delete what exists.
82    pub fn with_destructive(mut self, destructive: bool) -> Self {
83        self.destructive = Some(destructive);
84        self
85    }
86
87    /// Declares whether repeating a call has no further effect.
88    pub fn with_idempotent(mut self, idempotent: bool) -> Self {
89        self.idempotent = Some(idempotent);
90        self
91    }
92
93    /// Declares whether the tool reaches beyond a closed domain.
94    pub fn with_open_world(mut self, open_world: bool) -> Self {
95        self.open_world = Some(open_world);
96        self
97    }
98}
99
100/// One tool as its catalog describes it: the model-facing definition and
101/// the tool's declared [`ToolHints`].
102///
103/// A [`crate::DynamicToolSource`] lists these from
104/// [`crate::DynamicToolSource::describe`], and tool processors see the bound
105/// set through [`crate::ProcessorContext::tools`].
106#[derive(Debug, Clone, PartialEq)]
107#[non_exhaustive]
108pub struct ToolDescription {
109    /// The model-facing definition.
110    pub definition: ToolDefinition,
111    /// What the tool declares about its effects.
112    pub hints: ToolHints,
113}
114
115impl ToolDescription {
116    /// A description that declares no hints.
117    pub fn new(definition: ToolDefinition) -> Self {
118        Self {
119            definition,
120            hints: ToolHints::default(),
121        }
122    }
123
124    /// Replaces the declared hints.
125    pub fn with_hints(mut self, hints: ToolHints) -> Self {
126        self.hints = hints;
127        self
128    }
129}
130
131/// Identity of one tool dispatch, handed to [`Tool::execute`].
132#[derive(Debug, Clone)]
133#[non_exhaustive]
134pub struct ToolCallContext {
135    /// The declaration block whose result this dispatch produces.
136    pub call_block_id: BlockId,
137    /// The effective input after any pre-processing edits.
138    pub input: ToolCallPayload,
139    /// Notes added before execution. `ToolBatch::resolve_at` prepends these
140    /// to the returned result's notes; tool implementations should return
141    /// only notes they add and must not copy this field into the result.
142    pub result_notes: Vec<TextPayload>,
143}
144impl ToolCallContext {
145    /// A call context with no result notes.
146    pub fn new(call_block_id: BlockId, input: ToolCallPayload) -> Self {
147        Self {
148            call_block_id,
149            input,
150            result_notes: Vec::new(),
151        }
152    }
153}
154
155impl ToolCallContext {
156    /// Builds execution material from a committed declaration.
157    pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
158        Self {
159            call_block_id,
160            input: declaration.clone(),
161            result_notes: Vec::new(),
162        }
163    }
164}
165
166/// Provenance a caller attaches to bytes handed to [`ArtifactStore::persist`],
167/// so the store can label what it receives.
168#[non_exhaustive]
169pub struct ArtifactHint {
170    /// The tool whose output produced the bytes.
171    pub tool_name: String,
172    /// The tool call the bytes belong to.
173    pub call_block_id: BlockId,
174    /// The [`ArtifactKind`] classification of the bytes.
175    pub kind: ArtifactKind,
176}
177impl ArtifactHint {
178    /// A hint for the artifact one call produced.
179    pub fn new(tool_name: impl Into<String>, call_block_id: BlockId, kind: ArtifactKind) -> Self {
180        Self {
181            tool_name: tool_name.into(),
182            call_block_id,
183            kind,
184        }
185    }
186}
187
188/// Error surface of the [`ArtifactStore`] port.
189#[derive(Debug, thiserror::Error)]
190#[non_exhaustive]
191pub enum StoreError {
192    /// Persisting the artifact failed; carries the human-readable cause.
193    #[error("persist failed: {0}")]
194    Persist(String),
195    /// Reading an artifact back failed; carries the human-readable cause.
196    #[error("read failed: {0}")]
197    Read(String),
198}
199
200/// Persistence port for tool artifacts — where oversized tool outputs are
201/// spilled and read back. Callers persist raw bytes plus an [`ArtifactHint`]
202/// and receive an [`ArtifactRef`] to embed in the result; concrete stores
203/// are host concerns.
204#[async_trait]
205pub trait ArtifactStore: Send + Sync {
206    /// Stores `data`, tagged with `hint`, and returns the [`ArtifactRef`]
207    /// describing the persisted artifact.
208    async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
209    /// Reads back the bytes stored under `id`; an optional byte range bounds
210    /// the read.
211    async fn read(
212        &self,
213        id: &str,
214        range: Option<std::ops::Range<u64>>,
215    ) -> Result<Vec<u8>, StoreError>;
216}
217
218/// The tool port: one callable tool the model can invoke. Implementations
219/// live outside the kernel; the driver's executor dispatches them. A tool
220/// returns only its recorded result. Handling unknown outcomes and retaining
221/// output belong to the execution consumer, not tool declarations.
222///
223/// # Requirements on `execute`
224///
225/// An executor may poll every call of one batch on a single task, with
226/// nothing spawned. An implementation therefore:
227///
228/// - must not block the thread. Blocking or CPU-heavy work runs on a
229///   blocking thread (for example `tokio::task::spawn_blocking`) and the
230///   tool awaits it;
231/// - must watch its [`CallControl`] itself. A turn stop — cancellation or
232///   the turn deadline — drops the call future: the executor stops polling,
233///   a started call settles as
234///   [`ToolResultStatus::UnknownOutcome`](crate::context::tool_data::ToolResultStatus::UnknownOutcome).
235///   Once the executor observes the stop it polls the call no further, so a
236///   value returned after that is not recorded. Returning promptly on
237///   cancellation releases the resources the future still owns; it does not
238///   make the result observed;
239/// - must return, cleanup included, by its effective call deadline to
240///   report
241///   [`ToolResultStatus::TimedOut`](crate::context::tool_data::ToolResultStatus::TimedOut)
242///   or
243///   [`ToolResultStatus::Cancelled`](crate::context::tool_data::ToolResultStatus::Cancelled).
244///   The executor enforces a call deadline with `timeout_at`, which polls the
245///   call before its own timer and drops the future once the deadline has
246///   expired. A tool that races the same deadline and returns without
247///   awaiting anything further is therefore recorded. A tool that awaits
248///   cleanup after it stops has to stop early enough for that cleanup to
249///   finish before the deadline; otherwise the future is dropped mid-cleanup
250///   and the call settles as `UnknownOutcome`.
251///
252/// Dropping the future runs on the executor's task, so [`Drop`] must not
253/// block and must be idempotent. A future that starts external work — a
254/// spawned task, a child process, a remote operation — cleans it up in
255/// [`Drop`].
256///
257/// For a tool that meets these, a stop takes effect at its next yield point.
258/// A tool that holds the thread also holds its sibling calls and the
259/// executor's own stop and timeout checks, so nothing is guaranteed for it:
260/// not cancellation, not the deadline, not a per-call timeout.
261///
262/// Calls of one batch are concurrent, not parallel, and their number is not
263/// bounded. A tool that needs a limit shares a semaphore across its calls.
264#[async_trait]
265pub trait Tool: Send + Sync {
266    /// The model-facing [`ToolDefinition`] for this tool.
267    fn definition(&self) -> ToolDefinition;
268    /// What this tool declares about its effects. An executor reads it when
269    /// it binds the tool, next to [`Tool::definition`], and shows it to tool
270    /// processors. The default declares nothing.
271    fn hints(&self) -> ToolHints {
272        ToolHints::default()
273    }
274    /// Runs one call under the call's [`CallControl`], returning the
275    /// recorded result. `store` is the host's [`ArtifactStore`] when one is
276    /// configured: a tool that produces media or oversized output persists
277    /// the bytes there and returns a reference; a tool that does not need
278    /// storage ignores it.
279    async fn execute(
280        &self,
281        ctx: &ToolCallContext,
282        control: &CallControl,
283        store: Option<&dyn ArtifactStore>,
284    ) -> ToolResultPayload;
285}