bamboo-server 2026.4.30

HTTP server and API layer for the Bamboo agent framework
Documentation
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
//! `PolicyAwareToolExecutor`: enforces a subagent profile's [`ToolPolicy`]
//! at tool-call time.
//!
//! This is the runtime half of the SubagentProfile feature. Profile loading
//! and prompt injection live in `subagent_profiles` and
//! `session_app::child_session`; here we wrap the child-session
//! [`ToolExecutor`] so that tool calls are filtered against the calling
//! child's `subagent_type` metadata.
//!
//! ## Why a wrapper instead of changing `SpawnContext`
//!
//! `bamboo-engine`'s `SpawnContext` carries a single `Arc<dyn ToolExecutor>`
//! shared by every child session. Different child sessions can have
//! different `subagent_type`s and therefore different
//! [`ToolPolicy`]s. Rather than changing the engine to dispatch executors
//! per session (which would ripple into `SpawnContext`, `SpawnScheduler`
//! and `ScheduleManager`), this wrapper sits in front of the existing
//! executor and resolves the policy on the fly using
//! [`ToolExecutionContext::session_id`] and the in-memory sessions cache
//! that the server already maintains.
//!
//! ## Behaviour summary
//!
//! - Tool _execution_ is filtered:
//!   - [`ToolPolicy::Inherit`] → forwarded unchanged.
//!   - [`ToolPolicy::Allowlist`] → forwarded only if the tool name is on
//!     the allow list; otherwise rejected with a clear
//!     `ToolError::Execution` message.
//!   - [`ToolPolicy::Denylist`] → rejected if the tool name is on the
//!     deny list; otherwise forwarded.
//! - Tool _discovery_ (`list_tools`) is **not** filtered here. The
//!   advertised tool surface is per-session and is filtered upstream via
//!   the engine's `disabled_tools` mechanism (a later PR will wire the
//!   profile policy into that list as well). Filtering at the wrapper
//!   level would over-restrict callers that share the wrapper but are not
//!   actually subject to a child policy.
//! - When the wrapper cannot determine a policy (no `session_id`, the
//!   session is not in cache, no `subagent_type` metadata, or the
//!   profile is unknown), it forwards unchanged. This keeps the change
//!   strictly additive: any existing call path that has not yet adopted
//!   subagent profiles continues to behave exactly as before.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use bamboo_agent_core::tools::{
    ToolCall, ToolError, ToolExecutionContext, ToolExecutor, ToolResult, ToolSchema,
};
use bamboo_agent_core::Session;
use bamboo_domain::subagent::{SubagentProfileRegistry, ToolPolicy};
use tokio::sync::RwLock;

/// Tool executor that enforces a subagent profile's [`ToolPolicy`] when
/// executing tool calls from a child session.
pub struct PolicyAwareToolExecutor {
    inner: Arc<dyn ToolExecutor>,
    profiles: Arc<SubagentProfileRegistry>,
    sessions: Arc<RwLock<HashMap<String, Session>>>,
}

impl PolicyAwareToolExecutor {
    pub fn new(
        inner: Arc<dyn ToolExecutor>,
        profiles: Arc<SubagentProfileRegistry>,
        sessions: Arc<RwLock<HashMap<String, Session>>>,
    ) -> Self {
        Self {
            inner,
            profiles,
            sessions,
        }
    }

    /// Look up the `subagent_type` metadata for a session id from the
    /// in-memory cache. Returns `None` when the session is not cached or
    /// the metadata key is missing / blank.
    async fn subagent_type_for_session(&self, session_id: &str) -> Option<String> {
        let sessions = self.sessions.read().await;
        let value = sessions
            .get(session_id)?
            .metadata
            .get("subagent_type")?
            .trim();
        if value.is_empty() {
            None
        } else {
            Some(value.to_string())
        }
    }

