Skip to main content

base/interface/tool/
registry.rs

1//! `ToolRegistry` and its two implementations, in-memory and layered.
2
3use super::*;
4
5/// Identifies one registration, so it can be withdrawn without disturbing
6/// anything else that happens to share the tool's name.
7///
8/// A name is not enough. `register` appends, so a name can legitimately be
9/// present more than once, and "remove the tool called X" would then withdraw
10/// whichever copy happened to be first — including one that a different
11/// contributor added.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct RegistrationId(u64);
14
15impl RegistrationId {
16    /// Mint an id. Public because every registry in the engine hands out
17    /// disposers keyed by one, and they do not all live in this module.
18    pub fn next() -> Self {
19        use std::sync::atomic::{AtomicU64, Ordering};
20        static NEXT: AtomicU64 = AtomicU64::new(1);
21        Self(NEXT.fetch_add(1, Ordering::Relaxed))
22    }
23}
24
25/// A handle that withdraws one registration.
26///
27/// **Dropping it does nothing.** Undoing on drop would be the more idiomatic
28/// Rust shape, but it makes the overwhelmingly common call —
29/// `registry.register(tool);` with the result ignored — silently unregister
30/// the tool it just added. Withdrawal is therefore explicit: hold the handle
31/// if you will need it, ignore it if you will not.
32/// Not `#[must_use]`: the overwhelmingly common case is registering something
33/// for the lifetime of the process and never withdrawing it, and a lint on
34/// every one of those would be noise that teaches people to silence lints.
35pub struct Disposer {
36    id: RegistrationId,
37    undo: Option<Box<dyn FnOnce(RegistrationId) + Send + Sync>>,
38}
39
40impl std::fmt::Debug for Disposer {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("Disposer").field("id", &self.id).finish()
43    }
44}
45
46impl Disposer {
47    pub fn new(
48        id: RegistrationId,
49        undo: impl FnOnce(RegistrationId) + Send + Sync + 'static,
50    ) -> Self {
51        Self {
52            id,
53            undo: Some(Box::new(undo)),
54        }
55    }
56
57    /// A handle over a registration that cannot be withdrawn — for an
58    /// implementation whose contents are fixed after construction.
59    pub fn inert(id: RegistrationId) -> Self {
60        Self { id, undo: None }
61    }
62
63    pub fn id(&self) -> RegistrationId {
64        self.id
65    }
66
67    /// Withdraw the registration this handle stands for.
68    pub fn dispose(mut self) {
69        if let Some(undo) = self.undo.take() {
70            undo(self.id);
71        }
72    }
73}
74
75pub trait ToolRegistry: Send + Sync + 'static {
76    fn list(&self) -> Vec<Arc<dyn Tool>>;
77    fn get(&self, n: &str) -> Option<Arc<dyn Tool>>;
78
79    /// Add a tool, returning a handle that can withdraw exactly this
80    /// registration.
81    fn register(&self, t: Arc<dyn Tool>) -> Disposer;
82
83    /// Substitute the entry for `t.name()`, or append when there is none.
84    ///
85    /// Distinct from [`register`](Self::register) because that one appends and
86    /// [`get`](Self::get) returns the first name match, so re-registering an
87    /// existing name leaves the original in front and the new instance
88    /// unreachable.
89    fn replace(&self, t: Arc<dyn Tool>) -> Disposer;
90
91    /// Withdraw every registration under `name`. Returns how many went.
92    ///
93    /// Present so a contributor can be unloaded cleanly. Masking a tool with a
94    /// deny rule leaves it in the registry, still visible to anything that
95    /// enumerates it; removal is what actually takes it out.
96    fn remove(&self, name: &str) -> usize;
97
98    fn names(&self) -> Vec<String> {
99        self.list().iter().map(|t| t.name().to_string()).collect()
100    }
101    fn len(&self) -> usize {
102        self.list().len()
103    }
104    fn is_empty(&self) -> bool {
105        self.len() == 0
106    }
107}
108
109#[derive(Clone)]
110pub struct InMemoryToolRegistry {
111    pub(crate) tools: Arc<std::sync::RwLock<Vec<Entry>>>,
112}
113
114/// A registered tool plus the id its `Disposer` refers to.
115#[derive(Clone)]
116pub struct Entry {
117    pub id: RegistrationId,
118    pub tool: Arc<dyn Tool>,
119}
120impl InMemoryToolRegistry {
121    pub fn new() -> Self {
122        Self {
123            tools: Arc::new(std::sync::RwLock::new(Vec::new())),
124        }
125    }
126    pub fn register(&self, t: Arc<dyn Tool>) -> Disposer {
127        let id = RegistrationId::next();
128        self.tools
129            .write()
130            .unwrap_or_else(|e| e.into_inner())
131            .push(Entry { id, tool: t });
132        self.disposer_for(id)
133    }
134
135    fn disposer_for(&self, id: RegistrationId) -> Disposer {
136        let tools = self.tools.clone();
137        Disposer::new(id, move |id| {
138            tools
139                .write()
140                .unwrap_or_else(|e| e.into_inner())
141                .retain(|e| e.id != id);
142        })
143    }
144
145    /// Swap the entry for `t.name()`, or append when there is none.
146    ///
147    /// [`register`](Self::register) appends unconditionally while
148    /// [`get`](Self::get) returns the *first* name match, so re-registering an
149    /// existing name leaves the original in front and the new instance
150    /// unreachable. Use this wherever the intent is to substitute a tool that
151    /// is already present — wrapping one in a decorator, for instance.
152    pub fn replace(&self, t: Arc<dyn Tool>) -> Disposer {
153        let id = RegistrationId::next();
154        {
155            let mut w = self.tools.write().unwrap_or_else(|e| e.into_inner());
156            match w.iter().position(|x| x.tool.name() == t.name()) {
157                Some(i) => w[i] = Entry { id, tool: t },
158                None => w.push(Entry { id, tool: t }),
159            }
160        }
161        self.disposer_for(id)
162    }
163
164    /// Withdraw every registration.
165    pub fn clear(&self) {
166        self.tools
167            .write()
168            .unwrap_or_else(|e| e.into_inner())
169            .clear();
170    }
171
172    /// Withdraw every registration under `name`; returns how many went.
173    pub fn remove(&self, name: &str) -> usize {
174        let mut w = self.tools.write().unwrap_or_else(|e| e.into_inner());
175        let before = w.len();
176        w.retain(|e| e.tool.name() != name);
177        before - w.len()
178    }
179    pub fn get(&self, n: &str) -> Option<Arc<dyn Tool>> {
180        self.tools
181            .read()
182            .unwrap_or_else(|e| e.into_inner())
183            .iter()
184            .find(|e| e.tool.name() == n)
185            .map(|e| e.tool.clone())
186    }
187    pub fn list(&self) -> Vec<Arc<dyn Tool>> {
188        self.tools
189            .read()
190            .unwrap_or_else(|e| e.into_inner())
191            .iter()
192            .map(|e| e.tool.clone())
193            .collect()
194    }
195    pub fn names(&self) -> Vec<String> {
196        self.tools
197            .read()
198            .unwrap_or_else(|e| e.into_inner())
199            .iter()
200            .map(|e| e.tool.name().to_string())
201            .collect()
202    }
203    pub fn len(&self) -> usize {
204        self.tools.read().unwrap_or_else(|e| e.into_inner()).len()
205    }
206    pub fn is_empty(&self) -> bool {
207        self.len() == 0
208    }
209}
210impl ToolRegistry for InMemoryToolRegistry {
211    fn list(&self) -> Vec<Arc<dyn Tool>> {
212        InMemoryToolRegistry::list(self)
213    }
214    fn get(&self, n: &str) -> Option<Arc<dyn Tool>> {
215        InMemoryToolRegistry::get(self, n)
216    }
217    fn register(&self, t: Arc<dyn Tool>) -> Disposer {
218        InMemoryToolRegistry::register(self, t)
219    }
220    fn replace(&self, t: Arc<dyn Tool>) -> Disposer {
221        InMemoryToolRegistry::replace(self, t)
222    }
223    fn remove(&self, name: &str) -> usize {
224        InMemoryToolRegistry::remove(self, name)
225    }
226}
227impl Default for InMemoryToolRegistry {
228    fn default() -> Self {
229        Self::new()
230    }
231}
232
233/// A registry that layers one set of tools over another.
234///
235/// Exists to answer a question a single implementation cannot: is
236/// [`ToolRegistry`] actually a contract, or just the shape of
237/// [`InMemoryToolRegistry`]? Writing a second implementation is what finds the
238/// methods that leaked an assumption about the first — and this one does not
239/// store `Vec<Entry>` at all, so anything that only worked because the backing
240/// store was a vector shows up here.
241///
242/// Reads consult the overlay first, then the base, so an overlay entry shadows
243/// a base entry of the same name. Writes only ever touch the overlay: the base
244/// is borrowed, and silently mutating something you were handed is how a
245/// "layer" becomes a leak.
246pub struct LayeredToolRegistry {
247    base: Arc<dyn ToolRegistry>,
248    overlay: InMemoryToolRegistry,
249    hidden: std::sync::RwLock<std::collections::HashSet<String>>,
250}
251
252impl LayeredToolRegistry {
253    pub fn new(base: Arc<dyn ToolRegistry>) -> Self {
254        Self {
255            base,
256            overlay: InMemoryToolRegistry::new(),
257            hidden: Default::default(),
258        }
259    }
260
261    /// Names hidden from `list`/`get` without touching the base registry.
262    ///
263    /// The layer's reason for existing: an embedder that wants a narrower tool
264    /// surface than the one it was handed, without the right to modify it.
265    pub fn hide(&self, name: &str) {
266        self.hidden
267            .write()
268            .unwrap_or_else(|e| e.into_inner())
269            .insert(name.to_string());
270    }
271
272    fn is_hidden(&self, name: &str) -> bool {
273        self.hidden
274            .read()
275            .unwrap_or_else(|e| e.into_inner())
276            .contains(name)
277    }
278}
279
280impl ToolRegistry for LayeredToolRegistry {
281    fn list(&self) -> Vec<Arc<dyn Tool>> {
282        let mut out = self.overlay.list();
283        let shadowed: std::collections::HashSet<String> =
284            out.iter().map(|t| t.name().to_string()).collect();
285        for t in self.base.list() {
286            if !self.is_hidden(t.name()) && !shadowed.contains(t.name()) {
287                out.push(t);
288            }
289        }
290        out
291    }
292
293    fn get(&self, n: &str) -> Option<Arc<dyn Tool>> {
294        match self.overlay.get(n) {
295            Some(t) => Some(t),
296            None if self.is_hidden(n) => None,
297            None => self.base.get(n),
298        }
299    }
300
301    /// Registering a name the layer hid makes the new entry visible; the base
302    /// entry stays hidden behind it.
303    fn register(&self, t: Arc<dyn Tool>) -> Disposer {
304        self.overlay.register(t)
305    }
306
307    fn replace(&self, t: Arc<dyn Tool>) -> Disposer {
308        self.overlay.replace(t)
309    }
310
311    /// Removes from the overlay, then hides whatever the base still exposes.
312    /// "Removed" has to mean "not visible through this registry" — leaving a
313    /// base entry reachable after a `remove` would be the exact leak this
314    /// layer exists to avoid.
315    fn remove(&self, name: &str) -> usize {
316        let removed = self.overlay.remove(name);
317        if !self.is_hidden(name) && self.base.get(name).is_some() {
318            self.hide(name);
319            return removed + 1;
320        }
321        removed
322    }
323}
324
325#[cfg(test)]
326mod registry_contract_tests {
327    use super::*;
328
329    #[derive(Debug)]
330    struct Stub(&'static str);
331
332    #[async_trait::async_trait]
333    impl Tool for Stub {
334        fn name(&self) -> &str {
335            self.0
336        }
337        fn description(&self) -> &str {
338            "stub"
339        }
340        fn spec(&self) -> ToolSpec {
341            ToolSpec::new()
342        }
343        fn input_schema(&self, _: PathStyle) -> Value {
344            serde_json::json!({"type": "object"})
345        }
346        async fn call(
347            &self,
348            _i: Value,
349            _c: ToolContext,
350            _p: ProgressSender,
351        ) -> Result<ToolResult, ToolError> {
352            Ok(ToolResult::text("ok"))
353        }
354    }
355
356    fn stub(n: &'static str) -> Arc<dyn Tool> {
357        Arc::new(Stub(n))
358    }
359
360    /// The same assertions against every implementation. A contract only one
361    /// type satisfies is not a contract.
362    fn contract(reg: &dyn ToolRegistry) {
363        let d = reg.register(stub("Alpha"));
364        assert!(reg.get("Alpha").is_some());
365        assert!(reg.names().contains(&"Alpha".to_string()));
366
367        // A disposer withdraws its own registration and nothing else.
368        let keep = reg.register(stub("Beta"));
369        d.dispose();
370        assert!(reg.get("Alpha").is_none(), "disposed tool still reachable");
371        assert!(
372            reg.get("Beta").is_some(),
373            "disposer took an unrelated entry"
374        );
375        let _ = keep;
376
377        // `replace` substitutes rather than shadowing.
378        reg.register(stub("Gamma"));
379        reg.replace(stub("Gamma"));
380        assert_eq!(
381            reg.list().iter().filter(|t| t.name() == "Gamma").count(),
382            1,
383            "replace left the original in place"
384        );
385
386        assert_eq!(reg.remove("Gamma"), 1);
387        assert!(reg.get("Gamma").is_none());
388        assert_eq!(reg.remove("NeverRegistered"), 0);
389    }
390
391    #[test]
392    fn in_memory_registry_satisfies_the_contract() {
393        contract(&InMemoryToolRegistry::new());
394    }
395
396    #[test]
397    fn layered_registry_satisfies_the_contract() {
398        contract(&LayeredToolRegistry::new(Arc::new(
399            InMemoryToolRegistry::new(),
400        )));
401    }
402
403    /// Dropping a disposer must *not* withdraw — the common call ignores the
404    /// return value, and undoing on drop would silently unregister everything.
405    #[test]
406    fn dropping_a_disposer_keeps_the_registration() {
407        let reg = InMemoryToolRegistry::new();
408        drop(reg.register(stub("Alpha")));
409        assert!(reg.get("Alpha").is_some());
410    }
411
412    /// Two registrations of one name are distinct, and a disposer takes only
413    /// the one it was handed back for.
414    #[test]
415    fn a_disposer_targets_its_own_registration_not_the_name() {
416        let reg = InMemoryToolRegistry::new();
417        let first = reg.register(stub("Dup"));
418        reg.register(stub("Dup"));
419        assert_eq!(reg.list().iter().filter(|t| t.name() == "Dup").count(), 2);
420        first.dispose();
421        assert_eq!(
422            reg.list().iter().filter(|t| t.name() == "Dup").count(),
423            1,
424            "disposing one registration took both"
425        );
426    }
427
428    /// The layer must not mutate what it was handed.
429    #[test]
430    fn the_layer_never_writes_through_to_its_base() {
431        let base = Arc::new(InMemoryToolRegistry::new());
432        base.register(stub("FromBase"));
433        let layer = LayeredToolRegistry::new(base.clone());
434
435        layer.register(stub("FromLayer"));
436        assert_eq!(base.len(), 1, "layer wrote into its base");
437
438        assert!(layer.get("FromBase").is_some(), "base entry not visible");
439        assert_eq!(layer.remove("FromBase"), 1);
440        assert!(layer.get("FromBase").is_none(), "removal did not hide it");
441        assert!(
442            base.get("FromBase").is_some(),
443            "removal reached through into the base"
444        );
445    }
446
447    /// An overlay entry shadows a base entry of the same name.
448    #[test]
449    fn overlay_shadows_the_base_without_duplicating() {
450        let base = Arc::new(InMemoryToolRegistry::new());
451        base.register(stub("Shared"));
452        let layer = LayeredToolRegistry::new(base);
453        layer.register(stub("Shared"));
454        assert_eq!(
455            layer.list().iter().filter(|t| t.name() == "Shared").count(),
456            1
457        );
458    }
459}