bob-adapters 0.3.2

Adapter implementations for Bob Agent Framework ports
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
//! # Built-in Tool Port
//!
//! Workspace-sandboxed file and shell tools that run locally without
//! requiring an external MCP server.
//!
//! ## Tools
//!
//! | Tool ID            | Description                      |
//! |-------------------|----------------------------------|
//! | `local/file_read`  | Read a file relative to workspace |
//! | `local/file_write` | Write a file relative to workspace|
//! | `local/file_list`  | List directory contents           |
//! | `local/shell_exec` | Execute a shell command           |
//!
//! ## Security
//!
//! All file operations are sandboxed to the workspace directory.
//! Absolute paths and `..` traversal are rejected.

use std::path::{Component, Path, PathBuf};

use bob_core::{
    error::ToolError,
    types::{ToolCall, ToolDescriptor, ToolResult},
};
use serde_json::json;

/// Built-in tool port providing workspace-sandboxed file and shell operations.
#[derive(Debug, Clone)]
pub struct BuiltinToolPort {
    workspace: PathBuf,
}

impl BuiltinToolPort {
    /// Create a new built-in tool port rooted at the given workspace directory.
    #[must_use]
    pub fn new(workspace: PathBuf) -> Self {
        Self { workspace }
    }

    /// Resolve a relative path safely within the workspace sandbox.
    ///
    /// Rejects absolute paths and parent-directory (`..`) traversal.
    fn resolve_safe_path(&self, relative: &str) -> Result<PathBuf, ToolError> {
        let path = Path::new(relative);

        if path.is_absolute() {
            return Err(ToolError::Execution("absolute paths not allowed in sandbox".to_string()));
        }

        for component in path.components() {
            if matches!(component, Component::ParentDir | Component::Prefix(_)) {
                return Err(ToolError::Execution(
                    "parent directory traversal (..) not allowed".to_string(),
                ));
            }
        }

        Ok(self.workspace.join(relative))
    }

    async fn workspace_canonical_path(&self) -> Result<PathBuf, ToolError> {
        tokio::fs::canonicalize(&self.workspace).await.map_err(|err| {
            ToolError::Execution(format!(
                "failed to resolve workspace path '{}': {err}",
                self.workspace.display()
            ))
        })
    }

