cats 0.1.15

Coding Agent ToolS - A comprehensive toolkit for building AI-powered coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Grep tool implementation compatible with OpenCode
//!
//! Fast content search tool using regex patterns.

use crate::core::{Tool, ToolArgs, ToolError, ToolResult};
use anyhow::Result;
use regex::Regex;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use walkdir::WalkDir;

const MAX_LINE_LENGTH: usize = 2000;
const LIMIT: usize = 100;

/// Grep tool parameters
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GrepParams {
    /// The regex pattern to search for in file contents
    pub pattern: String,
    /// The directory to search in. For current directory send ".". If starts with "/" it is absolute, if not it is relative.
    pub path: String,
    /// File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")
    pub include: Option<String>,
}

/// Grep tool for searching file contents
pub struct GrepTool {
    name: String,
}

impl GrepTool {
    pub fn new() -> Self {
        Self {
            name: "grep".to_string(),
        }
    }
}

impl Default for GrepTool {
    fn default() -> Self {
        Self::new()
    }
}

impl Tool for GrepTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        "Fast content search tool that searches file contents using regular expressions. The 'path' parameter is required. For current directory send '.'. If starts with '/' it is absolute, if not it is relative."
    }

    fn signature(&self) -> &str {
        "grep --pattern <regex> --path <directory> [--include <glob>]"
    }

    fn validate_args(&self, args: &ToolArgs) -> Result<(), ToolError> {
        let has_pattern = args
            .get_named_arg("pattern")
            .map(|s| !s.is_empty())
            .unwrap_or(false);
        if !has_pattern && args.args.iter().all(|s| s.is_empty()) {
            return Err(ToolError::InvalidArgs {
                message: "grep tool requires a non-empty 'pattern' argument".to_string(),
            });
        }
        Ok(())
    }

    fn execute(
        &mut self,
        args: &ToolArgs,
        state: &Arc<Mutex<crate::state::ToolState>>,
    ) -> Result<ToolResult> {
        let params = parse_grep_args(args)?;

        if params.pattern.is_empty() {
            return Err(ToolError::InvalidArgs {
                message: "pattern is required".to_string(),
            }
            .into());
        }

        // Get working directory from ToolState at execution time
        let working_dir = state
            .lock()
            .map(|s| s.working_directory.clone())
            .unwrap_or_else(|_| std::env::current_dir().unwrap_or_default());

        let search_path = PathBuf::from(&params.path);

        let search_path = if search_path.is_absolute() {
            search_path
        } else {
            working_dir.join(&search_path)
        };

        // Compile the regex pattern
        let regex = Regex::new(&params.pattern)
            .map_err(|e| anyhow::anyhow!("Invalid regex pattern: {}", e))?;

        // Parse include glob pattern if provided
        let include_glob = params
            .include
            .as_ref()
            .map(|g| glob::Pattern::new(g))
            .transpose()
            .map_err(|e| anyhow::anyhow!("Invalid include pattern: {}", e))?;

        let mut matches: Vec<(PathBuf, std::time::SystemTime, usize, String)> = Vec::new();
        let mut truncated = false;

        for entry in WalkDir::new(&search_path)
            .follow_links(false)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
        {
            if truncated {
                break;
            }

            let path = entry.path().to_path_buf();

            // Check include pattern
            if let Some(ref glob) = include_glob {
                let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if !glob.matches(filename) {
                    continue;
                }
            }

            // Skip binary files
            if is_likely_binary(&path) {
                continue;
            }

            // Read file and search
            if let Ok(content) = fs::read_to_string(&path) {
                let mtime = fs::metadata(&path)
                    .ok()
                    .and_then(|m| m.modified().ok())
                    .unwrap_or(std::time::SystemTime::UNIX_EPOCH);

                for (line_num, line) in content.lines().enumerate() {
                    if matches.len() >= LIMIT {
                        truncated = true;
                        break;
                    }

                    if regex.is_match(line) {
                        let truncated_line = if line.len() > MAX_LINE_LENGTH {
                            format!("{}...", &line[..MAX_LINE_LENGTH])
                        } else {
                            line.to_string()
                        };

                        matches.push((path.clone(), mtime, line_num + 1, truncated_line));
                    }
                }
            }
        }

        // Sort by modification time (most recent first)
        matches.sort_by(|a, b| b.1.cmp(&a.1));

        if matches.is_empty() {
            return Ok(ToolResult::success_with_data(
                "No files found".to_string(),
                serde_json::json!({
                    "matches": 0,
                    "truncated": false,
                }),
            ));
        }

        // Format output
        let mut output_lines = vec![format!("Found {} matches", matches.len())];
        let mut current_file: Option<&PathBuf> = None;

        for (path, _mtime, line_num, line_text) in &matches {
            if current_file != Some(path) {
                if current_file.is_some() {
                    output_lines.push("".to_string());
                }
                current_file = Some(path);
                output_lines.push(format!("{}:", path.display()));
            }
            output_lines.push(format!("  Line {}: {}", line_num, line_text));
        }

        if truncated {
            output_lines.push("".to_string());
            output_lines.push(
                "(Results are truncated. Consider using a more specific path or pattern.)"
                    .to_string(),
            );
        }

        Ok(ToolResult::success_with_data(
            output_lines.join("\n"),
            serde_json::json!({
                "matches": matches.len(),
                "truncated": truncated,
            }),
        ))
    }

    fn get_parameters_schema(&self) -> serde_json::Value {
        let schema = schemars::schema_for!(GrepParams);
        serde_json::to_value(schema).unwrap_or_default()
    }
}

