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
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
//! Edit tool implementation compatible with OpenCode
//!
//! Performs exact string replacements in files with multiple fallback strategies.

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

/// Edit tool parameters
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EditParams {
    /// The absolute path to the file to modify
    pub file_path: String,
    /// The text to replace
    pub old_string: String,
    /// The text to replace it with (must be different from oldString)
    pub new_string: String,
    /// Replace all occurrences of oldString (default false)
    pub replace_all: Option<bool>,
}

/// Edit tool for performing string replacements in files
pub struct EditTool {
    name: String,
}

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

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

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

    fn description(&self) -> &str {
        "Performs exact string replacements in files"
    }

    fn signature(&self) -> &str {
        "edit --file-path <path> --old-string <old> --new-string <new> [--replace-all]"
    }

    fn validate_args(&self, args: &ToolArgs) -> Result<(), ToolError> {
        if args.get_named_arg("file_path").is_none() && args.args.is_empty() {
            return Err(ToolError::InvalidArgs {
                message: "edit tool requires a 'file_path' argument".to_string(),
            });
        }
        if args.get_named_arg("old_string").is_none() && args.args.len() < 2 {
            return Err(ToolError::InvalidArgs {
                message: "edit tool requires an 'old_string' argument".to_string(),
            });
        }
        if args.get_named_arg("new_string").is_none() && args.args.len() < 3 {
            return Err(ToolError::InvalidArgs {
                message: "edit tool requires a 'new_string' argument".to_string(),
            });
        }
        Ok(())
    }

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

        if params.old_string == params.new_string {
            return Err(anyhow::anyhow!("oldString and newString must be different").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 filepath = if Path::new(&params.file_path).is_absolute() {
            PathBuf::from(&params.file_path)
        } else {
            working_dir.join(&params.file_path)
        };

        if !filepath.exists() {
            return Err(ToolError::FileNotFound {
                path: filepath.display().to_string(),
            }
            .into());
        }

        if filepath.is_dir() {
            return Err(anyhow::anyhow!(
                "Path is a directory, not a file: {}",
                filepath.display()
            ));
        }

        // Read file content
        let content = fs::read_to_string(&filepath)?;
        let replace_all = params.replace_all.unwrap_or(false);

        // Perform replacement
        let new_content = replace_in_content(
            &content,
            &params.old_string,
            &params.new_string,
            replace_all,
        )?;

        // Write back
        fs::write(&filepath, &new_content)?;

        // Generate diff summary
        let additions = new_content.lines().count() as i32 - content.lines().count() as i32;
        let changes = if replace_all {
            "multiple locations".to_string()
        } else {
            "1 location".to_string()
        };

        let message = format!(
            "Edited file: {} (changes in {})",
            filepath.display(),
            changes
        );

        Ok(ToolResult::success_with_data(
            message,
            serde_json::json!({
                "file_path": filepath.display().to_string(),
                "old_string": params.old_string,
                "new_string": params.new_string,
                "replace_all": replace_all,
                "additions": additions,
            }),
        ))
    }

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

fn parse_edit_args(args: &ToolArgs) -> Result<EditParams> {
    let file_path = args
        .get_named_arg("file_path")
        .cloned()
        .or_else(|| args.get_named_arg("filePath").cloned())
        .or_else(|| args.args.first().cloned())
        .ok_or_else(|| anyhow::anyhow!("file_path is required"))?;

    let old_string = args
        .get_named_arg("old_string")
        .cloned()
        .or_else(|| args.get_named_arg("oldString").cloned())
        .or_else(|| args.args.get(1).cloned())
        .ok_or_else(|| anyhow::anyhow!("old_string is required"))?;

    let new_string = args
        .get_named_arg("new_string")
        .cloned()
        .or_else(|| args.get_named_arg("newString").cloned())
        .or_else(|| args.args.get(2).cloned())
        .ok_or_else(|| anyhow::anyhow!("new_string is required"))?;

    let replace_all = args
        .get_named_arg("replace_all")
        .or_else(|| args.get_named_arg("replaceAll"))
        .map(|s| s == "true");

    Ok(EditParams {
        file_path,
        old_string,
        new_string,
        replace_all,
    })
}

/// Replace string in content with multiple fallback strategies
pub fn replace_in_content(
    content: &str,
    old_string: &str,
    new_string: &str,
    replace_all: bool,
) -> Result<String> {
    // Try simple replacement first
    if content.contains(old_string) {
        let occurrences = content.matches(old_string).count();

        if occurrences > 1 && !replace_all {
            return Err(anyhow::anyhow!(
                "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match."
            ));
        }

        if replace_all {
            return Ok(content.replace(old_string, new_string));
        }

        // Replace first occurrence
        if let Some(pos) = content.find(old_string) {
            let mut result =
                String::with_capacity(content.len() - old_string.len() + new_string.len());
            result.push_str(&content[..pos]);
            result.push_str(new_string);
            result.push_str(&content[pos + old_string.len()..]);
            return Ok(result);
        }
    }

    // Try line-trimmed matching
    for replaced in line_trimmed_replacer(content, old_string) {
        if let Some(new_content) = try_replace(content, &replaced, new_string, replace_all)? {
            return Ok(new_content);
        }
    }

    // Try whitespace normalized matching
    for replaced in whitespace_normalized_replacer(content, old_string) {
        if let Some(new_content) = try_replace(content, &replaced, new_string, replace_all)? {
            return Ok(new_content);
        }
    }

    // Try trimmed boundary matching
    for replaced in trimmed_boundary_replacer(content, old_string) {
        if let Some(new_content) = try_replace(content, &replaced, new_string, replace_all)? {
            return Ok(new_content);
        }
    }

    Err(anyhow::anyhow!("oldString not found in content"))
}

fn try_replace(
    content: &str,
    old_string: &str,
    new_string: &str,
    replace_all: bool,
) -> Result<Option<String>> {
    let occurrences = content.matches(old_string).count();

    if occurrences == 0 {
        return Ok(None);
    }

    if occurrences > 1 && !replace_all {
        return Ok(None);
    }

    if replace_all {
        return Ok(Some(content.replace(old_string, new_string)));
    }

    // Replace first occurrence only
    if let Some(pos) = content.find(old_string) {
        let mut result = String::with_capacity(content.len() - old_string.len() + new_string.len());
        result.push_str(&content[..pos]);
        result.push_str(new_string);
        result.push_str(&content[pos + old_string.len()..]);
        return Ok(Some(result));
    }

    Ok(None)
}

/// Line-trimmed replacer: matches ignoring leading/trailing whitespace on each line
fn line_trimmed_replacer<'a>(content: &'a str, find: &'a str) -> Vec<String> {
    let mut results = Vec::new();
    let original_lines: Vec<&str> = content.lines().collect();
    let search_lines: Vec<&str> = find.lines().collect();

    if search_lines.is_empty() {
        return results;
    }

    let search_lines: Vec<&str> = if search_lines.last().map(|l| l.is_empty()) == Some(true) {
        search_lines[..search_lines.len() - 1].to_vec()
    } else {
        search_lines
    };

    if search_lines.is_empty() {
        return results;
    }

    for i in 0..=original_lines.len().saturating_sub(search_lines.len()) {
        let mut matches = true;

        for (j, search_line) in search_lines.iter().enumerate() {
            if original_lines[i + j].trim() != search_line.trim() {
                matches = false;
                break;
            }
        }

        if matches {
            // Extract the original matched content
            let matched: String = original_lines[i..i + search_lines.len()].join("\n");
            results.push(matched);
        }
    }

    results
}

