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
use async_trait::async_trait;
use bamboo_agent_core::{Tool, ToolClass, ToolCtx, ToolError, ToolOutcome, ToolResult};
use serde::Deserialize;
use serde_json::json;
use std::path::Path;

use super::read_tracker;

const BLOCKED_DEVICE_PATHS: &[&str] = &[
    "/dev/zero",
    "/dev/random",
    "/dev/urandom",
    "/dev/full",
    "/dev/stdin",
    "/dev/tty",
    "/dev/console",
    "/dev/stdout",
    "/dev/stderr",
    "/dev/fd/0",
    "/dev/fd/1",
    "/dev/fd/2",
];

const MAX_READ_SIZE: u64 = 10 * 1024 * 1024; // 10 MB

#[derive(Debug, Deserialize)]
struct ReadArgs {
    file_path: String,
    #[serde(default)]
    offset: Option<usize>,
    #[serde(default)]
    limit: Option<usize>,
}

pub struct ReadTool;

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

    fn is_blocked_device_path(path: &Path) -> bool {
        let display = path.to_string_lossy();
        if BLOCKED_DEVICE_PATHS
            .iter()
            .any(|blocked| display == *blocked)
        {
            return true;
        }

        display.starts_with("/proc/")
            && (display.ends_with("/fd/0")
                || display.ends_with("/fd/1")
                || display.ends_with("/fd/2"))
    }
}

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

fn slice_bounds(total: usize, offset: usize, limit: Option<usize>) -> (usize, usize) {
    let start = offset.min(total);
    let end = limit
        .map(|value| start.saturating_add(value).min(total))
        .unwrap_or(total);
    (start, end)
}

fn continuation_hint(
    noun: &str,
    start: usize,
    end: usize,
    total: usize,
    limit: Option<usize>,
) -> Option<String> {
    if end >= total {
        return None;
    }

    let shown = end.saturating_sub(start);
    let limit_fragment = match limit {
        Some(value) => format!(", limit={value}"),
        None => String::new(),
    };

    if shown == 0 {
        return Some(format!(
            "[TRUNCATED] No {noun} returned. Continue with offset={end}{limit_fragment}"
        ));
    }

    Some(format!(
        "[TRUNCATED] Showing {noun} {first}-{end} of {total}. Continue with offset={end}{limit_fragment}",
        first = start + 1
    ))
}

fn render_file_with_line_numbers(content: &str, offset: usize, limit: Option<usize>) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let (start, end) = slice_bounds(lines.len(), offset, limit);

    let mut rendered = lines[start..end]
        .iter()
        .enumerate()
        .map(|(idx, line)| format!("{:>6}\t{}", start + idx + 1, line))
        .collect::<Vec<_>>()
        .join("\n");

    if let Some(hint) = continuation_hint("lines", start, end, lines.len(), limit) {
        if !rendered.is_empty() {
            rendered.push('\n');
        }
        rendered.push_str(&hint);
    }

    rendered
}

