coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Enhanced search tools for CoderLib
//!
//! This module provides advanced search capabilities matching OpenCode's grep functionality.
//! Features include regex patterns, file type filtering, recursive search, and context lines.

use async_trait::async_trait;
use regex::{Regex, RegexBuilder};
use std::path::{Path, PathBuf};
use std::collections::HashSet;
use std::ffi::OsStr;

use crate::integration::HostIntegration;
use crate::tools::{Tool, ToolResponse, ToolError, Permission, validation};

/// Tool for searching files by name pattern
pub struct FileSearchTool;

impl FileSearchTool {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for FileSearchTool {
    async fn execute(
        &self,
        parameters: serde_json::Value,
        _host: &dyn HostIntegration,
    ) -> Result<ToolResponse, ToolError> {
        let pattern = validation::require_string(&parameters, "pattern")?;
        let search_path = validation::optional_path(&parameters, "path")
            .unwrap_or_else(|| PathBuf::from("."));
        let max_results = parameters.get("max_results")
            .and_then(|v| v.as_u64())
            .unwrap_or(100) as usize;
        
        validation::validate_safe_path(&search_path)?;
        
        let regex = Regex::new(&pattern)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid regex pattern: {}", e)))?;
        
        let mut results = Vec::new();
        
        fn search_recursive(
            dir: &std::path::Path,
            regex: &Regex,
            results: &mut Vec<PathBuf>,
            max_results: usize,
        ) -> Result<(), ToolError> {
            if results.len() >= max_results {
                return Ok(());
            }
            
            let entries = std::fs::read_dir(dir)
                .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
            
            for entry in entries {
                if results.len() >= max_results {
                    break;
                }
                
                let entry = entry.map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
                let path = entry.path();
                
                if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                    if regex.is_match(file_name) {
                        results.push(path.clone());
                    }

                    if path.is_dir() && !file_name.starts_with('.') {
                        search_recursive(&path, regex, results, max_results)?;
                    }
                }
            }
            
            Ok(())
        }
        
        search_recursive(&search_path, &regex, &mut results, max_results)?;
        
        if results.is_empty() {
            Ok(ToolResponse::success("No files found matching the pattern".to_string()))
        } else {
            let result_text = results
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join("\n");
            
            let metadata = serde_json::json!({
                "pattern": pattern,
                "search_path": search_path,
                "total_results": results.len(),
                "max_results": max_results,
            });
            
            Ok(ToolResponse::with_metadata(result_text, metadata))
        }
    }
    
    fn requires_permission(&self) -> Permission {
        Permission::ReadFile(PathBuf::new())
    }
    
    fn description(&self) -> &str {
        "Search for files by name pattern using regex"
    }
    
    fn name(&self) -> &str {
        "file_search"
    }
    
    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regex pattern to search for in file names"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to search in (defaults to current directory)"
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 100)"
                }
            },
            "required": ["pattern"]
        })
    }
    
    fn clone_box(&self) -> Box<dyn Tool> {
        Box::new(FileSearchTool::new())
    }
}

/// Tool for searching content within files
pub struct ContentSearchTool;

impl ContentSearchTool {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for ContentSearchTool {
    async fn execute(
        &self,
        parameters: serde_json::Value,
        host: &dyn HostIntegration,
    ) -> Result<ToolResponse, ToolError> {
        let pattern = validation::require_string(&parameters, "pattern")?;
        let file_path = validation::require_path(&parameters, "file")?;
        let context_lines = parameters.get("context_lines")
            .and_then(|v| v.as_u64())
            .unwrap_or(2) as usize;
        
        validation::validate_safe_path(&file_path)?;
        
        let regex = Regex::new(&pattern)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid regex pattern: {}", e)))?;
        
        let content = host.get_file_content(&file_path).await
            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
        
        let lines: Vec<&str> = content.lines().collect();
        let mut matches = Vec::new();
        
        for (line_num, line) in lines.iter().enumerate() {
            if regex.is_match(line) {
                let start = line_num.saturating_sub(context_lines);
                let end = std::cmp::min(line_num + context_lines + 1, lines.len());
                
                let mut context = Vec::new();
                for i in start..end {
                    let marker = if i == line_num { ">" } else { " " };
                    context.push(format!("{} {:4}: {}", marker, i + 1, lines[i]));
                }
                
                matches.push(format!("Match at line {}:\n{}", line_num + 1, context.join("\n")));
            }
        }
        
        if matches.is_empty() {
            Ok(ToolResponse::success("No matches found".to_string()))
        } else {
            let result_text = matches.join("\n\n");
            let metadata = serde_json::json!({
                "pattern": pattern,
                "file": file_path,
                "total_matches": matches.len(),
                "context_lines": context_lines,
            });
            
            Ok(ToolResponse::with_metadata(result_text, metadata))
        }
    }
    
