agent-sdk 0.8.0

Rust Agent SDK for building LLM agents
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
use crate::{Environment, PrimitiveToolName, Tool, ToolContext, ToolResult, ToolTier};
use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;

use super::PrimitiveToolContext;

/// Tool for searching file contents using regex patterns
pub struct GrepTool<E: Environment> {
    ctx: PrimitiveToolContext<E>,
}

impl<E: Environment> GrepTool<E> {
    #[must_use]
    pub const fn new(environment: Arc<E>, capabilities: crate::AgentCapabilities) -> Self {
        Self {
            ctx: PrimitiveToolContext::new(environment, capabilities),
        }
    }
}

#[derive(Debug, Deserialize)]
struct GrepInput {
    /// Regex pattern to search for
    pattern: String,
    /// Path to search in (file or directory)
    #[serde(default)]
    path: Option<String>,
    /// Search recursively in directories (default: true)
    #[serde(default = "default_recursive")]
    recursive: bool,
    /// Case insensitive search (default: false)
    #[serde(default)]
    case_insensitive: bool,
}

const fn default_recursive() -> bool {
    true
}

impl<E: Environment + 'static> Tool<()> for GrepTool<E> {
    type Name = PrimitiveToolName;

    fn name(&self) -> PrimitiveToolName {
        PrimitiveToolName::Grep
    }

    fn display_name(&self) -> &'static str {
        "Search Files"
    }

    fn description(&self) -> &'static str {
        "Search for a regex pattern in files. Returns matching lines with file paths and line numbers."
    }

    fn tier(&self) -> ToolTier {
        ToolTier::Observe
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regex pattern to search for"
                },
                "path": {
                    "type": "string",
                    "description": "Path to search in (file or directory). Defaults to environment root."
                },
                "recursive": {
                    "type": "boolean",
                    "description": "Search recursively in directories. Default: true"
                },
                "case_insensitive": {
                    "type": "boolean",
                    "description": "Case insensitive search. Default: false"
                }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(&self, _ctx: &ToolContext<()>, input: Value) -> Result<ToolResult> {
        let input: GrepInput =
            serde_json::from_value(input).context("Invalid input for grep tool")?;

        let search_path = input.path.as_ref().map_or_else(
            || self.ctx.environment.root().to_string(),
            |p| self.ctx.environment.resolve_path(p),
        );

        // Check read capability
        if let Err(reason) = self.ctx.capabilities.check_read(&search_path) {
            return Ok(ToolResult::error(format!(
                "Permission denied: cannot search in '{search_path}': {reason}"
            )));
        }

        // Build pattern with case insensitivity if requested
        let pattern = if input.case_insensitive {
            format!("(?i){}", input.pattern)
        } else {
            input.pattern.clone()
        };

        // Execute grep
        let matches = self
            .ctx
            .environment
            .grep(&pattern, &search_path, input.recursive)
            .await
            .context("Failed to execute grep")?;

        // Filter out matches in files the agent can't read
        let accessible_matches: Vec<_> = matches
            .into_iter()
            .filter(|m| self.ctx.capabilities.check_read(&m.path).is_ok())
            .collect();

        if accessible_matches.is_empty() {
            return Ok(ToolResult::success(format!(
                "No matches found for pattern '{}'",
                input.pattern
            )));
        }

        let count = accessible_matches.len();
        let max_results = 50;

        let output_lines: Vec<String> = accessible_matches
            .iter()
            .take(max_results)
            .map(|m| {
                format!(
                    "{}:{}:{}",
                    m.path,
                    m.line_number,
                    truncate_line(&m.line_content, 200)
                )
            })
            .collect();

        let output = if count > max_results {
            format!(
                "Found {count} matches (showing first {max_results}):\n{}",
                output_lines.join("\n")
            )
        } else {
            format!("Found {count} matches:\n{}", output_lines.join("\n"))
        };

        Ok(ToolResult::success(output))
    }
}

