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