opi_coding_agent/tool/
edit.rs1use 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 pub path: String,
15 pub old_string: String,
17 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 = match super::validate_workspace_path(&self.workspace_root, &args.path) {
68 Ok(p) => p,
69 Err(msg) => {
70 return Box::pin(async move {
71 Ok(ToolResult {
72 content: vec![OutputContent::Text { text: msg }],
73 details: None,
74 is_error: true,
75 terminate: false,
76 })
77 });
78 }
79 };
80 let workspace_root = self.workspace_root.clone();
81 let path_for_display = args.path.clone();
82 Box::pin(async move {
83 let content = match tokio::fs::read_to_string(&file_path).await {
84 Ok(c) => c,
85 Err(e) => {
86 return Ok(ToolResult {
87 content: vec![OutputContent::Text {
88 text: format!("failed to read {}: {e}", file_path.display()),
89 }],
90 details: None,
91 is_error: true,
92 terminate: false,
93 });
94 }
95 };
96
97 if !content.contains(&args.old_string) {
98 return Ok(ToolResult {
99 content: vec![OutputContent::Text {
100 text: format!("old_string not found in {}", file_path.display()),
101 }],
102 details: None,
103 is_error: true,
104 terminate: false,
105 });
106 }
107
108 let before = content.clone();
110
111 let new_content = content.replacen(&args.old_string, &args.new_string, 1);
113
114 if let Err(e) = tokio::fs::write(&file_path, &new_content).await {
115 return Ok(ToolResult {
116 content: vec![OutputContent::Text {
117 text: format!("failed to write {}: {e}", file_path.display()),
118 }],
119 details: None,
120 is_error: true,
121 terminate: false,
122 });
123 }
124
125 let details = serde_json::json!({
126 "workspace_root": workspace_root.to_string_lossy(),
127 "path": path_for_display,
128 "before": before,
129 "after": new_content,
130 });
131
132 Ok(ToolResult {
133 content: vec![OutputContent::Text {
134 text: format!("edited {}", path_for_display),
135 }],
136 details: Some(details),
137 is_error: false,
138 terminate: false,
139 })
140 })
141 }
142
143 fn execution_mode(&self) -> ExecutionMode {
144 ExecutionMode::Sequential
145 }
146}