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

use crate::permission::PermissionType;

/// Tool for the LLM to proactively request additional permissions from the user.
///
/// Instead of failing when a permission is denied, the LLM can call this tool
/// to explain why it needs certain permissions and ask the user for approval.
///
/// The tool returns a payload that signals the agent loop to pause and ask
/// the user for permission approval (similar to how `conclusion_with_options` pauses for
/// user input).
///
/// Inspired by Codex's `request_permissions` tool which allows the model to
/// request filesystem and network permissions at runtime.
pub struct RequestPermissionsTool;

impl RequestPermissionsTool {
    pub fn new() -> Self {
        Self
    }
}

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

/// Validate a permission type string and return the matching PermissionType.
fn parse_permission_type(s: &str) -> Result<PermissionType, String> {
    match s {
        "write_file" | "WriteFile" => Ok(PermissionType::WriteFile),
        "execute_command" | "ExecuteCommand" => Ok(PermissionType::ExecuteCommand),
        "git_write" | "GitWrite" => Ok(PermissionType::GitWrite),
        "http_request" | "HttpRequest" => Ok(PermissionType::HttpRequest),
        "delete_operation" | "DeleteOperation" => Ok(PermissionType::DeleteOperation),
        "terminal_session" | "TerminalSession" => Ok(PermissionType::TerminalSession),
        other => Err(format!(
            "Unknown permission type '{}'. Valid types: write_file, execute_command, git_write, http_request, delete_operation, terminal_session",
            other
        )),
    }
}

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

    fn description(&self) -> &str {
        "Request additional permissions from the user. Use this when you need to perform an operation that requires elevated permissions (e.g., writing to a specific directory, executing a dangerous command, making HTTP requests). The user will be prompted to approve or deny the request."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "reason": {
                    "type": "string",
                    "description": "Clear explanation of why these permissions are needed"
                },
                "permissions": {
                    "type": "array",
                    "description": "List of permissions being requested",
                    "items": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string",
                                "description": "Permission type: write_file, execute_command, git_write, http_request, delete_operation, terminal_session",
                                "enum": ["write_file", "execute_command", "git_write", "http_request", "delete_operation", "terminal_session"]
                            },
                            "resource": {
                                "type": "string",
                                "description": "The resource pattern (file path, URL pattern, command pattern, etc.)"
                            },
                            "description": {
                                "type": "string",
                                "description": "Optional human-readable description of this specific permission"
                            }
                        },
                        "required": ["type", "resource"]
                    },
                    "minItems": 1
                }
            },
            "required": ["reason", "permissions"]
        })
    }

    async fn invoke(
        &self,
        args: serde_json::Value,
        _ctx: ToolCtx,
    ) -> Result<ToolOutcome, ToolError> {
        let reason = args["reason"]
            .as_str()
            .ok_or_else(|| ToolError::InvalidArguments("Missing 'reason' parameter".to_string()))?
            .trim();

        if reason.is_empty() {
            return Err(ToolError::InvalidArguments(
                "'reason' cannot be empty".to_string(),
            ));
        }

        let permissions = args["permissions"].as_array().ok_or_else(|| {
            ToolError::InvalidArguments("Missing 'permissions' array parameter".to_string())
        })?;

        if permissions.is_empty() {
            return Err(ToolError::InvalidArguments(
                "'permissions' array must contain at least one item".to_string(),
            ));
        }

        // Validate each permission entry
        let mut validated_permissions = Vec::new();
        for (i, perm) in permissions.iter().enumerate() {
            let perm_type_str = perm["type"].as_str().ok_or_else(|| {
                ToolError::InvalidArguments(format!("permissions[{}]: missing 'type' field", i))
            })?;

            let perm_type = parse_permission_type(perm_type_str)
                .map_err(|e| ToolError::InvalidArguments(format!("permissions[{}]: {}", i, e)))?;

            let resource = perm["resource"].as_str().ok_or_else(|| {
                ToolError::InvalidArguments(format!("permissions[{}]: missing 'resource' field", i))
            })?;

            if resource.trim().is_empty() {
                return Err(ToolError::InvalidArguments(format!(
                    "permissions[{}]: 'resource' cannot be empty",
                    i
                )));
            }

            let description = perm["description"]
                .as_str()
                .unwrap_or_else(|| perm_type.description());

            validated_permissions.push(json!({
                "type": perm_type_str,
                "resource": resource.trim(),
                "description": description,
                "risk_level": perm_type.risk_level().label(),
            }));
        }

        // Build a human-readable question for the UI
        let mut question = format!("**Permission Request**\n\n{}\n\n", reason);
        question.push_str("**Requested permissions:**\n");
        for perm in &validated_permissions {
            let risk = perm["risk_level"].as_str().unwrap_or("Unknown");
            let desc = perm["description"].as_str().unwrap_or("");
            let resource = perm["resource"].as_str().unwrap_or("");
            let ptype = perm["type"].as_str().unwrap_or("");
            question.push_str(&format!(
                "- **[{}]** {} `{}` — {}\n",
                risk, ptype, resource, desc
            ));
        }

        let result_payload = json!({
            "status": "awaiting_permission_approval",
            "question": question,
            "reason": reason,
            "permissions": validated_permissions,
            "options": ["Approve", "Deny"],
            "allow_custom": false
        });

        Ok(ToolOutcome::Completed(ToolResult {
            success: true,
            result: result_payload.to_string(),
            display_preference: Some("request_permissions".to_string()),
            images: Vec::new(),
        }))
    }
}

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

    #[test]
    fn test_tool_name() {
        let tool = RequestPermissionsTool::new();
        assert_eq!(tool.name(), "request_permissions");
    }

    #[tokio::test]
    async fn test_valid_single_permission_request() {
        let tool = RequestPermissionsTool::new();
        let out = tool
            .invoke(
                json!({
                    "reason": "Need to write deployment config",
                    "permissions": [{
                        "type": "write_file",
                        "resource": "/etc/nginx/conf.d/*"
                    }]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap();
        let ToolOutcome::Completed(result) = out else {
            panic!("expected Completed")
        };

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

        let payload: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(payload["status"], "awaiting_permission_approval");
        assert!(payload["question"]
            .as_str()
            .unwrap()
            .contains("deployment config"));
        assert_eq!(payload["permissions"].as_array().unwrap().len(), 1);
        assert_eq!(payload["options"], json!(["Approve", "Deny"]));
    }

    #[tokio::test]
    async fn test_valid_multiple_permissions() {
        let tool = RequestPermissionsTool::new();
        let out = tool
            .invoke(
                json!({
                    "reason": "Need to deploy the application",
                    "permissions": [
                        {
                            "type": "execute_command",
                            "resource": "docker compose up -d",
                            "description": "Start Docker containers"
                        },
                        {
                            "type": "http_request",
                            "resource": "registry.example.com",
                            "description": "Pull container images"
                        }
                    ]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap();
        let ToolOutcome::Completed(result) = out else {
            panic!("expected Completed")
        };

        assert!(result.success);
        let payload: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(payload["permissions"].as_array().unwrap().len(), 2);
        assert_eq!(payload["permissions"][0]["risk_level"], "High Risk");
        assert_eq!(payload["permissions"][1]["risk_level"], "Medium Risk");
    }

    #[tokio::test]
    async fn test_missing_reason() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "permissions": [{"type": "write_file", "resource": "/tmp/test"}]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(matches!(err, ToolError::InvalidArguments(msg) if msg.contains("reason")));
    }

    #[tokio::test]
    async fn test_empty_reason() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "reason": "   ",
                    "permissions": [{"type": "write_file", "resource": "/tmp/test"}]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(matches!(err, ToolError::InvalidArguments(msg) if msg.contains("empty")));
    }

    #[tokio::test]
    async fn test_missing_permissions() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "reason": "Need access"
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(matches!(err, ToolError::InvalidArguments(msg) if msg.contains("permissions")));
    }

    #[tokio::test]
    async fn test_empty_permissions_array() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "reason": "Need access",
                    "permissions": []
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(matches!(err, ToolError::InvalidArguments(msg) if msg.contains("at least one")));
    }

    #[tokio::test]
    async fn test_invalid_permission_type() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "reason": "Need access",
                    "permissions": [{"type": "invalid_type", "resource": "/tmp"}]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(
            matches!(err, ToolError::InvalidArguments(msg) if msg.contains("Unknown permission type"))
        );
    }

    #[tokio::test]
    async fn test_missing_resource() {
        let tool = RequestPermissionsTool::new();
        let err = tool
            .invoke(
                json!({
                    "reason": "Need access",
                    "permissions": [{"type": "write_file"}]
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap_err();

        assert!(matches!(err, ToolError::InvalidArguments(msg) if msg.contains("resource")));
    }

    #[tokio::test]
    async fn test_all_permission_types() {
        let tool = RequestPermissionsTool::new();
        let types = [
            "write_file",
            "execute_command",
            "git_write",
            "http_request",
            "delete_operation",
            "terminal_session",
        ];

        for ptype in types {
            let result = tool
                .invoke(
                    json!({
                        "reason": format!("Test {}", ptype),
                        "permissions": [{"type": ptype, "resource": "/test"}]
                    }),
                    ToolCtx::none("t"),
                )
                .await;
            assert!(
                result.is_ok(),
                "Permission type '{}' should be valid",
                ptype
            );
        }
    }

    #[tokio::test]
    async fn test_pascal_case_permission_types() {
        let tool = RequestPermissionsTool::new();
        let types = [
            "WriteFile",
            "ExecuteCommand",
            "GitWrite",
            "HttpRequest",
            "DeleteOperation",
            "TerminalSession",
        ];

        for ptype in types {
            let result = tool
                .invoke(
                    json!({
                        "reason": format!("Test {}", ptype),
                        "permissions": [{"type": ptype, "resource": "/test"}]
                    }),
                    ToolCtx::none("t"),
                )
                .await;
            assert!(
                result.is_ok(),
                "PascalCase permission type '{}' should be valid",
                ptype
            );
        }
    }

    #[test]
    fn test_parse_permission_type() {
        assert_eq!(
            parse_permission_type("write_file").unwrap(),
            PermissionType::WriteFile
        );
        assert_eq!(
            parse_permission_type("WriteFile").unwrap(),
            PermissionType::WriteFile
        );
        assert!(parse_permission_type("unknown").is_err());
    }
}