Skip to main content

trusty_code/tools/
registry.rs

1//! Tool registry — HashMap dispatcher + schema emitter.
2//!
3//! Why: Replaces hardcoded `if name == "delegate_to_agent"` dispatch with a
4//! polymorphic registry so new tools (`web_search`, `load_skill`, etc.) plug in
5//! without touching the PM loop. This is the SOA seam.
6//! What: `ToolRegistry` holds `Arc<dyn ToolExecutor>` keyed by name; emits a
7//! vector of JSON schemas for the LLM request; dispatches named tool calls to
8//! the right executor. RBAC-gated dispatch via `dispatch_for_user`.
9//! Test: Unit tests construct a registry with a `MockTool` and assert that
10//! `dispatch("mock")` returns the mock's output and `schemas()` contains the
11//! mock's schema.
12
13use std::collections::HashMap;
14use std::sync::Arc;
15
16use serde_json::Value;
17
18use crate::rbac::UserIdentity;
19use crate::tools::traits::{ToolExecutor, ToolResult};
20
21/// Registry of tools available to an LLM session.
22///
23/// Why: Centralizes tool lookup and schema emission so the PM loop and
24/// multi-turn sub-agent loop stay short and test-friendly.
25/// What: `HashMap<String, Arc<dyn ToolExecutor>>` with `register`, `dispatch`,
26/// `dispatch_gated`, `dispatch_for_user`, `schemas`, and `filter_tools_for_user`.
27/// Test: See unit tests below.
28#[derive(Default)]
29pub struct ToolRegistry {
30    tools: HashMap<String, Arc<dyn ToolExecutor>>,
31}
32
33impl ToolRegistry {
34    /// Construct an empty registry.
35    ///
36    /// Why: Callers build up the registry incrementally via `register`.
37    /// What: Returns a `ToolRegistry` with no tools registered.
38    /// Test: `new_registry_is_empty`.
39    pub fn new() -> Self {
40        Self {
41            tools: HashMap::new(),
42        }
43    }
44
45    /// Register a tool by its `name()`.
46    ///
47    /// Why: Using the tool's own name prevents mismatches between registered
48    /// key and schema-declared function name.
49    /// What: Inserts into the map. A `debug_assert!` panics in debug builds on
50    /// duplicate names so collisions surface during development.
51    /// Test: `register_then_dispatch_succeeds`, `register_panics_on_duplicate_in_debug`.
52    pub fn register(&mut self, tool: Arc<dyn ToolExecutor>) {
53        let name = tool.name().to_string();
54        debug_assert!(
55            !self.tools.contains_key(&name),
56            "duplicate tool registration for '{name}' — collisions overwrite and cause dispatch bugs"
57        );
58        self.tools.insert(name, tool);
59    }
60
61    /// Copy in every tool from `other` this registry does not already hold.
62    ///
63    /// Why (#8031): a `--no-delegate` run merges the NAMED agent's own tool set
64    /// (built by the same `RegistryFactory` a delegation of that agent would
65    /// use) into a top-level registry that already carries the harness tools —
66    /// `finish_task`, `use_skill` — the factory also builds. [`Self::register`]
67    /// asserts on a duplicate name, so the overlap needs a first-wins merge
68    /// rather than a loop of `register` calls.
69    /// What: for each of `other`'s entries, inserts a cloned `Arc` only when
70    /// this registry has no tool of that name; an existing registration always
71    /// wins. Order-independent.
72    /// Test: `merge_missing_adds_new_tools`, `merge_missing_keeps_the_existing_tool`.
73    pub fn merge_missing(&mut self, other: &ToolRegistry) {
74        for (name, tool) in &other.tools {
75            self.tools
76                .entry(name.clone())
77                .or_insert_with(|| Arc::clone(tool));
78        }
79    }
80
81    /// Whether a tool with the given name is registered.
82    ///
83    /// Why: Lets callers skip registration when a tool already exists.
84    /// What: HashMap membership check.
85    /// Test: `contains_after_register`.
86    pub fn contains(&self, name: &str) -> bool {
87        self.tools.contains_key(name)
88    }
89
90    /// Dispatch a named tool call.
91    ///
92    /// Why: Single place where missing-tool errors are surfaced as a structured
93    /// `ToolResult::Error` so the LLM loop can continue.
94    /// What: Looks up `name`, calls `execute(args)`, returns the `ToolResult`.
95    /// Test: Dispatch to an unregistered name returns `ToolResult::Error`;
96    /// dispatch to a registered one returns `ToolResult::Success`.
97    pub async fn dispatch(&self, name: &str, args: Value) -> ToolResult {
98        let Some(tool) = self.tools.get(name) else {
99            return ToolResult::err(format!("no tool registered with name '{name}'"));
100        };
101        tool.execute(args).await
102    }
103
104    /// Dispatch with an optional per-agent allowlist.
105    ///
106    /// Why: Per-agent tool gating prevents, e.g., the plan-agent from shelling
107    /// out or the research-agent from delegating. Allowlist is checked
108    /// centrally so every call site inherits the same policy.
109    /// What: If `allowed` is `Some` and does not contain `name`, returns a
110    /// recoverable `ToolResult::Error` naming what is permitted. Otherwise
111    /// delegates to `dispatch`.
112    /// Test: `dispatch_gated_rejects_disallowed`.
113    pub async fn dispatch_gated(
114        &self,
115        name: &str,
116        args: Value,
117        allowed: Option<&[String]>,
118    ) -> ToolResult {
119        if let Some(list) = allowed
120            && !list.iter().any(|a| a == name)
121        {
122            return ToolResult::err(format!(
123                "Tool '{name}' is not permitted for this agent. Allowed: {}",
124                list.join(", ")
125            ));
126        }
127        self.dispatch(name, args).await
128    }
129
130    /// Dispatch honoring a `UserIdentity`'s `ServiceTier`.
131    ///
132    /// Why: Some tools must be denied to less-trusted transports (Slack guest
133    /// users, unauthenticated HTTP) even if the LLM tries to call them.
134    /// Enforcing the tier check at the dispatch boundary means transport authors
135    /// can't accidentally bypass RBAC by forgetting to pre-filter the tool list.
136    /// What: If the tool is registered AND `user.can_access_tier` is `false`,
137    /// returns `ToolResult::Error`. Otherwise delegates to `dispatch_gated`.
138    /// Test: `dispatch_for_user_blocks_restricted_tier`.
139    pub async fn dispatch_for_user(
140        &self,
141        name: &str,
142        args: Value,
143        allowed: Option<&[String]>,
144        user: &UserIdentity,
145    ) -> ToolResult {
146        if let Some(tool) = self.tools.get(name)
147            && !user.can_access_tier(tool.restricted_tiers())
148        {
149            return ToolResult::err("This tool is not available for your access tier.");
150        }
151        self.dispatch_gated(name, args, allowed).await
152    }
153
154    /// Build a new registry containing only the tools named in `allowed`.
155    ///
156    /// Why: The agent loop calls `dispatch_gated(name, args, None)` — it does
157    /// not thread a per-agent allowlist through every dispatch. The robust place
158    /// to enforce an agent's `tools.allowed` (issue #1029 acceptance criterion)
159    /// is therefore *before* the loop runs: hand the loop a registry that simply
160    /// does not contain the denied tools, so a denied call surfaces as the same
161    /// structured "no tool registered" error and the model can self-correct.
162    /// Unknown names in `allowed` are ignored (they register nothing); this keeps
163    /// a typo in an agent config from being a hard error.
164    /// What: Returns a fresh `ToolRegistry` whose map holds cloned `Arc`s for
165    /// exactly the registered tools whose `name()` appears in `allowed`,
166    /// preserving the shared executors (no re-construction). Order-independent.
167    /// Test: `gated_keeps_only_allowed`, `gated_ignores_unknown_names`.
168    pub fn gated(&self, allowed: &[String]) -> ToolRegistry {
169        let tools = self
170            .tools
171            .iter()
172            .filter(|(name, _)| allowed.iter().any(|a| a == *name))
173            .map(|(name, tool)| (name.clone(), Arc::clone(tool)))
174            .collect();
175        ToolRegistry { tools }
176    }
177
178    /// Emit all registered tool schemas as raw JSON values.
179    ///
180    /// Why: The sub-agent tool-calling loop attaches raw JSON schemas to LLM
181    /// requests; the OpenAI-compatible schema is produced by each tool.
182    /// What: Collects `tool.schema()` for every registered tool.
183    /// Test: Registering two tools returns a vector of length 2.
184    pub fn schemas(&self) -> Vec<Value> {
185        self.tools.values().map(|t| t.schema()).collect()
186    }
187
188    /// Return the raw schema for a single registered tool by name.
189    ///
190    /// Why: `llm::ToolCallExtractor` (#1023) validates one tool call's
191    /// arguments at a time; looking up exactly one schema is cheaper and
192    /// simpler than enumerating and filtering the full `schemas()` vector on
193    /// every dispatch.
194    /// What: Returns `Some(tool.schema())` for a registered `name`, else `None`.
195    /// Test: `schema_for_returns_registered_tool_schema`, `schema_for_none_when_missing`.
196    pub fn schema_for(&self, name: &str) -> Option<Value> {
197        self.tools.get(name).map(|t| t.schema())
198    }
199
200    /// Return the subset of registered tools that `user` may invoke.
201    ///
202    /// Why: Schema emission for the LLM request must reflect what the user can
203    /// actually call, otherwise the model will hallucinate denied calls.
204    /// What: Returns cloned `Arc`s for tools where `user.can_access_tier` is true.
205    /// Test: `filter_tools_for_user_drops_restricted`.
206    pub fn filter_tools_for_user(&self, user: &UserIdentity) -> Vec<Arc<dyn ToolExecutor>> {
207        self.tools
208            .values()
209            .filter(|t| user.can_access_tier(t.restricted_tiers()))
210            .cloned()
211            .collect()
212    }
213}
214
215// ── Tests ─────────────────────────────────────────────────────────────────────
216
217#[cfg(test)]
218mod tests {
219    use std::sync::Arc;
220
221    use async_trait::async_trait;
222    use serde_json::{Value, json};
223
224    use super::ToolRegistry;
225    use crate::rbac::{ServiceTier, UserIdentity};
226    use crate::tools::traits::{ToolExecutor, ToolResult};
227
228    /// Minimal mock tool for registry tests.
229    struct MockTool {
230        name: &'static str,
231        restricted: Vec<ServiceTier>,
232    }
233
234    impl MockTool {
235        fn new(name: &'static str) -> Self {
236            Self {
237                name,
238                restricted: vec![],
239            }
240        }
241
242        fn restricted(mut self, tier: ServiceTier) -> Self {
243            self.restricted.push(tier);
244            self
245        }
246    }
247
248    #[async_trait]
249    impl ToolExecutor for MockTool {
250        fn name(&self) -> &str {
251            self.name
252        }
253
254        fn schema(&self) -> Value {
255            json!({"type": "function", "function": {"name": self.name, "description": "mock"}})
256        }
257
258        async fn execute(&self, _args: Value) -> ToolResult {
259            ToolResult::ok(format!("mock-{} executed", self.name))
260        }
261
262        fn restricted_tiers(&self) -> &[ServiceTier] {
263            &self.restricted
264        }
265    }
266
267    /// A new registry has no tools.
268    ///
269    /// Why: Guard the baseline.
270    /// What: `new()` + `contains("any")` → false.
271    /// Test: This test.
272    #[test]
273    fn new_registry_is_empty() {
274        let reg = ToolRegistry::new();
275        assert!(!reg.contains("anything"));
276        assert!(reg.schemas().is_empty());
277    }
278
279    /// Registering a tool makes it findable.
280    ///
281    /// Why: Verify the basic register+contains contract.
282    /// What: Register "mock", then `contains("mock")` is true.
283    /// Test: This test.
284    #[test]
285    fn contains_after_register() {
286        let mut reg = ToolRegistry::new();
287        reg.register(Arc::new(MockTool::new("mock")));
288        assert!(reg.contains("mock"));
289    }
290
291    /// Dispatch to an unknown tool returns a structured error.
292    ///
293    /// Why: The LLM loop must not panic or abort on a missing tool.
294    /// What: `dispatch("unknown", {})` returns `ToolResult::Error`.
295    /// Test: This test.
296    #[tokio::test]
297    async fn dispatch_unknown_returns_error() {
298        let reg = ToolRegistry::new();
299        let result = reg.dispatch("unknown", json!({})).await;
300        assert!(result.is_error());
301        assert!(result.content().contains("no tool registered"));
302    }
303
304    /// Dispatch to a registered tool returns its output.
305    ///
306    /// Why: Verify the happy-path dispatch contract.
307    /// What: Register "mock", dispatch to it, assert success content.
308    /// Test: This test.
309    #[tokio::test]
310    async fn dispatch_registered_tool_succeeds() {
311        let mut reg = ToolRegistry::new();
312        reg.register(Arc::new(MockTool::new("mock")));
313        let result = reg.dispatch("mock", json!({})).await;
314        assert!(!result.is_error());
315        assert!(result.content().contains("mock-mock executed"));
316    }
317
318    /// `schemas()` returns one entry per registered tool.
319    ///
320    /// Why: Verify schema emission count.
321    /// What: Register two tools; `schemas()` returns 2 items.
322    /// Test: This test.
323    #[test]
324    fn schemas_returns_one_per_tool() {
325        let mut reg = ToolRegistry::new();
326        reg.register(Arc::new(MockTool::new("tool_a")));
327        reg.register(Arc::new(MockTool::new("tool_b")));
328        assert_eq!(reg.schemas().len(), 2);
329    }
330
331    /// `schema_for` returns the registered tool's schema.
332    ///
333    /// Why: Guard the direct single-tool lookup used by `ToolCallExtractor`.
334    /// What: Register "mock", fetch its schema by name, assert its shape.
335    /// Test: this test.
336    #[test]
337    fn schema_for_returns_registered_tool_schema() {
338        let mut reg = ToolRegistry::new();
339        reg.register(Arc::new(MockTool::new("mock")));
340        let schema = reg.schema_for("mock").expect("schema present");
341        assert_eq!(schema["function"]["name"], "mock");
342    }
343
344    /// `schema_for` returns `None` for an unregistered name.
345    ///
346    /// Why: Guard the miss path — no panic, no default schema fabricated.
347    /// What: Query a name that was never registered.
348    /// Test: this test.
349    #[test]
350    fn schema_for_none_when_missing() {
351        let reg = ToolRegistry::new();
352        assert!(reg.schema_for("does_not_exist").is_none());
353    }
354
355    /// `dispatch_gated` rejects a tool not in the allowlist.
356    ///
357    /// Why: Per-agent allowlists must be enforced at dispatch.
358    /// What: Register "mock", call `dispatch_gated("mock", {}, Some(&["other"]))`,
359    /// expect error.
360    /// Test: This test.
361    #[tokio::test]
362    async fn dispatch_gated_rejects_disallowed() {
363        let mut reg = ToolRegistry::new();
364        reg.register(Arc::new(MockTool::new("mock")));
365        let allowed = vec!["other".to_string()];
366        let result = reg.dispatch_gated("mock", json!({}), Some(&allowed)).await;
367        assert!(result.is_error());
368        assert!(result.content().contains("not permitted"));
369    }
370
371    /// `dispatch_gated` with `allowed = None` passes through.
372    ///
373    /// Why: `None` allowlist means no per-agent restriction.
374    /// What: `dispatch_gated("mock", {}, None)` calls through to dispatch.
375    /// Test: This test.
376    #[tokio::test]
377    async fn dispatch_gated_none_allowlist_permits() {
378        let mut reg = ToolRegistry::new();
379        reg.register(Arc::new(MockTool::new("mock")));
380        let result = reg.dispatch_gated("mock", json!({}), None).await;
381        assert!(!result.is_error());
382    }
383
384    /// `dispatch_for_user` blocks a restricted tier.
385    ///
386    /// Why: RBAC must be enforced at dispatch.
387    /// What: Register a tool restricted to `[ReadOnly]`, dispatch as a
388    /// `ReadOnly` user, expect error.
389    /// Test: This test.
390    #[tokio::test]
391    async fn dispatch_for_user_blocks_restricted_tier() {
392        let mut reg = ToolRegistry::new();
393        let tool = MockTool::new("secret_tool").restricted(ServiceTier::ReadOnly);
394        reg.register(Arc::new(tool));
395
396        let user = UserIdentity::new("u1", "alice", ServiceTier::ReadOnly);
397        let result = reg
398            .dispatch_for_user("secret_tool", json!({}), None, &user)
399            .await;
400        assert!(result.is_error());
401        assert!(result.content().contains("access tier"));
402    }
403
404    /// `dispatch_for_user` allows an unrestricted tier.
405    ///
406    /// Why: `All` tier must pass unrestricted tools.
407    /// What: Register an unrestricted tool, dispatch as `All`, expect success.
408    /// Test: This test.
409    #[tokio::test]
410    async fn dispatch_for_user_allows_unrestricted() {
411        let mut reg = ToolRegistry::new();
412        reg.register(Arc::new(MockTool::new("open_tool")));
413
414        let user = UserIdentity::default(); // tier = All
415        let result = reg
416            .dispatch_for_user("open_tool", json!({}), None, &user)
417            .await;
418        assert!(!result.is_error());
419    }
420
421    /// `gated` retains only the tools named in the allowlist.
422    ///
423    /// Why: This is the enforcement point for an agent's `tools.allowed`; the
424    /// resulting registry must contain exactly the permitted tools.
425    /// What: Register three tools, gate to two of them, assert membership.
426    /// Test: This test.
427    #[test]
428    fn gated_keeps_only_allowed() {
429        let mut reg = ToolRegistry::new();
430        reg.register(Arc::new(MockTool::new("read_file")));
431        reg.register(Arc::new(MockTool::new("write_file")));
432        reg.register(Arc::new(MockTool::new("bash")));
433
434        let allowed = vec!["read_file".to_string(), "bash".to_string()];
435        let gated = reg.gated(&allowed);
436
437        assert!(gated.contains("read_file"), "allowed tool must survive");
438        assert!(gated.contains("bash"), "allowed tool must survive");
439        assert!(
440            !gated.contains("write_file"),
441            "denied tool must be dropped from the gated registry"
442        );
443        assert_eq!(gated.schemas().len(), 2, "exactly the two allowed tools");
444    }
445
446    /// `gated` silently ignores allowlist entries that match no registered tool.
447    ///
448    /// Why: A typo in an agent's `tools.allowed` should not be a hard error; it
449    /// simply contributes no tool to the gated registry.
450    /// What: Gate with a mix of a real and a bogus name; only the real one survives.
451    /// Test: This test.
452    #[test]
453    fn gated_ignores_unknown_names() {
454        let mut reg = ToolRegistry::new();
455        reg.register(Arc::new(MockTool::new("read_file")));
456
457        let allowed = vec!["read_file".to_string(), "does_not_exist".to_string()];
458        let gated = reg.gated(&allowed);
459
460        assert!(gated.contains("read_file"));
461        assert_eq!(gated.schemas().len(), 1, "unknown name registers nothing");
462    }
463
464    /// `gated` with an empty allowlist produces an empty registry.
465    ///
466    /// Why: An agent that explicitly allows no tools must be handed a registry
467    /// with no tools (the model then has nothing to call).
468    /// What: Gate a populated registry with `&[]`; assert empty.
469    /// Test: This test.
470    #[test]
471    fn gated_empty_allowlist_is_empty() {
472        let mut reg = ToolRegistry::new();
473        reg.register(Arc::new(MockTool::new("read_file")));
474        let gated = reg.gated(&[]);
475        assert!(gated.schemas().is_empty());
476        assert!(!gated.contains("read_file"));
477    }
478
479    /// `filter_tools_for_user` drops tools that the user's tier is blocked for.
480    ///
481    /// Why: LLM should not see tools it cannot call.
482    /// What: Register one restricted and one open tool; filter for `ReadOnly`.
483    /// Expected: only the open tool survives.
484    /// Test: This test.
485    #[test]
486    fn filter_tools_for_user_drops_restricted() {
487        let mut reg = ToolRegistry::new();
488        reg.register(Arc::new(MockTool::new("open")));
489        reg.register(Arc::new(
490            MockTool::new("restricted").restricted(ServiceTier::ReadOnly),
491        ));
492
493        let user = UserIdentity::new("u", "u", ServiceTier::ReadOnly);
494        let filtered = reg.filter_tools_for_user(&user);
495        assert_eq!(filtered.len(), 1, "only the open tool should survive");
496        assert_eq!(filtered[0].name(), "open");
497    }
498
499    /// `merge_missing` copies in tools the target does not already hold.
500    ///
501    /// Why (#8031): the `--no-delegate` merge would be a no-op if new names
502    /// were dropped.
503    /// What: merge a registry holding `write_file` into one holding
504    /// `finish_task`; both must be present afterwards.
505    /// Test: This test.
506    #[test]
507    fn merge_missing_adds_new_tools() {
508        let mut target = ToolRegistry::new();
509        target.register(Arc::new(MockTool::new("finish_task")));
510        let mut source = ToolRegistry::new();
511        source.register(Arc::new(MockTool::new("write_file")));
512
513        target.merge_missing(&source);
514        assert!(target.contains("finish_task"));
515        assert!(target.contains("write_file"));
516    }
517
518    /// `merge_missing` never overwrites an existing registration.
519    ///
520    /// Why (#8031): the harness tools are registered first and the agent's
521    /// factory builds its own `finish_task`/`use_skill`; the already-wired
522    /// instance must win rather than be silently replaced.
523    /// What: both registries hold `finish_task`; after the merge, dispatching
524    /// it still reaches the target's own instance.
525    /// Test: This test.
526    #[tokio::test]
527    async fn merge_missing_keeps_the_existing_tool() {
528        let mut target = ToolRegistry::new();
529        target.register(Arc::new(MockTool::new("finish_task")));
530        let kept = Arc::as_ptr(target.tools.get("finish_task").expect("registered"));
531
532        let mut source = ToolRegistry::new();
533        source.register(Arc::new(MockTool::new("finish_task")));
534        target.merge_missing(&source);
535
536        let after = Arc::as_ptr(target.tools.get("finish_task").expect("still registered"));
537        assert!(
538            std::ptr::addr_eq(kept, after),
539            "merge_missing must leave the pre-existing registration in place"
540        );
541        assert_eq!(target.schemas().len(), 1, "no duplicate entry is created");
542    }
543}