    fn requires_permission(&self) -> Permission {
        Permission::ReadFile(PathBuf::new())
    }
    
    fn description(&self) -> &str {
        "Search for content within a file using regex"
    }
    
    fn name(&self) -> &str {
        "content_search"
    }
    
    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regex pattern to search for in file content"
                },
                "file": {
                    "type": "string",
                    "description": "Path to the file to search in"
                },
                "context_lines": {
                    "type": "integer",
                    "description": "Number of context lines to show around matches (default: 2)"
                }
            },
            "required": ["pattern", "file"]
        })
    }
    
    fn clone_box(&self) -> Box<dyn Tool> {
        Box::new(ContentSearchTool::new())
    }
}

/// Advanced grep tool that combines file and content search with OpenCode-level functionality
pub struct GrepTool;

impl GrepTool {
    pub fn new() -> Self {
        Self
    }

    /// Check if a file is likely binary by examining the first few bytes
    fn is_binary_file(path: &Path) -> bool {
        if let Ok(mut file) = std::fs::File::open(path) {
            use std::io::Read;
            let mut buffer = [0; 512];
            if let Ok(bytes_read) = file.read(&mut buffer) {
                // Check for null bytes or high percentage of non-printable characters
                let null_count = buffer[..bytes_read].iter().filter(|&&b| b == 0).count();
                let non_printable = buffer[..bytes_read].iter()
                    .filter(|&&b| b < 32 && b != 9 && b != 10 && b != 13)
                    .count();

                return null_count > 0 || (non_printable as f64 / bytes_read as f64) > 0.3;
            }
        }
        false
    }

    /// Check if file extension matches the allowed types
    fn matches_file_types(path: &Path, file_types: &HashSet<String>) -> bool {
        if file_types.is_empty() {
            return true;
        }

        if let Some(extension) = path.extension().and_then(OsStr::to_str) {
            file_types.contains(&extension.to_lowercase())
        } else {
            // Include files without extensions if "none" is specified
            file_types.contains("none")
        }
    }

    /// Parse file types from comma-separated string
    fn parse_file_types(types_str: &str) -> HashSet<String> {
        types_str.split(',')
            .map(|s| s.trim().to_lowercase())
            .filter(|s| !s.is_empty())
            .collect()
    }
}