fn parse_grep_args(args: &ToolArgs) -> Result<GrepParams> {
    let pattern = args
        .get_named_arg("pattern")
        .cloned()
        .filter(|s| !s.is_empty())
        .or_else(|| args.args.first().cloned())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| anyhow::anyhow!("pattern is required and must be non-empty"))?
        .trim()
        .to_string();

    if pattern.is_empty() {
        return Err(anyhow::anyhow!("pattern must not be empty or whitespace-only"));
    }

    let path = args
        .get_named_arg("path")
        .cloned()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| anyhow::anyhow!("path parameter is required. Send '.' for current directory"))?;

    let include = args.get_named_arg("include").cloned();

    Ok(GrepParams {
        pattern,
        path,
        include,
    })
}

fn is_likely_binary(path: &Path) -> bool {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|s| s.to_lowercase())
        .unwrap_or_default();

    matches!(
        ext.as_str(),
        "zip"
            | "tar"
            | "gz"
            | "exe"
            | "dll"
            | "so"
            | "class"
            | "jar"
            | "war"
            | "7z"
            | "png"
            | "jpg"
            | "jpeg"
            | "gif"
            | "pdf"
            | "ico"
            | "webp"
            | "mp3"
            | "mp4"
            | "avi"
            | "mov"
            | "wasm"
            | "pyc"
            | "pyo"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_grep_tool_creation() {
        let tool = GrepTool::new();
        assert_eq!(tool.name(), "grep");
    }

    #[test]
    fn test_grep_tool_find_content() {
        let temp_dir = TempDir::new().unwrap();

        // Create test files
        fs::write(
            temp_dir.path().join("test1.txt"),
            "Hello, World!\nThis is a test.",
        )
        .unwrap();
        fs::write(temp_dir.path().join("test2.txt"), "No match here.").unwrap();
        fs::write(
            temp_dir.path().join("test3.rs"),
            "fn main() { println!(\"Hello\"); }",
        )
        .unwrap();

        let mut tool = GrepTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec!["Hello".to_string()],
            vec![(
                "path".to_string(),
                temp_dir.path().to_str().unwrap().to_string(),
            )]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);
        assert!(result.message.contains("test1.txt"));
        assert!(result.message.contains("test3.rs"));
        assert!(!result.message.contains("test2.txt"));
    }

    #[test]
    fn test_grep_tool_with_include() {
        let temp_dir = TempDir::new().unwrap();

        fs::write(temp_dir.path().join("test.txt"), "Hello, World!").unwrap();
        fs::write(temp_dir.path().join("test.rs"), "Hello, Rust!").unwrap();

        let mut tool = GrepTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec!["Hello".to_string()],
            vec![
                (
                    "path".to_string(),
                    temp_dir.path().to_str().unwrap().to_string(),
                ),
                ("include".to_string(), "*.rs".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);
        assert!(result.message.contains("test.rs"));
        assert!(!result.message.contains("test.txt"));
    }

    #[test]
    fn test_grep_tool_no_matches() {
        let temp_dir = TempDir::new().unwrap();

        fs::write(temp_dir.path().join("test.txt"), "Nothing to see here.").unwrap();

        let mut tool = GrepTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec!["nonexistent".to_string()],
            vec![(
                "path".to_string(),
                temp_dir.path().to_str().unwrap().to_string(),
            )]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);
        assert!(result.message.contains("No files found"));
    }

    #[test]
    fn test_grep_tool_regex_pattern() {
        let temp_dir = TempDir::new().unwrap();

        fs::write(temp_dir.path().join("test.txt"), "Line 1\nLine 2\nLine 123").unwrap();

        let mut tool = GrepTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec!["Line \\d+".to_string()],
            vec![(
                "path".to_string(),
                temp_dir.path().to_str().unwrap().to_string(),
            )]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);
        assert!(result.message.contains("Line 1"));
        assert!(result.message.contains("Line 2"));
        assert!(result.message.contains("Line 123"));
    }

    #[test]
    fn test_grep_tool_validation() {
        let tool = GrepTool::new();
        let args = ToolArgs::from_args(&[]);

        let result = tool.validate_args(&args);
        assert!(result.is_err());
    }
}