    async fn nearest_existing_ancestor(path: &Path) -> Result<PathBuf, ToolError> {
        let mut probe = path.to_path_buf();
        loop {
            match tokio::fs::symlink_metadata(&probe).await {
                Ok(_) => return Ok(probe),
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    let Some(parent) = probe.parent() else {
                        return Err(ToolError::Execution(format!(
                            "path '{}' has no existing ancestor",
                            path.display()
                        )));
                    };
                    probe = parent.to_path_buf();
                }
                Err(err) => {
                    return Err(ToolError::Execution(format!(
                        "failed to inspect path '{}': {err}",
                        probe.display()
                    )));
                }
            }
        }
    }

    async fn ensure_within_workspace(&self, candidate: &Path) -> Result<(), ToolError> {
        let workspace = self.workspace_canonical_path().await?;
        let ancestor = Self::nearest_existing_ancestor(candidate).await?;
        let canonical_ancestor = tokio::fs::canonicalize(&ancestor).await.map_err(|err| {
            ToolError::Execution(format!("failed to resolve path '{}': {err}", ancestor.display()))
        })?;
        if !canonical_ancestor.starts_with(&workspace) {
            return Err(ToolError::Execution(format!(
                "path '{}' resolves outside workspace sandbox",
                candidate.display()
            )));
        }
        Ok(())
    }

    /// Execute the `local/file_read` tool.
    async fn file_read(&self, args: &serde_json::Value) -> Result<serde_json::Value, ToolError> {
        let path_str = args
            .get("path")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| ToolError::Execution("missing 'path' argument".to_string()))?;

        let full_path = self.resolve_safe_path(path_str)?;
        self.ensure_within_workspace(&full_path).await?;
        let content = tokio::fs::read_to_string(&full_path)
            .await
            .map_err(|e| ToolError::Execution(format!("read failed: {e}")))?;

        Ok(json!({ "content": content, "path": path_str }))
    }

    /// Execute the `local/file_write` tool.
    async fn file_write(&self, args: &serde_json::Value) -> Result<serde_json::Value, ToolError> {
        let path_str = args
            .get("path")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| ToolError::Execution("missing 'path' argument".to_string()))?;

        let content = args
            .get("content")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| ToolError::Execution("missing 'content' argument".to_string()))?;

        let full_path = self.resolve_safe_path(path_str)?;
        self.ensure_within_workspace(&full_path).await?;

        // Create parent directories if needed.
        if let Some(parent) = full_path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| ToolError::Execution(format!("mkdir failed: {e}")))?;
        }

        tokio::fs::write(&full_path, content)
            .await
            .map_err(|e| ToolError::Execution(format!("write failed: {e}")))?;

        Ok(json!({ "written": true, "path": path_str, "bytes": content.len() }))
    }

    /// Execute the `local/file_list` tool.
    async fn file_list(&self, args: &serde_json::Value) -> Result<serde_json::Value, ToolError> {
        let path_str = args.get("path").and_then(serde_json::Value::as_str).unwrap_or(".");

        let full_path = self.resolve_safe_path(path_str)?;
        self.ensure_within_workspace(&full_path).await?;
        let mut entries = Vec::new();
        let mut dir = tokio::fs::read_dir(&full_path)
            .await
            .map_err(|e| ToolError::Execution(format!("read_dir failed: {e}")))?;

        loop {
            match dir.next_entry().await {
                Ok(Some(entry)) => {
                    let name = entry.file_name().to_string_lossy().to_string();
                    let is_dir = entry.file_type().await.is_ok_and(|ft| ft.is_dir());
                    entries.push(json!({
                        "name": name,
                        "is_dir": is_dir,
                    }));
                }
                Ok(None) => break,
                Err(e) => {
                    return Err(ToolError::Execution(format!("readdir entry failed: {e}")));
                }
            }
        }

        Ok(json!({ "path": path_str, "entries": entries }))
    }

    /// Execute the `local/shell_exec` tool.
    async fn shell_exec(&self, args: &serde_json::Value) -> Result<serde_json::Value, ToolError> {
        let command = args
            .get("command")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| ToolError::Execution("missing 'command' argument".to_string()))?;

        let timeout_ms =
            args.get("timeout_ms").and_then(serde_json::Value::as_u64).unwrap_or(15_000);

        let output = tokio::time::timeout(
            std::time::Duration::from_millis(timeout_ms),
            tokio::process::Command::new("/bin/sh")
                .arg("-c")
                .arg(command)
                .current_dir(&self.workspace)
                .output(),
        )
        .await
        .map_err(|_| ToolError::Timeout { name: "local/shell_exec".to_string() })?
        .map_err(|e| ToolError::Execution(format!("exec failed: {e}")))?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let exit_code = output.status.code().unwrap_or(-1);

        Ok(json!({
            "exit_code": exit_code,
            "stdout": stdout,
            "stderr": stderr,
        }))
    }
}

#[async_trait::async_trait]
impl bob_core::ports::ToolPort for BuiltinToolPort {
    async fn list_tools(&self) -> Result<Vec<ToolDescriptor>, ToolError> {
        Ok(vec![
            ToolDescriptor::new("local/file_read", "Read file contents from the workspace")
                .with_input_schema(json!({
                    "type": "object",
                    "properties": {
                        "path": { "type": "string", "description": "Relative path within workspace" }
                    },
                    "required": ["path"]
                })),
            ToolDescriptor::new("local/file_write", "Write content to a file in the workspace")
                .with_input_schema(json!({
                    "type": "object",
                    "properties": {
                        "path": { "type": "string", "description": "Relative path within workspace" },
                        "content": { "type": "string", "description": "File content to write" }
                    },
                    "required": ["path", "content"]
                })),
            ToolDescriptor::new("local/file_list", "List directory contents in the workspace")
                .with_input_schema(json!({
                    "type": "object",
                    "properties": {
                        "path": { "type": "string", "description": "Relative directory path (default: '.')" }
                    }
                })),
            ToolDescriptor::new("local/shell_exec", "Execute a shell command in the workspace directory")
                .with_input_schema(json!({
                    "type": "object",
                    "properties": {
                        "command": { "type": "string", "description": "Shell command to execute" },
                        "timeout_ms": { "type": "integer", "description": "Timeout in milliseconds (default: 15000)" }
                    },
                    "required": ["command"]
                })),
        ])
    }

