vtcode_core/tools/file_ops/
write.rs1use super::FileOpsTool;
2use super::diff_preview::{build_diff_preview, diff_preview_error_skip, diff_preview_size_skip};
3mod chunked;
4mod fs_ops;
5use crate::config::constants::diff;
6use crate::config::constants::tools;
7use crate::tools::builder::ToolResponseBuilder;
8use crate::tools::edited_file_monitor::conflict_override_snapshot;
9use crate::tools::error_helpers::deserialize_tool_args;
10use crate::tools::traits::FileTool;
11use crate::tools::types::WriteInput;
12use crate::utils::file_utils::{ensure_dir_exists, read_file_with_context};
13use anyhow::{Context, Result, anyhow};
14use serde_json::{Value, json};
15use std::borrow::Cow;
16use std::future::Future;
17use std::io::ErrorKind;
18
19const MAX_WRITE_BYTES: usize = 64_000;
20
21async fn write_text_file(path: &std::path::Path, content: &str) -> Result<()> {
22 tokio::fs::write(path, content.as_bytes())
25 .await
26 .with_context(|| format!("Failed to write file content: {}", path.display()))
27}
28
29async fn create_text_file(path: &std::path::Path, content: &str) -> Result<(), std::io::Error> {
30 let path = path.to_path_buf();
33 let bytes = content.as_bytes().to_vec();
34 tokio::task::spawn_blocking(move || {
35 use std::io::Write;
36 let mut options = std::fs::OpenOptions::new();
37 options.create_new(true).write(true);
38 let mut file = options.open(&path)?;
39 file.write_all(&bytes)?;
40 file.flush()
41 })
42 .await
43 .map_err(|err| std::io::Error::other(format!("write task join failed: {err}")))?
44}
45
46impl FileOpsTool {
47 pub fn write_file(&self, args: Value) -> impl Future<Output = Result<Value>> + '_ {
51 self.write_file_internal(args, true)
52 }
53
54 pub(crate) async fn write_file_internal(&self, args: Value, acquire_mutation: bool) -> Result<Value> {
55 let input: WriteInput = deserialize_tool_args(&args, "write_file")?;
56 let override_snapshot = conflict_override_snapshot(&args);
57
58 let file_path = self.normalize_and_validate_user_path(&input.path).await?;
59
60 if self.should_exclude(&file_path).await {
61 return Err(anyhow!("Error: Path '{}' is excluded by .vtcodegitignore", input.path));
62 }
63
64 let content_size = input.content.len();
65 if content_size > MAX_WRITE_BYTES {
66 return Err(anyhow!(
67 "Content exceeds safe write limit ({MAX_WRITE_BYTES} bytes, got {content_size} bytes). \
68 Use bounded apply_patch operations to write large files."
69 ));
70 }
71
72 let _mutation_lease = if acquire_mutation {
73 Some(self.edited_file_monitor.acquire_mutation(&file_path).await)
74 } else {
75 None
76 };
77
78 if let Some(parent) = file_path.parent() {
80 ensure_dir_exists(parent).await?;
81 }
82
83 let file_exists = tokio::fs::try_exists(&file_path).await?;
84
85 let mut existing_content: Option<String> = None;
86 let mut diff_preview: Option<Value> = None;
87
88 if file_exists {
89 match read_file_with_context(&file_path, "existing file content").await {
90 Ok(content) => existing_content = Some(content),
91 Err(error) => {
92 diff_preview =
93 Some(diff_preview_error_skip("failed_to_read_existing_content", Some(&error.to_string())));
94 }
95 }
96 }
97
98 let effective_mode = if input.overwrite && input.mode != "overwrite" && input.mode != "fail_if_exists" {
99 return Err(anyhow!(
100 "Conflicting parameters: overwrite=true but mode='{}'. Use mode='overwrite' or omit overwrite.",
101 input.mode
102 ));
103 } else if input.overwrite {
104 "overwrite"
105 } else {
106 input.mode.as_str()
107 };
108
109 if effective_mode == "skip_if_exists" && file_exists {
110 return Ok(ToolResponseBuilder::new(tools::WRITE_FILE)
111 .success()
112 .message("File already exists")
113 .field("skipped", json!(true))
114 .field("reason", json!("File already exists"))
115 .field("diff", json!([]))
116 .build_json());
117 }
118 if effective_mode == "fail_if_exists" && file_exists {
119 return Err(anyhow!(
120 "File '{}' exists. Use mode='overwrite' (or overwrite=true) to replace, or choose append/skip_if_exists.",
121 input.path
122 ));
123 }
124
125 if acquire_mutation && let Some(content) = existing_content.as_deref() {
126 if effective_mode == "append" {
127 let line_count = content.lines().count();
128 self.edited_file_monitor.source_inspection().require(
129 &file_path,
130 content,
131 std::slice::from_ref(&(line_count.saturating_sub(1)..line_count)),
132 )?;
133 } else {
134 self.edited_file_monitor.source_inspection().require_full(&file_path, content)?;
135 }
136 } else if file_exists && existing_content.is_none() {
137 return Err(anyhow!("Existing content must be readable before replacement"));
138 }
139
140 let intended_content = match effective_mode {
141 "overwrite" => Some(input.content.clone()),
142 "append" => existing_content
143 .as_ref()
144 .map(|content| format!("{content}{}", input.content))
145 .or_else(|| Some(input.content.clone())),
146 "skip_if_exists" | "fail_if_exists" => Some(input.content.clone()),
147 _ => None,
148 };
149
150 if let Some(conflict) = self
155 .edited_file_monitor
156 .detect_conflict(&file_path, intended_content.clone(), override_snapshot)
157 .await?
158 {
159 return Ok(conflict.to_tool_output(&self.workspace_root));
160 }
161
162 let final_written_content = match effective_mode {
163 "append" => intended_content.clone().unwrap_or_else(|| input.content.clone()),
164 _ => input.content.clone(),
165 };
166
167 match effective_mode {
168 "overwrite" => {
169 write_text_file(&file_path, &input.content).await?;
170 }
171 "append" => {
172 let path = file_path.clone();
175 let bytes = input.content.as_bytes().to_vec();
176 tokio::task::spawn_blocking(move || {
177 use std::io::Write;
178 let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
179 file.write_all(&bytes)?;
180 file.flush()
181 })
182 .await
183 .map_err(|err| anyhow!("append task join failed: {err}"))?
184 .with_context(|| format!("Failed to append file content: {}", file_path.display()))?;
185 }
186 "skip_if_exists" => {
187 if let Err(err) = create_text_file(&file_path, &input.content).await {
188 if err.kind() == ErrorKind::AlreadyExists {
189 return Ok(ToolResponseBuilder::new(tools::WRITE_FILE)
190 .success()
191 .message("File already exists")
192 .field("skipped", json!(true))
193 .field("reason", json!("File already exists"))
194 .field("diff", json!([]))
195 .build_json());
196 }
197 return Err(err).with_context(|| format!("Failed to create file content: {}", file_path.display()));
198 }
199 }
200 "fail_if_exists" => {
201 if let Err(err) = create_text_file(&file_path, &input.content).await {
202 if err.kind() == ErrorKind::AlreadyExists {
203 return Err(anyhow!(
204 "File '{}' exists. Use mode='overwrite' (or overwrite=true) to replace, or choose append/skip_if_exists.",
205 input.path
206 ));
207 }
208 return Err(err).with_context(|| format!("Failed to create file content: {}", file_path.display()));
209 }
210 }
211 _ => {
212 return Err(anyhow!(
213 "Error: Unsupported write mode '{effective_mode}'. Allowed: overwrite, append, skip_if_exists, fail_if_exists."
214 ));
215 }
216 }
217
218 if acquire_mutation {
219 let support = crate::tools::source_inspection::call_key(tools::WRITE_FILE, &args);
220 if let Some(before) = &existing_content {
221 self.edited_file_monitor.source_inspection().record_edit(
222 &file_path,
223 before,
224 &final_written_content,
225 std::slice::from_ref(&if effective_mode == "append" {
226 let removed = usize::from(!before.is_empty() && !before.ends_with('\n'));
227 let start = before.lines().count().saturating_sub(removed);
228 crate::tools::source_inspection::mutations::InspectedReplacement {
229 start,
230 removed,
231 added: final_written_content.lines().count().saturating_sub(start),
232 }
233 } else {
234 crate::tools::source_inspection::mutations::InspectedReplacement {
235 start: 0,
236 removed: before.lines().count(),
237 added: final_written_content.lines().count(),
238 }
239 }),
240 support,
241 );
242 } else {
243 self.edited_file_monitor.source_inspection().record_created(
244 &file_path,
245 &final_written_content,
246 support,
247 );
248 }
249 }
250
251 self.log_write_operation(&file_path, content_size, false).await?;
253 if let Err(err) = self
254 .edited_file_monitor
255 .record_agent_write_text(&file_path, &final_written_content)
256 {
257 tracing::warn!(
258 path = %file_path.display(),
259 error = %err,
260 "Failed to refresh edited-file snapshot after write"
261 );
262 }
263
264 if diff_preview.is_none() {
265 let existing_snapshot = existing_content.as_deref();
266 let total_len = if effective_mode == "append" {
267 existing_snapshot.map(|content| content.len()).unwrap_or_default() + input.content.len()
268 } else {
269 input.content.len()
270 };
271
272 if total_len > diff::MAX_PREVIEW_BYTES
273 || existing_snapshot
274 .map(|content| content.len() > diff::MAX_PREVIEW_BYTES)
275 .unwrap_or(false)
276 {
277 diff_preview = Some(diff_preview_size_skip());
278 } else {
279 let final_snapshot: Cow<'_, str> = if effective_mode == "append" {
280 if let Some(existing) = existing_snapshot {
281 Cow::Owned(format!("{existing}{}", input.content))
282 } else {
283 Cow::Borrowed(input.content.as_str())
284 }
285 } else {
286 Cow::Borrowed(input.content.as_str())
287 };
288
289 diff_preview = Some(build_diff_preview(&input.path, existing_snapshot, final_snapshot.as_ref()));
290 }
291 }
292
293 let mut builder = ToolResponseBuilder::new(tools::WRITE_FILE)
294 .success()
295 .message(format!("Successfully wrote file {}", self.workspace_relative_display(&file_path)))
296 .field("path", json!(self.workspace_relative_display(&file_path)))
297 .field("mode", json!(effective_mode))
298 .field("bytes_written", json!(input.content.len()))
299 .field("file_existed", json!(file_exists));
300
301 if let Some(preview) = diff_preview {
302 let mut canonical_preview = preview.clone();
303 if let Some(fields) = canonical_preview.as_object_mut() {
304 fields.insert("path".to_string(), json!(self.workspace_relative_display(&file_path)));
305 fields.insert("operation".to_string(), json!(if file_exists { "updated" } else { "created" }));
306 }
307 builder = builder
308 .field("created", json!(!file_exists))
309 .field("diff_preview", preview)
310 .field("diff", json!([canonical_preview]));
311 }
312
313 Ok(builder.build_json())
314 }
315}