fn render_directory_entries(entries: &[String], offset: usize, limit: Option<usize>) -> String {
    let (start, end) = slice_bounds(entries.len(), offset, limit);
    let mut rendered = entries[start..end]
        .iter()
        .enumerate()
        .map(|(idx, entry)| format!("{:>6}\t{}", start + idx + 1, entry))
        .collect::<Vec<_>>()
        .join("\n");

    if let Some(hint) = continuation_hint("entries", start, end, entries.len(), limit) {
        if !rendered.is_empty() {
            rendered.push('\n');
        }
        rendered.push_str(&hint);
    }

    rendered
}

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

    fn description(&self) -> &str {
        "Read a local file or directory with line-numbered output (supports offset/limit). Use this before Edit/Write on existing files. Safe for text files and directories; binary files are omitted and blocking device paths are rejected."
    }

    fn classify(&self, _args: &serde_json::Value) -> ToolClass {
        ToolClass::READONLY_PARALLEL
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "The absolute path to the file or directory to read"
                },
                "offset": {
                    "type": "number",
                    "description": "The line offset to start reading from. Omit when you want the full file or directory listing."
                },
                "limit": {
                    "type": "number",
                    "description": "The maximum number of lines or directory entries to read. Omit for the full result when safe."
                }
            },
            "required": ["file_path"],
            "additionalProperties": false
        })
    }

    async fn invoke(
        &self,
        args: serde_json::Value,
        ctx: ToolCtx,
    ) -> Result<ToolOutcome, ToolError> {
        let parsed: ReadArgs = serde_json::from_value(args)
            .map_err(|e| ToolError::InvalidArguments(format!("Invalid Read args: {}", e)))?;

        let path = Path::new(parsed.file_path.trim());
        if !path.is_absolute() {
            return Err(ToolError::InvalidArguments(
                "file_path must be an absolute path".to_string(),
            ));
        }
        if Self::is_blocked_device_path(path) {
            return Err(ToolError::InvalidArguments(format!(
                "Refusing to read blocking or unbounded device path: {}",
                path.display()
            )));
        }

        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| ToolError::Execution(format!("Failed to read path: {}", e)))?;

        if metadata.is_dir() {
            let mut dir = tokio::fs::read_dir(path)
                .await
                .map_err(|e| ToolError::Execution(format!("Failed to read directory: {}", e)))?;
            let mut entries = Vec::new();
            while let Some(entry) = dir
                .next_entry()
                .await
                .map_err(|e| ToolError::Execution(format!("Failed to iterate directory: {}", e)))?
            {
                let mut name = entry.file_name().to_string_lossy().to_string();
                if entry
                    .file_type()
                    .await
                    .map_err(|e| ToolError::Execution(format!("Failed to inspect entry: {}", e)))?
                    .is_dir()
                {
                    name.push('/');
                }
                entries.push(name);
            }
            entries.sort();

            let rendered =
                render_directory_entries(&entries, parsed.offset.unwrap_or(0), parsed.limit);
            return Ok(ToolOutcome::Completed(ToolResult {
                success: true,
                result: rendered,
                display_preference: Some("Collapsible".to_string()),
                images: Vec::new(),
            }));
        }

        if metadata.len() > MAX_READ_SIZE {
            return Err(ToolError::Execution(format!(
                "File is {} bytes, which exceeds the maximum readable size of {} bytes ({} MB). \
                 Use Grep to search within this file instead.",
                metadata.len(),
                MAX_READ_SIZE,
                MAX_READ_SIZE / 1024 / 1024
            )));
        }

        let bytes = tokio::fs::read(path)
            .await
            .map_err(|e| ToolError::Execution(format!("Failed to read file: {}", e)))?;

        if let Some(session_id) = ctx.session_id() {
            read_tracker::mark_read(session_id, parsed.file_path.trim()).await;
        }

        if bytes.contains(&0) {
            return Ok(ToolOutcome::Completed(ToolResult {
                success: true,
                result: "[Binary file omitted]".to_string(),
                display_preference: Some("Collapsible".to_string()),
                images: Vec::new(),
            }));
        }

        let content = String::from_utf8_lossy(&bytes).to_string();
        let rendered =
            render_file_with_line_numbers(&content, parsed.offset.unwrap_or(0), parsed.limit);

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::WriteTool;
    use serde_json::json;

    #[tokio::test]
    async fn binary_read_still_marks_file_as_read_for_session_write_gate() {
        let file = tempfile::NamedTempFile::new().unwrap();
        tokio::fs::write(file.path(), vec![0_u8, 1, 2, 3])
            .await
            .unwrap();
        let file_path = file.path().to_string_lossy().to_string();
        let make_ctx = || ToolCtx {
            session_id: Some(std::sync::Arc::from("session_binary_read")),
            tool_call_id: std::sync::Arc::from("call_1"),
            event_tx: None,
            available_tool_schemas: std::sync::Arc::from(Vec::new()),
            bypass_permissions: false,
            can_async_resume: false,
            async_completion_sink: None,
            bash_completion_sink: None,
        };

        let read_tool = ReadTool::new();
        let read_out = read_tool
            .invoke(json!({ "file_path": file_path }), make_ctx())
            .await
            .unwrap();
        let ToolOutcome::Completed(read_result) = read_out else {
            panic!("expected Completed")
        };
        assert!(read_result.success);
        assert!(read_result.result.contains("Binary file omitted"));

        let write_tool = WriteTool::new();
        let write_out = write_tool
            .invoke(
                json!({
                    "file_path": file.path(),
                    "content": "now text"
                }),
                make_ctx(),
            )
            .await
            .unwrap();
        let ToolOutcome::Completed(write_result) = write_out else {
            panic!("expected Completed")
        };
        assert!(write_result.success);
    }

    #[tokio::test]
    async fn read_directory_supports_offset_limit_and_marks_subdirs() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::create_dir_all(dir.path().join("b-dir"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("a.txt"), "a")
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("c.txt"), "c")
            .await
            .unwrap();

        let tool = ReadTool::new();
        let out = tool
            .invoke(
                json!({
                    "file_path": dir.path(),
                    "offset": 1,
                    "limit": 1
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap();
        let ToolOutcome::Completed(result) = out else {
            panic!("expected Completed")
        };

        assert!(result.success);
        assert!(result.result.contains("b-dir/"));
        assert!(result.result.contains("TRUNCATED"));
    }

    #[tokio::test]
    async fn read_file_adds_continuation_hint_when_truncated() {
        let file = tempfile::NamedTempFile::new().unwrap();
        tokio::fs::write(file.path(), "l1\nl2\nl3\n").await.unwrap();

        let tool = ReadTool::new();
        let out = tool
            .invoke(
                json!({
                    "file_path": file.path(),
                    "offset": 0,
                    "limit": 1
                }),
                ToolCtx::none("t"),
            )
            .await
            .unwrap();
        let ToolOutcome::Completed(result) = out else {
            panic!("expected Completed")
        };

        assert!(result.success);
        assert!(result.result.contains("l1"));
        assert!(result.result.contains("Continue with offset=1"));
    }

    #[tokio::test]
    async fn read_rejects_blocking_device_paths() {
        let tool = ReadTool::new();
        let result = tool
            .invoke(
                json!({
                    "file_path": "/dev/stdin"
                }),
                ToolCtx::none("t"),
            )
            .await;

        let error = result.expect_err("device path should be rejected");
        assert!(matches!(error, ToolError::InvalidArguments(_)));
        assert!(error
            .to_string()
            .contains("Refusing to read blocking or unbounded device path"));
    }
}