    async fn call_tool(&self, call: ToolCall) -> Result<ToolResult, ToolError> {
        let result = match call.name.as_str() {
            "local/file_read" => self.file_read(&call.arguments).await,
            "local/file_write" => self.file_write(&call.arguments).await,
            "local/file_list" => self.file_list(&call.arguments).await,
            "local/shell_exec" => self.shell_exec(&call.arguments).await,
            _ => return Err(ToolError::NotFound { name: call.name }),
        };

        match result {
            Ok(output) => Ok(ToolResult { name: call.name, output, is_error: false }),
            Err(e) => Ok(ToolResult {
                name: call.name,
                output: json!({ "error": e.to_string() }),
                is_error: true,
            }),
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #[cfg(unix)]
    use std::os::unix::fs as unix_fs;

    use bob_core::ports::ToolPort;

    use super::*;

    #[tokio::test]
    async fn list_tools_returns_four_builtins() {
        let port = BuiltinToolPort::new(PathBuf::from("/tmp"));
        let tools = port.list_tools().await;
        assert!(tools.is_ok());
        let tools = tools.unwrap_or_default();
        assert_eq!(tools.len(), 4);
        assert!(tools.iter().all(|t| t.id.starts_with("local/")));
    }

    #[test]
    fn resolve_safe_path_rejects_absolute() {
        let port = BuiltinToolPort::new(PathBuf::from("/workspace"));
        assert!(port.resolve_safe_path("/etc/passwd").is_err());
    }

    #[test]
    fn resolve_safe_path_rejects_traversal() {
        let port = BuiltinToolPort::new(PathBuf::from("/workspace"));
        assert!(port.resolve_safe_path("../etc/passwd").is_err());
        assert!(port.resolve_safe_path("foo/../../etc/passwd").is_err());
    }

    #[test]
    fn resolve_safe_path_allows_relative() {
        let port = BuiltinToolPort::new(PathBuf::from("/workspace"));
        let result = port.resolve_safe_path("src/main.rs");
        assert!(result.is_ok());
        assert_eq!(result.unwrap_or_default(), PathBuf::from("/workspace/src/main.rs"));
    }

    #[tokio::test]
    async fn file_read_on_temp_file() {
        let dir = tempfile::tempdir().unwrap_or_else(|_| {
            // Fallback that won't be reached in tests but satisfies no-unwrap lint
            tempfile::TempDir::new().unwrap_or_else(|_| unreachable!())
        });
        let file_path = dir.path().join("test.txt");
        std::fs::write(&file_path, "hello").unwrap_or_default();

        let port = BuiltinToolPort::new(dir.path().to_path_buf());
        let result =
            port.call_tool(ToolCall::new("local/file_read", json!({ "path": "test.txt" }))).await;

        assert!(result.is_ok());
        if let Ok(r) = result {
            assert!(!r.is_error);
            assert_eq!(r.output.get("content").and_then(|v| v.as_str()), Some("hello"));
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn file_read_rejects_symlink_escape() {
        let workspace = tempfile::tempdir().unwrap_or_else(|_| unreachable!());
        let outside = tempfile::tempdir().unwrap_or_else(|_| unreachable!());
        let outside_file = outside.path().join("secret.txt");
        let wrote = std::fs::write(&outside_file, "secret");
        assert!(wrote.is_ok());

        let link_path = workspace.path().join("link.txt");
        let linked = unix_fs::symlink(&outside_file, &link_path);
        assert!(linked.is_ok(), "should create symlink test fixture");

        let port = BuiltinToolPort::new(workspace.path().to_path_buf());
        let result =
            port.call_tool(ToolCall::new("local/file_read", json!({ "path": "link.txt" }))).await;

        assert!(result.is_ok());
        if let Ok(tool_result) = result {
            assert!(tool_result.is_error, "symlink escape must be blocked");
            let error = tool_result
                .output
                .get("error")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            assert!(error.contains("outside workspace"));
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn file_write_rejects_symlink_escape() {
        let workspace = tempfile::tempdir().unwrap_or_else(|_| unreachable!());
        let outside = tempfile::tempdir().unwrap_or_else(|_| unreachable!());
        let outside_dir = outside.path().join("target");
        let created = std::fs::create_dir_all(&outside_dir);
        assert!(created.is_ok());

        let link_path = workspace.path().join("escape");
        let linked = unix_fs::symlink(&outside_dir, &link_path);
        assert!(linked.is_ok(), "should create symlink test fixture");

        let port = BuiltinToolPort::new(workspace.path().to_path_buf());
        let result = port
            .call_tool(ToolCall::new(
                "local/file_write",
                json!({
                    "path": "escape/pwned.txt",
                    "content": "blocked"
                }),
            ))
            .await;

        assert!(result.is_ok());
        if let Ok(tool_result) = result {
            assert!(tool_result.is_error, "symlink escape must be blocked");
        }
        assert!(
            !outside_dir.join("pwned.txt").exists(),
            "write must not touch paths outside workspace"
        );
    }
}