1use crate::{AgentTool, ToolCallEventStream};
2use agent_client_protocol as acp;
3use anyhow::{Result, anyhow};
4use futures::FutureExt as _;
5use gpui::{App, AppContext, Entity, SharedString, Task};
6use language_model::LanguageModelToolResultContent;
7use project::Project;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::fmt::Write;
11use std::{cmp, path::PathBuf, sync::Arc};
12use util::paths::PathMatcher;
13
14/// Fast file path pattern matching tool that works with any codebase size
15///
16/// - Supports glob patterns like "**/*.js" or "src/**/*.ts"
17/// - Returns matching file paths sorted alphabetically
18/// - Prefer the `grep` tool to this tool when searching for symbols unless you have specific information about paths.
19/// - Use this tool when you need to find files by name patterns
20/// - Results are paginated with 50 matches per page. Use the optional 'offset' parameter to request subsequent pages.
21#[derive(Debug, Serialize, Deserialize, JsonSchema)]
22pub struct FindPathToolInput {
23 /// The glob to match against every path in the project.
24 ///
25 /// <example>
26 /// If the project has the following root directories:
27 ///
28 /// - directory1/a/something.txt
29 /// - directory2/a/things.txt
30 /// - directory3/a/other.txt
31 ///
32 /// You can get back the first two paths by providing a glob of "*thing*.txt"
33 /// </example>
34 pub glob: String,
35 /// Optional starting position for paginated results (0-based).
36 /// When not provided, starts from the beginning.
37 #[serde(default)]
38 pub offset: usize,
39}
40
41#[derive(Debug, Serialize, Deserialize)]
42pub struct FindPathToolOutput {
43 offset: usize,
44 current_matches_page: Vec<PathBuf>,
45 all_matches_len: usize,
46}
47
48impl From<FindPathToolOutput> for LanguageModelToolResultContent {
49 fn from(output: FindPathToolOutput) -> Self {
50 if output.current_matches_page.is_empty() {
51 "No matches found".into()
52 } else {
53 let mut llm_output = format!("Found {} total matches.", output.all_matches_len);
54 if output.all_matches_len > RESULTS_PER_PAGE {
55 write!(
56 &mut llm_output,
57 "\nShowing results {}-{} (provide 'offset' parameter for more results):",
58 output.offset + 1,
59 output.offset + output.current_matches_page.len()
60 )
61 .unwrap();
62 }
63
64 for mat in output.current_matches_page {
65 write!(&mut llm_output, "\n{}", mat.display()).unwrap();
66 }
67
68 llm_output.into()
69 }
70 }
71}
72
73const RESULTS_PER_PAGE: usize = 50;
74
75pub struct FindPathTool {
76 project: Entity<Project>,
77}
78
79impl FindPathTool {
80 pub fn new(project: Entity<Project>) -> Self {
81 Self { project }
82 }
83}
84
85impl AgentTool for FindPathTool {
86 type Input = FindPathToolInput;
87 type Output = FindPathToolOutput;
88
89 const NAME: &'static str = "find_path";
90
91 fn kind() -> acp::ToolKind {
92 acp::ToolKind::Search
93 }
94
95 fn initial_title(
96 &self,
97 input: Result<Self::Input, serde_json::Value>,
98 _cx: &mut App,
99 ) -> SharedString {
100 let mut title = "Find paths".to_string();
101 if let Ok(input) = input {
102 title.push_str(&format!(" matching “`{}`”", input.glob));
103 }
104 title.into()
105 }
106
107 fn run(
108 self: Arc<Self>,
109 input: Self::Input,
110 event_stream: ToolCallEventStream,
111 cx: &mut App,
112 ) -> Task<Result<FindPathToolOutput>> {
113 let search_paths_task = search_paths(&input.glob, self.project.clone(), cx);
114
115 cx.background_spawn(async move {
116 let matches = futures::select! {
117 result = search_paths_task.fuse() => result?,
118 _ = event_stream.cancelled_by_user().fuse() => {
119 anyhow::bail!("Path search cancelled by user");
120 }
121 };
122 let paginated_matches: &[PathBuf] = &matches[cmp::min(input.offset, matches.len())
123 ..cmp::min(input.offset + RESULTS_PER_PAGE, matches.len())];
124
125 event_stream.update_fields(
126 acp::ToolCallUpdateFields::new()
127 .title(if paginated_matches.is_empty() {
128 "No matches".into()
129 } else if paginated_matches.len() == 1 {
130 "1 match".into()
131 } else {
132 format!("{} matches", paginated_matches.len())
133 })
134 .content(
135 paginated_matches
136 .iter()
137 .map(|path| {
138 acp::ToolCallContent::Content(acp::Content::new(
139 acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
140 path.to_string_lossy(),
141 format!("file://{}", path.display()),
142 )),
143 ))
144 })
145 .collect::<Vec<_>>(),
146 ),
147 );
148
149 Ok(FindPathToolOutput {
150 offset: input.offset,
151 current_matches_page: paginated_matches.to_vec(),
152 all_matches_len: matches.len(),
153 })
154 })
155 }
156}
157
158fn search_paths(glob: &str, project: Entity<Project>, cx: &mut App) -> Task<Result<Vec<PathBuf>>> {
159 let path_style = project.read(cx).path_style(cx);
160 let path_matcher = match PathMatcher::new(
161 [
162 // Sometimes models try to search for "". In this case, return all paths in the project.
163 if glob.is_empty() { "*" } else { glob },
164 ],
165 path_style,
166 ) {
167 Ok(matcher) => matcher,
168 Err(err) => return Task::ready(Err(anyhow!("Invalid glob: {err}"))),
169 };
170 let snapshots: Vec<_> = project
171 .read(cx)
172 .worktrees(cx)
173 .map(|worktree| worktree.read(cx).snapshot())
174 .collect();
175
176 cx.background_spawn(async move {
177 let mut results = Vec::new();
178 for snapshot in snapshots {
179 for entry in snapshot.entries(false, 0) {
180 if path_matcher.is_match(&snapshot.root_name().join(&entry.path)) {
181 results.push(snapshot.absolutize(&entry.path));
182 }
183 }
184 }
185
186 Ok(results)
187 })
188}
189
190#[cfg(test)]
191mod test {
192 use super::*;
193 use gpui::TestAppContext;
194 use project::{FakeFs, Project};
195 use settings::SettingsStore;
196 use util::path;
197
198 #[gpui::test]
199 async fn test_find_path_tool(cx: &mut TestAppContext) {
200 init_test(cx);
201
202 let fs = FakeFs::new(cx.executor());
203 fs.insert_tree(
204 "/root",
205 serde_json::json!({
206 "apple": {
207 "banana": {
208 "carrot": "1",
209 },
210 "bandana": {
211 "carbonara": "2",
212 },
213 "endive": "3"
214 }
215 }),
216 )
217 .await;
218 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
219
220 let matches = cx
221 .update(|cx| search_paths("root/**/car*", project.clone(), cx))
222 .await
223 .unwrap();
224 assert_eq!(
225 matches,
226 &[
227 PathBuf::from(path!("/root/apple/banana/carrot")),
228 PathBuf::from(path!("/root/apple/bandana/carbonara"))
229 ]
230 );
231
232 let matches = cx
233 .update(|cx| search_paths("**/car*", project.clone(), cx))
234 .await
235 .unwrap();
236 assert_eq!(
237 matches,
238 &[
239 PathBuf::from(path!("/root/apple/banana/carrot")),
240 PathBuf::from(path!("/root/apple/bandana/carbonara"))
241 ]
242 );
243 }
244
245 fn init_test(cx: &mut TestAppContext) {
246 cx.update(|cx| {
247 let settings_store = SettingsStore::test(cx);
248 cx.set_global(settings_store);
249 });
250 }
251}