opencrabs 0.3.17

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Edit File Tool
//!
//! Intelligently modify portions of files (find/replace, line-based edits).

use super::error::{Result, ToolError, validate_file_path};
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::fs;

/// Edit file tool
pub struct EditTool;

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "operation")]
enum EditOperation {
    /// Replace old_text with new_text
    #[serde(rename = "replace")]
    Replace { old_text: String, new_text: String },

    /// Replace text at specific line range
    #[serde(rename = "replace_lines")]
    ReplaceLines {
        start_line: usize,
        end_line: usize,
        new_text: String,
    },

    /// Insert text at specific line
    #[serde(rename = "insert_line")]
    InsertLine { line: usize, text: String },

    /// Delete lines
    #[serde(rename = "delete_lines")]
    DeleteLines { start_line: usize, end_line: usize },

    /// Regex replace
    #[serde(rename = "regex_replace")]
    RegexReplace {
        pattern: String,
        replacement: String,
    },
}

#[derive(Debug, Deserialize, Serialize)]
struct EditInput {
    /// Path to the file to edit
    path: String,

    /// Edit operation to perform
    #[serde(flatten)]
    operation: EditOperation,
}

impl EditTool {
    /// Normalize the incoming JSON so the model can call us with the
    /// Claude-style `{path, old_text, new_text}` shape without the
    /// explicit `operation` tag. Also accepts legacy aliases
    /// (`old_string`/`new_string`).
    fn normalize_input(mut value: Value) -> Value {
        let Some(obj) = value.as_object_mut() else {
            return value;
        };

        // Accept `old_string`/`new_string` aliases (Anthropic Edit tool).
        if !obj.contains_key("old_text")
            && let Some(v) = obj.remove("old_string")
        {
            obj.insert("old_text".to_string(), v);
        }
        if !obj.contains_key("new_text")
            && let Some(v) = obj.remove("new_string")
        {
            obj.insert("new_text".to_string(), v);
        }

        // Infer `operation` when the model omitted it.
        if !obj.contains_key("operation") {
            let inferred = if obj.contains_key("old_text") && obj.contains_key("new_text") {
                Some("replace")
            } else if obj.contains_key("start_line")
                && obj.contains_key("end_line")
                && obj.contains_key("new_text")
            {
                Some("replace_lines")
            } else if obj.contains_key("line") && obj.contains_key("text") {
                Some("insert_line")
            } else if obj.contains_key("start_line") && obj.contains_key("end_line") {
                Some("delete_lines")
            } else if obj.contains_key("pattern") && obj.contains_key("replacement") {
                Some("regex_replace")
            } else {
                None
            };
            if let Some(op) = inferred {
                obj.insert("operation".to_string(), Value::String(op.to_string()));
            }
        }

        value
    }
}

#[async_trait]
impl Tool for EditTool {
    fn name(&self) -> &str {
        "edit_file"
    }

