Skip to main content

vtcode_core/tools/file_ops/
tool.rs

1//! File operations tool implementation.
2
3use crate::config::constants::tools;
4use crate::tools::edited_file_monitor::EditedFileMonitor;
5use crate::tools::error_helpers::deserialize_tool_args;
6use crate::tools::grep_file::GrepSearchManager;
7use crate::tools::traits::{CacheableTool, FileTool, ModeTool, Tool};
8use crate::tools::types::{ListInput, PathArgs};
9use crate::tools::validation::paths::validate_non_root_listing_path;
10use crate::utils::path::canonicalize_workspace;
11use crate::utils::vtcodegitignore::should_exclude_file;
12use anyhow::{Result, anyhow};
13use async_trait::async_trait;
14use serde_json::Value;
15use std::fs::FileType;
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use vtcode_commons::WorkspacePathDisplay;
19
20/// File operations tool with multiple modes
21#[derive(Clone)]
22pub struct FileOpsTool {
23    pub(super) workspace_root: PathBuf,
24    pub(super) canonical_workspace_root: PathBuf,
25    /// Root resolved once for entry rendering; listing loops must not re-resolve it per entry.
26    pub(super) path_display: WorkspacePathDisplay,
27    pub(super) grep_manager: Arc<GrepSearchManager>,
28    pub(super) edited_file_monitor: Arc<EditedFileMonitor>,
29}
30
31impl FileOpsTool {
32    pub fn new(workspace_root: PathBuf, grep_search: Arc<GrepSearchManager>) -> Self {
33        let edited_file_monitor = Arc::new(EditedFileMonitor::new());
34        Self::new_with_monitor(workspace_root, grep_search, edited_file_monitor)
35    }
36
37    pub fn new_with_monitor(
38        workspace_root: PathBuf,
39        grep_search: Arc<GrepSearchManager>,
40        edited_file_monitor: Arc<EditedFileMonitor>,
41    ) -> Self {
42        // grep_file manager is unused; keep param to avoid broad call-site churn
43        let canonical_workspace_root = canonicalize_workspace(&workspace_root);
44        let path_display = WorkspacePathDisplay::new(&workspace_root);
45
46        Self {
47            workspace_root,
48            canonical_workspace_root,
49            path_display,
50            grep_manager: grep_search,
51            edited_file_monitor,
52        }
53    }
54
55    /// Borrow the edited-file monitor without exposing shared ownership.
56    pub fn edited_file_monitor_ref(&self) -> &EditedFileMonitor {
57        self.edited_file_monitor.as_ref()
58    }
59
60    /// Get the shared edited-file monitor handle for callers that need to clone it.
61    pub fn edited_file_monitor(&self) -> &Arc<EditedFileMonitor> {
62        &self.edited_file_monitor
63    }
64
65    fn normalize_list_mode(mode: &str) -> Option<&'static str> {
66        if mode.eq_ignore_ascii_case("list") || mode.eq_ignore_ascii_case("file") || mode.eq_ignore_ascii_case("files")
67        {
68            Some("list")
69        } else if mode.eq_ignore_ascii_case("recursive") {
70            Some("recursive")
71        } else if mode.eq_ignore_ascii_case("find_name") {
72            Some("find_name")
73        } else if mode.eq_ignore_ascii_case("find_content") {
74            Some("find_content")
75        } else if mode.eq_ignore_ascii_case("largest") {
76            Some("largest")
77        } else if mode.eq_ignore_ascii_case("tree") {
78            Some("tree")
79        } else {
80            None
81        }
82    }
83
84    /// Get relative path as JSON value (for API responses)
85    #[inline]
86    pub(super) fn relative_path_json(&self, path: &Path) -> String {
87        self.path_display.render(path)
88    }
89
90    /// Ignore check for a path whose directory-ness the caller already proved.
91    ///
92    /// Only for callers that established the flag from the target itself; use
93    /// [`Self::should_exclude_with_file_type`] when starting from a walk type.
94    pub(super) async fn should_exclude_with_is_dir(&self, path: &Path, is_dir: bool) -> bool {
95        crate::utils::vtcodegitignore::should_exclude_file_with_is_dir(path, is_dir).await
96    }
97
98    /// Ignore check that reuses a `FileType` the walker already returned.
99    ///
100    /// Symlinks still stat: their own type cannot tell us whether the target is
101    /// a directory, and the matcher has always judged the target.
102    pub(super) async fn should_exclude_with_file_type(&self, path: &Path, file_type: Option<FileType>) -> bool {
103        crate::utils::vtcodegitignore::should_exclude_file_with_file_type(path, file_type).await
104    }
105
106    /// Workspace-relative key for a path produced by a traversal.
107    ///
108    /// Keys are compared, not displayed, and tree building derives one per
109    /// walked directory, so this prefers the syscall-free lexical strip and
110    /// only resolves paths that do not lexically sit under either known root
111    /// (which then stay absolute, matching the pre-existing fallback).
112    pub(super) fn relative_key_json(&self, path: &Path) -> String {
113        self.path_display
114            .relative_lexical(path)
115            .unwrap_or_else(|| self.path_display.render(path))
116    }
117
118    /// Relative path for an entry whose own file type is already known.
119    ///
120    /// Only valid for entries reached through a traversal that cannot cross a
121    /// symlink (`read_dir` children of a canonical directory, or the shared
122    /// non-following walker). See [`WorkspacePathDisplay::render_entry`].
123    #[inline]
124    pub(super) fn relative_path_json_for_entry(&self, path: &Path, file_type: Option<FileType>) -> String {
125        self.path_display.render_entry(path, file_type)
126    }
127}
128
129#[async_trait]
130impl Tool for FileOpsTool {
131    async fn execute(&self, args: Value) -> Result<Value> {
132        let mut input: ListInput = deserialize_tool_args(&args, "list_files")?;
133        if input.mode.as_deref().is_some_and(|mode| mode.trim().is_empty()) {
134            input.mode = None;
135        }
136
137        // Standard path extraction from args (handles aliases)
138        let path_args: PathArgs = serde_json::from_value(args).unwrap_or(PathArgs { path: input.path.clone() });
139        input.path = path_args.path;
140
141        // Normalize path: strip /workspace prefix if present (common LLM pattern)
142        if input.path.starts_with("/workspace/") {
143            if let Some(stripped) = input.path.strip_prefix("/workspace/") {
144                input.path = stripped.to_string();
145            }
146        } else if input.path == "/workspace" {
147            input.path = ".".to_string();
148        }
149
150        validate_non_root_listing_path(Some(input.path.as_str()))?;
151
152        let should_promote_glob_to_recursive = input.mode.is_none()
153            && input
154                .glob_pattern
155                .as_deref()
156                .map(str::trim)
157                .is_some_and(|pattern| !pattern.is_empty() && (pattern.contains('/') || pattern.contains("**")));
158        if should_promote_glob_to_recursive {
159            input.mode = Some("recursive".to_string());
160        }
161
162        let raw_mode = input
163            .mode
164            .as_deref()
165            .map(str::trim)
166            .filter(|mode| !mode.is_empty())
167            .unwrap_or("list")
168            .to_string();
169        let mode = Self::normalize_list_mode(&raw_mode).unwrap_or(raw_mode.as_str());
170        input.mode = Some(mode.to_string());
171
172        self.execute_mode(mode, serde_json::to_value(input)?).await
173    }
174
175    fn name(&self) -> &str {
176        tools::LIST_FILES
177    }
178
179    fn description(&self) -> &str {
180        "Enhanced file discovery tool with multiple modes: list (default), recursive, find_name, find_content, largest (size ranking), tree (visual directory structure)"
181    }
182}
183
184#[async_trait]
185impl FileTool for FileOpsTool {
186    fn workspace_root(&self) -> &PathBuf {
187        &self.workspace_root
188    }
189
190    async fn should_exclude(&self, path: &Path) -> bool {
191        should_exclude_file(path).await
192    }
193}
194
195#[async_trait]
196impl ModeTool for FileOpsTool {
197    fn supported_modes(&self) -> Vec<&'static str> {
198        vec!["list", "recursive", "find_name", "find_content", "largest", "tree"]
199    }
200
201    async fn execute_mode(&self, mode: &str, args: Value) -> Result<Value> {
202        let input: ListInput = serde_json::from_value(args)?;
203
204        match mode {
205            "list" => self.execute_basic_list(&input).await,
206            "recursive" => self.execute_recursive_search(&input).await,
207            "find_name" => self.execute_find_by_name(&input).await,
208            "find_content" => self.execute_find_by_content(&input).await,
209            "largest" => self.execute_largest_files(&input).await,
210            "tree" => self.execute_tree_view(&input).await,
211            _ => Err(anyhow!("Unsupported file operation mode: {mode}")),
212        }
213    }
214}
215
216#[async_trait]
217impl CacheableTool for FileOpsTool {
218    fn cache_key(&self, args: &Value) -> String {
219        format!(
220            "files:{}:{}",
221            args.get("path").and_then(|p| p.as_str()).unwrap_or(""),
222            args.get("mode").and_then(|m| m.as_str()).unwrap_or("list")
223        )
224    }
225
226    fn should_cache(&self, args: &Value) -> bool {
227        // Cache list and recursive modes, but not content-based searches
228        let mode = args.get("mode").and_then(|m| m.as_str()).unwrap_or("list");
229        matches!(mode, "list" | "recursive" | "largest")
230    }
231
232    fn cache_ttl(&self) -> u64 {
233        60 // 1 minute for file listings
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::config::constants::diff;
241    use crate::tools::file_ops::diff_preview::{build_diff_preview, diff_preview_error_skip};
242    use crate::tools::grep_file::GrepSearchManager;
243    use serde_json::json;
244    use std::fs;
245    use std::sync::Arc;
246    use tempfile::TempDir;
247
248    #[test]
249    fn diff_preview_reports_truncation_and_omission() {
250        let after = (0..(diff::MAX_PREVIEW_LINES + 40))
251            .map(|idx| format!("line {idx}\n"))
252            .collect::<String>();
253
254        let preview = build_diff_preview("sample.txt", None, &after);
255
256        assert_eq!(preview["skipped"], Value::Bool(false));
257        assert_eq!(preview["truncated"], Value::Bool(true));
258        assert!(preview["omitted_line_count"].as_u64().unwrap() > 0);
259
260        let content = preview["content"].as_str().unwrap();
261        assert!(content.contains("lines omitted"));
262        assert!(content.lines().count() <= diff::HEAD_LINE_COUNT + diff::TAIL_LINE_COUNT + 1);
263    }
264
265    #[test]
266    fn diff_preview_skip_handles_error_detail() {
267        let preview = diff_preview_error_skip("failed", Some("InvalidData"));
268        assert_eq!(preview["reason"], Value::String("failed".to_string()));
269        assert_eq!(preview["detail"], Value::String("InvalidData".to_string()));
270        assert_eq!(preview["skipped"], Value::Bool(true));
271    }
272
273    #[tokio::test]
274    async fn globbed_list_pattern_promotes_to_recursive_mode() {
275        let temp_dir = TempDir::new().expect("workspace tempdir");
276        fs::create_dir_all(temp_dir.path().join("src/nested")).expect("create nested src");
277        fs::write(temp_dir.path().join("src/lib.rs"), "pub fn lib() {}\n").expect("write lib");
278        fs::write(temp_dir.path().join("src/nested/mod.rs"), "pub fn nested() {}\n").expect("write nested");
279        fs::write(temp_dir.path().join("src/notes.md"), "# notes\n").expect("write notes");
280
281        let grep_manager = Arc::new(GrepSearchManager::new(temp_dir.path().to_path_buf()));
282        let file_ops = FileOpsTool::new(temp_dir.path().to_path_buf(), grep_manager);
283
284        let result = file_ops
285            .execute(json!({
286                "path": "src",
287                "pattern": "**/*.rs",
288                "response_format": "detailed"
289            }))
290            .await
291            .expect("recursive glob list should succeed");
292
293        assert_eq!(result["mode"], json!("recursive"));
294        assert_eq!(result["pattern"], json!("**/*.rs"));
295
296        let items = result["items"].as_array().expect("items array");
297        assert_eq!(items.len(), 2);
298        assert!(
299            items
300                .iter()
301                .all(|item| { item["path"].as_str().is_some_and(|path| path.ends_with(".rs")) })
302        );
303    }
304
305    #[tokio::test]
306    async fn file_mode_alias_executes_basic_list() {
307        let temp_dir = TempDir::new().expect("workspace tempdir");
308        fs::create_dir_all(temp_dir.path().join("src")).expect("create src");
309        fs::write(temp_dir.path().join("src/lib.rs"), "pub fn lib() {}\n").expect("write lib");
310
311        let grep_manager = Arc::new(GrepSearchManager::new(temp_dir.path().to_path_buf()));
312        let file_ops = FileOpsTool::new(temp_dir.path().to_path_buf(), grep_manager);
313
314        let result = file_ops
315            .execute(json!({
316                "path": "src",
317                "mode": "file"
318            }))
319            .await
320            .expect("file alias should behave like list");
321
322        assert_eq!(result["mode"], json!("list"));
323        let items = result["items"].as_array().expect("items array");
324        assert_eq!(items.len(), 1);
325        assert_eq!(items[0]["path"], json!("src/lib.rs"));
326    }
327
328    #[tokio::test]
329    async fn blank_mode_defaults_to_basic_list() {
330        let temp_dir = TempDir::new().expect("workspace tempdir");
331        fs::create_dir_all(temp_dir.path().join("src")).expect("create src");
332        fs::write(temp_dir.path().join("src/lib.rs"), "pub fn lib() {}\n").expect("write lib");
333
334        let grep_manager = Arc::new(GrepSearchManager::new(temp_dir.path().to_path_buf()));
335        let file_ops = FileOpsTool::new(temp_dir.path().to_path_buf(), grep_manager);
336
337        let result = file_ops
338            .execute(json!({
339                "path": "src",
340                "mode": "",
341                "pattern": "*.rs"
342            }))
343            .await
344            .expect("blank mode should behave like missing mode");
345
346        assert_eq!(result["mode"], json!("list"));
347        let items = result["items"].as_array().expect("items array");
348        assert_eq!(items.len(), 1);
349        assert_eq!(items[0]["path"], json!("src/lib.rs"));
350    }
351
352    #[tokio::test]
353    async fn blank_mode_allows_recursive_glob_promotion() {
354        let temp_dir = TempDir::new().expect("workspace tempdir");
355        fs::create_dir_all(temp_dir.path().join("src/nested")).expect("create nested src");
356        fs::write(temp_dir.path().join("src/nested/lib.rs"), "pub fn lib() {}\n").expect("write lib");
357
358        let grep_manager = Arc::new(GrepSearchManager::new(temp_dir.path().to_path_buf()));
359        let file_ops = FileOpsTool::new(temp_dir.path().to_path_buf(), grep_manager);
360
361        let result = file_ops
362            .execute(json!({
363                "path": "src",
364                "mode": "",
365                "pattern": "**/*.rs"
366            }))
367            .await
368            .expect("blank mode should still allow recursive glob promotion");
369
370        assert_eq!(result["mode"], json!("recursive"));
371        let items = result["items"].as_array().expect("items array");
372        assert_eq!(items.len(), 1);
373        assert_eq!(items[0]["path"], json!("src/nested/lib.rs"));
374    }
375}