diff options
Diffstat (limited to 'src/tools')
| -rw-r--r-- | src/tools/fs.rs | 527 | ||||
| -rw-r--r-- | src/tools/mod.rs | 148 | ||||
| -rw-r--r-- | src/tools/shell.rs | 129 |
3 files changed, 804 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 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::path::{Path, PathBuf}; | ||
| 3 | |||
| 4 | use serde_json::Value; | ||
| 5 | |||
| 6 | const MAX_LINE_CHARS: usize = 400; | ||
| 7 | const MAX_READ_LINES: usize = 2000; | ||
| 8 | const MAX_MATCHES: usize = 200; | ||
| 9 | const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; | ||
| 10 | const PREVIEW_BUDGET: usize = 60; | ||
| 11 | |||
| 12 | const 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. | ||
| 25 | pub enum Change { | ||
| 26 | Write { path: String, content: String }, | ||
| 27 | Edit { path: String, old: String, new: String, text: String }, | ||
| 28 | } | ||
| 29 | |||
| 30 | impl 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 | |||
| 93 | pub 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 | |||
| 100 | pub 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 | |||
| 128 | pub 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 | |||
| 177 | pub 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 | |||
| 224 | pub 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 | |||
| 277 | fn 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 | |||
| 319 | fn 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 | |||
| 342 | fn 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 | |||
| 348 | fn 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 | |||
| 371 | fn 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 | |||
| 383 | fn 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 | |||
| 395 | fn 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 | |||
| 458 | fn 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 | |||
| 502 | fn 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 | |||
| 514 | fn 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 | |||
| 521 | fn 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 | } | ||
diff --git a/src/tools/mod.rs b/src/tools/mod.rs new file mode 100644 index 0000000..503de08 --- /dev/null +++ b/src/tools/mod.rs | |||
| @@ -0,0 +1,148 @@ | |||
| 1 | pub mod fs; | ||
| 2 | pub mod shell; | ||
| 3 | |||
| 4 | use serde_json::{json, Value}; | ||
| 5 | |||
| 6 | use fs::Change; | ||
| 7 | |||
| 8 | /// When a tool needs a human before it runs. | ||
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 10 | pub enum Approval { | ||
| 11 | /// Read-only or harmless. | ||
| 12 | Never, | ||
| 13 | /// Prompts on first use per session, then remembers. | ||
| 14 | Once, | ||
| 15 | /// Prompts on every call, no memory. | ||
| 16 | EveryCall, | ||
| 17 | } | ||
| 18 | |||
| 19 | pub fn approval(name: &str) -> Approval { | ||
| 20 | match name { | ||
| 21 | "write" | "edit" => Approval::Once, | ||
| 22 | "bash" => Approval::EveryCall, | ||
| 23 | _ => Approval::Never, | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | /// Tools that execute immediately. | ||
| 28 | pub fn run(name: &str, args: &Value) -> Result<String, String> { | ||
| 29 | match name { | ||
| 30 | "read" => fs::read(args), | ||
| 31 | "grep" => fs::grep(args), | ||
| 32 | "glob" => fs::glob(args), | ||
| 33 | "bash" => shell::bash(args, std::time::Duration::from_secs(120)), | ||
| 34 | other => Err(unknown(other)), | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | /// Tools that produce a change needing approval before it is applied. | ||
| 39 | pub fn plan(name: &str, args: &Value) -> Result<Change, String> { | ||
| 40 | match name { | ||
| 41 | "write" => fs::plan_write(args), | ||
| 42 | "edit" => fs::plan_edit(args), | ||
| 43 | other => Err(unknown(other)), | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | fn unknown(name: &str) -> String { | ||
| 48 | format!("unknown tool `{name}`; available: read, write, edit, bash, grep, glob") | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Static and in a fixed order, so the serialised prefix never changes. | ||
| 52 | pub fn schemas() -> Vec<Value> { | ||
| 53 | vec![ | ||
| 54 | json!({ | ||
| 55 | "type": "function", | ||
| 56 | "function": { | ||
| 57 | "name": "read", | ||
| 58 | "description": "Read a text file. Returns numbered lines. Read before editing.", | ||
| 59 | "parameters": { | ||
| 60 | "type": "object", | ||
| 61 | "properties": { | ||
| 62 | "path": { "type": "string", "description": "file path" }, | ||
| 63 | "offset": { "type": "integer", "description": "first line, 1-based (default 1)" }, | ||
| 64 | "limit": { "type": "integer", "description": "maximum lines (default and cap 2000)" } | ||
| 65 | }, | ||
| 66 | "required": ["path"] | ||
| 67 | } | ||
| 68 | } | ||
| 69 | }), | ||
| 70 | json!({ | ||
| 71 | "type": "function", | ||
| 72 | "function": { | ||
| 73 | "name": "write", | ||
| 74 | "description": "Create or replace a whole file. The parent directory must already exist.", | ||
| 75 | "parameters": { | ||
| 76 | "type": "object", | ||
| 77 | "properties": { | ||
| 78 | "path": { "type": "string" }, | ||
| 79 | "content": { "type": "string" } | ||
| 80 | }, | ||
| 81 | "required": ["path", "content"] | ||
| 82 | } | ||
| 83 | } | ||
| 84 | }), | ||
| 85 | json!({ | ||
| 86 | "type": "function", | ||
| 87 | "function": { | ||
| 88 | "name": "edit", | ||
| 89 | "description": "Replace one exact occurrence of `old` with `new`. Fails if `old` is missing or appears more than once, so include enough context to be unique.", | ||
| 90 | "parameters": { | ||
| 91 | "type": "object", | ||
| 92 | "properties": { | ||
| 93 | "path": { "type": "string" }, | ||
| 94 | "old": { "type": "string", "description": "exact existing text, including indentation" }, | ||
| 95 | "new": { "type": "string", "description": "replacement text" } | ||
| 96 | }, | ||
| 97 | "required": ["path", "old", "new"] | ||
| 98 | } | ||
| 99 | } | ||
| 100 | }), | ||
| 101 | json!({ | ||
| 102 | "type": "function", | ||
| 103 | "function": { | ||
| 104 | "name": "bash", | ||
| 105 | "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. Times out after 120s. Returns combined output and the exit code.", | ||
| 106 | "parameters": { | ||
| 107 | "type": "object", | ||
| 108 | "properties": { | ||
| 109 | "cmd": { "type": "string" }, | ||
| 110 | "cwd": { "type": "string", "description": "working directory (default: project root)" } | ||
| 111 | }, | ||
| 112 | "required": ["cmd"] | ||
| 113 | } | ||
| 114 | } | ||
| 115 | }), | ||
| 116 | json!({ | ||
| 117 | "type": "function", | ||
| 118 | "function": { | ||
| 119 | "name": "grep", | ||
| 120 | "description": "Search file contents for a literal string, recursively. Skips .git, target, node_modules and similar.", | ||
| 121 | "parameters": { | ||
| 122 | "type": "object", | ||
| 123 | "properties": { | ||
| 124 | "pattern": { "type": "string" }, | ||
| 125 | "path": { "type": "string", "description": "file or directory (default .)" }, | ||
| 126 | "ignore_case": { "type": "boolean" } | ||
| 127 | }, | ||
| 128 | "required": ["pattern"] | ||
| 129 | } | ||
| 130 | } | ||
| 131 | }), | ||
| 132 | json!({ | ||
| 133 | "type": "function", | ||
| 134 | "function": { | ||
| 135 | "name": "glob", | ||
| 136 | "description": "List files matching a glob. Supports *, ? and ** across path segments, e.g. **/*.rs.", | ||
| 137 | "parameters": { | ||
| 138 | "type": "object", | ||
| 139 | "properties": { | ||
| 140 | "pattern": { "type": "string" }, | ||
| 141 | "path": { "type": "string", "description": "directory to search (default .)" } | ||
| 142 | }, | ||
| 143 | "required": ["pattern"] | ||
| 144 | } | ||
| 145 | } | ||
| 146 | }), | ||
| 147 | ] | ||
| 148 | } | ||
diff --git a/src/tools/shell.rs b/src/tools/shell.rs new file mode 100644 index 0000000..9c214fb --- /dev/null +++ b/src/tools/shell.rs | |||
| @@ -0,0 +1,129 @@ | |||
| 1 | use std::fs::File; | ||
| 2 | use std::io::{Read, Seek, SeekFrom}; | ||
| 3 | use std::path::PathBuf; | ||
| 4 | use std::process::{Command, Stdio}; | ||
| 5 | use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 6 | use std::time::{Duration, Instant}; | ||
| 7 | |||
| 8 | use serde_json::Value; | ||
| 9 | |||
| 10 | const HEAD_BYTES: usize = 64 * 1024; | ||
| 11 | const TAIL_BYTES: i64 = 16 * 1024; | ||
| 12 | static COUNTER: AtomicU64 = AtomicU64::new(0); | ||
| 13 | |||
| 14 | pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | ||
| 15 | let cmd = match args.get("cmd").and_then(|v| v.as_str()) { | ||
| 16 | Some(cmd) => cmd.to_string(), | ||
| 17 | None => return Err("missing required argument `cmd`".into()), | ||
| 18 | }; | ||
| 19 | |||
| 20 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; | ||
| 21 | if !cwd.is_dir() { | ||
| 22 | return Err(format!("cwd is not a directory: {}", cwd.display())); | ||
| 23 | } | ||
| 24 | |||
| 25 | let path = std::env::temp_dir().join(format!( | ||
| 26 | "agent686-{}-{}.out", | ||
| 27 | std::process::id(), | ||
| 28 | COUNTER.fetch_add(1, Ordering::Relaxed) | ||
| 29 | )); | ||
| 30 | let mut file = std::fs::OpenOptions::new() | ||
| 31 | .read(true) | ||
| 32 | .write(true) | ||
| 33 | .create(true) | ||
| 34 | .truncate(true) | ||
| 35 | .open(&path) | ||
| 36 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 37 | let stdout = file.try_clone().map_err(|e| e.to_string())?; | ||
| 38 | let stderr = file.try_clone().map_err(|e| e.to_string())?; | ||
| 39 | |||
| 40 | let mut child = Command::new("sh") | ||
| 41 | .arg("-c") | ||
| 42 | .arg(&cmd) | ||
| 43 | .current_dir(&cwd) | ||
| 44 | .stdin(Stdio::null()) | ||
| 45 | .stdout(Stdio::from(stdout)) | ||
| 46 | .stderr(Stdio::from(stderr)) | ||
| 47 | .spawn() | ||
| 48 | .map_err(|e| format!("failed to start sh: {e}"))?; | ||
| 49 | |||
| 50 | let deadline = Instant::now() + timeout; | ||
| 51 | let mut timed_out = false; | ||
| 52 | let status = loop { | ||
| 53 | match child.try_wait().map_err(|e| e.to_string())? { | ||
| 54 | Some(status) => break status, | ||
| 55 | None => { | ||
| 56 | if Instant::now() >= deadline { | ||
| 57 | let _ = child.kill(); | ||
| 58 | timed_out = true; | ||
| 59 | break child.wait().map_err(|e| e.to_string())?; | ||
| 60 | } | ||
| 61 | std::thread::sleep(Duration::from_millis(20)); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | }; | ||
| 65 | |||
| 66 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; | ||
| 67 | drop(file); | ||
| 68 | let _ = std::fs::remove_file(&path); | ||
| 69 | |||
| 70 | let mut out = output; | ||
| 71 | if !out.is_empty() && !out.ends_with('\n') { | ||
| 72 | out.push('\n'); | ||
| 73 | } | ||
| 74 | if timed_out { | ||
| 75 | out.push_str(&format!( | ||
| 76 | "[timed out after {:.1}s; process killed]", | ||
| 77 | timeout.as_secs_f64() | ||
| 78 | )); | ||
| 79 | } else { | ||
| 80 | match status.code() { | ||
| 81 | Some(code) => out.push_str(&format!("[exit {code}]")), | ||
| 82 | None => { | ||
| 83 | use std::os::unix::process::ExitStatusExt; | ||
| 84 | out.push_str(&format!( | ||
| 85 | "[killed by signal {}]", | ||
| 86 | status.signal().unwrap_or_default() | ||
| 87 | )); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | Ok(out) | ||
| 92 | } | ||
| 93 | |||
| 94 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | ||
| 95 | let current = std::env::current_dir().map_err(|e| e.to_string())?; | ||
| 96 | Ok(match cwd { | ||
| 97 | Some(dir) => { | ||
| 98 | let path = PathBuf::from(dir); | ||
| 99 | if path.is_absolute() { | ||
| 100 | path | ||
| 101 | } else { | ||
| 102 | current.join(path) | ||
| 103 | } | ||
| 104 | } | ||
| 105 | None => current, | ||
| 106 | }) | ||
| 107 | } | ||
| 108 | |||
| 109 | fn read_capped(file: &mut File) -> Result<String, String> { | ||
| 110 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); | ||
| 111 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; | ||
| 112 | |||
| 113 | let mut out = Vec::new(); | ||
| 114 | if len <= HEAD_BYTES as u64 { | ||
| 115 | file.read_to_end(&mut out).map_err(|e| e.to_string())?; | ||
| 116 | } else { | ||
| 117 | file.take(HEAD_BYTES as u64) | ||
| 118 | .read_to_end(&mut out) | ||
| 119 | .map_err(|e| e.to_string())?; | ||
| 120 | let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); | ||
| 121 | out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); | ||
| 122 | file.seek(SeekFrom::End(-TAIL_BYTES)) | ||
| 123 | .map_err(|e| e.to_string())?; | ||
| 124 | let mut tail = Vec::new(); | ||
| 125 | file.read_to_end(&mut tail).map_err(|e| e.to_string())?; | ||
| 126 | out.extend_from_slice(&tail); | ||
| 127 | } | ||
| 128 | Ok(String::from_utf8_lossy(&out).into_owned()) | ||
| 129 | } | ||
