Skip to main content

ed_agent/
tool.rs

1//! Host-defined tools and the policies that guard them.
2
3use crate::maybe::{MaybeSend, MaybeSync};
4use serde::{Deserialize, Serialize};
5
6/// A tool the model may ask the host application to run.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct AgentToolDefinition {
9    pub name: String,
10    pub description: String,
11    /// JSON Schema encoded as a string.
12    pub parameters_schema: String,
13    pub risk: ToolRisk,
14}
15
16impl AgentToolDefinition {
17    pub fn read_only(
18        name: impl Into<String>,
19        description: impl Into<String>,
20        parameters_schema: impl Into<String>,
21    ) -> Self {
22        Self {
23            name: name.into(),
24            description: description.into(),
25            parameters_schema: parameters_schema.into(),
26            risk: ToolRisk::ReadOnly,
27        }
28    }
29
30    pub fn mutating(
31        name: impl Into<String>,
32        description: impl Into<String>,
33        parameters_schema: impl Into<String>,
34    ) -> Self {
35        Self {
36            name: name.into(),
37            description: description.into(),
38            parameters_schema: parameters_schema.into(),
39            risk: ToolRisk::Mutating,
40        }
41    }
42
43    pub(crate) fn validate(&self) -> Result<(), AgentError> {
44        let mut chars = self.name.chars();
45        let valid_first = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
46        let valid_rest = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
47        if !valid_first || !valid_rest || self.name.len() > 64 {
48            return Err(AgentError::InvalidTool {
49                reason: format!(
50                    "tool name {:?} must start with an ASCII letter and contain only letters, numbers, '_' or '-' (maximum 64 bytes)",
51                    self.name
52                ),
53            });
54        }
55        if self.description.trim().is_empty() {
56            return Err(AgentError::InvalidTool {
57                reason: format!("tool {:?} needs a description", self.name),
58            });
59        }
60        let schema: serde_json::Value =
61            serde_json::from_str(&self.parameters_schema).map_err(|error| {
62                AgentError::InvalidTool {
63                    reason: format!("tool {:?} has invalid JSON Schema: {error}", self.name),
64                }
65            })?;
66        if schema.get("type").and_then(serde_json::Value::as_str) != Some("object") {
67            return Err(AgentError::InvalidTool {
68                reason: format!("tool {:?} schema must have type object", self.name),
69            });
70        }
71        Ok(())
72    }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76pub enum ToolRisk {
77    ReadOnly,
78    Mutating,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct ToolCall {
83    pub id: String,
84    pub name: String,
85    pub arguments: String,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89pub struct ToolExecutionResult {
90    pub tool_call_id: String,
91    pub content: String,
92    pub is_error: bool,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct ApprovalRequest {
97    pub call: ToolCall,
98    pub risk: ToolRisk,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
102pub enum ApprovalDecision {
103    AllowOnce,
104    AllowForSession,
105    Deny,
106}
107
108#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
109#[cfg_attr(
110    not(all(target_arch = "wasm32", target_os = "unknown")),
111    async_trait::async_trait
112)]
113pub trait ToolExecutor: MaybeSend + MaybeSync + 'static {
114    async fn execute(&self, tool_name: &str, arguments: &str) -> Result<String, String>;
115}
116
117#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
118#[cfg_attr(
119    not(all(target_arch = "wasm32", target_os = "unknown")),
120    async_trait::async_trait
121)]
122pub trait ApprovalHandler: MaybeSend + MaybeSync + 'static {
123    async fn approve(&self, request: ApprovalRequest) -> ApprovalDecision;
124}
125
126#[derive(Debug, Default)]
127pub struct RejectingExecutor;
128
129#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
130#[cfg_attr(
131    not(all(target_arch = "wasm32", target_os = "unknown")),
132    async_trait::async_trait
133)]
134impl ToolExecutor for RejectingExecutor {
135    async fn execute(&self, tool_name: &str, _: &str) -> Result<String, String> {
136        Err(format!("no executor is registered for tool {tool_name:?}"))
137    }
138}
139
140#[derive(Debug, Default)]
141pub struct DenyApprovals;
142
143#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
144#[cfg_attr(
145    not(all(target_arch = "wasm32", target_os = "unknown")),
146    async_trait::async_trait
147)]
148impl ApprovalHandler for DenyApprovals {
149    async fn approve(&self, _: ApprovalRequest) -> ApprovalDecision {
150        ApprovalDecision::Deny
151    }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155pub struct AgentConfig {
156    pub max_tool_rounds: u8,
157    pub max_tool_output_chars: usize,
158}
159
160impl Default for AgentConfig {
161    fn default() -> Self {
162        Self {
163            max_tool_rounds: 8,
164            max_tool_output_chars: 10_000,
165        }
166    }
167}
168
169impl AgentConfig {
170    pub(crate) fn validated(self) -> Self {
171        Self {
172            max_tool_rounds: self.max_tool_rounds.clamp(1, 24),
173            max_tool_output_chars: self.max_tool_output_chars.max(1),
174        }
175    }
176
177    /// Whether another tool round may run, given how many already have.
178    ///
179    /// Asked twice per round, and the pair is what makes the loop terminate:
180    /// once to decide whether to offer tools to the model again, and once at
181    /// the top of the next round to decide whether to run it at all. If only
182    /// the first check existed, a model that requested tools it was never
183    /// offered would keep the loop alive indefinitely.
184    pub(crate) fn allows_round(&self, rounds: u8) -> bool {
185        rounds < self.max_tool_rounds
186    }
187}
188
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190pub struct AgentReply {
191    pub text: String,
192    pub duration_seconds: f64,
193    pub duration: String,
194    pub tool_rounds: u8,
195}
196
197#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
198pub enum AgentError {
199    #[error("invalid tool: {reason}")]
200    InvalidTool { reason: String },
201    #[error("a tool named {name:?} is already registered")]
202    DuplicateTool { name: String },
203    #[error("the loaded model does not support tool calling")]
204    UnsupportedModel,
205    #[error("the agent turn was cancelled")]
206    Cancelled,
207    #[error("the model returned an empty final reply")]
208    EmptyReply,
209    #[error("the agent stopped after {rounds} tool rounds without a final reply")]
210    ToolRoundsExhausted { rounds: u8 },
211    #[error("inference failed: {reason}")]
212    Inference { reason: String },
213}
214
215pub(crate) fn truncate_output(value: String, max_chars: usize) -> String {
216    if value.chars().count() <= max_chars {
217        return value;
218    }
219    let mut truncated: String = value.chars().take(max_chars).collect();
220    truncated.push_str("\n[tool output truncated by Ed]");
221    truncated
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn validates_tool_names_and_object_schemas() {
230        AgentToolDefinition::read_only("clock", "Read the clock", r#"{"type":"object"}"#)
231            .validate()
232            .unwrap();
233        assert!(
234            AgentToolDefinition::read_only("bad name", "Read", r#"{"type":"object"}"#)
235                .validate()
236                .is_err()
237        );
238        assert!(
239            AgentToolDefinition::read_only("clock", "Read", r#"{"type":"array"}"#)
240                .validate()
241                .is_err()
242        );
243    }
244
245    #[test]
246    fn a_validated_budget_always_allows_at_least_one_round() {
247        // A zero budget would mean registering tools quietly disabled them:
248        // the model would be offered tools it could never be allowed to use.
249        let config = AgentConfig {
250            max_tool_rounds: 0,
251            max_tool_output_chars: 0,
252        }
253        .validated();
254
255        assert!(config.allows_round(0));
256        assert!(!config.allows_round(1));
257        assert_eq!(config.max_tool_output_chars, 1);
258    }
259
260    #[test]
261    fn the_round_budget_closes_at_the_limit_and_stays_closed() {
262        let config = AgentConfig {
263            max_tool_rounds: 3,
264            max_tool_output_chars: 100,
265        }
266        .validated();
267
268        assert!(config.allows_round(2));
269        assert!(!config.allows_round(3));
270        // Past the limit too: `rounds` is only ever compared, never trusted to
271        // land exactly on the boundary.
272        assert!(!config.allows_round(u8::MAX));
273    }
274
275    #[test]
276    fn truncation_is_character_safe_and_explicit() {
277        assert_eq!(
278            truncate_output("héllo".into(), 2),
279            "hé\n[tool output truncated by Ed]"
280        );
281    }
282}