causa_runtime/executor/
registry.rs1use super::{ToolRegistryError, options::ToolExecutorOptions, source::DynamicEntry};
4use causa_kernel::{DynamicToolSource, Tool};
5use std::sync::{Arc, RwLock};
6
7pub(super) struct StaticEntry {
8 pub(super) name: String,
9 pub(super) tool: Arc<dyn Tool>,
10}
11
12pub struct ToolExecutor {
17 pub(super) tools: Vec<StaticEntry>,
18 pub(super) dynamic: RwLock<Vec<Arc<DynamicEntry>>>,
19 pub(super) options: ToolExecutorOptions,
20}
21
22impl std::fmt::Debug for ToolExecutor {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 f.debug_struct("ToolExecutor")
25 .field(
26 "tools",
27 &self.tools.iter().map(|e| &e.name).collect::<Vec<_>>(),
28 )
29 .field("dynamic", &self.dynamic_ids())
30 .finish()
31 }
32}
33
34impl ToolExecutor {
35 pub fn new(
38 tools: Vec<Arc<dyn Tool>>,
39 options: ToolExecutorOptions,
40 ) -> Result<Self, ToolRegistryError> {
41 let mut names = std::collections::HashSet::new();
42 let mut entries = Vec::with_capacity(tools.len());
43 for tool in tools {
44 let name = tool.definition().name;
45 if !names.insert(name.clone()) {
46 return Err(ToolRegistryError::DuplicateTool { name });
47 }
48 entries.push(StaticEntry { name, tool });
49 }
50 Ok(Self {
51 tools: entries,
52 dynamic: RwLock::new(Vec::new()),
53 options,
54 })
55 }
56
57 pub fn register_dynamic(
60 &self,
61 source: Arc<dyn DynamicToolSource>,
62 ) -> Result<(), ToolRegistryError> {
63 let id = source.id().to_owned();
64 let mut entries = self.dynamic.write().expect("dynamic registry lock");
65 if entries.iter().any(|entry| entry.id == id) {
66 return Err(ToolRegistryError::DuplicateSource { source_id: id });
67 }
68 entries.push(Arc::new(DynamicEntry::new(id, source)));
69 Ok(())
70 }
71
72 pub fn unregister_dynamic(
75 &self,
76 id: &str,
77 ) -> Result<Arc<dyn DynamicToolSource>, ToolRegistryError> {
78 let mut entries = self.dynamic.write().expect("dynamic registry lock");
79 let position = entries
80 .iter()
81 .position(|entry| entry.id == id)
82 .ok_or_else(|| ToolRegistryError::UnknownSource {
83 source_id: id.to_owned(),
84 })?;
85 Ok(entries.remove(position).source.clone())
86 }
87
88 pub fn dynamic_ids(&self) -> Vec<String> {
90 self.dynamic
91 .read()
92 .expect("dynamic registry lock")
93 .iter()
94 .map(|entry| entry.id.clone())
95 .collect()
96 }
97}