    /// Check whether a tool call is permitted under the given policy.
    /// Returns `Ok(())` when allowed, `Err(reason)` when blocked.
    fn check_policy(
        policy: &ToolPolicy,
        tool_name: &str,
        subagent_type: &str,
    ) -> Result<(), String> {
        match policy {
            ToolPolicy::Inherit => Ok(()),
            ToolPolicy::Allowlist { allow } => {
                if allow.iter().any(|t| t == tool_name) {
                    Ok(())
                } else {
                    Err(format!(
                        "tool '{tool_name}' is not permitted for subagent_type \
                         '{subagent_type}' (allowlist policy: {allow:?})"
                    ))
                }
            }
            ToolPolicy::Denylist { deny } => {
                if deny.iter().any(|t| t == tool_name) {
                    Err(format!(
                        "tool '{tool_name}' is denied for subagent_type \
                         '{subagent_type}' (denylist policy: {deny:?})"
                    ))
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Resolve the policy for a tool call: returns `Ok(())` when the call
    /// should proceed, or an `Err` payload to be surfaced as a
    /// `ToolError::Execution`. When no policy can be resolved the call is
    /// allowed (legacy / inherit behaviour).
    async fn evaluate(&self, call: &ToolCall, session_id: Option<&str>) -> Result<(), String> {
        let Some(session_id) = session_id else {
            return Ok(());
        };
        let Some(subagent_type) = self.subagent_type_for_session(session_id).await else {
            return Ok(());
        };
        let profile = self.profiles.resolve(&subagent_type);
        Self::check_policy(&profile.tools, call.function.name.trim(), &subagent_type)
    }
}

#[async_trait]
impl ToolExecutor for PolicyAwareToolExecutor {
    async fn execute(&self, call: &ToolCall) -> std::result::Result<ToolResult, ToolError> {
        // No session context available via plain `execute` — fall through.
        // The agent loop calls `execute_with_context`; this branch is only
        // hit by direct callers that don't carry session metadata, in
        // which case we mirror legacy behaviour exactly.
        self.inner.execute(call).await
    }

    async fn execute_with_context(
        &self,
        call: &ToolCall,
        ctx: ToolExecutionContext<'_>,
    ) -> std::result::Result<ToolResult, ToolError> {
        if let Err(reason) = self.evaluate(call, ctx.session_id).await {
            return Err(ToolError::Execution(reason));
        }
        self.inner.execute_with_context(call, ctx).await
    }

    fn list_tools(&self) -> Vec<ToolSchema> {
        // Discovery is intentionally not filtered here; see module docs.
        self.inner.list_tools()
    }

    fn tool_mutability(&self, tool_name: &str) -> bamboo_agent_core::tools::ToolMutability {
        self.inner.tool_mutability(tool_name)
    }

    fn call_mutability(&self, call: &ToolCall) -> bamboo_agent_core::tools::ToolMutability {
        self.inner.call_mutability(call)
    }

    fn tool_concurrency_safe(&self, tool_name: &str) -> bool {
        self.inner.tool_concurrency_safe(tool_name)
    }

    fn call_concurrency_safe(&self, call: &ToolCall) -> bool {
        self.inner.call_concurrency_safe(call)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bamboo_agent_core::tools::{FunctionCall, ToolMutability};
    use bamboo_domain::subagent::SubagentProfile;

    /// Tiny stand-in executor that records every name it was asked to
    /// execute and always succeeds with a fixed payload. We use it to
    /// assert "forwarded vs blocked" without spinning up the full builtin
    /// tool surface.
    struct RecordingExecutor {
        executed: Arc<RwLock<Vec<String>>>,
    }

    impl RecordingExecutor {
        fn new() -> (Arc<Self>, Arc<RwLock<Vec<String>>>) {
            let executed = Arc::new(RwLock::new(Vec::new()));
            let exec = Arc::new(Self {
                executed: executed.clone(),
            });
            (exec, executed)
        }
    }

    #[async_trait]
    impl ToolExecutor for RecordingExecutor {
        async fn execute(&self, call: &ToolCall) -> std::result::Result<ToolResult, ToolError> {
            self.executed.write().await.push(call.function.name.clone());
            Ok(ToolResult {
                success: true,
                result: "ok".to_string(),
                display_preference: None,
            })
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            Vec::new()
        }

        fn tool_mutability(&self, _tool_name: &str) -> ToolMutability {
            ToolMutability::ReadOnly
        }
    }

    fn make_call(name: &str) -> ToolCall {
        ToolCall {
            id: "call_1".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: "{}".to_string(),
            },
        }
    }

    fn registry_with(profile: SubagentProfile) -> Arc<SubagentProfileRegistry> {
        // The registry requires the fallback id to exist in the profile
        // set. Use the profile's own id so each test can declare just one
        // profile and still build a valid registry.
        let id = profile.id.clone();
        Arc::new(
            SubagentProfileRegistry::builder()
                .extend(vec![profile])
                .fallback_id(id)
                .build()
                .expect("registry build"),
        )
    }

    fn profile(id: &str, tools: ToolPolicy) -> SubagentProfile {
        SubagentProfile {
            id: id.to_string(),
            display_name: id.to_string(),
            description: String::new(),
            system_prompt: "p".to_string(),
            tools,
            model_hint: None,
            default_responsibility: None,
            ui: Default::default(),
        }
    }

    async fn sessions_with(
        session_id: &str,
        subagent_type: Option<&str>,
    ) -> Arc<RwLock<HashMap<String, Session>>> {
        let mut map = HashMap::new();
        let mut session = Session::new_child(session_id, "root", "test-model", "Child");
        if let Some(t) = subagent_type {
            session
                .metadata
                .insert("subagent_type".to_string(), t.to_string());
        }
        map.insert(session_id.to_string(), session);
        Arc::new(RwLock::new(map))
    }

    #[tokio::test]
    async fn inherit_policy_forwards_all_calls() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile("test", ToolPolicy::Inherit));
        let sessions = sessions_with("s1", Some("test")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let call = make_call("Read");
        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        exec.execute_with_context(&call, ctx).await.unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Read".to_string()]);
    }

    #[tokio::test]
    async fn allowlist_permits_listed_tool() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string(), "Grep".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("researcher")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        exec.execute_with_context(&make_call("Read"), ctx)
            .await
            .unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Read".to_string()]);
    }

    #[tokio::test]
    async fn allowlist_blocks_unlisted_tool() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("researcher")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        let err = exec
            .execute_with_context(&make_call("Edit"), ctx)
            .await
            .unwrap_err();
        match err {
            ToolError::Execution(msg) => {
                assert!(msg.contains("Edit"), "msg should name tool: {msg}");
                assert!(
                    msg.contains("researcher"),
                    "msg should name subagent_type: {msg}"
                );
                assert!(msg.contains("allowlist"), "msg should name mode: {msg}");
            }
            other => panic!("expected ToolError::Execution, got {other:?}"),
        }
        assert!(executed.read().await.is_empty());
    }

    #[tokio::test]
    async fn denylist_blocks_listed_tool() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "coder",
            ToolPolicy::Denylist {
                deny: vec!["SubSession".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("coder")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        let err = exec
            .execute_with_context(&make_call("SubSession"), ctx)
            .await
            .unwrap_err();
        match err {
            ToolError::Execution(msg) => {
                assert!(msg.contains("SubSession"));
                assert!(msg.contains("denylist"));
            }
            other => panic!("expected ToolError::Execution, got {other:?}"),
        }
        assert!(executed.read().await.is_empty());
    }

    #[tokio::test]
    async fn denylist_permits_unlisted_tool() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "coder",
            ToolPolicy::Denylist {
                deny: vec!["SubSession".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("coder")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        exec.execute_with_context(&make_call("Read"), ctx)
            .await
            .unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Read".to_string()]);
    }

    #[tokio::test]
    async fn missing_session_id_falls_through() {
        // No session_id in context → wrapper must not reject. This is the
        // "legacy / direct caller" path and must keep working.
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("researcher")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext::none("call_1");
        exec.execute_with_context(&make_call("Edit"), ctx)
            .await
            .unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Edit".to_string()]);
    }

    #[tokio::test]
    async fn unknown_session_falls_through() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string()],
            },
        ));
        // Cache contains a different session id than the one referenced.
        let sessions = sessions_with("other", Some("researcher")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("missing"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        exec.execute_with_context(&make_call("Edit"), ctx)
            .await
            .unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Edit".to_string()]);
    }

    #[tokio::test]
    async fn missing_subagent_type_metadata_falls_through() {
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string()],
            },
        ));
        // Session is cached but has no subagent_type metadata.
        let sessions = sessions_with("s1", None).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        let ctx = ToolExecutionContext {
            session_id: Some("s1"),
            tool_call_id: "call_1",
            event_tx: None,
            available_tool_schemas: None,
        };
        exec.execute_with_context(&make_call("Edit"), ctx)
            .await
            .unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Edit".to_string()]);
    }

    #[tokio::test]
    async fn execute_without_context_forwards() {
        // The plain `execute` path has no session context. We document this
        // by forwarding unconditionally.
        let (inner, executed) = RecordingExecutor::new();
        let registry = registry_with(profile(
            "researcher",
            ToolPolicy::Allowlist {
                allow: vec!["Read".to_string()],
            },
        ));
        let sessions = sessions_with("s1", Some("researcher")).await;
        let exec = PolicyAwareToolExecutor::new(inner, registry, sessions);

        exec.execute(&make_call("Edit")).await.unwrap();
        assert_eq!(executed.read().await.as_slice(), &["Edit".to_string()]);
    }
}