Skip to main content

aidaemon_tools/
search.rs

1//! `glob` and `grep`. Both walk the workspace with the `ignore` crate, so
2//! `.gitignore`, `.ignore` and hidden files are skipped like `ripgrep` does.
3
4use std::path::{Path, PathBuf};
5
6use async_trait::async_trait;
7use globset::{GlobBuilder, GlobMatcher};
8use serde::Deserialize;
9use serde_json::{Value, json};
10
11use aidaemon_core::{
12    AccessManifest, Tool, ToolAnnotations, ToolContext, ToolOutput, ToolResult, ToolSpec,
13};
14
15use crate::util::{fail, looks_binary, parse_args, truncate_chars};
16use crate::workspace::Workspace;
17
18/// Default cap on paths returned by `glob` and `grep` (files mode).
19pub const DEFAULT_MAX_RESULTS: usize = 200;
20/// Default cap on matching lines returned by `grep` (content mode).
21pub const DEFAULT_MAX_LINES: usize = 200;
22/// Matching lines are cut to this many characters.
23const MAX_MATCH_LINE_CHARS: usize = 300;
24/// Files larger than this are skipped by `grep`.
25const MAX_GREP_FILE_BYTES: u64 = 5 * 1024 * 1024;
26
27fn walker(base: &Path) -> ignore::Walk {
28    ignore::WalkBuilder::new(base)
29        .hidden(true)
30        .git_ignore(true)
31        .git_global(false)
32        .git_exclude(true)
33        .require_git(false)
34        .parents(true)
35        .follow_links(false)
36        .build()
37}
38
39fn resolve_base(ws: &Workspace, path: Option<&str>) -> Result<PathBuf, String> {
40    let base = match path {
41        Some(p) if !p.trim().is_empty() => ws.resolve(p).map_err(|e| e.to_string())?,
42        _ => ws.root().to_path_buf(),
43    };
44    if !base.exists() {
45        return Err(format!("`{}` does not exist", ws.display(&base)));
46    }
47    Ok(base)
48}
49
50fn declare_base(ws: &Workspace, arguments: &Value) -> Vec<String> {
51    let path = arguments
52        .get("path")
53        .and_then(Value::as_str)
54        .filter(|p| !p.trim().is_empty());
55    vec![match path {
56        Some(p) => ws.declare(p),
57        None => ws.root().display().to_string(),
58    }]
59}
60
61// --------------------------------------------------------------------- glob
62
63/// Find files by glob pattern, respecting `.gitignore`.
64#[derive(Debug, Clone)]
65pub struct Glob {
66    workspace: Workspace,
67    max_results: usize,
68}
69
70impl Glob {
71    pub fn new(workspace: Workspace) -> Self {
72        Self {
73            workspace,
74            max_results: DEFAULT_MAX_RESULTS,
75        }
76    }
77
78    pub fn with_max_results(mut self, max: usize) -> Self {
79        self.max_results = max.max(1);
80        self
81    }
82}
83
84#[derive(Deserialize)]
85#[serde(deny_unknown_fields)]
86struct GlobArgs {
87    pattern: String,
88    path: Option<String>,
89}
90
91fn build_glob(pattern: &str, literal_separator: bool) -> Result<GlobMatcher, String> {
92    GlobBuilder::new(pattern)
93        .literal_separator(literal_separator)
94        .build()
95        .map(|g| g.compile_matcher())
96        .map_err(|e| format!("invalid glob pattern `{pattern}`: {e}"))
97}
98
99#[async_trait]
100impl Tool for Glob {
101    fn spec(&self) -> ToolSpec {
102        ToolSpec {
103            name: "glob".into(),
104            description: format!(
105                "Find files whose path matches a glob pattern, relative to `path` (default: the \
106                 workspace root). `*` does not cross directories; use `**` for any depth, for \
107                 example `**/*.rs` or `src/**/mod.rs`. Files ignored by .gitignore and hidden \
108                 files are skipped. Returns sorted paths relative to the workspace root, at most \
109                 {} of them.",
110                self.max_results
111            ),
112            parameters: json!({
113                "type": "object",
114                "properties": {
115                    "pattern": {"type": "string", "description": "Glob pattern, for example `**/*.toml`."},
116                    "path": {"type": "string", "description": "Directory to search from, relative to the workspace root. Default: the root."}
117                },
118                "required": ["pattern"],
119                "additionalProperties": false
120            }),
121        }
122    }
123
124    fn annotations(&self) -> ToolAnnotations {
125        ToolAnnotations::READ_ONLY
126    }
127
128    fn access(&self, arguments: &Value) -> AccessManifest {
129        AccessManifest {
130            reads: declare_base(&self.workspace, arguments),
131            ..Default::default()
132        }
133    }
134
135    async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
136        let args: GlobArgs = match parse_args("glob", arguments) {
137            Ok(a) => a,
138            Err(e) => return Ok(fail(e)),
139        };
140        let base = match resolve_base(&self.workspace, args.path.as_deref()) {
141            Ok(b) => b,
142            Err(e) => return Ok(fail(e)),
143        };
144        let pattern = args.pattern.trim_start_matches("./").to_string();
145        let matcher = match build_glob(&pattern, true) {
146            Ok(m) => m,
147            Err(e) => return Ok(fail(e)),
148        };
149        let ws = self.workspace.clone();
150        let max = self.max_results;
151        let result = tokio::task::spawn_blocking(move || {
152            let mut found: Vec<String> = Vec::new();
153            for entry in walker(&base).flatten() {
154                if !entry.file_type().is_some_and(|t| t.is_file()) {
155                    continue;
156                }
157                let rel = entry.path().strip_prefix(&base).unwrap_or(entry.path());
158                if matcher.is_match(rel) {
159                    found.push(ws.display(entry.path()));
160                }
161            }
162            found.sort();
163            found
164        })
165        .await
166        .map_err(|e| format!("glob task failed: {e}"))?;
167
168        let total = result.len();
169        if total == 0 {
170            return Ok(ToolOutput::text(format!(
171                "No files match `{pattern}`. Patterns are relative to the search directory; \
172                 try `**/{pattern}` to search all depths."
173            ))
174            .with_details(json!({"matches": 0})));
175        }
176        let mut out = result
177            .iter()
178            .take(max)
179            .cloned()
180            .collect::<Vec<_>>()
181            .join("\n");
182        if total > max {
183            out.push_str(&format!(
184                "\n[Showing {max} of {total} matches. Narrow the pattern or the path to see the rest.]"
185            ));
186        }
187        Ok(ToolOutput::text(out).with_details(json!({
188            "matches": total,
189            "truncated": total > max,
190        })))
191    }
192}
193
194// --------------------------------------------------------------------- grep
195
196/// Search file contents with a regular expression.
197#[derive(Debug, Clone)]
198pub struct Grep {
199    workspace: Workspace,
200    max_results: usize,
201    max_lines: usize,
202}
203
204impl Grep {
205    pub fn new(workspace: Workspace) -> Self {
206        Self {
207            workspace,
208            max_results: DEFAULT_MAX_RESULTS,
209            max_lines: DEFAULT_MAX_LINES,
210        }
211    }
212
213    pub fn with_limits(mut self, max_files: usize, max_lines: usize) -> Self {
214        self.max_results = max_files.max(1);
215        self.max_lines = max_lines.max(1);
216        self
217    }
218}
219
220#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
221#[serde(rename_all = "snake_case")]
222enum GrepMode {
223    #[default]
224    Files,
225    Content,
226}
227
228#[derive(Deserialize)]
229#[serde(deny_unknown_fields)]
230struct GrepArgs {
231    pattern: String,
232    path: Option<String>,
233    glob: Option<String>,
234    #[serde(default)]
235    case_insensitive: bool,
236    #[serde(default)]
237    output_mode: GrepMode,
238}
239
240#[async_trait]
241impl Tool for Grep {
242    fn spec(&self) -> ToolSpec {
243        ToolSpec {
244            name: "grep".into(),
245            description: format!(
246                "Search file contents with a regular expression (Rust regex syntax, like \
247                 ripgrep). `output_mode` `files` (default) lists matching files; `content` \
248                 shows matching lines as `path:line:text`. Filter files with `glob` (matched \
249                 against the path, so `*.rs` matches at any depth). Skips .gitignored, hidden \
250                 and binary files. Returns at most {} files or {} lines.",
251                self.max_results, self.max_lines
252            ),
253            parameters: json!({
254                "type": "object",
255                "properties": {
256                    "pattern": {"type": "string", "description": "Regular expression to search for."},
257                    "path": {"type": "string", "description": "File or directory to search, relative to the workspace root. Default: the root."},
258                    "glob": {"type": "string", "description": "Only search files matching this glob, for example `*.py` or `src/**/*.ts`."},
259                    "case_insensitive": {"type": "boolean", "description": "Ignore case. Default false."},
260                    "output_mode": {"type": "string", "enum": ["files", "content"], "description": "`files` (default) or `content`."}
261                },
262                "required": ["pattern"],
263                "additionalProperties": false
264            }),
265        }
266    }
267
268    fn annotations(&self) -> ToolAnnotations {
269        ToolAnnotations::READ_ONLY
270    }
271
272    fn access(&self, arguments: &Value) -> AccessManifest {
273        AccessManifest {
274            reads: declare_base(&self.workspace, arguments),
275            ..Default::default()
276        }
277    }
278
279    async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
280        let args: GrepArgs = match parse_args("grep", arguments) {
281            Ok(a) => a,
282            Err(e) => return Ok(fail(e)),
283        };
284        let regex = match regex::RegexBuilder::new(&args.pattern)
285            .case_insensitive(args.case_insensitive)
286            .size_limit(10 * 1024 * 1024)
287            .build()
288        {
289            Ok(r) => r,
290            Err(e) => {
291                return Ok(fail(format!(
292                    "invalid regex `{}`: {e}. Escape special characters such as `(`, `[` or `{{` with a backslash.",
293                    args.pattern
294                )));
295            }
296        };
297        let filter = match args.glob.as_deref().filter(|g| !g.trim().is_empty()) {
298            Some(g) => match build_glob(g.trim_start_matches("./"), false) {
299                Ok(m) => Some(m),
300                Err(e) => return Ok(fail(e)),
301            },
302            None => None,
303        };
304        let base = match resolve_base(&self.workspace, args.path.as_deref()) {
305            Ok(b) => b,
306            Err(e) => return Ok(fail(e)),
307        };
308        let ws = self.workspace.clone();
309        let mode = args.output_mode;
310        let (max_files, max_lines) = (self.max_results, self.max_lines);
311
312        let (lines, files, total_lines) = tokio::task::spawn_blocking(move || {
313            let mut paths: Vec<PathBuf> = walker(&base)
314                .flatten()
315                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
316                .map(|e| e.into_path())
317                .filter(|p| {
318                    let rel = p.strip_prefix(&base).unwrap_or(p);
319                    let rel = if rel.as_os_str().is_empty() {
320                        Path::new(p.file_name().unwrap_or_default())
321                    } else {
322                        rel
323                    };
324                    filter.as_ref().is_none_or(|m| m.is_match(rel))
325                })
326                .collect();
327            paths.sort();
328
329            let mut lines: Vec<String> = Vec::new();
330            let mut files: Vec<String> = Vec::new();
331            let mut total_lines = 0usize;
332            for path in paths {
333                if std::fs::metadata(&path).map_or(true, |m| m.len() > MAX_GREP_FILE_BYTES) {
334                    continue;
335                }
336                let Ok(bytes) = std::fs::read(&path) else {
337                    continue;
338                };
339                if looks_binary(&bytes) {
340                    continue;
341                }
342                let text = String::from_utf8_lossy(&bytes);
343                let shown = ws.display(&path);
344                let mut matched = false;
345                for (i, line) in text.lines().enumerate() {
346                    if regex.is_match(line) {
347                        matched = true;
348                        if mode == GrepMode::Files {
349                            break;
350                        }
351                        total_lines += 1;
352                        if lines.len() < max_lines {
353                            let (line, _) = truncate_chars(line, MAX_MATCH_LINE_CHARS);
354                            lines.push(format!("{shown}:{}:{line}", i + 1));
355                        }
356                    }
357                }
358                if matched {
359                    files.push(shown);
360                }
361            }
362            (lines, files, total_lines)
363        })
364        .await
365        .map_err(|e| format!("grep task failed: {e}"))?;
366
367        if files.is_empty() {
368            return Ok(
369                ToolOutput::text(format!("No matches for `{}`.", args.pattern))
370                    .with_details(json!({"files": 0, "lines": 0})),
371            );
372        }
373        let out = match mode {
374            GrepMode::Files => {
375                let mut out = files
376                    .iter()
377                    .take(max_files)
378                    .cloned()
379                    .collect::<Vec<_>>()
380                    .join("\n");
381                if files.len() > max_files {
382                    out.push_str(&format!(
383                        "\n[Showing {max_files} of {} matching files. Narrow `path` or `glob`.]",
384                        files.len()
385                    ));
386                }
387                out
388            }
389            GrepMode::Content => {
390                let mut out = lines.join("\n");
391                if total_lines > lines.len() {
392                    out.push_str(&format!(
393                        "\n[Showing {} of {total_lines} matching lines in {} files. Narrow the pattern, `path` or `glob`.]",
394                        lines.len(),
395                        files.len()
396                    ));
397                }
398                out
399            }
400        };
401        Ok(ToolOutput::text(out).with_details(json!({
402            "files": files.len(),
403            "lines": total_lines,
404        })))
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use crate::testutil::{ctx, ws};
412
413    fn tree(ws: &Workspace) {
414        let r = ws.root();
415        std::fs::create_dir_all(r.join("src/nested")).unwrap();
416        std::fs::create_dir_all(r.join("target/debug")).unwrap();
417        std::fs::write(r.join(".gitignore"), "target/\n*.log\n").unwrap();
418        std::fs::write(r.join("src/lib.rs"), "pub fn alpha() {}\n// TODO: beta\n").unwrap();
419        std::fs::write(r.join("src/nested/mod.rs"), "fn Alpha() {}\n").unwrap();
420        std::fs::write(r.join("README.md"), "alpha docs\n").unwrap();
421        std::fs::write(r.join("target/debug/gen.rs"), "fn alpha() {}\n").unwrap();
422        std::fs::write(r.join("run.log"), "alpha log\n").unwrap();
423        std::fs::write(r.join("img.bin"), b"alpha\0binary").unwrap();
424    }
425
426    #[tokio::test]
427    async fn glob_respects_gitignore_and_sorts() {
428        let (_d, ws) = ws();
429        tree(&ws);
430        let tool = Glob::new(ws.clone());
431        let out = tool
432            .call(json!({"pattern": "**/*.rs"}), &ctx())
433            .await
434            .unwrap();
435        assert_eq!(out.content, "src/lib.rs\nsrc/nested/mod.rs");
436        let out = tool.call(json!({"pattern": "*.rs"}), &ctx()).await.unwrap();
437        assert!(out.content.starts_with("No files match"), "{}", out.content);
438        let out = tool
439            .call(json!({"pattern": "*.rs", "path": "src"}), &ctx())
440            .await
441            .unwrap();
442        assert_eq!(out.content, "src/lib.rs");
443        let out = tool.call(json!({"pattern": "*"}), &ctx()).await.unwrap();
444        assert!(!out.content.contains("run.log") && out.content.contains("README.md"));
445        let out = tool
446            .call(json!({"pattern": "*", "path": "../"}), &ctx())
447            .await
448            .unwrap();
449        assert!(out.is_error);
450    }
451
452    #[tokio::test]
453    async fn glob_caps_results() {
454        let (_d, ws) = ws();
455        for i in 0..12 {
456            std::fs::write(ws.root().join(format!("f{i:02}.txt")), "x").unwrap();
457        }
458        let tool = Glob::new(ws).with_max_results(5);
459        let out = tool
460            .call(json!({"pattern": "*.txt"}), &ctx())
461            .await
462            .unwrap();
463        assert_eq!(out.content.lines().count(), 6);
464        assert!(out.content.contains("Showing 5 of 12 matches"));
465        assert_eq!(out.details["truncated"], true);
466    }
467
468    #[tokio::test]
469    async fn grep_files_and_content_modes() {
470        let (_d, ws) = ws();
471        tree(&ws);
472        let tool = Grep::new(ws.clone());
473        let out = tool
474            .call(json!({"pattern": "alpha"}), &ctx())
475            .await
476            .unwrap();
477        assert_eq!(out.content, "README.md\nsrc/lib.rs");
478
479        let out = tool
480            .call(
481                json!({"pattern": "alpha", "case_insensitive": true, "glob": "*.rs"}),
482                &ctx(),
483            )
484            .await
485            .unwrap();
486        assert_eq!(out.content, "src/lib.rs\nsrc/nested/mod.rs");
487
488        let out = tool
489            .call(
490                json!({"pattern": "TODO|alpha", "output_mode": "content", "path": "src"}),
491                &ctx(),
492            )
493            .await
494            .unwrap();
495        assert_eq!(
496            out.content,
497            "src/lib.rs:1:pub fn alpha() {}\nsrc/lib.rs:2:// TODO: beta"
498        );
499
500        let out = tool
501            .call(
502                json!({"pattern": "alpha", "path": "src/lib.rs", "output_mode": "content"}),
503                &ctx(),
504            )
505            .await
506            .unwrap();
507        assert_eq!(out.content, "src/lib.rs:1:pub fn alpha() {}");
508
509        let out = tool.call(json!({"pattern": "zzz"}), &ctx()).await.unwrap();
510        assert!(!out.is_error && out.content.starts_with("No matches"));
511
512        let out = tool.call(json!({"pattern": "fn("}), &ctx()).await.unwrap();
513        assert!(out.is_error && out.content.contains("invalid regex"));
514
515        let out = tool
516            .call(json!({"pattern": "x", "output_mode": "lines"}), &ctx())
517            .await
518            .unwrap();
519        assert!(out.is_error);
520    }
521
522    #[tokio::test]
523    async fn grep_caps_content_lines() {
524        let (_d, ws) = ws();
525        let body: String = (0..50).map(|i| format!("hit {i}\n")).collect();
526        std::fs::write(ws.root().join("many.txt"), body).unwrap();
527        let tool = Grep::new(ws).with_limits(10, 5);
528        let out = tool
529            .call(json!({"pattern": "hit", "output_mode": "content"}), &ctx())
530            .await
531            .unwrap();
532        assert_eq!(out.content.lines().count(), 6);
533        assert!(out.content.contains("Showing 5 of 50 matching lines"));
534    }
535}