Skip to main content

aidaemon_core/
tool_loading.rs

1//! Deferred tools: registered with the agent and callable, but their schemas
2//! stay out of the model request until the run loads them.
3//!
4//! A tool registered with [`crate::AgentBuilder::deferred_tool_arc`] is
5//! listed by name and one line in the description of the built-in
6//! [`LOAD_TOOLS`] tool. Calling `load_tools` (or calling a deferred tool
7//! directly) adds it to the agent's [`LoadedTools`], and its full schema is
8//! sent from the next model request on. The host may share one
9//! `LoadedTools` across a session's turns, so what was loaded once stays
10//! loaded and the request's tool block stays byte-stable.
11
12use std::collections::BTreeSet;
13use std::sync::{Arc, RwLock};
14
15use async_trait::async_trait;
16use serde_json::{Value, json};
17
18use crate::CallEffects;
19use crate::provider::ToolSpec;
20use crate::tool::{Tool, ToolAnnotations, ToolContext, ToolOutput, ToolResult};
21
22/// The built-in tool that loads deferred tools.
23pub const LOAD_TOOLS: &str = "load_tools";
24
25/// The deferred tools whose schemas the model is sent. Cheap to clone;
26/// clones share the set.
27#[derive(Debug, Clone, Default)]
28pub struct LoadedTools(Arc<RwLock<BTreeSet<String>>>);
29
30impl LoadedTools {
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    pub fn contains(&self, name: &str) -> bool {
36        self.0
37            .read()
38            .unwrap_or_else(std::sync::PoisonError::into_inner)
39            .contains(name)
40    }
41
42    /// Mark `name` loaded. True when it was not loaded before.
43    pub fn load(&self, name: &str) -> bool {
44        self.0
45            .write()
46            .unwrap_or_else(std::sync::PoisonError::into_inner)
47            .insert(name.to_string())
48    }
49
50    /// Every loaded name, sorted.
51    pub fn names(&self) -> Vec<String> {
52        self.0
53            .read()
54            .unwrap_or_else(std::sync::PoisonError::into_inner)
55            .iter()
56            .cloned()
57            .collect()
58    }
59}
60
61/// One deferred tool as the index lists it.
62#[derive(Debug, Clone, PartialEq)]
63pub(crate) struct DeferredEntry {
64    pub name: String,
65    pub summary: String,
66}
67
68/// The first sentence of a description, capped: the index's one line.
69pub(crate) fn one_line(description: &str) -> String {
70    let first = description
71        .split_terminator(['\n'])
72        .next()
73        .unwrap_or_default()
74        .trim();
75    let sentence = match first.find(". ") {
76        Some(end) => &first[..=end],
77        None => first,
78    };
79    let sentence = sentence.trim();
80    if sentence.chars().count() <= 120 {
81        sentence.to_string()
82    } else {
83        let cut: String = sentence.chars().take(117).collect();
84        format!("{}...", cut.trim_end())
85    }
86}
87
88/// `load_tools`: adds deferred tools to the run. Its description is the
89/// index of every deferred tool, name-sorted.
90pub(crate) struct LoadToolsTool {
91    entries: Vec<DeferredEntry>,
92    loaded: LoadedTools,
93}
94
95impl LoadToolsTool {
96    pub(crate) fn new(mut entries: Vec<DeferredEntry>, loaded: LoadedTools) -> Self {
97        entries.sort_by(|a, b| a.name.cmp(&b.name));
98        Self { entries, loaded }
99    }
100
101    fn description(&self) -> String {
102        let mut text = String::from(
103            "Load more tools. These tools exist but their parameters are not shown yet; \
104             load the ones a step needs by name (or by part of a name), then call \
105             them. Loaded tools stay available.",
106        );
107        for entry in &self.entries {
108            text.push_str(&format!("\n- {}: {}", entry.name, entry.summary));
109        }
110        text
111    }
112
113    /// Entries whose name contains a fragment of `query`. Names are
114    /// machine identifiers from the index the model reads, so a fragment
115    /// ("config", "browser") is matched against them only; descriptions are
116    /// prose and never decide what loads.
117    fn matching(&self, query: &str) -> Vec<&DeferredEntry> {
118        let fragments: Vec<String> = query
119            .split(|c: char| !(c.is_alphanumeric() || c == '_'))
120            .filter(|w| w.len() > 1)
121            .map(str::to_lowercase)
122            .collect();
123        self.entries
124            .iter()
125            .filter(|entry| {
126                let name = entry.name.to_lowercase();
127                fragments.iter().any(|f| name.contains(f.as_str()))
128            })
129            .take(5)
130            .collect()
131    }
132}
133
134#[async_trait]
135impl Tool for LoadToolsTool {
136    fn spec(&self) -> ToolSpec {
137        ToolSpec {
138            name: LOAD_TOOLS.to_string(),
139            description: self.description(),
140            parameters: json!({
141                "type": "object",
142                "properties": {
143                    "names": {
144                        "type": "array",
145                        "items": {"type": "string"},
146                        "description": "Tool names from the list to load"
147                    },
148                    "query": {
149                        "type": "string",
150                        "description": "Part of a tool name from the list (e.g. \"config\"), when the exact name is unsure"
151                    }
152                },
153                "additionalProperties": false
154            }),
155        }
156    }
157
158    /// Changes only which schemas the next request carries.
159    fn annotations(&self) -> ToolAnnotations {
160        ToolAnnotations {
161            idempotent: true,
162            ..ToolAnnotations::READ_ONLY
163        }
164    }
165
166    fn effects(&self, _arguments: &Value) -> CallEffects {
167        CallEffects::none()
168    }
169
170    fn source_trust(&self, _arguments: &Value) -> crate::tool::SourceTrust {
171        crate::tool::SourceTrust::Trusted
172    }
173
174    async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
175        let mut wanted: Vec<String> = arguments
176            .get("names")
177            .and_then(Value::as_array)
178            .map(|names| {
179                names
180                    .iter()
181                    .filter_map(Value::as_str)
182                    .map(|name| name.trim().to_string())
183                    .collect()
184            })
185            .unwrap_or_default();
186        let query = arguments
187            .get("query")
188            .and_then(Value::as_str)
189            .unwrap_or_default();
190        if !query.trim().is_empty() {
191            wanted.extend(self.matching(query).into_iter().map(|e| e.name.clone()));
192        }
193        if wanted.is_empty() {
194            return Ok(ToolOutput::error(
195                "Nothing to load: pass `names` from the list in this tool's description, or a \
196                 `query`.",
197            ));
198        }
199        let mut loaded = Vec::new();
200        let mut already = Vec::new();
201        let mut unknown = Vec::new();
202        for name in wanted {
203            if !self.entries.iter().any(|entry| entry.name == name) {
204                if !unknown.contains(&name) {
205                    unknown.push(name);
206                }
207            } else if self.loaded.load(&name) {
208                loaded.push(name);
209            } else if !already.contains(&name) && !loaded.contains(&name) {
210                already.push(name);
211            }
212        }
213        let mut lines = Vec::new();
214        if !loaded.is_empty() {
215            lines.push(format!(
216                "Loaded: {}. Their parameters are available from your next step.",
217                loaded.join(", ")
218            ));
219        }
220        if !already.is_empty() {
221            lines.push(format!("Already loaded: {}.", already.join(", ")));
222        }
223        if !unknown.is_empty() {
224            lines.push(format!(
225                "Not a deferred tool: {} (tools already listed can be called directly).",
226                unknown.join(", ")
227            ));
228        }
229        let output = ToolOutput::text(lines.join("\n"));
230        Ok(if loaded.is_empty() && already.is_empty() {
231            ToolOutput {
232                is_error: true,
233                ..output
234            }
235        } else {
236            output
237        })
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    fn tool() -> (LoadToolsTool, LoadedTools) {
246        let loaded = LoadedTools::new();
247        let entries = vec![
248            DeferredEntry {
249                name: "browser".into(),
250                summary: "Drive a web browser.".into(),
251            },
252            DeferredEntry {
253                name: "manage_config".into(),
254                summary: "Read and change the daemon's config.".into(),
255            },
256        ];
257        (LoadToolsTool::new(entries, loaded.clone()), loaded)
258    }
259
260    #[test]
261    fn the_description_indexes_every_deferred_tool_by_name() {
262        let (tool, _) = tool();
263        let description = tool.spec().description;
264        let browser = description.find("- browser:").unwrap();
265        let config = description.find("- manage_config:").unwrap();
266        assert!(browser < config, "{description}");
267    }
268
269    #[tokio::test]
270    async fn names_and_queries_load_tools() {
271        let (tool, loaded) = tool();
272        let ctx = ToolContext::new("test:synthetic-session", "call-1");
273        let out = tool
274            .call(json!({"names": ["browser"]}), &ctx)
275            .await
276            .unwrap();
277        assert!(!out.is_error && out.content.contains("Loaded: browser"));
278        assert!(loaded.contains("browser"));
279        let out = tool.call(json!({"query": "config"}), &ctx).await.unwrap();
280        assert!(
281            out.content.contains("Loaded: manage_config"),
282            "{}",
283            out.content
284        );
285        let out = tool
286            .call(json!({"names": ["browser"]}), &ctx)
287            .await
288            .unwrap();
289        assert!(out.content.contains("Already loaded: browser"));
290        let out = tool.call(json!({"names": ["nope"]}), &ctx).await.unwrap();
291        assert!(out.is_error && out.content.contains("Not a deferred tool: nope"));
292    }
293
294    #[tokio::test]
295    async fn a_query_matches_tool_names_never_descriptions() {
296        let (tool, loaded) = tool();
297        let ctx = ToolContext::new("test:synthetic-session", "call-1");
298        // "web" appears only in browser's description: nothing loads.
299        let out = tool.call(json!({"query": "web"}), &ctx).await.unwrap();
300        assert!(out.is_error, "{}", out.content);
301        assert!(!loaded.contains("browser"));
302        let out = tool.call(json!({"query": "brows"}), &ctx).await.unwrap();
303        assert!(out.content.contains("Loaded: browser"), "{}", out.content);
304    }
305
306    #[test]
307    fn one_line_keeps_the_first_sentence() {
308        assert_eq!(one_line("Fetch a page. Then more."), "Fetch a page.");
309        assert_eq!(one_line("No period"), "No period");
310        assert!(one_line(&"x".repeat(300)).ends_with("..."));
311    }
312}