/// Whitespace normalized replacer: matches ignoring all whitespace differences
fn whitespace_normalized_replacer<'a>(content: &'a str, find: &'a str) -> Vec<String> {
    let mut results = Vec::new();

    let normalize = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
    let normalized_find = normalize(find);

    // Single line match
    for line in content.lines() {
        if normalize(line) == normalized_find {
            results.push(line.to_string());
        }
    }

    // Multi-line match
    let find_lines: Vec<&str> = find.lines().collect();
    if find_lines.len() > 1 {
        let content_lines: Vec<&str> = content.lines().collect();

        if content_lines.len() >= find_lines.len() {
            for i in 0..=content_lines.len() - find_lines.len() {
                let block: String = content_lines[i..i + find_lines.len()].join("\n");
                if normalize(&block) == normalized_find {
                    results.push(block);
                }
            }
        }
    }

    results
}

/// Trimmed boundary replacer: matches ignoring leading/trailing whitespace of the whole string
fn trimmed_boundary_replacer<'a>(content: &'a str, find: &'a str) -> Vec<String> {
    let mut results = Vec::new();
    let trimmed_find = find.trim();

    // Try direct trimmed match
    if content.contains(trimmed_find) {
        results.push(trimmed_find.to_string());
    }

    // Try block match where the block's trimmed content matches
    let find_lines: Vec<&str> = find.lines().collect();
    if find_lines.is_empty() {
        return results;
    }
    let content_lines: Vec<&str> = content.lines().collect();

    if content_lines.len() >= find_lines.len() {
        for i in 0..=content_lines.len() - find_lines.len() {
            let block: String = content_lines[i..i + find_lines.len()].join("\n");
            if block.trim() == trimmed_find {
                results.push(block);
            }
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_edit_tool_creation() {
        let tool = EditTool::new();
        assert_eq!(tool.name(), "edit");
    }

    #[test]
    fn test_edit_tool_simple_replace() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "Hello, World!").unwrap();

        let mut tool = EditTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec![temp_file.path().to_str().unwrap().to_string()],
            vec![
                ("old_string".to_string(), "World".to_string()),
                ("new_string".to_string(), "Rust".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);

        let content = fs::read_to_string(temp_file.path()).unwrap();
        assert_eq!(content.trim(), "Hello, Rust!");
    }

    #[test]
    fn test_edit_tool_replace_all() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "foo bar foo baz foo").unwrap();

        let mut tool = EditTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec![temp_file.path().to_str().unwrap().to_string()],
            vec![
                ("old_string".to_string(), "foo".to_string()),
                ("new_string".to_string(), "qux".to_string()),
                ("replace_all".to_string(), "true".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state).unwrap();
        assert!(result.success);

        let content = fs::read_to_string(temp_file.path()).unwrap();
        assert_eq!(content.trim(), "qux bar qux baz qux");
    }

    #[test]
    fn test_edit_tool_multiple_matches_error() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "foo bar foo").unwrap();

        let mut tool = EditTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec![temp_file.path().to_str().unwrap().to_string()],
            vec![
                ("old_string".to_string(), "foo".to_string()),
                ("new_string".to_string(), "bar".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("multiple matches"));
    }

    #[test]
    fn test_edit_tool_not_found() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "Hello, World!").unwrap();

        let mut tool = EditTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec![temp_file.path().to_str().unwrap().to_string()],
            vec![
                ("old_string".to_string(), "NotPresent".to_string()),
                ("new_string".to_string(), "New".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_edit_tool_same_string_error() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "Hello, World!").unwrap();

        let mut tool = EditTool::new();
        let state = Arc::new(Mutex::new(crate::state::ToolState::new()));
        let args = ToolArgs::with_named_args(
            vec![temp_file.path().to_str().unwrap().to_string()],
            vec![
                ("old_string".to_string(), "World".to_string()),
                ("new_string".to_string(), "World".to_string()),
            ]
            .into_iter()
            .collect(),
        );

        let result = tool.execute(&args, &state);
        assert!(result.is_err());
    }

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

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