code_symbols_tool.rs

  1use std::fmt::Write;
  2use std::path::PathBuf;
  3use std::sync::Arc;
  4
  5use crate::schema::json_schema_for;
  6use anyhow::{Result, anyhow};
  7use assistant_tool::outline;
  8use assistant_tool::{ActionLog, Tool, ToolResult};
  9use collections::IndexMap;
 10use gpui::{AnyWindowHandle, App, AsyncApp, Entity, Task};
 11use language_model::{LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
 12use project::{Project, Symbol};
 13use regex::{Regex, RegexBuilder};
 14use schemars::JsonSchema;
 15use serde::{Deserialize, Serialize};
 16use ui::IconName;
 17use util::markdown::MarkdownInlineCode;
 18
 19#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 20pub struct CodeSymbolsInput {
 21    /// The relative path of the source code file to read and get the symbols for.
 22    /// This tool should only be used on source code files, never on any other type of file.
 23    ///
 24    /// This path should never be absolute, and the first component
 25    /// of the path should always be a root directory in a project.
 26    ///
 27    /// If no path is specified, this tool returns a flat list of all symbols in the project
 28    /// instead of a hierarchical outline of a specific file.
 29    ///
 30    /// <example>
 31    /// If the project has the following root directories:
 32    ///
 33    /// - directory1
 34    /// - directory2
 35    ///
 36    /// If you want to access `file.md` in `directory1`, you should use the path `directory1/file.md`.
 37    /// If you want to access `file.md` in `directory2`, you should use the path `directory2/file.md`.
 38    /// </example>
 39    #[serde(default)]
 40    pub path: Option<String>,
 41
 42    /// Optional regex pattern to filter symbols by name.
 43    /// When provided, only symbols whose names match this pattern will be included in the results.
 44    ///
 45    /// <example>
 46    /// To find only symbols that contain the word "test", use the regex pattern "test".
 47    /// To find methods that start with "get_", use the regex pattern "^get_".
 48    /// </example>
 49    #[serde(default)]
 50    pub regex: Option<String>,
 51
 52    /// Whether the regex is case-sensitive. Defaults to false (case-insensitive).
 53    ///
 54    /// <example>
 55    /// Set to `true` to make regex matching case-sensitive.
 56    /// </example>
 57    #[serde(default)]
 58    pub case_sensitive: bool,
 59
 60    /// Optional starting position for paginated results (0-based).
 61    /// When not provided, starts from the beginning.
 62    #[serde(default)]
 63    pub offset: u32,
 64}
 65
 66impl CodeSymbolsInput {
 67    /// Which page of search results this is.
 68    pub fn page(&self) -> u32 {
 69        1 + (self.offset / RESULTS_PER_PAGE)
 70    }
 71}
 72
 73const RESULTS_PER_PAGE: u32 = 2000;
 74
 75pub struct CodeSymbolsTool;
 76
 77impl Tool for CodeSymbolsTool {
 78    fn name(&self) -> String {
 79        "code_symbols".into()
 80    }
 81
 82    fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
 83        false
 84    }
 85
 86    fn description(&self) -> String {
 87        include_str!("./code_symbols_tool/description.md").into()
 88    }
 89
 90    fn icon(&self) -> IconName {
 91        IconName::Code
 92    }
 93
 94    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
 95        json_schema_for::<CodeSymbolsInput>(format)
 96    }
 97
 98    fn ui_text(&self, input: &serde_json::Value) -> String {
 99        match serde_json::from_value::<CodeSymbolsInput>(input.clone()) {
100            Ok(input) => {
101                let page = input.page();
102
103                match &input.path {
104                    Some(path) => {
105                        let path = MarkdownInlineCode(path);
106                        if page > 1 {
107                            format!("List page {page} of code symbols for {path}")
108                        } else {
109                            format!("List code symbols for {path}")
110                        }
111                    }
112                    None => {
113                        if page > 1 {
114                            format!("List page {page} of project symbols")
115                        } else {
116                            "List all project symbols".to_string()
117                        }
118                    }
119                }
120            }
121            Err(_) => "List code symbols".to_string(),
122        }
123    }
124
125    fn run(
126        self: Arc<Self>,
127        input: serde_json::Value,
128        _messages: &[LanguageModelRequestMessage],
129        project: Entity<Project>,
130        action_log: Entity<ActionLog>,
131        _window: Option<AnyWindowHandle>,
132        cx: &mut App,
133    ) -> ToolResult {
134        let input = match serde_json::from_value::<CodeSymbolsInput>(input) {
135            Ok(input) => input,
136            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
137        };
138
139        let regex = match input.regex {
140            Some(regex_str) => match RegexBuilder::new(&regex_str)
141                .case_insensitive(!input.case_sensitive)
142                .build()
143            {
144                Ok(regex) => Some(regex),
145                Err(err) => return Task::ready(Err(anyhow!("Invalid regex: {err}"))).into(),
146            },
147            None => None,
148        };
149
150        cx.spawn(async move |cx| match input.path {
151            Some(path) => outline::file_outline(project, path, action_log, regex, cx).await,
152            None => project_symbols(project, regex, input.offset, cx).await,
153        })
154        .into()
155    }
156}
157
158async fn project_symbols(
159    project: Entity<Project>,
160    regex: Option<Regex>,
161    offset: u32,
162    cx: &mut AsyncApp,
163) -> anyhow::Result<String> {
164    let symbols = project
165        .update(cx, |project, cx| project.symbols("", cx))?
166        .await?;
167
168    if symbols.is_empty() {
169        return Err(anyhow!("No symbols found in project."));
170    }
171
172    let mut symbols_by_path: IndexMap<PathBuf, Vec<&Symbol>> = IndexMap::default();
173
174    for symbol in symbols
175        .iter()
176        .filter(|symbol| {
177            if let Some(regex) = &regex {
178                regex.is_match(&symbol.name)
179            } else {
180                true
181            }
182        })
183        .skip(offset as usize)
184        // Take 1 more than RESULTS_PER_PAGE so we can tell if there are more results.
185        .take((RESULTS_PER_PAGE as usize).saturating_add(1))
186    {
187        if let Some(worktree_path) = project.read_with(cx, |project, cx| {
188            project
189                .worktree_for_id(symbol.path.worktree_id, cx)
190                .map(|worktree| PathBuf::from(worktree.read(cx).root_name()))
191        })? {
192            let path = worktree_path.join(&symbol.path.path);
193            symbols_by_path.entry(path).or_default().push(symbol);
194        }
195    }
196
197    // If no symbols matched the filter, return early
198    if symbols_by_path.is_empty() {
199        return Err(anyhow!("No symbols found matching the criteria."));
200    }
201
202    let mut symbols_rendered = 0;
203    let mut has_more_symbols = false;
204    let mut output = String::new();
205
206    'outer: for (file_path, file_symbols) in symbols_by_path {
207        if symbols_rendered > 0 {
208            output.push('\n');
209        }
210
211        writeln!(&mut output, "{}", file_path.display()).ok();
212
213        for symbol in file_symbols {
214            if symbols_rendered >= RESULTS_PER_PAGE {
215                has_more_symbols = true;
216                break 'outer;
217            }
218
219            write!(&mut output, "  {} ", symbol.label.text()).ok();
220
221            // Convert to 1-based line numbers for display
222            let start_line = symbol.range.start.0.row as usize + 1;
223            let end_line = symbol.range.end.0.row as usize + 1;
224
225            if start_line == end_line {
226                writeln!(&mut output, "[L{}]", start_line).ok();
227            } else {
228                writeln!(&mut output, "[L{}-{}]", start_line, end_line).ok();
229            }
230
231            symbols_rendered += 1;
232        }
233    }
234
235    Ok(if symbols_rendered == 0 {
236        "No symbols found in the requested page.".to_string()
237    } else if has_more_symbols {
238        format!(
239            "{output}\nShowing symbols {}-{} (more symbols were found; use offset: {} to see next page)",
240            offset + 1,
241            offset + symbols_rendered,
242            offset + RESULTS_PER_PAGE,
243        )
244    } else {
245        output
246    })
247}