bamboo-engine 2026.8.24

Execution engine and orchestration 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
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::mpsc;

use super::{maybe_handle_user_question_tool, UserQuestionToolContext};
use crate::runtime::config::AgentLoopConfig;
use bamboo_agent_core::tools::{FunctionCall, ToolCall, ToolResult};
use bamboo_agent_core::{AgentEvent, Role, Session};
use bamboo_domain::session::runtime_state::{AgentRuntimeState, PlanModeState, PlanModeStatus};
use bamboo_memory::plan_store::PlanStore;
use chrono::Utc;

struct FailingClarificationPersistence;

#[async_trait]
impl bamboo_domain::RuntimeSessionPersistence for FailingClarificationPersistence {
    async fn save_runtime_session(&self, _session: &mut Session) -> std::io::Result<()> {
        Err(std::io::Error::other(
            "injected pending-question save failure",
        ))
    }
}

#[tokio::test]
async fn maybe_handle_user_question_tool_sets_pending_question_and_emits_events() {
    let tool_call = ToolCall {
        id: "ask-1".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "request_permissions".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let result = ToolResult {
        success: true,
        result: serde_json::json!({
            "question": "Continue?",
            "options": ["Yes", "No"],
            "allow_custom": false
        })
        .to_string(),
        display_preference: Some("request_permissions".to_string()),
        images: Vec::new(),
    };

    let (tx, mut rx) = mpsc::channel(8);
    let mut session = Session::new("session-1", "model");

    let handled = maybe_handle_user_question_tool(UserQuestionToolContext {
        tool_call: &tool_call,
        result: &result,
        session: &mut session,
        event_tx: &tx,
        metrics_collector: None,
        session_id: "session-1",
        round_id: "round-1",
        config: &AgentLoopConfig::default(),
    })
    .await;

    assert!(handled);
    assert_eq!(session.messages.len(), 1);
    assert!(matches!(session.messages[0].role, Role::Tool));
    let saved_payload: serde_json::Value =
        serde_json::from_str(&session.messages[0].content).expect("saved tool result payload");
    assert_eq!(saved_payload["question"], "Continue?");
    assert_eq!(saved_payload["allow_custom"], false);

    let pending = session
        .pending_question
        .as_ref()
        .expect("pending question should be set");
    assert_eq!(pending.tool_call_id, "ask-1");
    assert_eq!(pending.tool_name, "request_permissions");
    assert_eq!(pending.question, "Continue?");
    assert_eq!(pending.options, vec!["Yes".to_string(), "No".to_string()]);
    assert!(!pending.allow_custom);
    assert_eq!(
        pending.source,
        bamboo_agent_core::PendingQuestionSource::PauseTool
    );

    let first_event = rx.recv().await.expect("first event");
    match first_event {
        AgentEvent::ToolComplete {
            tool_call_id,
            result: event_result,
        } => {
            assert_eq!(tool_call_id, "ask-1");
            assert!(event_result.success);
        }
        other => panic!("unexpected first event: {other:?}"),
    }

    let second_event = rx.recv().await.expect("second event");
    match second_event {
        AgentEvent::NeedClarification {
            question,
            options,
            tool_call_id,
            tool_name,
            allow_custom,
            source,
        } => {
            assert_eq!(question, "Continue?");
            assert_eq!(options, Some(vec!["Yes".to_string(), "No".to_string()]));
            assert_eq!(tool_call_id, Some("ask-1".to_string()));
            assert_eq!(tool_name, Some("request_permissions".to_string()));
            assert!(!allow_custom);
            assert_eq!(
                source,
                Some(bamboo_agent_core::PendingQuestionSource::PauseTool)
            );
        }
        other => panic!("unexpected second event: {other:?}"),
    }
}

#[tokio::test]
async fn legacy_pending_question_persistence_failure_never_publishes_clarification() {
    let tool_call = ToolCall {
        id: "ask-failed-save".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "request_permissions".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let result = ToolResult {
        success: true,
        result: serde_json::json!({
            "question": "Continue?",
            "options": ["Yes", "No"],
            "allow_custom": false
        })
        .to_string(),
        display_preference: Some("request_permissions".to_string()),
        images: Vec::new(),
    };
    let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> =
        Arc::new(FailingClarificationPersistence);
    let config = AgentLoopConfig {
        persistence: Some(persistence),
        ..AgentLoopConfig::default()
    };
    let (tx, mut rx) = mpsc::channel(8);
    let mut session = Session::new("failed-save", "model");

    assert!(
        maybe_handle_user_question_tool(UserQuestionToolContext {
            tool_call: &tool_call,
            result: &result,
            session: &mut session,
            event_tx: &tx,
            metrics_collector: None,
            session_id: "failed-save",
            round_id: "round-1",
            config: &config,
        })
        .await
    );

    let events: Vec<_> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
    assert!(events.iter().any(
        |event| matches!(event, AgentEvent::Error { message } if message.contains("could not be saved"))
    ));
    assert!(events
        .iter()
        .all(|event| !matches!(event, AgentEvent::NeedClarification { .. })));
}

#[tokio::test]
async fn maybe_handle_user_question_tool_handles_request_permissions() {
    let tool_call = ToolCall {
        id: "perm-1".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "request_permissions".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let result = ToolResult {
        success: true,
        result: serde_json::json!({
            "status": "awaiting_permission_approval",
            "question": "**Permission Request**\n\nNeed write access\n\n**Requested permissions:**\n- write_file `/tmp/deploy`\n",
            "reason": "Need write access",
            "permissions": [{"type": "write_file", "resource": "/tmp/deploy", "risk_level": "Medium Risk"}],
            "options": ["Approve", "Deny"],
            "allow_custom": false
        })
        .to_string(),
        display_preference: Some("request_permissions".to_string()),
        images: Vec::new(),
    };

    let (tx, mut rx) = mpsc::channel(8);
    let mut session = Session::new("session-perm", "model");

    let handled = maybe_handle_user_question_tool(UserQuestionToolContext {
        tool_call: &tool_call,
        result: &result,
        session: &mut session,
        event_tx: &tx,
        metrics_collector: None,
        session_id: "session-perm",
        round_id: "round-1",
        config: &AgentLoopConfig::default(),
    })
    .await;

    assert!(
        handled,
        "request_permissions should be handled as a pause-tool"
    );
    assert_eq!(session.messages.len(), 1);
    assert!(matches!(session.messages[0].role, Role::Tool));

    let pending = session
        .pending_question
        .as_ref()
        .expect("pending question should be set for request_permissions");
    assert_eq!(pending.tool_call_id, "perm-1");
    assert_eq!(pending.tool_name, "request_permissions");
    assert!(pending.question.contains("Permission Request"));
    assert_eq!(
        pending.options,
        vec!["Approve".to_string(), "Deny".to_string()]
    );
    assert!(!pending.allow_custom);
    assert_eq!(
        pending.source,
        bamboo_agent_core::PendingQuestionSource::PauseTool
    );

    let first_event = rx.recv().await.expect("first event");
    assert!(matches!(first_event, AgentEvent::ToolComplete { .. }));

    let second_event = rx.recv().await.expect("second event");
    match second_event {
        AgentEvent::NeedClarification {
            question,
            options,
            tool_call_id,
            tool_name,
            allow_custom,
            source,
        } => {
            assert!(question.contains("Permission Request"));
            assert_eq!(
                options,
                Some(vec!["Approve".to_string(), "Deny".to_string()])
            );
            assert_eq!(tool_call_id, Some("perm-1".to_string()));
            assert_eq!(tool_name, Some("request_permissions".to_string()));
            assert!(!allow_custom);
            assert_eq!(
                source,
                Some(bamboo_agent_core::PendingQuestionSource::PauseTool)
            );
        }
        other => panic!("unexpected second event: {other:?}"),
    }
}

#[tokio::test]
async fn maybe_handle_user_question_tool_persists_exit_plan_file_and_emits_update() {
    let tool_call = ToolCall {
        id: "exit-1".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "ExitPlanMode".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let plan_body = "# Plan\n\n## investigate\n- task_id: investigate\n- Investigate\n\n## implement\n- task_id: implement\n- Implement\n\n## verify\n- task_id: verify\n- Verify";
    let result = ToolResult {
        success: true,
        result: serde_json::json!({
            "status": "awaiting_user_input",
            "question": "Review?",
            "options": ["Approve (Default mode)", "Stay in plan mode"],
            "allow_custom": false,
            "plan": plan_body,
            "exit_mode": "default"
        })
        .to_string(),
        display_preference: Some("conclusion_with_options".to_string()),
        images: Vec::new(),
    };

    let temp_dir = tempfile::tempdir().expect("temp dir");
    let config = AgentLoopConfig {
        app_data_dir: Some(temp_dir.path().to_path_buf()),
        ..AgentLoopConfig::default()
    };
    let (tx, mut rx) = mpsc::channel(8);
    let mut session = Session::new("session-exit-plan", "model");
    session.agent_runtime_state = Some(AgentRuntimeState::new("run-1"));
    session
        .agent_runtime_state
        .as_mut()
        .unwrap()
        .round
        .current_round = 5;
    session
        .agent_runtime_state
        .as_mut()
        .unwrap()
        .round
        .last_round_id = Some("round-5".to_string());
    session.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
        entered_at: Utc::now(),
        pre_permission_mode: "default".to_string(),
        plan_file_path: None,
        status: PlanModeStatus::Designing,
    });
    session.task_list = Some(bamboo_domain::TaskList {
        session_id: "session-exit-plan".to_string(),
        title: "Plan Tasks".to_string(),
        items: vec![
            bamboo_domain::TaskItem {
                id: "discovery".to_string(),
                description: "Discovery".to_string(),
                status: bamboo_domain::TaskItemStatus::Completed,
                ..bamboo_domain::TaskItem::default()
            },
            bamboo_domain::TaskItem {
                id: "investigate".to_string(),
                description: "Investigate".to_string(),
                status: bamboo_domain::TaskItemStatus::InProgress,
                ..bamboo_domain::TaskItem::default()
            },
            bamboo_domain::TaskItem {
                id: "implement".to_string(),
                description: "Implement".to_string(),
                status: bamboo_domain::TaskItemStatus::Pending,
                ..bamboo_domain::TaskItem::default()
            },
        ],
        created_at: Utc::now(),
        updated_at: Utc::now(),
    });

    let handled = maybe_handle_user_question_tool(UserQuestionToolContext {
        tool_call: &tool_call,
        result: &result,
        session: &mut session,
        event_tx: &tx,
        metrics_collector: None,
        session_id: "session-exit-plan",
        round_id: "round-1",
        config: &config,
    })
    .await;

    assert!(handled);
    let plan_mode = session
        .agent_runtime_state
        .as_ref()
        .and_then(|state| state.plan_mode.as_ref())
        .expect("plan mode should remain active while awaiting approval");
    assert_eq!(plan_mode.status, PlanModeStatus::AwaitingApproval);
    let plan_file_path = plan_mode
        .plan_file_path
        .as_ref()
        .expect("plan file path should be recorded");
    assert!(
        plan_file_path.contains("/plan/")
            || plan_file_path.ends_with("plan\\session-exit-plan.md")
            || plan_file_path.contains("\\plan\\")
    );
    let saved_plan = std::fs::read_to_string(plan_file_path).expect("saved plan file");
    assert_eq!(saved_plan, plan_body);

    let store = PlanStore::new(temp_dir.path()).expect("plan store");
    let state = store
        .read_state("session-exit-plan")
        .expect("read state")
        .expect("state should exist");
    assert_eq!(state.status.as_deref(), Some("awaiting_approval"));
    assert!(state.plan_hash.is_some());
    assert_eq!(state.active_section_id.as_deref(), Some("investigate"));
    assert_eq!(state.next_section_id.as_deref(), Some("implement"));
    assert_eq!(state.last_completed_task_id.as_deref(), Some("discovery"));
    assert_eq!(state.round_hint, Some(5));
    let cursor = store
        .read_cursor("session-exit-plan")
        .expect("read cursor")
        .expect("cursor should exist");
    assert_eq!(cursor.cursor_type.as_deref(), Some("task_item"));
    assert_eq!(cursor.current_section_id.as_deref(), Some("investigate"));
    assert_eq!(cursor.current_task_ordinal, Some(2));
    assert_eq!(cursor.next_task_id.as_deref(), Some("implement"));
    assert_eq!(cursor.next_task_ordinal, Some(3));
    assert_eq!(cursor.last_completed_task_id.as_deref(), Some("discovery"));
    assert_eq!(cursor.round_hint, Some(5));
    assert_eq!(cursor.round_id_hint.as_deref(), Some("round-5"));
    assert_eq!(
        cursor.suspension_hook_point.as_deref(),
        Some("AfterToolExecution")
    );
    assert_eq!(cursor.tool_call_boundary.as_deref(), Some("ExitPlanMode"));
    assert!(cursor
        .resume_note
        .as_deref()
        .unwrap_or("")
        .contains("Resume"));

    let first_event = rx.recv().await.expect("first event");
    assert!(matches!(first_event, AgentEvent::ToolComplete { .. }));

    let second_event = rx.recv().await.expect("second event");
    match second_event {
        AgentEvent::PlanFileUpdated {
            session_id,
            file_path,
            content_summary,
            status,
        } => {
            assert_eq!(session_id, "session-exit-plan");
            assert_eq!(file_path, *plan_file_path);
            assert!(content_summary.contains("# Plan") || content_summary.contains("Plan"));
            assert_eq!(
                status,
                Some(bamboo_domain::PlanModeStatus::AwaitingApproval)
            );
        }
        other => panic!("unexpected second event: {other:?}"),
    }

    let third_event = rx.recv().await.expect("third event");
    assert!(matches!(third_event, AgentEvent::NeedClarification { .. }));
}

#[tokio::test]
async fn maybe_handle_user_question_tool_ignores_unrelated_tool_calls() {
    let tool_call = ToolCall {
        id: "read-1".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "Read".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let result = ToolResult {
        success: true,
        result: "{}".to_string(),
        display_preference: None,
        images: Vec::new(),
    };

    let (tx, mut rx) = mpsc::channel(4);
    let mut session = Session::new("session-1", "model");

    let handled = maybe_handle_user_question_tool(UserQuestionToolContext {
        tool_call: &tool_call,
        result: &result,
        session: &mut session,
        event_tx: &tx,
        metrics_collector: None,
        session_id: "session-1",
        round_id: "round-1",
        config: &AgentLoopConfig::default(),
    })
    .await;

    assert!(!handled);
    assert!(session.pending_question.is_none());
    assert!(session.messages.is_empty());
    assert!(rx.try_recv().is_err());
}