Skip to main content

opi_coding_agent/tool/
glob.rs

1use std::future::Future;
2use std::path::PathBuf;
3use std::pin::Pin;
4
5use opi_agent::tool::{ExecutionMode, Tool, ToolError, ToolResult};
6use opi_ai::message::{OutputContent, ToolDef};
7use schemars::JsonSchema;
8use serde::Deserialize;
9use tokio_util::sync::CancellationToken;
10
11#[derive(Debug, Deserialize, JsonSchema)]
12pub struct GlobArgs {
13    /// Glob pattern to search for (e.g. "**/*.rs").
14    pub pattern: String,
15}
16
17pub struct GlobTool {
18    workspace_root: PathBuf,
19    schema: serde_json::Value,
20}
21
22impl GlobTool {
23    pub fn new(workspace_root: PathBuf) -> Self {
24        let schema = schemars::schema_for!(GlobArgs);
25        Self {
26            workspace_root,
27            schema: serde_json::to_value(&schema).unwrap_or_default(),
28        }
29    }
30}
31
32impl Tool for GlobTool {
33    fn definition(&self) -> ToolDef {
34        ToolDef {
35            name: "glob".into(),
36            description: "Gitignore-aware file discovery by glob pattern.".into(),
37            input_schema: self.schema.clone(),
38        }
39    }
40
41    fn execute(
42        &self,
43        _call_id: &str,
44        arguments: serde_json::Value,
45        _signal: CancellationToken,
46        _on_update: Option<opi_agent::tool::UpdateCallback>,
47    ) -> Pin<Box<dyn Future<Output = Result<ToolResult, ToolError>> + Send>> {
48        let args: GlobArgs = match serde_json::from_value(arguments) {
49            Ok(a) => a,
50            Err(e) => {
51                return Box::pin(async move {
52                    Ok(ToolResult {
53                        content: vec![OutputContent::Text {
54                            text: format!("invalid arguments: {e}"),
55                        }],
56                        details: None,
57                        is_error: true,
58                        terminate: false,
59                    })
60                });
61            }
62        };
63        let workspace_root = self.workspace_root.clone();
64        let pattern = args.pattern;
65        Box::pin(async move {
66            let glob_matcher = match globset::Glob::new(&pattern) {
67                Ok(g) => g.compile_matcher(),
68                Err(e) => {
69                    return Ok(ToolResult {
70                        content: vec![OutputContent::Text {
71                            text: format!("invalid glob pattern: {e}"),
72                        }],
73                        details: None,
74                        is_error: true,
75                        terminate: false,
76                    });
77                }
78            };
79
80            let mut matched_paths = Vec::new();
81            let mut builder = ignore::WalkBuilder::new(&workspace_root);
82            builder
83                .hidden(false)
84                .git_ignore(true)
85                .git_global(false)
86                .git_exclude(false)
87                .add_custom_ignore_filename(".gitignore");
88            let walker = builder.build();
89
90            for entry in walker.flatten() {
91                if entry.file_type().is_some_and(|ft| ft.is_file()) {
92                    let path = entry.path();
93                    let relative = path.strip_prefix(&workspace_root).unwrap_or(path);
94                    if glob_matcher.is_match(relative) || glob_matcher.is_match(path) {
95                        matched_paths.push(path.to_string_lossy().into_owned());
96                    }
97                }
98            }
99
100            let text = matched_paths.join("\n");
101            let details = serde_json::json!({
102                "workspace_root": workspace_root.to_string_lossy(),
103                "pattern": pattern,
104                "match_count": matched_paths.len(),
105            });
106
107            Ok(ToolResult {
108                content: vec![OutputContent::Text { text }],
109                details: Some(details),
110                is_error: false,
111                terminate: false,
112            })
113        })
114    }
115
116    fn execution_mode(&self) -> ExecutionMode {
117        ExecutionMode::Parallel
118    }
119}