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