1use std::collections::HashMap;
15use std::sync::Arc;
16
17use async_trait::async_trait;
18use serde_json::{Value, json};
19
20use crate::types::{AgentError, AgentResult};
21
22use super::{Content, Tool, ToolActivation, ToolContext, ToolExposure};
23
24pub struct ActivateTool {
26 activation: ToolActivation,
27 candidates: HashMap<String, (ToolExposure, Value)>,
29 late: std::sync::OnceLock<Arc<std::sync::RwLock<HashMap<String, Value>>>>,
36}
37
38impl ActivateTool {
39 pub fn new(
42 activation: ToolActivation,
43 candidates: Vec<(String, ToolExposure, Value)>,
44 ) -> Arc<Self> {
45 Arc::new(Self {
46 activation,
47 candidates: candidates
48 .into_iter()
49 .map(|(name, exposure, def)| (name, (exposure, def)))
50 .collect(),
51 late: std::sync::OnceLock::new(),
52 })
53 }
54
55 pub fn set_deferred_defs(&self, defs: Arc<std::sync::RwLock<HashMap<String, Value>>>) {
59 let _ = self.late.set(defs);
60 }
61
62 fn lookup(&self, name: &str) -> Option<(ToolExposure, Value)> {
65 if let Some(hit) = self.candidates.get(name) {
66 return Some(hit.clone());
67 }
68 let defs = self.late.get()?;
69 let def = defs
70 .read()
71 .expect("deferred-defs lock poisoned")
72 .get(name)
73 .cloned()?;
74 Some((ToolExposure::Deferred, def))
75 }
76
77 fn candidate_names(&self) -> Vec<String> {
80 let mut names: Vec<String> = self.candidates.keys().cloned().collect();
81 if let Some(defs) = self.late.get() {
82 let defs = defs.read().expect("deferred-defs lock poisoned");
83 for name in defs.keys() {
84 if !names.contains(name) {
85 names.push(name.clone());
86 }
87 }
88 }
89 names.sort_unstable();
90 names
91 }
92}
93
94#[async_trait]
95impl Tool for ActivateTool {
96 fn name(&self) -> &'static str {
97 "activate_tool"
98 }
99
100 fn description(&self) -> &'static str {
101 "Mount a tool whose schema is not loaded yet.\n\n\
102 Some tools are named in the system message but their schemas are NOT loaded — until\n\
103 they are, only the name is known, and calling one fails: there is no parameter\n\
104 schema to call it with. This tool loads it.\n\
105 Pass the tool's name exactly as the roster spells it. The result is that tool's full\n\
106 description and argument schema, and from your next turn on it is callable exactly\n\
107 like any tool already in your list — and it stays mounted for the rest of the\n\
108 session, so open it once and use it as often as you need.\n\
109 A name that is not mountable comes back with the ones that are. A name that is\n\
110 already mounted comes back saying so. Do not open a capability on the chance it\n\
111 comes in handy: every mounted tool is sent on every later request."
112 }
113
114 fn schema(&self) -> Value {
115 json!({
116 "type": "object",
117 "properties": {
118 "name": {
119 "type": "string",
120 "description": "The tool name exactly as the roster spells it."
121 }
122 },
123 "required": ["name"],
124 "additionalProperties": false,
125 })
126 }
127
128 fn exposure(&self) -> ToolExposure {
131 ToolExposure::Direct
132 }
133
134 async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
135 let name = args
136 .get("name")
137 .and_then(Value::as_str)
138 .map(str::trim)
139 .filter(|s| !s.is_empty())
140 .ok_or_else(|| AgentError::ToolArgsInvalid {
141 name: self.name().to_string(),
142 raw: "missing field `name` — pass the tool name exactly as the roster spells it"
143 .to_string(),
144 })?;
145
146 let Some((exposure, definition)) = self.lookup(name) else {
147 return Ok(vec![Content::text(format!(
148 "No tool named `{name}` is mountable. Mountable names: {}.",
149 self.candidate_names().join(", ")
150 ))]);
151 };
152
153 match exposure {
154 ToolExposure::Hidden => Ok(vec![Content::text(format!(
155 "`{name}` is internal and is not mountable. It is not in the roster."
156 ))]),
157 ToolExposure::Direct => Ok(vec![Content::text(format!(
158 "`{name}` is already mounted — call it directly."
159 ))]),
160 ToolExposure::Deferred => {
161 let first_open = self.activation.activate(name);
162 let status = if first_open {
163 "mounted"
164 } else {
165 "already mounted"
166 };
167 Ok(vec![Content::text(format!(
168 "`{name}` {status}. Call it from the next turn on, with these arguments:\n{}",
169 serde_json::to_string_pretty(&definition).unwrap_or_default()
170 ))])
171 }
172 }
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use std::sync::atomic::AtomicBool;
179
180 use super::*;
181 use crate::engine::EventBus;
182 use crate::tool::ExecClock;
183 use crate::types::SessionId;
184 use serde_json::json;
185
186 fn test_context() -> ToolContext {
187 let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
188 ToolContext {
189 session_id: SessionId::new(0),
190 user_event_tx: tx,
191 llm_client: None,
192 session_store: None,
193 language: crate::types::Language::En,
194 cancel_token: tokio_util::sync::CancellationToken::new(),
195 max_output_chars: None,
196 exec_clock: ExecClock::default(),
197 waiting_for_human: Arc::new(AtomicBool::new(false)),
198 event_bus: EventBus::new(1),
199 }
200 }
201
202 fn registry_free_tool() -> (ActivateTool, ToolActivation) {
203 let activation = ToolActivation::new();
204 let tool = ActivateTool::new(
205 activation.clone(),
206 vec![
207 (
208 "browser_navigate".to_string(),
209 ToolExposure::Deferred,
210 json!({
211 "name": "browser_navigate",
212 "description": "Open a URL in the browser.",
213 "parameters": {"type": "object", "properties": {"url": {"type": "string"}}},
214 }),
215 ),
216 (
217 "always_here".to_string(),
218 ToolExposure::Direct,
219 json!({"name": "always_here"}),
220 ),
221 (
222 "internal".to_string(),
223 ToolExposure::Hidden,
224 json!({"name": "internal"}),
225 ),
226 ],
227 );
228 let tool = Arc::try_unwrap(tool).ok().expect("single owner in tests");
230 (tool, activation)
231 }
232
233 async fn call(tool: &ActivateTool, args: Value) -> String {
234 let ctx = test_context();
235 let out = tool.call(&args, &ctx).await.expect("call succeeds");
236 out.iter()
237 .map(|c| match c {
238 Content::Text { text } => text.clone(),
239 _ => String::new(),
240 })
241 .collect()
242 }
243
244 #[tokio::test]
250 async fn opening_a_tool_mounts_it_and_hands_back_its_shape() {
251 let (tool, activation) = registry_free_tool();
252 let out = call(&tool, json!({"name": "browser_navigate"})).await;
253 assert!(
254 activation.is_active("browser_navigate"),
255 "opening must stick for the session"
256 );
257 assert!(out.contains("mounted"), "say what happened: {out}");
258 assert!(
259 out.contains("\"url\""),
260 "and hand back the real arguments, not just the name: {out}"
261 );
262 }
263
264 #[tokio::test]
270 async fn an_unknown_name_is_refused_with_the_real_ones() {
271 let (tool, _activation) = registry_free_tool();
272 let out = call(&tool, json!({"name": "browser_nav"})).await;
273 assert!(out.contains("No tool named `browser_nav`"), "{out}");
274 assert!(
275 out.contains("browser_navigate"),
276 "the answer must name the tool it meant: {out}"
277 );
278 }
279
280 #[tokio::test]
285 async fn an_internal_tool_cannot_be_mounted() {
286 let (tool, activation) = registry_free_tool();
287 let out = call(&tool, json!({"name": "internal"})).await;
288 assert!(out.contains("not mountable"), "{out}");
289 assert!(!activation.is_active("internal"), "and nothing was opened");
290 }
291
292 #[tokio::test]
298 async fn opening_twice_is_reported_as_already_mounted() {
299 let (tool, _activation) = registry_free_tool();
300 call(&tool, json!({"name": "browser_navigate"})).await;
301 let out = call(&tool, json!({"name": "browser_navigate"})).await;
302 assert!(out.contains("already mounted"), "{out}");
303 }
304
305 #[tokio::test]
310 async fn an_already_mounted_tool_is_said_to_be() {
311 let (tool, activation) = registry_free_tool();
312 let out = call(&tool, json!({"name": "always_here"})).await;
313 assert!(out.contains("already mounted"), "{out}");
314 assert!(
315 !activation.is_active("always_here"),
316 "a Direct tool needs no activation entry"
317 );
318 }
319
320 #[tokio::test]
329 async fn a_late_registered_deferred_tool_is_openable() {
330 let (tool, activation) = registry_free_tool();
331 let catalog: Arc<std::sync::RwLock<HashMap<String, Value>>> = Default::default();
332 catalog.write().unwrap().insert(
333 "close_agent".to_string(),
334 json!({"name": "close_agent", "description": "Close a sub-agent."}),
335 );
336 tool.set_deferred_defs(catalog);
337 let out = call(&tool, json!({"name": "close_agent"})).await;
338 assert!(
339 activation.is_active("close_agent"),
340 "opening must stick for the session: {out}"
341 );
342 assert!(out.contains("mounted"), "{out}");
343 assert!(
344 out.contains("Close a sub-agent"),
345 "hand back the real definition, not just the name: {out}"
346 );
347 }
348
349 #[tokio::test]
354 async fn a_missing_name_says_what_is_missing() {
355 let (tool, _activation) = registry_free_tool();
356 let err = tool.call(&json!({}), &test_context()).await;
357 let msg = format!("{:?}", err.expect_err("no name is an error"));
358 assert!(
359 msg.contains("`name`"),
360 "the error must name the field: {msg}"
361 );
362 }
363}