fn truncate_line(s: &str, max_len: usize) -> String {
    let trimmed = s.trim();
    if trimmed.len() <= max_len {
        trimmed.to_string()
    } else {
        format!("{}...", super::truncate_str(trimmed, max_len))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AgentCapabilities, InMemoryFileSystem};

    fn create_test_tool(
        fs: Arc<InMemoryFileSystem>,
        capabilities: AgentCapabilities,
    ) -> GrepTool<InMemoryFileSystem> {
        GrepTool::new(fs, capabilities)
    }

    fn tool_ctx() -> ToolContext<()> {
        ToolContext::new(())
    }

    // ===================
    // Unit Tests
    // ===================

    #[tokio::test]
    async fn test_grep_simple_pattern() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("test.rs", "fn main() {\n    println!(\"Hello\");\n}")
            .await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "println"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("Found 1 matches"));
        assert!(result.output.contains("println"));
        assert!(result.output.contains(":2:")); // Line number
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_regex_pattern() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("test.txt", "foo123\nbar456\nfoo789").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "foo\\d+"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("Found 2 matches"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_no_matches() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("test.txt", "Hello, World!").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "Rust"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("No matches found"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_case_insensitive() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        // Use ASCII-only text since unicode-case feature may not be enabled
        fs.write_file("test.txt", "Hello\nHELLO\nhello").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        // Use ASCII-only case-insensitive pattern (regex supports (?i-u) for ASCII)
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "[Hh][Ee][Ll][Ll][Oo]"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("Found 3 matches"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_with_path() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("src/main.rs", "fn main() {}").await?;
        fs.write_file("tests/test.rs", "fn test() {}").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(
                &tool_ctx(),
                json!({"pattern": "fn", "path": "/workspace/src"}),
            )
            .await?;

        assert!(result.success);
        assert!(result.output.contains("Found 1 matches"));
        assert!(result.output.contains("main.rs"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_non_recursive() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("file.txt", "match here").await?;
        fs.write_file("subdir/nested.txt", "match nested").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "match", "recursive": false}))
            .await?;

        assert!(result.success);
        // Should only find the top-level file
        assert!(result.output.contains("Found 1 matches"));
        assert!(result.output.contains("file.txt"));
        Ok(())
    }

    // ===================
    // Integration Tests
    // ===================

    #[tokio::test]
    async fn test_grep_permission_denied() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("test.txt", "content").await?;

        // No read permission
        let caps = AgentCapabilities::none();

        let tool = create_test_tool(fs, caps);
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "content"}))
            .await?;

        assert!(!result.success);
        assert!(result.output.contains("Permission denied"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_filters_inaccessible_files() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("src/main.rs", "fn main() {}").await?;
        fs.write_file("secrets/key.txt", "fn secret() {}").await?;

        // Allow src but deny secrets
        let caps =
            AgentCapabilities::read_only().with_denied_paths(vec!["/workspace/secrets/**".into()]);

        let tool = create_test_tool(fs, caps);
        let result = tool.execute(&tool_ctx(), json!({"pattern": "fn"})).await?;

        assert!(result.success);
        assert!(result.output.contains("Found 1 matches"));
        assert!(result.output.contains("main.rs"));
        assert!(!result.output.contains("key.txt"));
        Ok(())
    }

    // ===================
    // Edge Cases
    // ===================

    #[tokio::test]
    async fn test_grep_empty_file() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("empty.txt", "").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "anything"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("No matches found"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_many_matches_truncated() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));

        // Create file with many matching lines
        let content: String = (1..=100)
            .map(|i| format!("match line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        fs.write_file("many.txt", &content).await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "match"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("Found 100 matches"));
        assert!(result.output.contains("showing first 50"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_special_regex_characters() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("test.txt", "foo.bar\nbaz*qux\n(parens)")
            .await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());

        // Escaped dot
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "foo\\.bar"}))
            .await?;
        assert!(result.success);
        assert!(result.output.contains("Found 1 matches"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_multiple_files() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        fs.write_file("src/main.rs", "fn main() {}").await?;
        fs.write_file("src/lib.rs", "fn lib() {}").await?;
        fs.write_file("README.md", "# README").await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool.execute(&tool_ctx(), json!({"pattern": "fn"})).await?;

        assert!(result.success);
        assert!(result.output.contains("Found 2 matches"));
        Ok(())
    }

    #[tokio::test]
    async fn test_grep_tool_metadata() {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        let tool = create_test_tool(fs, AgentCapabilities::full_access());

        assert_eq!(tool.name(), PrimitiveToolName::Grep);
        assert_eq!(tool.tier(), ToolTier::Observe);
        assert!(tool.description().contains("Search"));

        let schema = tool.input_schema();
        assert!(schema.get("properties").is_some());
        assert!(schema["properties"].get("pattern").is_some());
        assert!(schema["properties"].get("path").is_some());
        assert!(schema["properties"].get("recursive").is_some());
        assert!(schema["properties"].get("case_insensitive").is_some());
    }

    #[tokio::test]
    async fn test_grep_invalid_input() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        let tool = create_test_tool(fs, AgentCapabilities::full_access());

        // Missing required pattern field
        let result = tool.execute(&tool_ctx(), json!({})).await;
        assert!(result.is_err());
        Ok(())
    }

    #[tokio::test]
    async fn test_truncate_line_function() {
        assert_eq!(truncate_line("short", 10), "short");
        assert_eq!(truncate_line("  trimmed  ", 10), "trimmed");
        assert_eq!(truncate_line("this is a longer line", 10), "this is a ...");
    }

    #[tokio::test]
    async fn test_grep_long_line_truncated() -> anyhow::Result<()> {
        let fs = Arc::new(InMemoryFileSystem::new("/workspace"));
        let long_line = "match ".to_string() + &"x".repeat(300);
        fs.write_file("long.txt", &long_line).await?;

        let tool = create_test_tool(fs, AgentCapabilities::full_access());
        let result = tool
            .execute(&tool_ctx(), json!({"pattern": "match"}))
            .await?;

        assert!(result.success);
        assert!(result.output.contains("..."));
        Ok(())
    }
}