Skip to main content

matrixcode_core/tools/
edit.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use super::{Tool, ToolDefinition};
6use crate::approval::RiskLevel;
7
8/// Maximum file size for safe editing (1MB)
9const MAX_EDIT_FILE_SIZE: u64 = 1_000_000;
10
11pub struct EditTool;
12
13#[async_trait]
14impl Tool for EditTool {
15    fn definition(&self) -> ToolDefinition {
16        ToolDefinition {
17            name: "edit".to_string(),
18            description: "在文件中查找精确匹配的字符串并替换为新内容。
19
20【重要】编辑前必须先读取:
21- 你必须在对话中至少用 read 工具读一次该文件
22- 如果尝试编辑前没读文件,此工具会报错
23- 确保了解文件当前状态和上下文后再修改
24
25适用场景:
26- 单处代码修改(改一个函数名)
27- 精确替换(必须唯一匹配)
28- 小范围改动(<10行)
29
30不适用场景:
31- ❌ 同一文件多处修改 → 用 multi_edit(批量替换)
32- ❌ 大范围重构 → 先 enter_plan_mode 规划
33- ❌ 创建新文件 → 用 write
34
35优先级:[高] 小改动首选,精确且安全".to_string(),
36            parameters: json!({
37                "type": "object",
38                "properties": {
39                    "path": {
40                        "type": "string",
41                        "description": "要编辑的文件路径"
42                    },
43                    "old_string": {
44                        "type": "string",
45                        "description": "要查找并替换的原始字符串(必须精确匹配)"
46                    },
47                    "new_string": {
48                        "type": "string",
49                        "description": "替换后的新字符串"
50                    }
51                },
52                "required": ["path", "old_string", "new_string"]
53            }),
54            ..Default::default()
55        }
56    }
57
58    async fn execute(&self, params: Value) -> Result<String> {
59        let path = params["path"]
60            .as_str()
61            .ok_or_else(|| anyhow::anyhow!("missing 'path'"))?;
62        let old_string = params["old_string"]
63            .as_str()
64            .ok_or_else(|| anyhow::anyhow!("missing 'old_string'"))?;
65        let new_string = params["new_string"]
66            .as_str()
67            .ok_or_else(|| anyhow::anyhow!("missing 'new_string'"))?;
68
69        // Check file size first
70        let metadata = tokio::fs::metadata(path).await?;
71        let file_size = metadata.len();
72
73        if file_size > MAX_EDIT_FILE_SIZE {
74            return Ok(format!(
75                "⚠️ File is too large ({:.1}MB) for safe editing.\n\
76                 Large file edits may cause memory issues.\n\
77                 Consider using other methods:\n\
78                 - Use `bash` with sed/awk for large files\n\
79                 - Split the file into smaller sections first",
80                file_size as f64 / 1_000_000.0
81            ));
82        }
83
84        let content = tokio::fs::read_to_string(path).await?;
85
86        let count = content.matches(old_string).count();
87        if count == 0 {
88            anyhow::bail!("old_string not found in {}", path);
89        }
90        if count > 1 {
91            anyhow::bail!(
92                "old_string found {} times in {} — must be unique",
93                count,
94                path
95            );
96        }
97
98        let new_content = content.replacen(old_string, new_string, 1);
99        tokio::fs::write(path, &new_content).await?;
100
101        // Return diff-style output
102        let old_lines: Vec<&str> = old_string.lines().collect();
103        let new_lines: Vec<&str> = new_string.lines().collect();
104        let mut diff = format!("Successfully edited {}\n", path);
105        for line in &old_lines {
106            diff.push_str(&format!("- {}\n", line));
107        }
108        for line in &new_lines {
109            diff.push_str(&format!("+ {}\n", line));
110        }
111        Ok(diff)
112    }
113
114    fn risk_level(&self) -> RiskLevel {
115        RiskLevel::Mutating
116    }
117}