1use std::collections::HashMap;
2use std::future::Future;
3use std::pin::Pin;
4
5use tokio_util::sync::CancellationToken;
6
7use crate::error::RuntimeError;
8use crate::value::Value;
9
10pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
15
16pub type ToolResult = Result<Value, RuntimeError>;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Tier {
20 Zero,
21 One,
22 Two,
23 Three,
24 Four,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
28pub enum ApprovalLevel {
29 Auto,
30 Approve,
31 Dangerous,
32}
33
34impl ApprovalLevel {
35 pub fn from_tier(tier: Tier) -> Self {
36 match tier {
37 Tier::Zero => ApprovalLevel::Auto,
38 Tier::One | Tier::Two => ApprovalLevel::Approve,
39 Tier::Three | Tier::Four => ApprovalLevel::Dangerous,
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum CancelBehavior {
46 AbortSafe,
47 Revertible,
48 Atomic,
49 Irreversible,
50}
51
52#[derive(Debug, Default, Clone)]
53pub struct ToolArgs {
54 pub positional: Vec<Value>,
55 pub named: Vec<(String, Value)>,
56}
57
58impl ToolArgs {
59 pub fn positional(&self, index: usize) -> Result<&Value, RuntimeError> {
60 self.positional
61 .get(index)
62 .ok_or_else(|| RuntimeError::MissingArg(format!("positional[{index}]")))
63 }
64
65 pub fn named(&self, name: &str) -> Option<&Value> {
66 self.named.iter().find(|(k, _)| k == name).map(|(_, v)| v)
67 }
68}
69
70#[derive(Clone, Default)]
71pub struct ToolCtx {
72 pub cancel: CancellationToken,
73 pub turn_id: Option<crate::event::TurnId>,
74 pub flow_run_id: Option<crate::event::FlowRunId>,
75 pub event_seq: Option<u64>,
76 pub prompt_resolver: Option<std::sync::Arc<dyn crate::rendezvous::PromptResolver>>,
77 pub registry: Option<std::sync::Arc<ToolRegistry>>,
78 pub sandbox: Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>,
79 pub events: Option<crate::event::EventSink>,
80 pub stdout_broadcast: Option<tokio::sync::broadcast::Sender<String>>,
81 pub session_messages: Option<std::sync::Arc<Vec<crate::message::Message>>>,
82 pub session_messages_handle:
83 Option<std::sync::Arc<std::sync::Mutex<Vec<crate::message::Message>>>>,
84 pub session_runtime: Option<std::sync::Arc<crate::session::Session>>,
85 pub compact_lock_handle: Option<std::sync::Arc<tokio::sync::Mutex<()>>>,
86 pub current_node_id: Option<String>,
87 pub stream_tx: Option<tokio::sync::broadcast::Sender<crate::stream::StreamFrame>>,
88 pub read_files:
89 Option<std::sync::Arc<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>>>,
90 pub approval: Option<std::sync::Arc<crate::session::ApprovalRegistry>>,
91 pub forms: Option<std::sync::Arc<crate::session::FormRegistry>>,
92 pub providers: Option<std::sync::Arc<crate::provider::ProviderRegistry>>,
93 pub session_dir: Option<std::path::PathBuf>,
94 pub data_root: Option<std::path::PathBuf>,
95 pub project_index: Option<std::sync::Arc<crate::index::AnchorIndex>>,
96 pub fs_access: crate::fs_access::FsAccessPolicy,
97 pub lifecycle_fire_tx:
98 Option<tokio::sync::mpsc::UnboundedSender<atman_dsl::ast::LifecycleEvent>>,
99 pub bg_registry: Option<std::sync::Arc<crate::tools::bash_bg::BgRegistry>>,
100 pub term_registry: Option<std::sync::Arc<crate::tools::term::TermRegistry>>,
101 pub watch_hub: Option<std::sync::Arc<crate::watch::WatchHub>>,
102 pub flow_registry: Option<std::sync::Arc<crate::tools::agent_ctrl::FlowRegistry>>,
103 pub task_registry: Option<crate::task_registry::TaskRegistry>,
104 pub session_id: Option<String>,
105 pub trust: Option<crate::trust::TrustConfig>,
106 pub current_model: Option<String>,
107 pub on_memory_recent: Option<std::sync::Arc<dyn Fn(u16) + Send + Sync>>,
109 pub history_store: Option<std::sync::Arc<dyn crate::history_store::HistoryStore>>,
110 pub agent_entry: Option<std::sync::Arc<crate::tools::agent_ctrl::FlowEntry>>,
111}
112
113impl ToolCtx {
114 pub fn new() -> Self {
115 Self::default()
116 }
117
118 pub fn with_anchors(
119 mut self,
120 turn_id: Option<crate::event::TurnId>,
121 flow_run_id: Option<crate::event::FlowRunId>,
122 event_seq: Option<u64>,
123 ) -> Self {
124 self.turn_id = turn_id;
125 self.flow_run_id = flow_run_id;
126 self.event_seq = event_seq;
127 self
128 }
129
130 pub fn with_registry(mut self, registry: std::sync::Arc<ToolRegistry>) -> Self {
131 self.registry = Some(registry);
132 self
133 }
134
135 pub fn with_sandbox(mut self, sandbox: std::sync::Arc<dyn crate::sandbox::Sandbox>) -> Self {
136 self.sandbox = Some(sandbox);
137 self
138 }
139
140 pub fn with_events(mut self, events: crate::event::EventSink) -> Self {
141 self.events = Some(events);
142 self
143 }
144
145 pub fn with_stdout_broadcast(mut self, tx: tokio::sync::broadcast::Sender<String>) -> Self {
146 self.stdout_broadcast = Some(tx);
147 self
148 }
149
150 pub fn with_session_messages(
151 mut self,
152 msgs: std::sync::Arc<Vec<crate::message::Message>>,
153 ) -> Self {
154 self.session_messages = Some(msgs);
155 self
156 }
157
158 pub fn with_session_messages_handle(
159 mut self,
160 handle: std::sync::Arc<std::sync::Mutex<Vec<crate::message::Message>>>,
161 ) -> Self {
162 self.session_messages_handle = Some(handle);
163 self
164 }
165
166 pub fn with_session_runtime(
167 mut self,
168 session: std::sync::Arc<crate::session::Session>,
169 ) -> Self {
170 self.session_runtime = Some(session);
171 self
172 }
173
174 pub fn with_compact_lock_handle(
175 mut self,
176 handle: std::sync::Arc<tokio::sync::Mutex<()>>,
177 ) -> Self {
178 self.compact_lock_handle = Some(handle);
179 self
180 }
181
182 pub fn with_current_node(mut self, node_id: Option<String>) -> Self {
183 self.current_node_id = node_id;
184 self
185 }
186
187 pub fn with_read_files(
188 mut self,
189 set: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>>,
190 ) -> Self {
191 self.read_files = Some(set);
192 self
193 }
194
195 pub fn with_providers(
196 mut self,
197 providers: std::sync::Arc<crate::provider::ProviderRegistry>,
198 ) -> Self {
199 self.providers = Some(providers);
200 self
201 }
202
203 pub fn with_session_dir(mut self, dir: std::path::PathBuf) -> Self {
204 self.session_dir = Some(dir);
205 self
206 }
207
208 pub fn with_data_root(mut self, dir: std::path::PathBuf) -> Self {
209 self.data_root = Some(dir);
210 self
211 }
212
213 pub fn with_approval(
214 mut self,
215 approval: std::sync::Arc<crate::session::ApprovalRegistry>,
216 ) -> Self {
217 self.approval = Some(approval);
218 self
219 }
220
221 pub fn with_fs_access(mut self, policy: crate::fs_access::FsAccessPolicy) -> Self {
222 self.fs_access = policy;
223 self
224 }
225
226 pub fn with_lifecycle_fire_tx(
227 mut self,
228 tx: tokio::sync::mpsc::UnboundedSender<atman_dsl::ast::LifecycleEvent>,
229 ) -> Self {
230 self.lifecycle_fire_tx = Some(tx);
231 self
232 }
233
234 pub fn with_forms(mut self, forms: std::sync::Arc<crate::session::FormRegistry>) -> Self {
235 self.forms = Some(forms);
236 self
237 }
238
239 pub fn with_bg_registry(
240 mut self,
241 registry: std::sync::Arc<crate::tools::bash_bg::BgRegistry>,
242 ) -> Self {
243 self.bg_registry = Some(registry);
244 self
245 }
246
247 pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
248 self.session_id = Some(id.into());
249 self
250 }
251
252 pub fn with_trust(mut self, trust: crate::trust::TrustConfig) -> Self {
253 self.trust = Some(trust);
254 self
255 }
256
257 pub fn with_current_model(mut self, model: impl Into<String>) -> Self {
258 self.current_model = Some(model.into());
259 self
260 }
261
262 pub fn with_term_registry(
263 mut self,
264 registry: std::sync::Arc<crate::tools::term::TermRegistry>,
265 ) -> Self {
266 self.term_registry = Some(registry);
267 self
268 }
269
270 pub fn with_watch_hub(mut self, hub: std::sync::Arc<crate::watch::WatchHub>) -> Self {
271 self.watch_hub = Some(hub);
272 self
273 }
274
275 pub fn with_flow_registry(
276 mut self,
277 registry: std::sync::Arc<crate::tools::agent_ctrl::FlowRegistry>,
278 ) -> Self {
279 self.flow_registry = Some(registry);
280 self
281 }
282
283 pub fn with_task_registry(mut self, registry: crate::task_registry::TaskRegistry) -> Self {
284 self.task_registry = Some(registry);
285 self
286 }
287
288 pub fn note_read(&self, path: &std::path::Path) {
289 if let Some(set) = &self.read_files
290 && let Ok(mut lock) = set.lock()
291 {
292 lock.insert(path.to_path_buf());
293 }
294 }
295
296 pub fn has_read(&self, path: &std::path::Path) -> bool {
297 self.read_files
298 .as_ref()
299 .and_then(|set| set.lock().ok().map(|lock| lock.contains(path)))
300 .unwrap_or(false)
301 }
302
303 pub fn with_project_index(mut self, idx: std::sync::Arc<crate::index::AnchorIndex>) -> Self {
304 self.project_index = Some(idx);
305 self
306 }
307
308 pub fn with_history_store(
309 mut self,
310 store: std::sync::Arc<dyn crate::history_store::HistoryStore>,
311 ) -> Self {
312 self.history_store = Some(store);
313 self
314 }
315
316 pub fn with_agent_entry(
317 mut self,
318 entry: std::sync::Arc<crate::tools::agent_ctrl::FlowEntry>,
319 ) -> Self {
320 self.agent_entry = Some(entry);
321 self
322 }
323
324 pub fn with_stream_tx(
325 mut self,
326 tx: tokio::sync::broadcast::Sender<crate::stream::StreamFrame>,
327 ) -> Self {
328 self.stream_tx = Some(tx);
329 self
330 }
331}
332
333pub trait Tool: Send + Sync {
334 fn name(&self) -> &str;
335 fn tier(&self) -> Tier;
336 fn approval_level(&self, _args: &ToolArgs, _ctx: &ToolCtx) -> ApprovalLevel {
337 ApprovalLevel::from_tier(self.tier())
338 }
339 fn cancel_behavior(&self) -> CancelBehavior {
340 CancelBehavior::AbortSafe
341 }
342 fn description(&self) -> Option<&str> {
343 None
344 }
345 fn input_schema(&self) -> serde_json::Value {
346 serde_json::json!({"type": "object"})
347 }
348 fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult>;
349 fn preview_call<'a>(
350 &'a self,
351 _args: &'a ToolArgs,
352 _ctx: &'a ToolCtx,
353 ) -> BoxFut<'a, Option<String>> {
354 Box::pin(async { None })
355 }
356}
357
358pub fn tool_spec(tool: &dyn Tool) -> ToolSpec {
359 ToolSpec {
360 name: tool.name().to_string(),
361 description: tool.description().map(str::to_string),
362 input_schema: tool.input_schema(),
363 }
364}
365
366#[derive(Debug, Clone, serde::Serialize)]
367pub struct ToolSpec {
368 pub name: String,
369 #[serde(skip_serializing_if = "Option::is_none")]
370 pub description: Option<String>,
371 pub input_schema: serde_json::Value,
372}
373
374#[derive(Default, Clone)]
375pub struct ToolRegistry {
376 tools: std::sync::Arc<std::sync::RwLock<HashMap<String, std::sync::Arc<dyn Tool>>>>,
377}
378
379impl ToolRegistry {
380 pub fn new() -> Self {
381 Self::default()
382 }
383
384 pub fn register(&self, tool: std::sync::Arc<dyn Tool>) {
385 self.tools
386 .write()
387 .unwrap()
388 .insert(tool.name().to_string(), tool);
389 }
390
391 pub fn get(&self, name: &str) -> Option<std::sync::Arc<dyn Tool>> {
392 self.tools.read().unwrap().get(name).cloned()
393 }
394
395 pub fn has(&self, name: &str) -> bool {
396 self.tools.read().unwrap().contains_key(name)
397 }
398
399 pub fn names(&self) -> Vec<String> {
400 self.tools.read().unwrap().keys().cloned().collect()
401 }
402
403 pub fn iter(&self) -> Vec<(String, std::sync::Arc<dyn Tool>)> {
404 self.tools
405 .read()
406 .unwrap()
407 .iter()
408 .map(|(k, v)| (k.clone(), v.clone()))
409 .collect()
410 }
411
412 pub fn unregister_prefix(&self, prefix: &str) {
414 self.tools
415 .write()
416 .unwrap()
417 .retain(|k, _| !k.starts_with(prefix));
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 #[test]
426 fn approval_level_default_maps_from_tier() {
427 assert_eq!(ApprovalLevel::from_tier(Tier::Zero), ApprovalLevel::Auto);
428 assert_eq!(ApprovalLevel::from_tier(Tier::One), ApprovalLevel::Approve);
429 assert_eq!(ApprovalLevel::from_tier(Tier::Two), ApprovalLevel::Approve);
430 assert_eq!(
431 ApprovalLevel::from_tier(Tier::Three),
432 ApprovalLevel::Dangerous
433 );
434 assert_eq!(
435 ApprovalLevel::from_tier(Tier::Four),
436 ApprovalLevel::Dangerous
437 );
438 }
439
440 #[test]
441 fn approval_level_ordered_auto_lt_approve_lt_dangerous() {
442 assert!(ApprovalLevel::Auto < ApprovalLevel::Approve);
443 assert!(ApprovalLevel::Approve < ApprovalLevel::Dangerous);
444 }
445}