bamboo-tools 2026.7.6

Tool execution and integrations 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
use async_trait::async_trait;
use bamboo_agent_core::{Tool, ToolCtx, ToolError, ToolOutcome, ToolResult};
use serde::Deserialize;
use serde_json::json;

const DEFAULT_OPTIONS: [&str; 2] = ["OK", "Need changes"];
const MAX_OPTIONS: usize = 6;
const MAX_LIST_ITEMS: usize = 8;

fn default_options() -> Vec<String> {
    DEFAULT_OPTIONS.iter().map(|s| (*s).to_string()).collect()
}

fn default_allow_custom() -> bool {
    true
}

fn normalize_text(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn normalize_optional_text(value: Option<String>) -> Option<String> {
    value.and_then(|raw| normalize_text(&raw))
}

fn normalize_text_list(values: Vec<String>) -> Vec<String> {
    values
        .into_iter()
        .filter_map(|value| normalize_text(&value))
        .take(MAX_LIST_ITEMS)
        .collect()
}

#[derive(Debug, Deserialize)]
struct ConclusionWithOptionsMermaidArgs {
    #[serde(default)]
    title: Option<String>,
    graph: String,
}

#[derive(Debug, Deserialize)]
struct ConclusionWithOptionsConclusionArgs {
    #[serde(default)]
    title: Option<String>,
    summary: String,
    #[serde(default)]
    key_points: Vec<String>,
    #[serde(default)]
    next_steps: Vec<String>,
    #[serde(default)]
    confidence: Option<String>,
    mermaid: ConclusionWithOptionsMermaidArgs,
}

#[derive(Debug, Deserialize)]
struct ConclusionWithOptionsArgs {
    question: String,
    #[serde(default)]
    options: Vec<String>,
    #[serde(default = "default_allow_custom")]
    allow_custom: bool,
    conclusion: ConclusionWithOptionsConclusionArgs,
}

/// Tool for asking user a question with multiple choice options
pub struct ConclusionWithOptionsTool;

impl ConclusionWithOptionsTool {
    /// Create a new ConclusionWithOptionsTool instance.
    ///
    /// This tool prompts the user with a question and provides multiple choice options.
    /// It supports custom answers when `allow_custom` is true.
    pub fn new() -> Self {
        Self
    }
}

impl Default for ConclusionWithOptionsTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Tool for ConclusionWithOptionsTool {
    fn name(&self) -> &str {
        "conclusion_with_options"
    }

    fn description(&self) -> &str {
        "Ask the user a question with options and wait for the user to select or enter a custom answer. Use this as the final interaction step when wrapping up a task turn or when the user must choose next steps. The `conclusion` object is required and must include both a summary and a Mermaid graph."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "question": {
                    "type": "string",
                    "description": "The question to display to the user"
                },
                "conclusion": {
                    "type": "object",
                    "description": "Structured wrap-up context shown before the confirmation question.",
                    "properties": {
                        "title": {
                            "type": "string",
                            "description": "Optional title for the conclusion block."
                        },
                        "summary": {
                            "type": "string",
                            "description": "Main summary text shown to the user."
                        },
                        "key_points": {
                            "type": "array",
                            "description": "Optional short bullet points supporting the summary.",
                            "items": { "type": "string" }
                        },
                        "next_steps": {
                            "type": "array",
                            "description": "Optional follow-up actions.",
                            "items": { "type": "string" }
                        },
                        "confidence": {
                            "type": "string",
                            "description": "Optional confidence label, for example high/medium/low."
                        },
                        "mermaid": {
                            "type": "object",
                            "description": "Mermaid chart payload rendered in the UI.",
                            "properties": {
                                "title": {
                                    "type": "string",
                                    "description": "Optional Mermaid section title."
                                },
                                "graph": {
                                    "type": "string",
                                    "description": "Mermaid graph definition text."
                                }
                            },
                            "required": ["graph"],
                            "additionalProperties": false
                        }
                    },
                    "required": ["summary", "mermaid"],
                    "additionalProperties": false
                },
                "options": {
                    "type": "array",
                    "description": "Candidate answer options (optional). If omitted or invalid, defaults to [\"OK\", \"Need changes\"].",
                    "items": {
                        "type": "string"
                    }
                },
                "allow_custom": {
                    "type": "boolean",
                    "description": "Whether to allow user to enter a custom answer (instead of selecting from options), default true",
                    "default": true
                }
            },
            "required": ["question", "conclusion"],
            "additionalProperties": false
        })
    }

    async fn invoke(
        &self,
        args: serde_json::Value,
        ctx: ToolCtx,
    ) -> Result<ToolOutcome, ToolError> {
        let parsed: ConclusionWithOptionsArgs = serde_json::from_value(args).map_err(|error| {
            ToolError::InvalidArguments(format!("Invalid conclusion_with_options args: {error}"))
        })?;
        let question = normalize_text(&parsed.question).ok_or_else(|| {
            ToolError::InvalidArguments("question must be a non-empty string".to_string())
        })?;
        let summary = normalize_text(&parsed.conclusion.summary).ok_or_else(|| {
            ToolError::InvalidArguments("conclusion.summary must be a non-empty string".to_string())
        })?;
        let mermaid_graph = normalize_text(&parsed.conclusion.mermaid.graph).ok_or_else(|| {
            ToolError::InvalidArguments(
                "conclusion.mermaid.graph must be a non-empty string".to_string(),
            )
        })?;

        let mut options = normalize_text_list(parsed.options);

        if options.len() < 2 {
            options = default_options();
        } else if options.len() > MAX_OPTIONS {
            options.truncate(MAX_OPTIONS);
        }

        let allow_custom = parsed.allow_custom;

        // The structured pending question drives the loop's suspend directly
        // (Phase B: no marker sniff). Built before the display payload, which
        // consumes `question`/`options`.
        let pending_question = bamboo_agent_core::PendingQuestion {
            tool_call_id: ctx.tool_call_id.to_string(),
            tool_name: self.name().to_string(),
            question: question.clone(),
            options: options.clone(),
            allow_custom,
            source: bamboo_agent_core::PendingQuestionSource::PauseTool,
        };

        // Build the display payload (rich conclusion data for the transcript + UI)
        let result_payload = json!({
            "status": "awaiting_user_input",
            "type": "conclusion_with_options",
            "question": question,
            "options": options,
            "allow_custom": allow_custom,
            "conclusion": {
                "title": normalize_optional_text(parsed.conclusion.title).unwrap_or_else(|| "Conclusion".to_string()),
                "summary": summary,
                "key_points": normalize_text_list(parsed.conclusion.key_points),
                "next_steps": normalize_text_list(parsed.conclusion.next_steps),
                "confidence": normalize_optional_text(parsed.conclusion.confidence),
                "mermaid": {
                    "title": normalize_optional_text(parsed.conclusion.mermaid.title),
                    "graph": mermaid_graph
                }
            }
        });

        Ok(ToolOutcome::NeedsHuman {
            question: pending_question,
            result: ToolResult {
                success: true,
                result: result_payload.to_string(),
                display_preference: Some("conclusion_with_options".to_string()),
                images: Vec::new(),
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn minimal_conclusion() -> serde_json::Value {
        json!({
            "summary": "Core changes are done and ready for confirmation.",
            "mermaid": {
                "graph": "graph TD\nA[Done]-->B[Confirm]"
            }
        })
    }

    #[test]
    fn test_conclusion_with_options_tool_name() {
        let tool = ConclusionWithOptionsTool::new();
        assert_eq!(tool.name(), "conclusion_with_options");
    }

    #[tokio::test]
    async fn test_execute_valid_input() {
        let tool = ConclusionWithOptionsTool::new();

        let out = tool
            .invoke(
                json!({
                    "question": "Please select deployment environment",
                    "options": ["Development", "Testing", "Production"],
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await
            .expect("tool should execute successfully");
        let ToolOutcome::NeedsHuman { result, .. } = out else {
            panic!("expected NeedsHuman")
        };

        assert!(result.success);
        assert_eq!(
            result.display_preference,
            Some("conclusion_with_options".to_string())
        );

        let parsed: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(parsed["status"], "awaiting_user_input");
        assert_eq!(parsed["question"], "Please select deployment environment");
        assert!(parsed["allow_custom"].as_bool().unwrap());
        assert_eq!(
            parsed["conclusion"]["summary"],
            "Core changes are done and ready for confirmation."
        );
        assert_eq!(
            parsed["conclusion"]["mermaid"]["graph"],
            "graph TD\nA[Done]-->B[Confirm]"
        );
    }

    #[tokio::test]
    async fn test_execute_accepts_two_options() {
        let tool = ConclusionWithOptionsTool::new();

        let result = tool
            .invoke(
                json!({
                    "question": "Please confirm?",
                    "options": ["Yes", "No"],
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_with_too_few_options_uses_defaults() {
        let tool = ConclusionWithOptionsTool::new();

        let out = tool
            .invoke(
                json!({
                    "question": "Please select?",
                    "options": ["Only one option"],
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await
            .expect("tool should execute with fallback defaults");
        let ToolOutcome::NeedsHuman { result, .. } = out else {
            panic!("expected NeedsHuman")
        };

        let parsed: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(parsed["options"], json!(["OK", "Need changes"]));
    }

    #[tokio::test]
    async fn test_execute_without_options_uses_defaults() {
        let tool = ConclusionWithOptionsTool::new();

        let out = tool
            .invoke(
                json!({
                    "question": "Any other requests before I finish?",
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await
            .expect("tool should execute without options");
        let ToolOutcome::NeedsHuman { result, .. } = out else {
            panic!("expected NeedsHuman")
        };

        let parsed: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(parsed["options"], json!(["OK", "Need changes"]));
    }

    #[tokio::test]
    async fn test_execute_truncates_options_to_six_items() {
        let tool = ConclusionWithOptionsTool::new();

        let out = tool
            .invoke(
                json!({
                    "question": "Please pick one",
                    "options": ["1", "2", "3", "4", "5", "6", "7"],
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await
            .expect("tool should execute and truncate options");
        let ToolOutcome::NeedsHuman { result, .. } = out else {
            panic!("expected NeedsHuman")
        };

        let parsed: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(parsed["options"], json!(["1", "2", "3", "4", "5", "6"]));
    }

    #[tokio::test]
    async fn test_execute_with_allow_custom_false() {
        let tool = ConclusionWithOptionsTool::new();

        let out = tool
            .invoke(
                json!({
                    "question": "Please confirm",
                    "options": ["Yes", "No", "Cancel"],
                    "allow_custom": false,
                    "conclusion": minimal_conclusion()
                }),
                ToolCtx::none("t"),
            )
            .await
            .expect("tool should execute");
        let ToolOutcome::NeedsHuman { result, .. } = out else {
            panic!("expected NeedsHuman")
        };

        let parsed: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert!(!parsed["allow_custom"].as_bool().unwrap());
    }

    #[tokio::test]
    async fn test_execute_rejects_missing_conclusion() {
        let tool = ConclusionWithOptionsTool::new();

        let result = tool
            .invoke(
                json!({
                    "question": "Please confirm"
                }),
                ToolCtx::none("t"),
            )
            .await;

        assert!(result.is_err());
        let error = result.expect_err("expected invalid args");
        if let ToolError::InvalidArguments(message) = error {
            assert!(message.contains("conclusion"));
        } else {
            panic!("expected invalid arguments");
        }
    }

    #[tokio::test]
    async fn test_execute_rejects_empty_mermaid_graph() {
        let tool = ConclusionWithOptionsTool::new();

        let result = tool
            .invoke(
                json!({
                    "question": "Please confirm",
                    "conclusion": {
                        "summary": "Summary",
                        "mermaid": { "graph": "   " }
                    }
                }),
                ToolCtx::none("t"),
            )
            .await;

        assert!(result.is_err());
        let error = result.expect_err("expected invalid args");
        if let ToolError::InvalidArguments(message) = error {
            assert!(message.contains("conclusion.mermaid.graph"));
        } else {
            panic!("expected invalid arguments");
        }
    }
}