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};
11use std::any::{Any, TypeId};
12use std::collections::HashMap;
13use std::fmt;
14use std::sync::Arc;
15
16use crate::context::block::{TextPayload, ToolCallPayload};
17use crate::context::ids::BlockId;
18use crate::context::tool_data::{ArtifactKind, ArtifactRef, ToolResultPayload};
19use crate::context::tools::ToolDefinition;
20use crate::ports::control::CallControl;
21
22/// The tool definitions bound for one invocation: what the executor can
23/// dispatch this round. A driver records a difference from the context's
24/// tool state as a [`crate::ToolChange`] block, and renderers read the tools
25/// from the frame, never from this value.
26///
27/// Serializable for logs and tests; the serialized form is not part of the
28/// stable set and may change in any release.
29#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
30#[non_exhaustive]
31pub struct ToolSurface {
32 /// Model-facing [`ToolDefinition`]s, in offer order.
33 pub definitions: Vec<ToolDefinition>,
34}
35
36impl ToolSurface {
37 /// A surface offering no tools.
38 pub fn empty() -> Self {
39 Self {
40 definitions: Vec::new(),
41 }
42 }
43
44 /// Builds a surface from the given definitions.
45 pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
46 Self { definitions }
47 }
48}
49
50/// Non-persisted, bind-time typed metadata carried beside [`ToolDefinition`].
51///
52/// Hosts and tool sources store arbitrary typed values keyed by [`TypeId`].
53/// Causa carries metadata from tool binding to [`crate::ProcessorContext`] and
54/// never inspects, interprets, or serializes it: metadata never enters
55/// [`crate::Context`], [`crate::ToolChange`], or model wire requests, and a
56/// change in metadata alone records no [`crate::ToolChange`].
57///
58/// Cloning is O(1) per entry because each value is reference-counted. An empty
59/// `ToolMetadata` allocates nothing.
60#[derive(Clone, Default)]
61pub struct ToolMetadata {
62 entries: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
63}
64
65impl ToolMetadata {
66 /// An empty metadata bag.
67 pub fn new() -> Self {
68 Self::default()
69 }
70
71 /// Inserts `value` and returns `self` for chained construction. Replaces
72 /// any previous value of type `T`.
73 pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
74 self.insert(value);
75 self
76 }
77
78 /// Inserts `value` under `TypeId::of::<T>()`, returning any previous value
79 /// of type `T`.
80 pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<Arc<T>> {
81 self.entries
82 .insert(TypeId::of::<T>(), Arc::new(value))
83 .and_then(|prev| prev.downcast::<T>().ok())
84 }
85
86 /// Borrows the value stored for type `T`, or `None` if no value of that
87 /// exact type is present.
88 pub fn get<T: Any>(&self) -> Option<&T> {
89 self.entries
90 .get(&TypeId::of::<T>())
91 .and_then(|arc| (&**arc as &dyn Any).downcast_ref::<T>())
92 }
93
94 /// Returns `true` when a value of exact type `T` is stored.
95 pub fn contains<T: Any>(&self) -> bool {
96 self.entries.contains_key(&TypeId::of::<T>())
97 }
98
99 /// Returns the number of stored metadata entries.
100 pub fn len(&self) -> usize {
101 self.entries.len()
102 }
103
104 /// Returns `true` when no metadata entries are stored.
105 pub fn is_empty(&self) -> bool {
106 self.entries.is_empty()
107 }
108}
109
110impl fmt::Debug for ToolMetadata {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.debug_struct("ToolMetadata")
113 .field("len", &self.entries.len())
114 .finish_non_exhaustive()
115 }
116}
117
118/// One tool as its catalog describes it: the model-facing definition and
119/// non-persisted [`ToolMetadata`].
120///
121/// A [`crate::DynamicToolSource`] lists these from
122/// [`crate::DynamicToolSource::describe`], and tool processors see the bound
123/// set through [`crate::ProcessorContext::tools`].
124#[derive(Debug, Clone)]
125#[non_exhaustive]
126pub struct ToolDescription {
127 /// The model-facing definition.
128 pub definition: ToolDefinition,
129 /// Non-persisted metadata declared beside the definition.
130 pub metadata: ToolMetadata,
131}
132
133impl ToolDescription {
134 /// A description with empty metadata.
135 pub fn new(definition: ToolDefinition) -> Self {
136 Self {
137 definition,
138 metadata: ToolMetadata::default(),
139 }
140 }
141
142 /// Replaces the tool metadata.
143 pub fn with_metadata(mut self, metadata: ToolMetadata) -> Self {
144 self.metadata = metadata;
145 self
146 }
147
148 /// Inserts a single metadata value of type `T`, replacing any prior value
149 /// of the same type.
150 pub fn with_meta<T: Any + Send + Sync>(mut self, value: T) -> Self {
151 self.metadata.insert(value);
152 self
153 }
154}
155
156/// Non-persisted, call-scoped typed attachments handed from before-processors
157/// to tool execution.
158///
159/// Each entry is stored behind an [`Arc`] keyed by [`TypeId`], keeping
160/// [`ToolCallContext::clone`] O(1) per entry during executor dispatch. An
161/// empty `CallAttachments` allocates nothing. Attachments are never persisted
162/// in [`crate::Context`], never included in [`ToolResultPayload`], and never
163/// sent to model protocols; [`crate::ToolBatch::resolve_at`] clears an entry's
164/// attachments as soon as the call resolves.
165#[derive(Clone, Default)]
166pub struct CallAttachments {
167 entries: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
168}
169
170impl CallAttachments {
171 /// An empty attachment bag.
172 pub fn new() -> Self {
173 Self::default()
174 }
175
176 /// Inserts `value` and returns `self` for chained construction. Replaces
177 /// any previous attachment of type `T`.
178 pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
179 self.insert(value);
180 self
181 }
182
183 /// Inserts `value` under `TypeId::of::<T>()`, returning any previous
184 /// attachment of type `T`.
185 pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<Arc<T>> {
186 self.entries
187 .insert(TypeId::of::<T>(), Arc::new(value))
188 .and_then(|prev| prev.downcast::<T>().ok())
189 }
190
191 /// Borrows the attachment stored for type `T`, or `None` if no attachment
192 /// of that exact type is present.
193 pub fn get<T: Any>(&self) -> Option<&T> {
194 self.entries
195 .get(&TypeId::of::<T>())
196 .and_then(|arc| (&**arc as &dyn Any).downcast_ref::<T>())
197 }
198
199 /// Returns `true` when an attachment of exact type `T` is stored.
200 pub fn contains<T: Any>(&self) -> bool {
201 self.entries.contains_key(&TypeId::of::<T>())
202 }
203
204 /// Removes and returns the attachment stored for type `T`, if present.
205 pub fn remove<T: Any + Send + Sync>(&mut self) -> Option<Arc<T>> {
206 self.entries
207 .remove(&TypeId::of::<T>())
208 .and_then(|prev| prev.downcast::<T>().ok())
209 }
210
211 /// Drops all stored attachments.
212 pub fn clear(&mut self) {
213 self.entries.clear();
214 }
215
216 /// Returns the number of stored attachments.
217 pub fn len(&self) -> usize {
218 self.entries.len()
219 }
220
221 /// Returns `true` when no attachments are stored.
222 pub fn is_empty(&self) -> bool {
223 self.entries.is_empty()
224 }
225}
226
227impl fmt::Debug for CallAttachments {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("CallAttachments")
230 .field("len", &self.entries.len())
231 .finish_non_exhaustive()
232 }
233}
234
235/// Identity of one tool dispatch, handed to [`Tool::execute`].
236#[derive(Debug, Clone)]
237#[non_exhaustive]
238pub struct ToolCallContext {
239 /// The declaration block whose result this dispatch produces.
240 pub call_block_id: BlockId,
241 /// The effective input after any pre-processing edits.
242 pub input: ToolCallPayload,
243 /// Notes added before execution. `ToolBatch::resolve_at` prepends these
244 /// to the returned result's notes; tool implementations should return
245 /// only notes they add and must not copy this field into the result.
246 pub result_notes: Vec<TextPayload>,
247 pub(crate) attachments: CallAttachments,
248}
249impl ToolCallContext {
250 /// A call context with no result notes and no attachments.
251 pub fn new(call_block_id: BlockId, input: ToolCallPayload) -> Self {
252 Self {
253 call_block_id,
254 input,
255 result_notes: Vec::new(),
256 attachments: CallAttachments::default(),
257 }
258 }
259
260 /// Builds execution material from a committed declaration.
261 pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
262 Self {
263 call_block_id,
264 input: declaration.clone(),
265 result_notes: Vec::new(),
266 attachments: CallAttachments::default(),
267 }
268 }
269
270 /// Borrows the call-scoped attachment of exact type `T`, if present.
271 pub fn attachment<T: Any>(&self) -> Option<&T> {
272 self.attachments.get::<T>()
273 }
274
275 /// Borrows the full call-scoped attachment bag.
276 pub fn attachments(&self) -> &CallAttachments {
277 &self.attachments
278 }
279
280 /// Attaches a value of type `T`, replacing any prior attachment of the same
281 /// type. Useful for unit-testing [`Tool::execute`] directly without a
282 /// [`crate::ToolBatch`].
283 pub fn with_attachment<T: Any + Send + Sync>(mut self, value: T) -> Self {
284 self.attachments.insert(value);
285 self
286 }
287}
288
289/// Provenance a caller attaches to bytes handed to [`ArtifactStore::persist`],
290/// so the store can label what it receives.
291#[non_exhaustive]
292pub struct ArtifactHint {
293 /// The tool whose output produced the bytes.
294 pub tool_name: String,
295 /// The tool call the bytes belong to.
296 pub call_block_id: BlockId,
297 /// The [`ArtifactKind`] classification of the bytes.
298 pub kind: ArtifactKind,
299}
300impl ArtifactHint {
301 /// A hint for the artifact one call produced.
302 pub fn new(tool_name: impl Into<String>, call_block_id: BlockId, kind: ArtifactKind) -> Self {
303 Self {
304 tool_name: tool_name.into(),
305 call_block_id,
306 kind,
307 }
308 }
309}
310
311/// Error surface of the [`ArtifactStore`] port.
312#[derive(Debug, thiserror::Error)]
313#[non_exhaustive]
314pub enum StoreError {
315 /// Persisting the artifact failed; carries the human-readable cause.
316 #[error("persist failed: {0}")]
317 Persist(String),
318 /// Reading an artifact back failed; carries the human-readable cause.
319 #[error("read failed: {0}")]
320 Read(String),
321}
322
323/// Persistence port for tool artifacts — where oversized tool outputs are
324/// spilled and read back. Callers persist raw bytes plus an [`ArtifactHint`]
325/// and receive an [`ArtifactRef`] to embed in the result; concrete stores
326/// are host concerns.
327#[async_trait]
328pub trait ArtifactStore: Send + Sync {
329 /// Stores `data`, tagged with `hint`, and returns the [`ArtifactRef`]
330 /// describing the persisted artifact.
331 async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
332 /// Reads back the bytes stored under `id`; an optional byte range bounds
333 /// the read.
334 async fn read(
335 &self,
336 id: &str,
337 range: Option<std::ops::Range<u64>>,
338 ) -> Result<Vec<u8>, StoreError>;
339}
340
341/// The tool port: one callable tool the model can invoke. Implementations
342/// live outside the kernel; the driver's executor dispatches them. A tool
343/// returns only its recorded result. Handling unknown outcomes and retaining
344/// output belong to the execution consumer, not tool declarations.
345///
346/// # Requirements on `execute`
347///
348/// An executor may poll every call of one batch on a single task, with
349/// nothing spawned. An implementation therefore:
350///
351/// - must not block the thread. Blocking or CPU-heavy work runs on a
352/// blocking thread (for example `tokio::task::spawn_blocking`) and the
353/// tool awaits it;
354/// - must watch its [`CallControl`] itself. A turn stop — cancellation or
355/// the turn deadline — drops the call future: the executor stops polling,
356/// a started call settles as
357/// [`ToolResultStatus::UnknownOutcome`](crate::context::tool_data::ToolResultStatus::UnknownOutcome).
358/// Once the executor observes the stop it polls the call no further, so a
359/// value returned after that is not recorded. Returning promptly on
360/// cancellation releases the resources the future still owns; it does not
361/// make the result observed;
362/// - must return, cleanup included, by its effective call deadline to
363/// report
364/// [`ToolResultStatus::TimedOut`](crate::context::tool_data::ToolResultStatus::TimedOut)
365/// or
366/// [`ToolResultStatus::Cancelled`](crate::context::tool_data::ToolResultStatus::Cancelled).
367/// The executor enforces a call deadline with `timeout_at`, which polls the
368/// call before its own timer and drops the future once the deadline has
369/// expired. A tool that races the same deadline and returns without
370/// awaiting anything further is therefore recorded. A tool that awaits
371/// cleanup after it stops has to stop early enough for that cleanup to
372/// finish before the deadline; otherwise the future is dropped mid-cleanup
373/// and the call settles as `UnknownOutcome`.
374///
375/// Dropping the future runs on the executor's task, so [`Drop`] must not
376/// block and must be idempotent. A future that starts external work — a
377/// spawned task, a child process, a remote operation — cleans it up in
378/// [`Drop`].
379///
380/// For a tool that meets these, a stop takes effect at its next yield point.
381/// A tool that holds the thread also holds its sibling calls and the
382/// executor's own stop and timeout checks, so nothing is guaranteed for it:
383/// not cancellation, not the deadline, not a per-call timeout.
384///
385/// Calls of one batch are concurrent, not parallel, and their number is not
386/// bounded. A tool that needs a limit shares a semaphore across its calls.
387#[async_trait]
388pub trait Tool: Send + Sync {
389 /// The model-facing [`ToolDefinition`] for this tool.
390 fn definition(&self) -> ToolDefinition;
391 /// Non-persisted metadata carried beside [`Tool::definition`]. An executor
392 /// reads it once when binding the tool and exposes it to tool processors
393 /// through [`crate::ProcessorContext::tool`] and
394 /// [`crate::ProcessorContext::tool_metadata`]. The default is empty.
395 fn metadata(&self) -> ToolMetadata {
396 ToolMetadata::default()
397 }
398 /// Runs one call under the call's [`CallControl`], returning the
399 /// recorded result. `store` is the host's [`ArtifactStore`] when one is
400 /// configured: a tool that produces media or oversized output persists
401 /// the bytes there and returns a reference; a tool that does not need
402 /// storage ignores it.
403 async fn execute(
404 &self,
405 ctx: &ToolCallContext,
406 control: &CallControl,
407 store: Option<&dyn ArtifactStore>,
408 ) -> ToolResultPayload;
409}