Skip to main content

atman_runtime/
tool.rs

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
10// `dyn Future` is now `Send` — AST Span was replaced with a custom `Copy + Send + Sync`
11// struct, removing the `proc_macro2::Span` (which held `Rc<()>`).  This means
12// providers, tools, and classifiers can be spawned with `tokio::spawn` instead
13// of requiring `spawn_local` + `LocalSet`.
14pub 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 task_registry: Option<crate::task_registry::TaskRegistry>,
102    pub session_id: Option<String>,
103    pub trust: Option<crate::trust::TrustConfig>,
104    pub current_model: Option<String>,
105    /// Called when memory.recent_turns is invoked, with the count of returned messages.
106    pub on_memory_recent: Option<std::sync::Arc<dyn Fn(u16) + Send + Sync>>,
107    pub history_store: Option<std::sync::Arc<dyn crate::history_store::HistoryStore>>,
108}
109
110impl ToolCtx {
111    pub fn new() -> Self {
112        Self::default()
113    }
114
115    pub fn with_anchors(
116        mut self,
117        turn_id: Option<crate::event::TurnId>,
118        flow_run_id: Option<crate::event::FlowRunId>,
119        event_seq: Option<u64>,
120    ) -> Self {
121        self.turn_id = turn_id;
122        self.flow_run_id = flow_run_id;
123        self.event_seq = event_seq;
124        self
125    }
126
127    pub fn with_registry(mut self, registry: std::sync::Arc<ToolRegistry>) -> Self {
128        self.registry = Some(registry);
129        self
130    }
131
132    pub fn with_sandbox(mut self, sandbox: std::sync::Arc<dyn crate::sandbox::Sandbox>) -> Self {
133        self.sandbox = Some(sandbox);
134        self
135    }
136
137    pub fn with_events(mut self, events: crate::event::EventSink) -> Self {
138        self.events = Some(events);
139        self
140    }
141
142    pub fn with_stdout_broadcast(mut self, tx: tokio::sync::broadcast::Sender<String>) -> Self {
143        self.stdout_broadcast = Some(tx);
144        self
145    }
146
147    pub fn with_session_messages(
148        mut self,
149        msgs: std::sync::Arc<Vec<crate::message::Message>>,
150    ) -> Self {
151        self.session_messages = Some(msgs);
152        self
153    }
154
155    pub fn with_session_messages_handle(
156        mut self,
157        handle: std::sync::Arc<std::sync::Mutex<Vec<crate::message::Message>>>,
158    ) -> Self {
159        self.session_messages_handle = Some(handle);
160        self
161    }
162
163    pub fn with_session_runtime(
164        mut self,
165        session: std::sync::Arc<crate::session::Session>,
166    ) -> Self {
167        self.session_runtime = Some(session);
168        self
169    }
170
171    pub fn with_compact_lock_handle(
172        mut self,
173        handle: std::sync::Arc<tokio::sync::Mutex<()>>,
174    ) -> Self {
175        self.compact_lock_handle = Some(handle);
176        self
177    }
178
179    pub fn with_current_node(mut self, node_id: Option<String>) -> Self {
180        self.current_node_id = node_id;
181        self
182    }
183
184    pub fn with_read_files(
185        mut self,
186        set: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>>,
187    ) -> Self {
188        self.read_files = Some(set);
189        self
190    }
191
192    pub fn with_providers(
193        mut self,
194        providers: std::sync::Arc<crate::provider::ProviderRegistry>,
195    ) -> Self {
196        self.providers = Some(providers);
197        self
198    }
199
200    pub fn with_session_dir(mut self, dir: std::path::PathBuf) -> Self {
201        self.session_dir = Some(dir);
202        self
203    }
204
205    pub fn with_data_root(mut self, dir: std::path::PathBuf) -> Self {
206        self.data_root = Some(dir);
207        self
208    }
209
210    pub fn with_approval(
211        mut self,
212        approval: std::sync::Arc<crate::session::ApprovalRegistry>,
213    ) -> Self {
214        self.approval = Some(approval);
215        self
216    }
217
218    pub fn with_fs_access(mut self, policy: crate::fs_access::FsAccessPolicy) -> Self {
219        self.fs_access = policy;
220        self
221    }
222
223    pub fn with_lifecycle_fire_tx(
224        mut self,
225        tx: tokio::sync::mpsc::UnboundedSender<atman_dsl::ast::LifecycleEvent>,
226    ) -> Self {
227        self.lifecycle_fire_tx = Some(tx);
228        self
229    }
230
231    pub fn with_forms(mut self, forms: std::sync::Arc<crate::session::FormRegistry>) -> Self {
232        self.forms = Some(forms);
233        self
234    }
235
236    pub fn with_bg_registry(
237        mut self,
238        registry: std::sync::Arc<crate::tools::bash_bg::BgRegistry>,
239    ) -> Self {
240        self.bg_registry = Some(registry);
241        self
242    }
243
244    pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
245        self.session_id = Some(id.into());
246        self
247    }
248
249    pub fn with_trust(mut self, trust: crate::trust::TrustConfig) -> Self {
250        self.trust = Some(trust);
251        self
252    }
253
254    pub fn with_current_model(mut self, model: impl Into<String>) -> Self {
255        self.current_model = Some(model.into());
256        self
257    }
258
259    pub fn with_term_registry(
260        mut self,
261        registry: std::sync::Arc<crate::tools::term::TermRegistry>,
262    ) -> Self {
263        self.term_registry = Some(registry);
264        self
265    }
266
267    pub fn with_task_registry(mut self, registry: crate::task_registry::TaskRegistry) -> Self {
268        self.task_registry = Some(registry);
269        self
270    }
271
272    pub fn note_read(&self, path: &std::path::Path) {
273        if let Some(set) = &self.read_files
274            && let Ok(mut lock) = set.lock()
275        {
276            lock.insert(path.to_path_buf());
277        }
278    }
279
280    pub fn has_read(&self, path: &std::path::Path) -> bool {
281        self.read_files
282            .as_ref()
283            .and_then(|set| set.lock().ok().map(|lock| lock.contains(path)))
284            .unwrap_or(false)
285    }
286
287    pub fn with_project_index(mut self, idx: std::sync::Arc<crate::index::AnchorIndex>) -> Self {
288        self.project_index = Some(idx);
289        self
290    }
291
292    pub fn with_history_store(
293        mut self,
294        store: std::sync::Arc<dyn crate::history_store::HistoryStore>,
295    ) -> Self {
296        self.history_store = Some(store);
297        self
298    }
299
300    pub fn with_stream_tx(
301        mut self,
302        tx: tokio::sync::broadcast::Sender<crate::stream::StreamFrame>,
303    ) -> Self {
304        self.stream_tx = Some(tx);
305        self
306    }
307}
308
309pub trait Tool: Send + Sync {
310    fn name(&self) -> &str;
311    fn tier(&self) -> Tier;
312    fn approval_level(&self, _args: &ToolArgs, _ctx: &ToolCtx) -> ApprovalLevel {
313        ApprovalLevel::from_tier(self.tier())
314    }
315    fn cancel_behavior(&self) -> CancelBehavior {
316        CancelBehavior::AbortSafe
317    }
318    fn description(&self) -> Option<&str> {
319        None
320    }
321    fn input_schema(&self) -> serde_json::Value {
322        serde_json::json!({"type": "object"})
323    }
324    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult>;
325    fn preview_call<'a>(
326        &'a self,
327        _args: &'a ToolArgs,
328        _ctx: &'a ToolCtx,
329    ) -> BoxFut<'a, Option<String>> {
330        Box::pin(async { None })
331    }
332}
333
334pub fn tool_spec(tool: &dyn Tool) -> ToolSpec {
335    ToolSpec {
336        name: tool.name().to_string(),
337        description: tool.description().map(str::to_string),
338        input_schema: tool.input_schema(),
339    }
340}
341
342#[derive(Debug, Clone, serde::Serialize)]
343pub struct ToolSpec {
344    pub name: String,
345    #[serde(skip_serializing_if = "Option::is_none")]
346    pub description: Option<String>,
347    pub input_schema: serde_json::Value,
348}
349
350#[derive(Default, Clone)]
351pub struct ToolRegistry {
352    tools: std::sync::Arc<std::sync::RwLock<HashMap<String, std::sync::Arc<dyn Tool>>>>,
353}
354
355impl ToolRegistry {
356    pub fn new() -> Self {
357        Self::default()
358    }
359
360    pub fn register(&self, tool: std::sync::Arc<dyn Tool>) {
361        self.tools
362            .write()
363            .unwrap()
364            .insert(tool.name().to_string(), tool);
365    }
366
367    pub fn get(&self, name: &str) -> Option<std::sync::Arc<dyn Tool>> {
368        self.tools.read().unwrap().get(name).cloned()
369    }
370
371    pub fn has(&self, name: &str) -> bool {
372        self.tools.read().unwrap().contains_key(name)
373    }
374
375    pub fn names(&self) -> Vec<String> {
376        self.tools.read().unwrap().keys().cloned().collect()
377    }
378
379    pub fn iter(&self) -> Vec<(String, std::sync::Arc<dyn Tool>)> {
380        self.tools
381            .read()
382            .unwrap()
383            .iter()
384            .map(|(k, v)| (k.clone(), v.clone()))
385            .collect()
386    }
387
388    /// Remove all tools whose name starts with `prefix` (e.g. `"mcp."`).
389    pub fn unregister_prefix(&self, prefix: &str) {
390        self.tools
391            .write()
392            .unwrap()
393            .retain(|k, _| !k.starts_with(prefix));
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn approval_level_default_maps_from_tier() {
403        assert_eq!(ApprovalLevel::from_tier(Tier::Zero), ApprovalLevel::Auto);
404        assert_eq!(ApprovalLevel::from_tier(Tier::One), ApprovalLevel::Approve);
405        assert_eq!(ApprovalLevel::from_tier(Tier::Two), ApprovalLevel::Approve);
406        assert_eq!(
407            ApprovalLevel::from_tier(Tier::Three),
408            ApprovalLevel::Dangerous
409        );
410        assert_eq!(
411            ApprovalLevel::from_tier(Tier::Four),
412            ApprovalLevel::Dangerous
413        );
414    }
415
416    #[test]
417    fn approval_level_ordered_auto_lt_approve_lt_dangerous() {
418        assert!(ApprovalLevel::Auto < ApprovalLevel::Approve);
419        assert!(ApprovalLevel::Approve < ApprovalLevel::Dangerous);
420    }
421}