Skip to main content

opi_coding_agent/tool/
edit.rs

1use std::future::Future;
2use std::path::PathBuf;
3use std::pin::Pin;
4
5use opi_agent::tool::{ExecutionMode, Tool, ToolError, ToolResult};
6use opi_ai::message::{OutputContent, ToolDef};
7use schemars::JsonSchema;
8use serde::Deserialize;
9use tokio_util::sync::CancellationToken;
10
11#[derive(Debug, Deserialize, JsonSchema)]
12pub struct EditArgs {
13    /// Relative path within workspace to edit.
14    pub path: String,
15    /// Exact string to find in the file.
16    pub old_string: String,
17    /// Replacement string.
18    pub new_string: String,
19}
20
21pub struct EditTool {
22    workspace_root: PathBuf,
23    schema: serde_json::Value,
24}
25
26impl EditTool {
27    pub fn new(workspace_root: PathBuf) -> Self {
28        let schema = schemars::schema_for!(EditArgs);
29        Self {
30            workspace_root,
31            schema: serde_json::to_value(&schema).unwrap_or_default(),
32        }
33    }
34}
35
36impl Tool for EditTool {
37    fn definition(&self) -> ToolDef {
38        ToolDef {
39            name: "edit".into(),
40            description: "Replace an exact string in a file.".into(),
41            input_schema: self.schema.clone(),
42        }
43    }
44
45    fn execute(
46        &self,
47        _call_id: &str,
48        arguments: serde_json::Value,
49        _signal: CancellationToken,
50        _on_update: Option<opi_agent::tool::UpdateCallback>,
51    ) -> Pin<Box<dyn Future<Output = Result<ToolResult, ToolError>> + Send>> {
52        let args: EditArgs = match serde_json::from_value(arguments) {
53            Ok(a) => a,
54            Err(e) => {
55                return Box::pin(async move {
56                    Ok(ToolResult {
57                        content: vec![OutputContent::Text {
58                            text: format!("invalid arguments: {e}"),
59                        }],
60                        details: None,
61                        is_error: true,
62                        terminate: false,
63                    })
64                });
65            }
66        };
67        let file_path = self.workspace_root.join(&args.path);
68        let workspace_root = self.workspace_root.clone();
69        Box::pin(async move {
70            let content = match tokio::fs::read_to_string(&file_path).await {
71                Ok(c) => c,
72                Err(e) => {
73                    return Ok(ToolResult {
74                        content: vec![OutputContent::Text {
75                            text: format!("failed to read {}: {e}", file_path.display()),
76                        }],
77                        details: None,
78                        is_error: true,
79                        terminate: false,
80                    });
81                }
82            };
83
84            if !content.contains(&args.old_string) {
85                return Ok(ToolResult {
86                    content: vec![OutputContent::Text {
87                        text: format!("old_string not found in {}", file_path.display()),
88                    }],
89                    details: None,
90                    is_error: true,
91                    terminate: false,
92                });
93            }
94
95            // Replace first occurrence only
96            let new_content = content.replacen(&args.old_string, &args.new_string, 1);
97
98            if let Err(e) = tokio::fs::write(&file_path, &new_content).await {
99                return Ok(ToolResult {
100                    content: vec![OutputContent::Text {
101                        text: format!("failed to write {}: {e}", file_path.display()),
102                    }],
103                    details: None,
104                    is_error: true,
105                    terminate: false,
106                });
107            }
108
109            let inside = file_path.starts_with(&workspace_root);
110            let details = serde_json::json!({
111                "workspace_root": workspace_root.to_string_lossy(),
112                "path": args.path,
113                "inside_workspace": inside,
114            });
115
116            Ok(ToolResult {
117                content: vec![OutputContent::Text {
118                    text: format!("edited {}", args.path),
119                }],
120                details: Some(details),
121                is_error: false,
122                terminate: false,
123            })
124        })
125    }
126
127    fn execution_mode(&self) -> ExecutionMode {
128        ExecutionMode::Sequential
129    }
130}