    fn description(&self) -> &str {
        "Edit a file intelligently using various operations: replace text, replace lines, insert lines, delete lines, or regex replace."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file to edit"
                },
                "operation": {
                    "type": "string",
                    "description": "Type of edit operation",
                    "enum": ["replace", "replace_lines", "insert_line", "delete_lines", "regex_replace"]
                },
                "old_text": {
                    "type": "string",
                    "description": "Text to find and replace (for 'replace' operation)"
                },
                "new_text": {
                    "type": "string",
                    "description": "Replacement text (for 'replace' and 'replace_lines' operations)"
                },
                "start_line": {
                    "type": "integer",
                    "description": "Starting line number (0-indexed, for line operations)",
                    "minimum": 0
                },
                "end_line": {
                    "type": "integer",
                    "description": "Ending line number (0-indexed, inclusive, for line operations)",
                    "minimum": 0
                },
                "line": {
                    "type": "integer",
                    "description": "Line number to insert at (0-indexed, for 'insert_line')",
                    "minimum": 0
                },
                "text": {
                    "type": "string",
                    "description": "Text to insert (for 'insert_line')"
                },
                "pattern": {
                    "type": "string",
                    "description": "Regex pattern to match (for 'regex_replace')"
                },
                "replacement": {
                    "type": "string",
                    "description": "Replacement text (for 'regex_replace')"
                },
            },
            "required": ["path"],
            "description": "If 'operation' is omitted but 'old_text' and 'new_text' are provided, 'replace' is inferred (Claude-style Edit shape)."
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![
            ToolCapability::ReadFiles,
            ToolCapability::WriteFiles,
            ToolCapability::SystemModification,
        ]
    }

    fn requires_approval(&self) -> bool {
        true // Editing files requires approval
    }

    fn validate_input(&self, input: &Value) -> Result<()> {
        let normalized = Self::normalize_input(input.clone());
        let _: EditInput = serde_json::from_value(normalized)
            .map_err(|e| ToolError::InvalidInput(format!("Invalid input: {}", e)))?;
        Ok(())
    }

    async fn execute(&self, input: Value, context: &ToolExecutionContext) -> Result<ToolResult> {
        let input: EditInput = serde_json::from_value(Self::normalize_input(input))?;

        // Validate path: safety check, existence, and file type
        let path = match validate_file_path(&input.path, &context.working_directory) {
            Ok(p) => p,
            Err(msg) => return Ok(ToolResult::error(msg)),
        };

        // Read file content
        let content = fs::read_to_string(&path).await.map_err(ToolError::Io)?;

        // Perform edit operation
        let new_content = match input.operation {
            EditOperation::Replace { old_text, new_text } => {
                if !content.contains(&old_text) {
                    return Ok(ToolResult::error(format!(
                        "Text not found in file: '{}'",
                        old_text
                    )));
                }
                content.replace(&old_text, &new_text)
            }

            EditOperation::ReplaceLines {
                start_line,
                end_line,
                new_text,
            } => {
                let lines: Vec<&str> = content.lines().collect();
                if start_line >= lines.len() || end_line >= lines.len() {
                    return Ok(ToolResult::error(format!(
                        "Line range {}-{} out of bounds (file has {} lines)",
                        start_line,
                        end_line,
                        lines.len()
                    )));
                }
                if start_line > end_line {
                    return Ok(ToolResult::error(
                        "start_line must be <= end_line".to_string(),
                    ));
                }

                let mut new_lines = Vec::new();
                new_lines.extend_from_slice(&lines[..start_line]);
                new_lines.push(&new_text);
                if end_line + 1 < lines.len() {
                    new_lines.extend_from_slice(&lines[end_line + 1..]);
                }
                new_lines.join("\n")
            }

            EditOperation::InsertLine { line, text } => {
                let lines: Vec<&str> = content.lines().collect();
                if line > lines.len() {
                    return Ok(ToolResult::error(format!(
                        "Line {} out of bounds (file has {} lines)",
                        line,
                        lines.len()
                    )));
                }

                let mut new_lines = Vec::new();
                new_lines.extend_from_slice(&lines[..line]);
                new_lines.push(&text);
                new_lines.extend_from_slice(&lines[line..]);
                new_lines.join("\n")
            }

            EditOperation::DeleteLines {
                start_line,
                end_line,
            } => {
                let lines: Vec<&str> = content.lines().collect();
                if start_line >= lines.len() || end_line >= lines.len() {
                    return Ok(ToolResult::error(format!(
                        "Line range {}-{} out of bounds (file has {} lines)",
                        start_line,
                        end_line,
                        lines.len()
                    )));
                }
                if start_line > end_line {
                    return Ok(ToolResult::error(
                        "start_line must be <= end_line".to_string(),
                    ));
                }

                let mut new_lines = Vec::new();
                new_lines.extend_from_slice(&lines[..start_line]);
                if end_line + 1 < lines.len() {
                    new_lines.extend_from_slice(&lines[end_line + 1..]);
                }
                new_lines.join("\n")
            }

            EditOperation::RegexReplace {
                pattern,
                replacement,
            } => {
                let regex = regex::Regex::new(&pattern)
                    .map_err(|e| ToolError::InvalidInput(format!("Invalid regex: {}", e)))?;

                if !regex.is_match(&content) {
                    return Ok(ToolResult::error(format!(
                        "Pattern not found in file: '{}'",
                        pattern
                    )));
                }

                regex
                    .replace_all(&content, replacement.as_str())
                    .to_string()
            }
        };

        // Write modified content
        fs::write(&path, &new_content)
            .await
            .map_err(ToolError::Io)?;

        let lines_before = content.lines().count();
        let lines_after = new_content.lines().count();

        // Build a compact diff for context (shown in expanded tool details)
        let diff = build_edit_diff(&content, &new_content);
        let mut output = format!(
            "Successfully edited {}. Lines: {}{}\n",
            path.display(),
            lines_before,
            lines_after
        );
        output.push_str(&diff);

        Ok(ToolResult::success(output))
    }
}