#[async_trait]
impl Tool for GrepTool {
    async fn execute(
        &self,
        parameters: serde_json::Value,
        host: &dyn HostIntegration,
    ) -> Result<ToolResponse, ToolError> {
        let pattern = validation::require_string(&parameters, "pattern")?;
        let search_path = validation::optional_path(&parameters, "path")
            .unwrap_or_else(|| PathBuf::from("."));

        // Advanced options
        let case_sensitive = parameters.get("case_sensitive")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        let recursive = parameters.get("recursive")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        let include_binary = parameters.get("include_binary")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let context_before = parameters.get("context_before")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize;
        let context_after = parameters.get("context_after")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize;
        let max_results = parameters.get("max_results")
            .and_then(|v| v.as_u64())
            .unwrap_or(1000) as usize;

        // File type filtering
        let file_types = if let Some(types) = parameters.get("file_types").and_then(|v| v.as_str()) {
            Self::parse_file_types(types)
        } else {
            HashSet::new()
        };

        validation::validate_safe_path(&search_path)?;

        // Build regex with case sensitivity option
        let regex = RegexBuilder::new(&pattern)
            .case_insensitive(!case_sensitive)
            .build()
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid regex pattern: {}", e)))?;

        let mut all_matches = Vec::new();
        let mut files_searched = 0;
        let mut files_with_matches = 0;

        // Recursive search function
        fn search_directory(
            dir: &Path,
            regex: &Regex,
            file_types: &HashSet<String>,
            include_binary: bool,
            context_before: usize,
            context_after: usize,
            recursive: bool,
            matches: &mut Vec<String>,
            files_searched: &mut usize,
            files_with_matches: &mut usize,
            max_results: usize,
        ) -> Result<(), ToolError> {
            if matches.len() >= max_results {
                return Ok(());
            }

            let entries = std::fs::read_dir(dir)
                .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read directory {}: {}", dir.display(), e)))?;

            for entry in entries {
                if matches.len() >= max_results {
                    break;
                }

                let entry = entry.map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
                let path = entry.path();

                if path.is_file() {
                    // Check file type filter
                    if !GrepTool::matches_file_types(&path, file_types) {
                        continue;
                    }

                    // Check if binary (unless explicitly included)
                    if !include_binary && GrepTool::is_binary_file(&path) {
                        continue;
                    }

                    *files_searched += 1;

                    // Search file content
                    if let Ok(content) = std::fs::read_to_string(&path) {
                        let lines: Vec<&str> = content.lines().collect();
                        let mut file_matches = Vec::new();

                        for (line_num, line) in lines.iter().enumerate() {
                            if regex.is_match(line) {
                                let start = line_num.saturating_sub(context_before);
                                let end = std::cmp::min(line_num + context_after + 1, lines.len());

                                let mut context = Vec::new();
                                for i in start..end {
                                    let marker = if i == line_num { ">" } else { " " };
                                    context.push(format!("{} {:4}: {}", marker, i + 1, lines[i]));
                                }

                                file_matches.push(format!("  Line {}:\n{}", line_num + 1, context.join("\n")));
                            }
                        }

                        if !file_matches.is_empty() {
                            *files_with_matches += 1;
                            let file_result = format!("{}:\n{}", path.display(), file_matches.join("\n\n"));
                            matches.push(file_result);
                        }
                    }
                } else if path.is_dir() && recursive {
                    // Skip hidden directories
                    if let Some(dir_name) = path.file_name().and_then(OsStr::to_str) {
                        if !dir_name.starts_with('.') {
                            search_directory(
                                &path, regex, file_types, include_binary,
                                context_before, context_after, recursive,
                                matches, files_searched, files_with_matches, max_results
                            )?;
                        }
                    }
                }
            }

            Ok(())
        }

        if search_path.is_file() {
            // Search single file
            if GrepTool::matches_file_types(&search_path, &file_types) &&
               (include_binary || !GrepTool::is_binary_file(&search_path)) {

                files_searched = 1;
                let content = host.get_file_content(&search_path).await
                    .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;

                let lines: Vec<&str> = content.lines().collect();
                let mut file_matches = Vec::new();

                for (line_num, line) in lines.iter().enumerate() {
                    if regex.is_match(line) {
                        let start = line_num.saturating_sub(context_before);
                        let end = std::cmp::min(line_num + context_after + 1, lines.len());

                        let mut context = Vec::new();
                        for i in start..end {
                            let marker = if i == line_num { ">" } else { " " };
                            context.push(format!("{} {:4}: {}", marker, i + 1, lines[i]));
                        }

                        file_matches.push(format!("  Line {}:\n{}", line_num + 1, context.join("\n")));
                    }
                }

                if !file_matches.is_empty() {
                    files_with_matches = 1;
                    let file_result = format!("{}:\n{}", search_path.display(), file_matches.join("\n\n"));
                    all_matches.push(file_result);
                }
            }
        } else {
            // Search directory
            search_directory(
                &search_path, &regex, &file_types, include_binary,
                context_before, context_after, recursive,
                &mut all_matches, &mut files_searched, &mut files_with_matches, max_results
            )?;
        }

        let result_text = if all_matches.is_empty() {
            format!("No matches found for pattern '{}' in {} files searched", pattern, files_searched)
        } else {
            all_matches.join("\n\n")
        };

        let metadata = serde_json::json!({
            "pattern": pattern,
            "search_path": search_path,
            "case_sensitive": case_sensitive,
            "recursive": recursive,
            "include_binary": include_binary,
            "context_before": context_before,
            "context_after": context_after,
            "file_types": file_types.iter().collect::<Vec<_>>(),
            "files_searched": files_searched,
            "files_with_matches": files_with_matches,
            "total_matches": all_matches.len(),
            "max_results": max_results,
        });

        Ok(ToolResponse::with_metadata(result_text, metadata))
    }

    fn requires_permission(&self) -> Permission {
        Permission::ReadFile(PathBuf::new())
    }

    fn description(&self) -> &str {
        "Advanced grep tool with regex patterns, file type filtering, and context lines"
    }

    fn name(&self) -> &str {
        "grep"
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regex pattern to search for"
                },
                "path": {
                    "type": "string",
                    "description": "File or directory to search in (defaults to current directory)"
                },
                "case_sensitive": {
                    "type": "boolean",
                    "description": "Whether the search should be case sensitive (default: true)"
                },
                "recursive": {
                    "type": "boolean",
                    "description": "Whether to search subdirectories recursively (default: true)"
                },
                "include_binary": {
                    "type": "boolean",
                    "description": "Whether to include binary files in search (default: false)"
                },
                "context_before": {
                    "type": "integer",
                    "description": "Number of lines to show before each match (default: 0)"
                },
                "context_after": {
                    "type": "integer",
                    "description": "Number of lines to show after each match (default: 0)"
                },
                "file_types": {
                    "type": "string",
                    "description": "Comma-separated list of file extensions to include (e.g., 'rs,go,py')"
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of matches to return (default: 1000)"
                }
            },
            "required": ["pattern"]
        })
    }

    fn clone_box(&self) -> Box<dyn Tool> {
        Box::new(GrepTool::new())
    }
}