summaryrefslogtreecommitdiffstats
path: root/src/tools/fs.rs
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
commit343f2a8a6148b8004d6f4d74fb779b4f30c9686a (patch)
tree2ea1ddab346565309da644517c3478d2a9096e55 /src/tools/fs.rs
parentM0: streaming provider, SSE decoder, mock provider, i686 build gate (diff)
downloadagent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.tar.gz
agent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.zip
M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate
- append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386
Diffstat (limited to 'src/tools/fs.rs')
-rw-r--r--src/tools/fs.rs527
1 files changed, 527 insertions, 0 deletions
diff --git a/src/tools/fs.rs b/src/tools/fs.rs
new file mode 100644
index 0000000..6addf8d
--- /dev/null
+++ b/src/tools/fs.rs
@@ -0,0 +1,527 @@
1use std::fs;
2use std::path::{Path, PathBuf};
3
4use serde_json::Value;
5
6const MAX_LINE_CHARS: usize = 400;
7const MAX_READ_LINES: usize = 2000;
8const MAX_MATCHES: usize = 200;
9const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024;
10const PREVIEW_BUDGET: usize = 60;
11
12const SKIP_DIRS: &[&str] = &[
13 ".git",
14 "target",
15 "node_modules",
16 "dist",
17 "build",
18 ".venv",
19 "vendor",
20 ".cache",
21];
22
23/// A pending file change. Built and previewed first, applied only after the
24/// human agrees.
25pub enum Change {
26 Write { path: String, content: String },
27 Edit { path: String, old: String, new: String, text: String },
28}
29
30impl Change {
31 pub fn path(&self) -> &str {
32 match self {
33 Change::Write { path, .. } | Change::Edit { path, .. } => path,
34 }
35 }
36
37 pub fn preview(&self) -> String {
38 match self {
39 Change::Write { path, content } => match fs::read_to_string(path) {
40 Ok(old) if old == *content => format!("{path}: unchanged"),
41 Ok(old) => diff_preview(&old, content),
42 Err(_) => new_file_preview(path, content),
43 },
44 Change::Edit {
45 path,
46 old,
47 new,
48 text,
49 } => {
50 let at = text.find(old.as_str()).unwrap_or(0);
51 edit_preview(path, text, old, new, at)
52 }
53 }
54 }
55
56 pub fn apply(self) -> Result<String, String> {
57 match self {
58 Change::Write { path, content } => {
59 let parent = Path::new(&path).parent();
60 if let Some(parent) = parent {
61 if !parent.as_os_str().is_empty() && !parent.is_dir() {
62 return Err(format!(
63 "parent directory does not exist: {} (create it with bash first)",
64 parent.display()
65 ));
66 }
67 }
68 fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?;
69 Ok(format!(
70 "wrote {} bytes ({} lines) to {path}",
71 content.len(),
72 content.lines().count()
73 ))
74 }
75 Change::Edit {
76 path,
77 old,
78 new,
79 mut text,
80 } => {
81 let at = text
82 .find(old.as_str())
83 .ok_or_else(|| format!("{path}: text to replace disappeared"))?;
84 let line = text[..at].matches('\n').count() + 1;
85 text.replace_range(at..at + old.len(), &new);
86 fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?;
87 Ok(format!("edited {path}: 1 replacement at line {line}"))
88 }
89 }
90 }
91}
92
93pub fn plan_write(args: &Value) -> Result<Change, String> {
94 Ok(Change::Write {
95 path: req(args, "path")?,
96 content: req(args, "content")?,
97 })
98}
99
100pub fn plan_edit(args: &Value) -> Result<Change, String> {
101 let path = req(args, "path")?;
102 let old = req(args, "old")?;
103 let new = req(args, "new")?;
104 if old.is_empty() {
105 return Err("`old` must not be empty; use write to create a file".into());
106 }
107 let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
108 let hits: Vec<usize> = text.match_indices(&old).map(|(i, _)| i).collect();
109 match hits.len() {
110 0 => Err(format!(
111 "text to replace was not found in {path}. Read the file and copy the exact \
112 text, including indentation."
113 )),
114 1 => Ok(Change::Edit {
115 path,
116 old,
117 new,
118 text,
119 }),
120 n => Err(format!(
121 "text to replace appears {n} times in {path} (lines {}); include more \
122 surrounding context so it is unique.",
123 line_list(&text, &hits)
124 )),
125 }
126}
127
128pub fn read(args: &Value) -> Result<String, String> {
129 let path = req(args, "path")?;
130 let offset = args
131 .get("offset")
132 .and_then(|v| v.as_u64())
133 .unwrap_or(1)
134 .max(1) as usize;
135 let limit = args
136 .get("limit")
137 .and_then(|v| v.as_u64())
138 .unwrap_or(MAX_READ_LINES as u64)
139 .clamp(1, MAX_READ_LINES as u64) as usize;
140
141 let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?;
142 if bytes.iter().take(8192).any(|&b| b == 0) {
143 return Err(format!(
144 "{path}: looks like a binary file and will not be shown"
145 ));
146 }
147 let text = String::from_utf8_lossy(&bytes);
148 let lines: Vec<&str> = text.lines().collect();
149 if lines.is_empty() {
150 return Ok(format!("{path}: empty file"));
151 }
152 if offset > lines.len() {
153 return Ok(format!(
154 "{path} has {} lines; offset {offset} is past the end",
155 lines.len()
156 ));
157 }
158
159 let end = (offset + limit - 1).min(lines.len());
160 let mut out = String::with_capacity((end - offset + 2) * 40);
161 for number in offset..=end {
162 out.push_str(&format!(
163 "{number:>6}\t{}\n",
164 clip(lines[number - 1], MAX_LINE_CHARS)
165 ));
166 }
167 if end < lines.len() {
168 out.push_str(&format!(
169 "… {} more line(s); continue with offset={}\n",
170 lines.len() - end,
171 end + 1
172 ));
173 }
174 Ok(out)
175}
176
177pub fn grep(args: &Value) -> Result<String, String> {
178 let pattern = req(args, "pattern")?;
179 if pattern.is_empty() {
180 return Err("pattern must not be empty".into());
181 }
182 let base = args
183 .get("path")
184 .and_then(|v| v.as_str())
185 .unwrap_or(".")
186 .to_string();
187 let ignore_case = args
188 .get("ignore_case")
189 .and_then(|v| v.as_bool())
190 .unwrap_or(false);
191 let needle = if ignore_case {
192 pattern.to_lowercase()
193 } else {
194 pattern.clone()
195 };
196
197 let root = Path::new(&base);
198 let files = if root.is_file() {
199 vec![root.to_path_buf()]
200 } else {
201 let mut files = Vec::new();
202 walk(root, &mut files);
203 files
204 };
205
206 let mut out = String::new();
207 let mut matches = 0usize;
208 for file in files {
209 if matches >= MAX_MATCHES {
210 break;
211 }
212 grep_file(&file, &needle, ignore_case, &mut matches, &mut out);
213 }
214
215 if matches == 0 {
216 return Ok(format!("no matches for `{pattern}` under {base}"));
217 }
218 if matches >= MAX_MATCHES {
219 out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n"));
220 }
221 Ok(out)
222}
223
224pub fn glob(args: &Value) -> Result<String, String> {
225 let pattern = req(args, "pattern")?;
226 let base = args
227 .get("path")
228 .and_then(|v| v.as_str())
229 .unwrap_or(".")
230 .to_string();
231 let root = Path::new(&base);
232 if !root.is_dir() {
233 return Err(format!("not a directory: {base}"));
234 }
235
236 let mut files = Vec::new();
237 walk(root, &mut files);
238
239 // A pattern without a slash is matched against the file name at any depth.
240 let bare = !pattern.contains('/');
241 let mut hits = Vec::new();
242 for file in files {
243 let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("");
244 let hit = if bare {
245 wildcard_match(pattern.as_bytes(), name.as_bytes())
246 } else {
247 let relative = file
248 .strip_prefix(root)
249 .unwrap_or(&file)
250 .to_string_lossy()
251 .to_string();
252 glob_match(&pattern, &relative)
253 };
254 if hit {
255 hits.push(file);
256 if hits.len() >= MAX_MATCHES {
257 break;
258 }
259 }
260 }
261
262 if hits.is_empty() {
263 return Ok(format!("no files match `{pattern}` under {base}"));
264 }
265
266 let mut out = String::new();
267 for hit in &hits {
268 out.push_str(&hit.display().to_string());
269 out.push('\n');
270 }
271 if hits.len() >= MAX_MATCHES {
272 out.push_str(&format!("… stopped after {MAX_MATCHES} files\n"));
273 }
274 Ok(out)
275}
276
277fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) {
278 let meta = match fs::metadata(path) {
279 Ok(m) => m,
280 Err(_) => return,
281 };
282 if meta.len() > MAX_SCAN_BYTES {
283 return;
284 }
285 let bytes = match fs::read(path) {
286 Ok(b) => b,
287 Err(_) => return,
288 };
289 if bytes.iter().take(8192).any(|&b| b == 0) {
290 return;
291 }
292 let text = String::from_utf8_lossy(&bytes);
293 let mut needle = needle_lower.to_string();
294 if !ignore_case {
295 needle = needle.to_string();
296 }
297
298 for (index, line) in text.lines().enumerate() {
299 if *count >= MAX_MATCHES {
300 return;
301 }
302 let hit = if ignore_case {
303 line.to_lowercase().contains(&needle)
304 } else {
305 line.contains(&needle)
306 };
307 if hit {
308 *count += 1;
309 out.push_str(&format!(
310 "{}:{}: {}\n",
311 path.display(),
312 index + 1,
313 clip(line.trim_end(), 200)
314 ));
315 }
316 }
317}
318
319fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
320 let entries = match fs::read_dir(dir) {
321 Ok(entries) => entries,
322 Err(_) => return,
323 };
324 for entry in entries.flatten() {
325 let file_type = match entry.file_type() {
326 Ok(t) => t,
327 Err(_) => continue,
328 };
329 let path = entry.path();
330 if file_type.is_dir() {
331 let name = entry.file_name();
332 if SKIP_DIRS.iter().any(|skip| name == *skip) {
333 continue;
334 }
335 walk(&path, out);
336 } else if file_type.is_file() {
337 out.push(path);
338 }
339 }
340}
341
342fn glob_match(pattern: &str, path: &str) -> bool {
343 let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
344 let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
345 match_segments(&p, &s)
346}
347
348fn match_segments(pattern: &[&str], path: &[&str]) -> bool {
349 match pattern.split_first() {
350 None => path.is_empty(),
351 Some((&"**", rest)) => {
352 if match_segments(rest, path) {
353 return true;
354 }
355 for skip in 0..path.len() {
356 if match_segments(rest, &path[skip + 1..]) {
357 return true;
358 }
359 }
360 false
361 }
362 Some((segment, rest)) => match path.split_first() {
363 None => false,
364 Some((name, tail)) => {
365 wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail)
366 }
367 },
368 }
369}
370
371fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool {
372 match pattern.split_first() {
373 None => text.is_empty(),
374 Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])),
375 Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]),
376 Some((byte, rest)) => match text.split_first() {
377 Some((first, tail)) => first == byte && wildcard_match(rest, tail),
378 None => false,
379 },
380 }
381}
382
383fn new_file_preview(path: &str, content: &str) -> String {
384 let lines: Vec<&str> = content.lines().collect();
385 let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len());
386 for line in lines.iter().take(PREVIEW_BUDGET) {
387 out.push_str(&format!("+ {}\n", clip(line, 200)));
388 }
389 if lines.len() > PREVIEW_BUDGET {
390 out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET));
391 }
392 out
393}
394
395fn diff_preview(old: &str, new: &str) -> String {
396 let a: Vec<&str> = old.lines().collect();
397 let b: Vec<&str> = new.lines().collect();
398
399 let mut prefix = 0;
400 while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {
401 prefix += 1;
402 }
403 let mut suffix = 0;
404 while suffix < a.len().saturating_sub(prefix)
405 && suffix < b.len().saturating_sub(prefix)
406 && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]
407 {
408 suffix += 1;
409 }
410
411 let start = prefix.saturating_sub(2);
412 let a_end = a.len() - suffix;
413 let b_end = b.len() - suffix;
414
415 let mut out = format!(
416 "@@ -{},{} +{},{} @@\n",
417 start + 1,
418 a_end.saturating_sub(start),
419 start + 1,
420 b_end.saturating_sub(start)
421 );
422 let mut budget = PREVIEW_BUDGET;
423
424 for line in &a[start..prefix] {
425 if budget == 0 {
426 break;
427 }
428 budget -= 1;
429 out.push_str(&format!(" {}\n", clip(line, 200)));
430 }
431 for line in &a[prefix..a_end] {
432 if budget == 0 {
433 break;
434 }
435 budget -= 1;
436 out.push_str(&format!("- {}\n", clip(line, 200)));
437 }
438 for line in &b[prefix..b_end] {
439 if budget == 0 {
440 break;
441 }
442 budget -= 1;
443 out.push_str(&format!("+ {}\n", clip(line, 200)));
444 }
445 for line in a[a_end..(a_end + 2).min(a.len())].iter() {
446 if budget == 0 {
447 break;
448 }
449 budget -= 1;
450 out.push_str(&format!(" {}\n", clip(line, 200)));
451 }
452 if budget == 0 {
453 out.push_str("… diff truncated\n");
454 }
455 out
456}
457
458fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String {
459 let lines: Vec<&str> = text.lines().collect();
460 let line_no = text[..at].matches('\n').count() + 1;
461 let old_lines = old.lines().count().max(1);
462
463 let mut out = format!("@@ {path}:{line_no} @@\n");
464 let mut budget = PREVIEW_BUDGET;
465
466 let before_start = (line_no - 1).saturating_sub(2);
467 for line in &lines[before_start..line_no.saturating_sub(1)] {
468 if budget == 0 {
469 break;
470 }
471 budget -= 1;
472 out.push_str(&format!(" {}\n", clip(line, 200)));
473 }
474 for line in old.lines() {
475 if budget == 0 {
476 break;
477 }
478 budget -= 1;
479 out.push_str(&format!("- {}\n", clip(line, 200)));
480 }
481 for line in new.lines() {
482 if budget == 0 {
483 break;
484 }
485 budget -= 1;
486 out.push_str(&format!("+ {}\n", clip(line, 200)));
487 }
488 let after_start = (line_no - 1 + old_lines).min(lines.len());
489 for line in &lines[after_start..(after_start + 2).min(lines.len())] {
490 if budget == 0 {
491 break;
492 }
493 budget -= 1;
494 out.push_str(&format!(" {}\n", clip(line, 200)));
495 }
496 if budget == 0 {
497 out.push_str("… diff truncated\n");
498 }
499 out
500}
501
502fn line_list(text: &str, offsets: &[usize]) -> String {
503 let mut numbers: Vec<String> = offsets
504 .iter()
505 .take(10)
506 .map(|&at| (text[..at].matches('\n').count() + 1).to_string())
507 .collect();
508 if offsets.len() > 10 {
509 numbers.push("…".into());
510 }
511 numbers.join(", ")
512}
513
514fn req(args: &Value, key: &str) -> Result<String, String> {
515 match args.get(key).and_then(|v| v.as_str()) {
516 Some(value) => Ok(value.to_string()),
517 None => Err(format!("missing required argument `{key}`")),
518 }
519}
520
521fn clip(s: &str, max: usize) -> String {
522 if s.chars().count() <= max {
523 return s.to_string();
524 }
525 let cut: String = s.chars().take(max).collect();
526 format!("{cut}…")
527}