/// Build a compact unified-style diff between old and new content.
/// Shows only changed lines with `-`/`+` prefixes (capped at 40 diff lines).
fn build_edit_diff(old: &str, new: &str) -> String {
    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();

    let mut diff = String::new();
    let mut diff_lines = 0usize;
    let max_diff_lines = 40;

    // Simple LCS-based diff: walk both sequences
    let mut i = 0;
    let mut j = 0;
    while i < old_lines.len() || j < new_lines.len() {
        if diff_lines >= max_diff_lines {
            diff.push_str("... (diff truncated)\n");
            break;
        }
        if i < old_lines.len() && j < new_lines.len() && old_lines[i] == new_lines[j] {
            // Lines match — skip (context not needed for compact diff)
            i += 1;
            j += 1;
        } else {
            // Find how far ahead the old line appears in new (or vice versa)
            let new_ahead = new_lines[j..]
                .iter()
                .position(|l| i < old_lines.len() && *l == old_lines[i]);
            let old_ahead = old_lines[i..]
                .iter()
                .position(|l| j < new_lines.len() && *l == new_lines[j]);

            match (new_ahead, old_ahead) {
                (Some(na), Some(oa)) if na <= oa => {
                    // new has insertions before the match
                    for line in &new_lines[j..j + na] {
                        diff.push_str(&format!("+ {}\n", line));
                        diff_lines += 1;
                        if diff_lines >= max_diff_lines {
                            break;
                        }
                    }
                    j += na;
                }
                (Some(_), Some(oa)) => {
                    // old has deletions before the match
                    for line in &old_lines[i..i + oa] {
                        diff.push_str(&format!("- {}\n", line));
                        diff_lines += 1;
                        if diff_lines >= max_diff_lines {
                            break;
                        }
                    }
                    i += oa;
                }
                (Some(na), None) => {
                    for line in &new_lines[j..j + na] {
                        diff.push_str(&format!("+ {}\n", line));
                        diff_lines += 1;
                        if diff_lines >= max_diff_lines {
                            break;
                        }
                    }
                    j += na;
                }
                (None, Some(oa)) => {
                    for line in &old_lines[i..i + oa] {
                        diff.push_str(&format!("- {}\n", line));
                        diff_lines += 1;
                        if diff_lines >= max_diff_lines {
                            break;
                        }
                    }
                    i += oa;
                }
                (None, None) => {
                    // No match ahead — emit both as changed
                    if i < old_lines.len() {
                        diff.push_str(&format!("- {}\n", old_lines[i]));
                        diff_lines += 1;
                        i += 1;
                    }
                    if diff_lines < max_diff_lines && j < new_lines.len() {
                        diff.push_str(&format!("+ {}\n", new_lines[j]));
                        diff_lines += 1;
                        j += 1;
                    }
                }
            }
        }
    }

    diff
}