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)]
20pub struct ToolDefinition {
21 /// The name the model uses to invoke the tool.
22 pub name: String,
23 /// Short summary of what the tool does, shown to the model.
24 pub description: String,
25 /// Schema of the arguments the tool accepts, embedded verbatim in the
26 /// rendered request.
27 pub parameters: serde_json::Value,
28}
29
30/// Identity of one tool dispatch, handed to [`Tool::execute`].
31#[derive(Debug, Clone)]
32pub struct ToolCallContext {
33 /// The declaration block whose result this dispatch produces.
34 pub call_block_id: BlockId,
35 /// The effective input after any pre-processing edits.
36 pub input: ToolCallPayload,
37 /// Notes added before execution. `ToolBatch::resolve_at` prepends these
38 /// to the returned result's notes; tool implementations should return
39 /// only notes they add and must not copy this field into the result.
40 pub result_notes: Vec<TextPayload>,
41}
42
43impl ToolCallContext {
44 /// Builds execution material from a committed declaration.
45 pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
46 Self {
47 call_block_id,
48 input: declaration.clone(),
49 result_notes: Vec::new(),
50 }
51 }
52}
53
54/// Provenance a caller attaches to bytes handed to [`ArtifactStore::persist`],
55/// so the store can label what it receives.
56pub struct ArtifactHint {
57 /// The tool whose output produced the bytes.
58 pub tool_name: String,
59 /// The tool call the bytes belong to.
60 pub call_block_id: BlockId,
61 /// The [`ArtifactKind`] classification of the bytes.
62 pub kind: ArtifactKind,
63}
64
65/// Error surface of the [`ArtifactStore`] port.
66#[derive(Debug, thiserror::Error)]
67pub enum StoreError {
68 /// Persisting the artifact failed; carries the human-readable cause.
69 #[error("persist failed: {0}")]
70 Persist(String),
71 /// Reading an artifact back failed; carries the human-readable cause.
72 #[error("read failed: {0}")]
73 Read(String),
74}
75
76/// Persistence port for tool artifacts — where oversized tool outputs are
77/// spilled and read back. Callers persist raw bytes plus an [`ArtifactHint`]
78/// and receive an [`ArtifactRef`] to embed in the result; concrete stores
79/// are host concerns.
80#[async_trait]
81pub trait ArtifactStore: Send + Sync {
82 /// Stores `data`, tagged with `hint`, and returns the [`ArtifactRef`]
83 /// describing the persisted artifact.
84 async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
85 /// Reads back the bytes stored under `id`; an optional byte range bounds
86 /// the read.
87 async fn read(
88 &self,
89 id: &str,
90 range: Option<std::ops::Range<u64>>,
91 ) -> Result<Vec<u8>, StoreError>;
92}
93
94/// The tool port: one callable tool the model can invoke. Implementations
95/// live outside the kernel; the driver's executor dispatches them. A tool
96/// returns only its recorded result. Handling unknown outcomes and retaining
97/// output belong to the execution consumer, not tool declarations.
98#[async_trait]
99pub trait Tool: Send + Sync {
100 /// The model-facing [`ToolDefinition`] for this tool.
101 fn definition(&self) -> ToolDefinition;
102 /// Runs one call under the call's [`CallControl`], returning the
103 /// recorded result.
104 async fn execute(&self, ctx: &ToolCallContext, control: &CallControl) -> ToolResultPayload;
105 /// Extension point for tools that persist artifacts: receives the host's
106 /// [`ArtifactStore`] when one is configured (`None` otherwise). The
107 /// default ignores the store and delegates to [`Tool::execute`].
108 async fn execute_with_store(
109 &self,
110 ctx: &ToolCallContext,
111 control: &CallControl,
112 store: Option<&dyn ArtifactStore>,
113 ) -> ToolResultPayload {
114 let _ = store;
115 self.execute(ctx, control).await
116 }
117}