1use std::str::FromStr;
2
3use futures_util::stream;
4use serde_json::json;
5use tea_control::CancellationScope;
6use tea_protocol::ToolIdempotency;
7use tea_tools::{
8 BoxToolExecutionStream, ToolConcurrency, ToolEffect, ToolExecutionEvent,
9 ToolExecutionSemantics, ToolExecutor, ToolName, ToolRetrySafety, ToolSpec, ToolSpecError,
10 ToolTimeout, ToolVersion, ValidatedToolInvocation,
11};
12
13use crate::edit_diff::code_change;
14use crate::file::{atomic_write_if_unchanged, read_utf8};
15use crate::output::{failure, success};
16use crate::read::string_argument;
17use crate::{FileToolError, FileToolErrorCode, WorkspaceRoot};
18
19#[derive(Debug, Clone)]
21pub struct EditTool {
22 workspace: WorkspaceRoot,
23}
24
25impl EditTool {
26 #[must_use]
28 pub const fn new(workspace: WorkspaceRoot) -> Self {
29 Self { workspace }
30 }
31
32 pub fn spec() -> Result<ToolSpec, ToolSpecError> {
38 ToolSpec::new(
39 ToolName::from_str("edit").map_err(|_| ToolSpecError::InvalidDescription)?,
40 ToolVersion::from_str("1.0.0").map_err(|_| ToolSpecError::InvalidDescription)?,
41 "Atomically replace exact UTF-8 text in one workspace file.",
42 json!({
43 "type":"object",
44 "properties":{
45 "path":{"type":"string","minLength":1,"maxLength":4096},
46 "oldText":{"type":"string","minLength":1,"maxLength":crate::MAX_WRITE_BYTES},
47 "newText":{"type":"string","maxLength":crate::MAX_WRITE_BYTES},
48 "expectedReplacements":{"type":"integer","minimum":1,"maximum":100_000}
49 },
50 "required":["path","oldText","newText"],
51 "additionalProperties":false
52 }),
53 json!({
54 "type":"object",
55 "properties":{
56 "path":{"type":"string"},
57 "replacements":{"type":"integer","minimum":1},
58 "writtenBytes":{"type":"integer","minimum":0}
59 },
60 "required":["path","replacements","writtenBytes"],
61 "additionalProperties":false
62 }),
63 [ToolEffect::FsRead, ToolEffect::FsWrite],
64 ToolExecutionSemantics::new(
65 ToolIdempotency::NonIdempotent,
66 ToolRetrySafety::ExplicitOnly,
67 ToolConcurrency::Serial,
68 ToolTimeout::from_millis(30_000)?,
69 )?,
70 )?
71 .with_prompt_hint(
72 "Use edit for exact text replacement; ambiguous matches fail unless expectedReplacements is set.",
73 )
74 }
75
76 fn run(
77 &self,
78 invocation: &ValidatedToolInvocation,
79 ) -> Result<ToolExecutionEvent, FileToolError> {
80 let path = string_argument(invocation, "path")?;
81 let old_text = string_argument(invocation, "oldText")?;
82 let new_text = string_argument(invocation, "newText")?;
83 let expected = expected_replacements(invocation)?;
84 let existing = self.workspace.resolve_existing(path)?;
85 let source = read_utf8(&self.workspace, &existing, crate::MAX_WRITE_BYTES)?;
86 let matches = source.match_indices(old_text).count();
87 if matches == 0 {
88 return Err(FileToolError::new(FileToolErrorCode::NoMatch));
89 }
90 let expected = expected.unwrap_or(1);
91 if matches != expected {
92 return Err(FileToolError::new(FileToolErrorCode::MatchCountMismatch));
93 }
94 let result = source.replace(old_text, new_text);
95 if result.len() > crate::MAX_WRITE_BYTES {
96 return Err(FileToolError::new(FileToolErrorCode::TooLarge));
97 }
98 let change = code_change(
99 existing.display_path(),
100 &source,
101 &result,
102 tea_protocol::CodeChangeKind::Update,
103 )?;
104 let mutation = self.workspace.resolve_mutation(path)?;
105 atomic_write_if_unchanged(
106 &self.workspace,
107 &existing,
108 &mutation,
109 &source,
110 result.as_bytes(),
111 )?;
112 let event = success(
113 format!(
114 "replaced {matches} match(es) in {}",
115 existing.display_path()
116 ),
117 json!({
118 "path":existing.display_path(),
119 "replacements":matches,
120 "writtenBytes":result.len()
121 }),
122 );
123 let ToolExecutionEvent::Finished(result) = event else {
124 return Err(FileToolError::new(FileToolErrorCode::Internal));
125 };
126 Ok(ToolExecutionEvent::Finished(result.with_presentation(
127 tea_protocol::ToolPresentation::CodeChange(change),
128 )))
129 }
130
131 fn preview_change(
132 &self,
133 invocation: &ValidatedToolInvocation,
134 ) -> Result<tea_protocol::CodeChange, FileToolError> {
135 let path = string_argument(invocation, "path")?;
136 let old_text = string_argument(invocation, "oldText")?;
137 let new_text = string_argument(invocation, "newText")?;
138 let expected = expected_replacements(invocation)?;
139 let existing = self.workspace.resolve_existing(path)?;
140 let source = read_utf8(&self.workspace, &existing, crate::MAX_WRITE_BYTES)?;
141 let matches = source.match_indices(old_text).count();
142 if matches == 0 {
143 return Err(FileToolError::new(FileToolErrorCode::NoMatch));
144 }
145 let expected = expected.unwrap_or(1);
146 if matches != expected {
147 return Err(FileToolError::new(FileToolErrorCode::MatchCountMismatch));
148 }
149 let result = source.replace(old_text, new_text);
150 if result.len() > crate::MAX_WRITE_BYTES {
151 return Err(FileToolError::new(FileToolErrorCode::TooLarge));
152 }
153 code_change(
154 existing.display_path(),
155 &source,
156 &result,
157 tea_protocol::CodeChangeKind::Update,
158 )
159 }
160}
161
162impl ToolExecutor for EditTool {
163 fn preview(
164 &self,
165 invocation: &ValidatedToolInvocation,
166 ) -> Option<tea_protocol::ToolPresentation> {
167 self.preview_change(invocation)
168 .ok()
169 .map(tea_protocol::ToolPresentation::CodeChange)
170 }
171
172 fn execute(
173 &self,
174 invocation: ValidatedToolInvocation,
175 cancellation: CancellationScope,
176 ) -> BoxToolExecutionStream {
177 let executor = self.clone();
178 Box::pin(stream::once(async move {
179 if cancellation.is_cancelled() {
180 ToolExecutionEvent::Failed(tea_tools::ToolExecutionFailure::cancelled())
181 } else {
182 executor.run(&invocation).unwrap_or_else(failure)
183 }
184 }))
185 }
186}
187
188fn expected_replacements(
189 invocation: &ValidatedToolInvocation,
190) -> Result<Option<usize>, FileToolError> {
191 invocation
192 .arguments()
193 .get("expectedReplacements")
194 .map(|value| {
195 value
196 .as_u64()
197 .and_then(|value| usize::try_from(value).ok())
198 .ok_or_else(|| FileToolError::new(FileToolErrorCode::InvalidArguments))
199 })
200 .transpose()
201}