claude/tool-permission-system
claude/code-feature-parity-q003hm
claude/elegant-carson-l1menh
claude/sigit-acp-local-chat-cx6380
claude/sigit-cloud-agent-expansion-reox0a
claude/tool-permission-system
claude/zen-feynman-0u78dk
development
feature/agent-tools-multiedit-glob-todos-remember
feature/background-commands
feature/commit-coauthor-attribution
feature/headless-mode
feature/init-command
feature/load-local-model-explicitly
feature/session-persistence-compaction
feature/sigit-code-cloud
feature/subagent-tool
feature/tool-permission-system
feature/tui-repo-tabs
feature/tui-tabs
main
release/v1.3.1
| 1 | //! Agent tools: schema definitions + execution for siGit Code. |
| 2 | |
| 3 | use regex::Regex; |
| 4 | use serde_json::{Value, json}; |
| 5 | use std::fs; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::process::Command; |
| 8 | |
| 9 | const WEBSITE_READ_CHAR_LIMIT: usize = 20_000; |
| 10 | const WEBSITE_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); |
| 11 | const WEBSITE_USER_AGENT: &str = |
| 12 | "siGit/0.1 (+https://github.com/getsigit/sigit; website-reading tool)"; |
| 13 | |
| 14 | const READ_FILE_CHAR_LIMIT: usize = 10_000; |
| 15 | const SEARCH_FILES_MATCH_LIMIT: usize = 50; |
| 16 | /// Upper bound on `max_results` for `search_files` and the number of paths |
| 17 | /// returned by `glob`, so a broad pattern can't flood the context window. |
| 18 | const SEARCH_RESULTS_HARD_CAP: usize = 1_000; |
| 19 | |
| 20 | // ── Tool schemas ───────────────────────────────────────────────────────────── |
| 21 | |
| 22 | pub struct AgentTool { |
| 23 | pub name: &'static str, |
| 24 | pub description: &'static str, |
| 25 | pub parameters_schema: Value, |
| 26 | } |
| 27 | |
| 28 | pub fn all_tools() -> Vec<AgentTool> { |
| 29 | vec![ |
| 30 | AgentTool { |
| 31 | name: "read_file", |
| 32 | description: "Read the contents of a file at the given path. \ |
| 33 | Prefer an absolute path when possible. Use start_line and \ |
| 34 | end_line to read a specific range instead of the whole file — \ |
| 35 | strongly prefer this when you already know which lines matter. \ |
| 36 | Output is truncated to 10 000 characters.", |
| 37 | parameters_schema: json!({ |
| 38 | "type": "object", |
| 39 | "properties": { |
| 40 | "path": { |
| 41 | "type": "string", |
| 42 | "description": "Absolute or relative path to the file to read." |
| 43 | }, |
| 44 | "start_line": { |
| 45 | "type": "integer", |
| 46 | "description": "First line to read (1-based, inclusive). Omit to start from the beginning." |
| 47 | }, |
| 48 | "end_line": { |
| 49 | "type": "integer", |
| 50 | "description": "Last line to read (1-based, inclusive). Omit to read to the end." |
| 51 | } |
| 52 | }, |
| 53 | "required": ["path"], |
| 54 | "additionalProperties": false |
| 55 | }), |
| 56 | }, |
| 57 | AgentTool { |
| 58 | name: "create_directory", |
| 59 | description: "Create a directory at the given path. \ |
| 60 | Prefer an absolute path when possible. Missing parent \ |
| 61 | directories are created automatically. Use this before \ |
| 62 | create_file when the parent path does not exist. Succeeds \ |
| 63 | if the directory already exists.", |
| 64 | parameters_schema: json!({ |
| 65 | "type": "object", |
| 66 | "properties": { |
| 67 | "path": { |
| 68 | "type": "string", |
| 69 | "description": "Absolute or relative path to the directory to create." |
| 70 | } |
| 71 | }, |
| 72 | "required": ["path"], |
| 73 | "additionalProperties": false |
| 74 | }), |
| 75 | }, |
| 76 | AgentTool { |
| 77 | name: "list_directory", |
| 78 | description: "List files and directories at the given path. \ |
| 79 | Prefer an absolute path when possible. Each entry is \ |
| 80 | prefixed with [DIR] or [FILE]. Directories are listed \ |
| 81 | first, sorted alphabetically.", |
| 82 | parameters_schema: json!({ |
| 83 | "type": "object", |
| 84 | "properties": { |
| 85 | "path": { |
| 86 | "type": "string", |
| 87 | "description": "Absolute or relative path to the directory to list." |
| 88 | } |
| 89 | }, |
| 90 | "required": ["path"], |
| 91 | "additionalProperties": false |
| 92 | }), |
| 93 | }, |
| 94 | AgentTool { |
| 95 | name: "search_files", |
| 96 | description: "Search for a regex pattern across files in a directory tree. \ |
| 97 | Prefer an absolute root path when possible. Returns matching \ |
| 98 | lines in `file:line_number: content` format. Skips binary \ |
| 99 | files and hidden directories. Pass `file_glob` to restrict the \ |
| 100 | search to files whose name matches a glob (e.g. \"*.rs\"), and \ |
| 101 | `max_results` to raise or lower the default cap of 50 matches.", |
| 102 | parameters_schema: json!({ |
| 103 | "type": "object", |
| 104 | "properties": { |
| 105 | "pattern": { |
| 106 | "type": "string", |
| 107 | "description": "Regular expression pattern to search for." |
| 108 | }, |
| 109 | "path": { |
| 110 | "type": "string", |
| 111 | "description": "Root directory to search in. Defaults to \".\" (current directory)." |
| 112 | }, |
| 113 | "file_glob": { |
| 114 | "type": "string", |
| 115 | "description": "Optional glob on the file name (not the full path), e.g. \"*.rs\" or \"*.{ts,tsx}\". Only matching files are searched." |
| 116 | }, |
| 117 | "max_results": { |
| 118 | "type": "integer", |
| 119 | "description": "Maximum number of matching lines to return (default 50, capped at 1000)." |
| 120 | } |
| 121 | }, |
| 122 | "required": ["pattern"], |
| 123 | "additionalProperties": false |
| 124 | }), |
| 125 | }, |
| 126 | AgentTool { |
| 127 | name: "read_website", |
| 128 | description: "Fetch a web page and return readable text content. \ |
| 129 | Use this when the user gives you a URL and asks you to read, \ |
| 130 | summarize, inspect, or extract information from the page. \ |
| 131 | Supports normal http and https URLs. Output is truncated if the \ |
| 132 | page is very large.", |
| 133 | parameters_schema: json!({ |
| 134 | "type": "object", |
| 135 | "properties": { |
| 136 | "url": { |
| 137 | "type": "string", |
| 138 | "description": "Absolute http or https URL to fetch." |
| 139 | } |
| 140 | }, |
| 141 | "required": ["url"], |
| 142 | "additionalProperties": false |
| 143 | }), |
| 144 | }, |
| 145 | AgentTool { |
| 146 | name: "create_file", |
| 147 | description: "Create a new file at the given path with the provided content. \ |
| 148 | Prefer an absolute path when possible. Parent directories are \ |
| 149 | created automatically if they do not exist. Fails if the file \ |
| 150 | already exists — use edit_file to modify existing files.", |
| 151 | parameters_schema: json!({ |
| 152 | "type": "object", |
| 153 | "properties": { |
| 154 | "path": { |
| 155 | "type": "string", |
| 156 | "description": "Absolute or relative path for the new file." |
| 157 | }, |
| 158 | "content": { |
| 159 | "type": "string", |
| 160 | "description": "The full text content to write into the new file." |
| 161 | } |
| 162 | }, |
| 163 | "required": ["path", "content"], |
| 164 | "additionalProperties": false |
| 165 | }), |
| 166 | }, |
| 167 | AgentTool { |
| 168 | name: "edit_file", |
| 169 | description: "Edit an existing file by replacing an exact substring (old_text) with \ |
| 170 | new text (new_text). Prefer an absolute path when possible. By \ |
| 171 | default old_text must appear exactly once; set replace_all to true \ |
| 172 | to replace every occurrence (useful for renaming a symbol). Use \ |
| 173 | read_file first to see the current content and identify the exact \ |
| 174 | text to replace. To append to a file, match the last few lines as \ |
| 175 | old_text and include them plus the new content as new_text.", |
| 176 | parameters_schema: json!({ |
| 177 | "type": "object", |
| 178 | "properties": { |
| 179 | "path": { |
| 180 | "type": "string", |
| 181 | "description": "Path to the existing file to edit." |
| 182 | }, |
| 183 | "old_text": { |
| 184 | "type": "string", |
| 185 | "description": "The exact text span to find and replace. Must match exactly once unless replace_all is true." |
| 186 | }, |
| 187 | "new_text": { |
| 188 | "type": "string", |
| 189 | "description": "The replacement text that will take the place of old_text." |
| 190 | }, |
| 191 | "replace_all": { |
| 192 | "type": "boolean", |
| 193 | "description": "Replace every occurrence of old_text instead of requiring a unique match. Defaults to false." |
| 194 | } |
| 195 | }, |
| 196 | "required": ["path", "old_text", "new_text"], |
| 197 | "additionalProperties": false |
| 198 | }), |
| 199 | }, |
| 200 | AgentTool { |
| 201 | name: "delete_file", |
| 202 | description: "Delete a file or empty directory at the given path. \ |
| 203 | Prefer an absolute path when possible. Refuses to delete \ |
| 204 | non-empty directories to prevent accidental data loss. \ |
| 205 | Use read_file or list_directory first to confirm the target.", |
| 206 | parameters_schema: json!({ |
| 207 | "type": "object", |
| 208 | "properties": { |
| 209 | "path": { |
| 210 | "type": "string", |
| 211 | "description": "Absolute or relative path to the file or empty directory to delete." |
| 212 | } |
| 213 | }, |
| 214 | "required": ["path"], |
| 215 | "additionalProperties": false |
| 216 | }), |
| 217 | }, |
| 218 | AgentTool { |
| 219 | name: "run_command", |
| 220 | description: "Run a shell command and return its combined stdout and stderr output. \ |
| 221 | The command runs in the given working directory (defaults to the \ |
| 222 | user's home directory). Always use an absolute working directory \ |
| 223 | path. Use this for build tools (cargo, npm, make), package managers, \ |
| 224 | linters, test runners, and git commands, including git init, \ |
| 225 | porcelain commands like status/add/commit/checkout, and plumbing \ |
| 226 | commands like rev-parse, hash-object, update-ref, and cat-file. \ |
| 227 | For `git clone`, always specify the full absolute destination path \ |
| 228 | as the last argument (e.g. `git clone <url> /absolute/path/to/dir`) \ |
| 229 | and set cwd to the parent directory. Never run `git clone` without \ |
| 230 | an explicit destination. If the user asks for a new repo or scaffold, \ |
| 231 | use this for `git clone`, `git init`, and normal repo setup steps. \ |
| 232 | In smbCloud repos, prefer existing workspace commands, Rails \ |
| 233 | conventions, and deploy flows over inventing new command sequences. \ |
| 234 | Commands that run indefinitely (servers, watchers) will be killed \ |
| 235 | after 120 seconds.", |
| 236 | parameters_schema: json!({ |
| 237 | "type": "object", |
| 238 | "properties": { |
| 239 | "command": { |
| 240 | "type": "string", |
| 241 | "description": "The shell command to execute (e.g. \"cargo update\", \"git status\", \"git rev-parse HEAD\")." |
| 242 | }, |
| 243 | "cwd": { |
| 244 | "type": "string", |
| 245 | "description": "Working directory for the command. Defaults to \".\" (current directory)." |
| 246 | } |
| 247 | }, |
| 248 | "required": ["command"], |
| 249 | "additionalProperties": false |
| 250 | }), |
| 251 | }, |
| 252 | AgentTool { |
| 253 | name: "multi_edit", |
| 254 | description: "Apply several exact-substring edits to a single file in one call. \ |
| 255 | Edits are applied in order, each to the result of the previous one, \ |
| 256 | and the whole batch is atomic — if any edit fails to match, the file \ |
| 257 | is left untouched and an error explains which edit failed. Prefer \ |
| 258 | this over multiple edit_file calls when changing several spots in the \ |
| 259 | same file. Each edit has old_text (must match exactly once, or every \ |
| 260 | time when replace_all is true) and new_text.", |
| 261 | parameters_schema: json!({ |
| 262 | "type": "object", |
| 263 | "properties": { |
| 264 | "path": { |
| 265 | "type": "string", |
| 266 | "description": "Path to the existing file to edit." |
| 267 | }, |
| 268 | "edits": { |
| 269 | "type": "array", |
| 270 | "description": "Ordered list of edits to apply to the file.", |
| 271 | "items": { |
| 272 | "type": "object", |
| 273 | "properties": { |
| 274 | "old_text": { |
| 275 | "type": "string", |
| 276 | "description": "The exact text span to find and replace." |
| 277 | }, |
| 278 | "new_text": { |
| 279 | "type": "string", |
| 280 | "description": "The replacement text." |
| 281 | }, |
| 282 | "replace_all": { |
| 283 | "type": "boolean", |
| 284 | "description": "Replace every occurrence instead of requiring a unique match. Defaults to false." |
| 285 | } |
| 286 | }, |
| 287 | "required": ["old_text", "new_text"], |
| 288 | "additionalProperties": false |
| 289 | } |
| 290 | } |
| 291 | }, |
| 292 | "required": ["path", "edits"], |
| 293 | "additionalProperties": false |
| 294 | }), |
| 295 | }, |
| 296 | AgentTool { |
| 297 | name: "glob", |
| 298 | description: "Find files by name using a glob pattern (e.g. \"**/*.rs\", \ |
| 299 | \"src/**/*.{ts,tsx}\", \"Cargo.toml\"). Returns matching file paths, \ |
| 300 | most-recently-modified first. Supports `*` (any run of non-separator \ |
| 301 | characters), `**` (any number of directories), `?` (one character), \ |
| 302 | and `{a,b}` alternation. Use this to locate files by name; use \ |
| 303 | search_files to search file contents.", |
| 304 | parameters_schema: json!({ |
| 305 | "type": "object", |
| 306 | "properties": { |
| 307 | "pattern": { |
| 308 | "type": "string", |
| 309 | "description": "Glob pattern matched against paths relative to the search root." |
| 310 | }, |
| 311 | "path": { |
| 312 | "type": "string", |
| 313 | "description": "Root directory to search in. Defaults to \".\" (current directory)." |
| 314 | } |
| 315 | }, |
| 316 | "required": ["pattern"], |
| 317 | "additionalProperties": false |
| 318 | }), |
| 319 | }, |
| 320 | AgentTool { |
| 321 | name: "write_todos", |
| 322 | description: "Record or update a checklist of the steps for the current task. \ |
| 323 | Use this for any multi-step task to plan the work and show progress: \ |
| 324 | call it once up front with all the steps as `pending`, then call it \ |
| 325 | again whenever a step's status changes. Mark exactly one step \ |
| 326 | `in_progress` at a time and `completed` as soon as it is done. \ |
| 327 | Keep the list short and outcome-focused.", |
| 328 | parameters_schema: json!({ |
| 329 | "type": "object", |
| 330 | "properties": { |
| 331 | "todos": { |
| 332 | "type": "array", |
| 333 | "description": "The full, current checklist (replaces any previous list).", |
| 334 | "items": { |
| 335 | "type": "object", |
| 336 | "properties": { |
| 337 | "content": { |
| 338 | "type": "string", |
| 339 | "description": "Short imperative description of the step." |
| 340 | }, |
| 341 | "status": { |
| 342 | "type": "string", |
| 343 | "enum": ["pending", "in_progress", "completed"], |
| 344 | "description": "Current status of the step." |
| 345 | } |
| 346 | }, |
| 347 | "required": ["content", "status"], |
| 348 | "additionalProperties": false |
| 349 | } |
| 350 | } |
| 351 | }, |
| 352 | "required": ["todos"], |
| 353 | "additionalProperties": false |
| 354 | }), |
| 355 | }, |
| 356 | AgentTool { |
| 357 | name: "remember", |
| 358 | description: "Persist a durable note, preference, or convention by appending it to \ |
| 359 | this project's instruction file (AGENTS.md / CLAUDE.md). Use this \ |
| 360 | when the user asks you to remember something for next time, or states \ |
| 361 | a lasting preference about how to work in this project. The note is \ |
| 362 | written to the nearest existing instruction file, or a new CLAUDE.md \ |
| 363 | at the repository root if none exists yet.", |
| 364 | parameters_schema: json!({ |
| 365 | "type": "object", |
| 366 | "properties": { |
| 367 | "note": { |
| 368 | "type": "string", |
| 369 | "description": "The fact or preference to remember, phrased as a standalone instruction." |
| 370 | } |
| 371 | }, |
| 372 | "required": ["note"], |
| 373 | "additionalProperties": false |
| 374 | }), |
| 375 | }, |
| 376 | ] |
| 377 | } |
| 378 | |
| 379 | // ── Tool execution ─────────────────────────────────────────────────────────── |
| 380 | |
| 381 | pub async fn execute_tool(name: &str, arguments: &str) -> String { |
| 382 | match name { |
| 383 | "read_file" => exec_read_file(arguments), |
| 384 | "list_directory" => exec_list_directory(arguments), |
| 385 | "search_files" => exec_search_files(arguments), |
| 386 | "read_website" => { |
| 387 | // reqwest::blocking panics inside a tokio runtime, so run on the blocking pool. |
| 388 | let args = arguments.to_owned(); |
| 389 | tokio::task::spawn_blocking(move || exec_read_website(&args)) |
| 390 | .await |
| 391 | .unwrap_or_else(|err| format!("Error: read_website task failed: {err}")) |
| 392 | } |
| 393 | "create_directory" => exec_create_directory(arguments), |
| 394 | "create_file" => exec_create_file(arguments), |
| 395 | "edit_file" => exec_edit_file(arguments), |
| 396 | "multi_edit" => exec_multi_edit(arguments), |
| 397 | "glob" => exec_glob(arguments), |
| 398 | "write_todos" => exec_write_todos(arguments), |
| 399 | "remember" => exec_remember(arguments), |
| 400 | "delete_file" => exec_delete_file(arguments), |
| 401 | "run_command" => exec_run_command(arguments), |
| 402 | "skill" => crate::skills::activate_skill(arguments), |
| 403 | // Tools discovered from MCP servers are namespaced `mcp__<server>__<tool>` |
| 404 | // and forwarded to the owning server. |
| 405 | _ if crate::mcp::is_mcp_tool(name) => crate::mcp::call_tool(name, arguments).await, |
| 406 | _ => format!("Unknown tool: {name}"), |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | fn absolute_path(path: &Path) -> PathBuf { |
| 411 | if path.is_absolute() { |
| 412 | path.to_path_buf() |
| 413 | } else { |
| 414 | std::env::current_dir() |
| 415 | .unwrap_or_else(|_| PathBuf::from(".")) |
| 416 | .join(path) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | fn absolute_path_string(path: &Path) -> String { |
| 421 | absolute_path(path).display().to_string() |
| 422 | } |
| 423 | |
| 424 | // ── read_file ──────────────────────────────────────────────────────────────── |
| 425 | |
| 426 | fn exec_read_file(arguments: &str) -> String { |
| 427 | let args: Value = match serde_json::from_str(arguments) { |
| 428 | Ok(v) => v, |
| 429 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 430 | }; |
| 431 | |
| 432 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 433 | Some(p) => p, |
| 434 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 435 | }; |
| 436 | |
| 437 | let start_line = args |
| 438 | .get("start_line") |
| 439 | .and_then(Value::as_u64) |
| 440 | .map(|n| n as usize); |
| 441 | let end_line = args |
| 442 | .get("end_line") |
| 443 | .and_then(Value::as_u64) |
| 444 | .map(|n| n as usize); |
| 445 | |
| 446 | let path = Path::new(path_str); |
| 447 | let absolute_path = absolute_path(path); |
| 448 | let absolute_path_str = absolute_path.display().to_string(); |
| 449 | |
| 450 | if !absolute_path.exists() { |
| 451 | return format!("Error: path does not exist: {absolute_path_str}"); |
| 452 | } |
| 453 | |
| 454 | if !absolute_path.is_file() { |
| 455 | return format!("Error: path is not a file: {absolute_path_str}"); |
| 456 | } |
| 457 | |
| 458 | match fs::read_to_string(&absolute_path) { |
| 459 | Ok(contents) => { |
| 460 | if start_line.is_some() || end_line.is_some() { |
| 461 | let lines: Vec<&str> = contents.lines().collect(); |
| 462 | let total = lines.len(); |
| 463 | let start = start_line.unwrap_or(1).max(1); |
| 464 | let end = end_line.unwrap_or(total).min(total); |
| 465 | |
| 466 | if start > total { |
| 467 | return format!( |
| 468 | "Error: start_line {start} is beyond end of file ({total} lines)" |
| 469 | ); |
| 470 | } |
| 471 | |
| 472 | let selected: Vec<&str> = lines[(start - 1)..end].to_vec(); |
| 473 | let range_text = selected.join("\n"); |
| 474 | format!("Lines {start}-{end} of {total} in {absolute_path_str}:\n{range_text}") |
| 475 | } else if contents.len() > READ_FILE_CHAR_LIMIT { |
| 476 | let truncated: String = contents.chars().take(READ_FILE_CHAR_LIMIT).collect(); |
| 477 | format!( |
| 478 | "{truncated}\n\n--- truncated (showing {READ_FILE_CHAR_LIMIT} of {} characters) ---", |
| 479 | contents.len() |
| 480 | ) |
| 481 | } else { |
| 482 | contents |
| 483 | } |
| 484 | } |
| 485 | Err(err) => format!("Error: could not read file: {err}"), |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | // ── list_directory ─────────────────────────────────────────────────────────── |
| 490 | |
| 491 | fn exec_list_directory(arguments: &str) -> String { |
| 492 | let args: Value = match serde_json::from_str(arguments) { |
| 493 | Ok(v) => v, |
| 494 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 495 | }; |
| 496 | |
| 497 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 498 | Some(p) => p, |
| 499 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 500 | }; |
| 501 | |
| 502 | let path = Path::new(path_str); |
| 503 | let absolute_path = absolute_path(path); |
| 504 | let absolute_path_str = absolute_path.display().to_string(); |
| 505 | |
| 506 | if !absolute_path.exists() { |
| 507 | return format!("Error: path does not exist: {absolute_path_str}"); |
| 508 | } |
| 509 | |
| 510 | if !absolute_path.is_dir() { |
| 511 | return format!("Error: path is not a directory: {absolute_path_str}"); |
| 512 | } |
| 513 | |
| 514 | let entries = match fs::read_dir(&absolute_path) { |
| 515 | Ok(rd) => rd, |
| 516 | Err(err) => return format!("Error: could not read directory: {err}"), |
| 517 | }; |
| 518 | |
| 519 | let mut dirs: Vec<String> = Vec::new(); |
| 520 | let mut files: Vec<String> = Vec::new(); |
| 521 | |
| 522 | for entry in entries { |
| 523 | let entry = match entry { |
| 524 | Ok(e) => e, |
| 525 | Err(err) => { |
| 526 | files.push(format!("[ERR] {err}")); |
| 527 | continue; |
| 528 | } |
| 529 | }; |
| 530 | |
| 531 | let name = entry.file_name().to_string_lossy().to_string(); |
| 532 | |
| 533 | let is_dir = match entry.file_type() { |
| 534 | Ok(ft) => ft.is_dir(), |
| 535 | Err(_) => false, |
| 536 | }; |
| 537 | |
| 538 | if is_dir { |
| 539 | dirs.push(format!("[DIR] {name}")); |
| 540 | } else { |
| 541 | files.push(format!("[FILE] {name}")); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | dirs.sort(); |
| 546 | files.sort(); |
| 547 | |
| 548 | dirs.extend(files); |
| 549 | |
| 550 | if dirs.is_empty() { |
| 551 | return format!("(empty directory: {absolute_path_str})"); |
| 552 | } |
| 553 | |
| 554 | dirs.join("\n") |
| 555 | } |
| 556 | |
| 557 | // ── search_files ───────────────────────────────────────────────────────────── |
| 558 | |
| 559 | fn exec_search_files(arguments: &str) -> String { |
| 560 | let args: Value = match serde_json::from_str(arguments) { |
| 561 | Ok(v) => v, |
| 562 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 563 | }; |
| 564 | |
| 565 | let pattern_str = match args.get("pattern").and_then(Value::as_str) { |
| 566 | Some(p) => p, |
| 567 | None => return "Error: missing required parameter \"pattern\"".to_string(), |
| 568 | }; |
| 569 | |
| 570 | let root_str = args.get("path").and_then(Value::as_str).unwrap_or("."); |
| 571 | |
| 572 | let re = match Regex::new(pattern_str) { |
| 573 | Ok(r) => r, |
| 574 | Err(err) => return format!("Error: invalid regex pattern: {err}"), |
| 575 | }; |
| 576 | |
| 577 | // Optional file-name filter compiled from a glob (e.g. "*.rs"). |
| 578 | let name_filter = match args.get("file_glob").and_then(Value::as_str) { |
| 579 | Some(glob) => match Regex::new(&glob_to_regex(glob)) { |
| 580 | Ok(r) => Some(r), |
| 581 | Err(err) => return format!("Error: invalid file_glob: {err}"), |
| 582 | }, |
| 583 | None => None, |
| 584 | }; |
| 585 | |
| 586 | let limit = args |
| 587 | .get("max_results") |
| 588 | .and_then(Value::as_u64) |
| 589 | .map(|n| (n as usize).clamp(1, SEARCH_RESULTS_HARD_CAP)) |
| 590 | .unwrap_or(SEARCH_FILES_MATCH_LIMIT); |
| 591 | |
| 592 | let root = Path::new(root_str); |
| 593 | let absolute_root = absolute_path(root); |
| 594 | let absolute_root_str = absolute_root.display().to_string(); |
| 595 | |
| 596 | if !absolute_root.exists() { |
| 597 | return format!("Error: path does not exist: {absolute_root_str}"); |
| 598 | } |
| 599 | |
| 600 | if !absolute_root.is_dir() { |
| 601 | return format!("Error: path is not a directory: {absolute_root_str}"); |
| 602 | } |
| 603 | |
| 604 | let mut matches: Vec<String> = Vec::new(); |
| 605 | walk_and_search( |
| 606 | &absolute_root, |
| 607 | &re, |
| 608 | name_filter.as_ref(), |
| 609 | limit, |
| 610 | &mut matches, |
| 611 | ); |
| 612 | |
| 613 | if matches.is_empty() { |
| 614 | return format!("No matches found for pattern: {pattern_str}"); |
| 615 | } |
| 616 | |
| 617 | let total = matches.len(); |
| 618 | if total > limit { |
| 619 | matches.truncate(limit); |
| 620 | matches.push(format!( |
| 621 | "\n--- truncated (showing {limit} of {total}+ matches; raise max_results to see more) ---" |
| 622 | )); |
| 623 | } |
| 624 | |
| 625 | matches.join("\n") |
| 626 | } |
| 627 | |
| 628 | /// Collects up to `limit + 1` matches (the extra signals truncation) so a broad |
| 629 | /// pattern can't walk an entire tree once enough hits are found. |
| 630 | fn walk_and_search( |
| 631 | dir: &Path, |
| 632 | re: &Regex, |
| 633 | name_filter: Option<&Regex>, |
| 634 | limit: usize, |
| 635 | matches: &mut Vec<String>, |
| 636 | ) { |
| 637 | let entries = match fs::read_dir(dir) { |
| 638 | Ok(rd) => rd, |
| 639 | Err(_) => return, |
| 640 | }; |
| 641 | |
| 642 | let mut sorted: Vec<fs::DirEntry> = entries.filter_map(Result::ok).collect(); |
| 643 | sorted.sort_by_key(|e| e.file_name()); |
| 644 | |
| 645 | for entry in sorted { |
| 646 | if matches.len() > limit { |
| 647 | return; |
| 648 | } |
| 649 | |
| 650 | let path = entry.path(); |
| 651 | let name = entry.file_name(); |
| 652 | let name_str = name.to_string_lossy(); |
| 653 | |
| 654 | if name_str.starts_with('.') { |
| 655 | continue; |
| 656 | } |
| 657 | |
| 658 | if path.is_dir() { |
| 659 | walk_and_search(&path, re, name_filter, limit, matches); |
| 660 | } else if path.is_file() { |
| 661 | if let Some(filter) = name_filter |
| 662 | && !filter.is_match(&name_str) |
| 663 | { |
| 664 | continue; |
| 665 | } |
| 666 | search_file(&path, re, matches); |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | /// skips non-UTF-8 files (probably binary). |
| 672 | fn search_file(path: &Path, re: &Regex, matches: &mut Vec<String>) { |
| 673 | let contents = match fs::read_to_string(path) { |
| 674 | Ok(c) => c, |
| 675 | Err(_) => return, |
| 676 | }; |
| 677 | |
| 678 | let display_path = absolute_path_string(path); |
| 679 | |
| 680 | for (line_idx, line) in contents.lines().enumerate() { |
| 681 | if re.is_match(line) { |
| 682 | let line_number = line_idx + 1; |
| 683 | matches.push(format!("{display_path}:{line_number}: {line}")); |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | // ── read_website ───────────────────────────────────────────────────────────── |
| 689 | |
| 690 | fn exec_read_website(arguments: &str) -> String { |
| 691 | let args: Value = match serde_json::from_str(arguments) { |
| 692 | Ok(v) => v, |
| 693 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 694 | }; |
| 695 | |
| 696 | let url = match args.get("url").and_then(Value::as_str) { |
| 697 | Some(u) => u, |
| 698 | None => return "Error: missing required parameter \"url\"".to_string(), |
| 699 | }; |
| 700 | |
| 701 | if !(url.starts_with("http://") || url.starts_with("https://")) { |
| 702 | return format!("Error: url must start with http:// or https://: {url}"); |
| 703 | } |
| 704 | |
| 705 | let client = match reqwest::blocking::Client::builder() |
| 706 | .timeout(WEBSITE_READ_TIMEOUT) |
| 707 | .user_agent(WEBSITE_USER_AGENT) |
| 708 | .build() |
| 709 | { |
| 710 | Ok(client) => client, |
| 711 | Err(err) => return format!("Error: failed to build website client: {err}"), |
| 712 | }; |
| 713 | |
| 714 | let response = match client.get(url).send() { |
| 715 | Ok(r) => r, |
| 716 | Err(err) => return format!("Error: failed to fetch website: {err}"), |
| 717 | }; |
| 718 | |
| 719 | let final_url = response.url().to_string(); |
| 720 | let status = response.status(); |
| 721 | if !status.is_success() { |
| 722 | return format!("Error: website returned HTTP {status} for {final_url}"); |
| 723 | } |
| 724 | |
| 725 | let body = match response.text() { |
| 726 | Ok(text) => text, |
| 727 | Err(err) => return format!("Error: failed to read website body: {err}"), |
| 728 | }; |
| 729 | |
| 730 | let title = Regex::new(r"(?is)<title[^>]*>(.*?)</title>") |
| 731 | .unwrap() |
| 732 | .captures(&body) |
| 733 | .and_then(|captures| captures.get(1)) |
| 734 | .map(|m| { |
| 735 | Regex::new(r"\s+") |
| 736 | .unwrap() |
| 737 | .replace_all(m.as_str(), " ") |
| 738 | .trim() |
| 739 | .to_string() |
| 740 | }) |
| 741 | .filter(|title| !title.is_empty()); |
| 742 | |
| 743 | let with_block_breaks = Regex::new( |
| 744 | r"(?is)</?(?:p|div|section|article|main|aside|header|footer|nav|li|ul|ol|h1|h2|h3|h4|h5|h6|br|tr|td|th)[^>]*>", |
| 745 | ) |
| 746 | .unwrap() |
| 747 | .replace_all(&body, "\n"); |
| 748 | let without_scripts = Regex::new(r"(?is)<script[^>]*>.*?</script>") |
| 749 | .unwrap() |
| 750 | .replace_all(&with_block_breaks, " "); |
| 751 | let without_styles = Regex::new(r"(?is)<style[^>]*>.*?</style>") |
| 752 | .unwrap() |
| 753 | .replace_all(&without_scripts, " "); |
| 754 | let without_tags = Regex::new(r"(?is)<[^>]+>") |
| 755 | .unwrap() |
| 756 | .replace_all(&without_styles, " "); |
| 757 | let normalized_newlines = without_tags |
| 758 | .replace(" ", " ") |
| 759 | .replace("&", "&") |
| 760 | .replace("<", "<") |
| 761 | .replace(">", ">") |
| 762 | .replace(""", "\"") |
| 763 | .replace("'", "'"); |
| 764 | let collapsed_lines = Regex::new(r"[ \t]+") |
| 765 | .unwrap() |
| 766 | .replace_all(&normalized_newlines, " "); |
| 767 | let collapsed_breaks = Regex::new(r"\n\s*\n+") |
| 768 | .unwrap() |
| 769 | .replace_all(&collapsed_lines, "\n\n"); |
| 770 | let cleaned = collapsed_breaks |
| 771 | .lines() |
| 772 | .map(str::trim) |
| 773 | .filter(|line| !line.is_empty()) |
| 774 | .collect::<Vec<_>>() |
| 775 | .join("\n"); |
| 776 | |
| 777 | if cleaned.is_empty() { |
| 778 | return format!("Fetched {url}, but no readable text content was found."); |
| 779 | } |
| 780 | |
| 781 | let mut metadata = vec![format!("URL: {final_url}")]; |
| 782 | if let Some(title) = &title { |
| 783 | metadata.push(format!("Title: {title}")); |
| 784 | } |
| 785 | |
| 786 | let body_text = match title { |
| 787 | Some(title) if !cleaned.starts_with(&title) => cleaned, |
| 788 | _ => cleaned, |
| 789 | }; |
| 790 | |
| 791 | let output = format!("{}\n\n{}", metadata.join("\n"), body_text); |
| 792 | |
| 793 | if output.len() > WEBSITE_READ_CHAR_LIMIT { |
| 794 | let truncated: String = output.chars().take(WEBSITE_READ_CHAR_LIMIT).collect(); |
| 795 | return format!( |
| 796 | "{truncated}\n\n--- truncated (showing {WEBSITE_READ_CHAR_LIMIT} of {} characters) ---", |
| 797 | output.len() |
| 798 | ); |
| 799 | } |
| 800 | |
| 801 | output |
| 802 | } |
| 803 | |
| 804 | // ── create_directory ───────────────────────────────────────────────────────── |
| 805 | |
| 806 | fn exec_create_directory(arguments: &str) -> String { |
| 807 | let args: Value = match serde_json::from_str(arguments) { |
| 808 | Ok(v) => v, |
| 809 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 810 | }; |
| 811 | |
| 812 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 813 | Some(p) => p, |
| 814 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 815 | }; |
| 816 | |
| 817 | let path = Path::new(path_str); |
| 818 | let absolute_path = absolute_path(path); |
| 819 | let absolute_path_str = absolute_path.display().to_string(); |
| 820 | |
| 821 | if absolute_path.exists() { |
| 822 | if absolute_path.is_dir() { |
| 823 | return format!("Directory already exists: {absolute_path_str}"); |
| 824 | } |
| 825 | return format!("Error: path exists and is not a directory: {absolute_path_str}"); |
| 826 | } |
| 827 | |
| 828 | match fs::create_dir_all(&absolute_path) { |
| 829 | Ok(()) => format!("Created directory: {absolute_path_str}"), |
| 830 | Err(err) => format!("Error: could not create directory: {err}"), |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | /// fails if file exists so the LLM is forced to use `edit_file` for modifications. |
| 835 | fn exec_create_file(arguments: &str) -> String { |
| 836 | let args: Value = match serde_json::from_str(arguments) { |
| 837 | Ok(v) => v, |
| 838 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 839 | }; |
| 840 | |
| 841 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 842 | Some(p) => p, |
| 843 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 844 | }; |
| 845 | |
| 846 | let content = match args.get("content").and_then(Value::as_str) { |
| 847 | Some(c) => c, |
| 848 | None => return "Error: missing required parameter \"content\"".to_string(), |
| 849 | }; |
| 850 | |
| 851 | let path = Path::new(path_str); |
| 852 | let absolute_path = absolute_path(path); |
| 853 | let absolute_path_str = absolute_path.display().to_string(); |
| 854 | |
| 855 | if absolute_path.exists() { |
| 856 | return format!( |
| 857 | "Error: file already exists: {absolute_path_str} — use edit_file to modify existing files" |
| 858 | ); |
| 859 | } |
| 860 | |
| 861 | if let Some(parent) = absolute_path.parent() |
| 862 | && !parent.as_os_str().is_empty() |
| 863 | && !parent.exists() |
| 864 | && let Err(err) = fs::create_dir_all(parent) |
| 865 | { |
| 866 | return format!("Error: could not create parent directories: {err}"); |
| 867 | } |
| 868 | |
| 869 | match fs::write(&absolute_path, content) { |
| 870 | Ok(()) => format!( |
| 871 | "Created file: {absolute_path_str} ({} bytes)", |
| 872 | content.len() |
| 873 | ), |
| 874 | Err(err) => format!("Error: could not write file: {err}"), |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | // ── edit_file / multi_edit ───────────────────────────────────────────────── |
| 879 | |
| 880 | /// Apply one exact-substring replacement to `contents`. Returns the updated |
| 881 | /// string, or a human-readable explanation of why the match failed so the model |
| 882 | /// can correct itself in a single follow-up instead of guessing blindly. |
| 883 | fn apply_edit( |
| 884 | contents: &str, |
| 885 | old_text: &str, |
| 886 | new_text: &str, |
| 887 | replace_all: bool, |
| 888 | ) -> Result<String, String> { |
| 889 | if old_text.is_empty() { |
| 890 | return Err("old_text is empty; nothing to match".to_string()); |
| 891 | } |
| 892 | if old_text == new_text { |
| 893 | return Err("old_text and new_text are identical; no change to make".to_string()); |
| 894 | } |
| 895 | |
| 896 | let occurrences = contents.matches(old_text).count(); |
| 897 | |
| 898 | if occurrences == 0 { |
| 899 | return Err(format!( |
| 900 | "old_text not found. Use read_file to copy the exact text \ |
| 901 | (including whitespace and indentation) to replace.{}", |
| 902 | nearest_line_hint(contents, old_text) |
| 903 | )); |
| 904 | } |
| 905 | |
| 906 | if occurrences > 1 && !replace_all { |
| 907 | return Err(format!( |
| 908 | "old_text appears {occurrences} times; include more surrounding context so it \ |
| 909 | matches exactly once, or set replace_all to true to change every occurrence." |
| 910 | )); |
| 911 | } |
| 912 | |
| 913 | if replace_all { |
| 914 | Ok(contents.replace(old_text, new_text)) |
| 915 | } else { |
| 916 | Ok(contents.replacen(old_text, new_text, 1)) |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | /// When `old_text` doesn't match verbatim, point at the line whose trimmed text |
| 921 | /// equals the first trimmed line of `old_text` — the usual culprit is a |
| 922 | /// whitespace/indentation mismatch, and naming the line lets the model fix it. |
| 923 | fn nearest_line_hint(contents: &str, old_text: &str) -> String { |
| 924 | let first = old_text.lines().find(|l| !l.trim().is_empty()); |
| 925 | let Some(first) = first.map(str::trim) else { |
| 926 | return String::new(); |
| 927 | }; |
| 928 | for (idx, line) in contents.lines().enumerate() { |
| 929 | if line.trim() == first { |
| 930 | return format!( |
| 931 | " (the first line of old_text appears at line {}, so the difference is likely \ |
| 932 | whitespace or indentation)", |
| 933 | idx + 1 |
| 934 | ); |
| 935 | } |
| 936 | } |
| 937 | String::new() |
| 938 | } |
| 939 | |
| 940 | fn exec_edit_file(arguments: &str) -> String { |
| 941 | let args: Value = match serde_json::from_str(arguments) { |
| 942 | Ok(v) => v, |
| 943 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 944 | }; |
| 945 | |
| 946 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 947 | Some(p) => p, |
| 948 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 949 | }; |
| 950 | |
| 951 | let old_text = match args.get("old_text").and_then(Value::as_str) { |
| 952 | Some(t) => t, |
| 953 | None => return "Error: missing required parameter \"old_text\"".to_string(), |
| 954 | }; |
| 955 | |
| 956 | let new_text = match args.get("new_text").and_then(Value::as_str) { |
| 957 | Some(t) => t, |
| 958 | None => return "Error: missing required parameter \"new_text\"".to_string(), |
| 959 | }; |
| 960 | |
| 961 | let replace_all = args |
| 962 | .get("replace_all") |
| 963 | .and_then(Value::as_bool) |
| 964 | .unwrap_or(false); |
| 965 | |
| 966 | let path = Path::new(path_str); |
| 967 | let absolute_path = absolute_path(path); |
| 968 | let absolute_path_str = absolute_path.display().to_string(); |
| 969 | |
| 970 | if !absolute_path.exists() { |
| 971 | return format!( |
| 972 | "Error: file does not exist: {absolute_path_str} — use create_file for new files" |
| 973 | ); |
| 974 | } |
| 975 | |
| 976 | if !absolute_path.is_file() { |
| 977 | return format!("Error: path is not a file: {absolute_path_str}"); |
| 978 | } |
| 979 | |
| 980 | let contents = match fs::read_to_string(&absolute_path) { |
| 981 | Ok(c) => c, |
| 982 | Err(err) => return format!("Error: could not read file: {err}"), |
| 983 | }; |
| 984 | |
| 985 | let updated = match apply_edit(&contents, old_text, new_text, replace_all) { |
| 986 | Ok(updated) => updated, |
| 987 | Err(why) => return format!("Error: {why} (in {absolute_path_str})"), |
| 988 | }; |
| 989 | |
| 990 | match fs::write(&absolute_path, &updated) { |
| 991 | Ok(()) => format!( |
| 992 | "Edited file: {absolute_path_str} ({} bytes written)", |
| 993 | updated.len() |
| 994 | ), |
| 995 | Err(err) => format!("Error: could not write file: {err}"), |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | /// Apply a batch of edits to one file atomically: each edit is applied to the |
| 1000 | /// result of the previous one, and the file is only written if *every* edit |
| 1001 | /// matches. A failure leaves the file untouched. |
| 1002 | fn exec_multi_edit(arguments: &str) -> String { |
| 1003 | let args: Value = match serde_json::from_str(arguments) { |
| 1004 | Ok(v) => v, |
| 1005 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1006 | }; |
| 1007 | |
| 1008 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 1009 | Some(p) => p, |
| 1010 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 1011 | }; |
| 1012 | |
| 1013 | let edits = match args.get("edits").and_then(Value::as_array) { |
| 1014 | Some(e) if !e.is_empty() => e, |
| 1015 | Some(_) => return "Error: \"edits\" must contain at least one edit".to_string(), |
| 1016 | None => return "Error: missing required parameter \"edits\"".to_string(), |
| 1017 | }; |
| 1018 | |
| 1019 | let path = Path::new(path_str); |
| 1020 | let absolute_path = absolute_path(path); |
| 1021 | let absolute_path_str = absolute_path.display().to_string(); |
| 1022 | |
| 1023 | if !absolute_path.exists() { |
| 1024 | return format!( |
| 1025 | "Error: file does not exist: {absolute_path_str} — use create_file for new files" |
| 1026 | ); |
| 1027 | } |
| 1028 | |
| 1029 | if !absolute_path.is_file() { |
| 1030 | return format!("Error: path is not a file: {absolute_path_str}"); |
| 1031 | } |
| 1032 | |
| 1033 | let mut working = match fs::read_to_string(&absolute_path) { |
| 1034 | Ok(c) => c, |
| 1035 | Err(err) => return format!("Error: could not read file: {err}"), |
| 1036 | }; |
| 1037 | |
| 1038 | for (idx, edit) in edits.iter().enumerate() { |
| 1039 | let old_text = match edit.get("old_text").and_then(Value::as_str) { |
| 1040 | Some(t) => t, |
| 1041 | None => return format!("Error: edit #{} is missing \"old_text\"", idx + 1), |
| 1042 | }; |
| 1043 | let new_text = match edit.get("new_text").and_then(Value::as_str) { |
| 1044 | Some(t) => t, |
| 1045 | None => return format!("Error: edit #{} is missing \"new_text\"", idx + 1), |
| 1046 | }; |
| 1047 | let replace_all = edit |
| 1048 | .get("replace_all") |
| 1049 | .and_then(Value::as_bool) |
| 1050 | .unwrap_or(false); |
| 1051 | |
| 1052 | match apply_edit(&working, old_text, new_text, replace_all) { |
| 1053 | Ok(updated) => working = updated, |
| 1054 | Err(why) => { |
| 1055 | return format!( |
| 1056 | "Error: edit #{} failed: {why}. No changes were written to {absolute_path_str}.", |
| 1057 | idx + 1 |
| 1058 | ); |
| 1059 | } |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | match fs::write(&absolute_path, &working) { |
| 1064 | Ok(()) => format!( |
| 1065 | "Applied {} edits to {absolute_path_str} ({} bytes written)", |
| 1066 | edits.len(), |
| 1067 | working.len() |
| 1068 | ), |
| 1069 | Err(err) => format!("Error: could not write file: {err}"), |
| 1070 | } |
| 1071 | } |
| 1072 | |
| 1073 | // ── glob ───────────────────────────────────────────────────────────────────── |
| 1074 | |
| 1075 | /// Translate a shell-style glob into an anchored regex. Supports `*` |
| 1076 | /// (non-separator run), `**` (any number of directories), `?` (one |
| 1077 | /// non-separator), and `{a,b}` alternation; everything else is matched |
| 1078 | /// literally. Used both by the `glob` tool (against relative paths) and by |
| 1079 | /// `search_files`' `file_glob` filter (against bare file names). |
| 1080 | fn glob_to_regex(glob: &str) -> String { |
| 1081 | let chars: Vec<char> = glob.chars().collect(); |
| 1082 | let mut re = String::from("^"); |
| 1083 | let mut brace_depth = 0usize; |
| 1084 | let mut i = 0; |
| 1085 | |
| 1086 | while i < chars.len() { |
| 1087 | let c = chars[i]; |
| 1088 | match c { |
| 1089 | '*' => { |
| 1090 | if i + 1 < chars.len() && chars[i + 1] == '*' { |
| 1091 | i += 1; // consume the second '*' |
| 1092 | if i + 1 < chars.len() && chars[i + 1] == '/' { |
| 1093 | // `**/` matches zero or more leading directories. |
| 1094 | re.push_str("(?:.*/)?"); |
| 1095 | i += 1; // consume the '/' |
| 1096 | } else { |
| 1097 | re.push_str(".*"); |
| 1098 | } |
| 1099 | } else { |
| 1100 | re.push_str("[^/]*"); |
| 1101 | } |
| 1102 | } |
| 1103 | '?' => re.push_str("[^/]"), |
| 1104 | '{' => { |
| 1105 | brace_depth += 1; |
| 1106 | re.push_str("(?:"); |
| 1107 | } |
| 1108 | '}' if brace_depth > 0 => { |
| 1109 | brace_depth -= 1; |
| 1110 | re.push(')'); |
| 1111 | } |
| 1112 | ',' if brace_depth > 0 => re.push('|'), |
| 1113 | // Escape regex metacharacters so they match literally. (`{` is always |
| 1114 | // consumed by the brace arm above; an unmatched `}` lands here.) |
| 1115 | '.' | '+' | '(' | ')' | '|' | '^' | '$' | '\\' | '[' | ']' | '}' => { |
| 1116 | re.push('\\'); |
| 1117 | re.push(c); |
| 1118 | } |
| 1119 | other => re.push(other), |
| 1120 | } |
| 1121 | i += 1; |
| 1122 | } |
| 1123 | |
| 1124 | re.push('$'); |
| 1125 | re |
| 1126 | } |
| 1127 | |
| 1128 | fn exec_glob(arguments: &str) -> String { |
| 1129 | let args: Value = match serde_json::from_str(arguments) { |
| 1130 | Ok(v) => v, |
| 1131 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1132 | }; |
| 1133 | |
| 1134 | let pattern = match args.get("pattern").and_then(Value::as_str) { |
| 1135 | Some(p) => p, |
| 1136 | None => return "Error: missing required parameter \"pattern\"".to_string(), |
| 1137 | }; |
| 1138 | |
| 1139 | let re = match Regex::new(&glob_to_regex(pattern)) { |
| 1140 | Ok(r) => r, |
| 1141 | Err(err) => return format!("Error: invalid glob pattern: {err}"), |
| 1142 | }; |
| 1143 | |
| 1144 | let root_str = args.get("path").and_then(Value::as_str).unwrap_or("."); |
| 1145 | let absolute_root = absolute_path(Path::new(root_str)); |
| 1146 | let absolute_root_str = absolute_root.display().to_string(); |
| 1147 | |
| 1148 | if !absolute_root.exists() { |
| 1149 | return format!("Error: path does not exist: {absolute_root_str}"); |
| 1150 | } |
| 1151 | if !absolute_root.is_dir() { |
| 1152 | return format!("Error: path is not a directory: {absolute_root_str}"); |
| 1153 | } |
| 1154 | |
| 1155 | let mut found: Vec<(std::time::SystemTime, String)> = Vec::new(); |
| 1156 | glob_walk(&absolute_root, &absolute_root, &re, &mut found); |
| 1157 | |
| 1158 | if found.is_empty() { |
| 1159 | return format!("No files match glob: {pattern}"); |
| 1160 | } |
| 1161 | |
| 1162 | // Most-recently-modified first. |
| 1163 | found.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); |
| 1164 | |
| 1165 | let total = found.len(); |
| 1166 | let mut paths: Vec<String> = found.into_iter().map(|(_, p)| p).collect(); |
| 1167 | if total > SEARCH_RESULTS_HARD_CAP { |
| 1168 | paths.truncate(SEARCH_RESULTS_HARD_CAP); |
| 1169 | paths.push(format!( |
| 1170 | "\n--- truncated (showing {SEARCH_RESULTS_HARD_CAP} of {total} files) ---" |
| 1171 | )); |
| 1172 | } |
| 1173 | |
| 1174 | paths.join("\n") |
| 1175 | } |
| 1176 | |
| 1177 | fn glob_walk(root: &Path, dir: &Path, re: &Regex, out: &mut Vec<(std::time::SystemTime, String)>) { |
| 1178 | if out.len() > SEARCH_RESULTS_HARD_CAP { |
| 1179 | return; |
| 1180 | } |
| 1181 | |
| 1182 | let entries = match fs::read_dir(dir) { |
| 1183 | Ok(rd) => rd, |
| 1184 | Err(_) => return, |
| 1185 | }; |
| 1186 | |
| 1187 | let mut sorted: Vec<fs::DirEntry> = entries.filter_map(Result::ok).collect(); |
| 1188 | sorted.sort_by_key(|e| e.file_name()); |
| 1189 | |
| 1190 | for entry in sorted { |
| 1191 | if out.len() > SEARCH_RESULTS_HARD_CAP { |
| 1192 | return; |
| 1193 | } |
| 1194 | |
| 1195 | let path = entry.path(); |
| 1196 | let name = entry.file_name(); |
| 1197 | if name.to_string_lossy().starts_with('.') { |
| 1198 | continue; |
| 1199 | } |
| 1200 | |
| 1201 | if path.is_dir() { |
| 1202 | glob_walk(root, &path, re, out); |
| 1203 | } else if path.is_file() { |
| 1204 | let relative = path |
| 1205 | .strip_prefix(root) |
| 1206 | .unwrap_or(&path) |
| 1207 | .to_string_lossy() |
| 1208 | .replace('\\', "/"); |
| 1209 | if re.is_match(&relative) { |
| 1210 | let mtime = entry |
| 1211 | .metadata() |
| 1212 | .and_then(|m| m.modified()) |
| 1213 | .unwrap_or(std::time::SystemTime::UNIX_EPOCH); |
| 1214 | out.push((mtime, absolute_path_string(&path))); |
| 1215 | } |
| 1216 | } |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | // ── write_todos ────────────────────────────────────────────────────────────── |
| 1221 | |
| 1222 | /// Renders the model's task checklist back as the tool result so the surface |
| 1223 | /// (TUI / ACP client) can show live progress. Pure presentation — the list is |
| 1224 | /// owned by the model, not persisted here. |
| 1225 | fn exec_write_todos(arguments: &str) -> String { |
| 1226 | let args: Value = match serde_json::from_str(arguments) { |
| 1227 | Ok(v) => v, |
| 1228 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1229 | }; |
| 1230 | |
| 1231 | let todos = match args.get("todos").and_then(Value::as_array) { |
| 1232 | Some(t) if !t.is_empty() => t, |
| 1233 | Some(_) => return "Error: \"todos\" must contain at least one item".to_string(), |
| 1234 | None => return "Error: missing required parameter \"todos\"".to_string(), |
| 1235 | }; |
| 1236 | |
| 1237 | let mut lines = Vec::with_capacity(todos.len()); |
| 1238 | let mut completed = 0usize; |
| 1239 | |
| 1240 | for (idx, todo) in todos.iter().enumerate() { |
| 1241 | let content = match todo.get("content").and_then(Value::as_str) { |
| 1242 | Some(c) => c.trim(), |
| 1243 | None => return format!("Error: todo #{} is missing \"content\"", idx + 1), |
| 1244 | }; |
| 1245 | let status = todo |
| 1246 | .get("status") |
| 1247 | .and_then(Value::as_str) |
| 1248 | .unwrap_or("pending"); |
| 1249 | |
| 1250 | let marker = match status { |
| 1251 | "completed" => { |
| 1252 | completed += 1; |
| 1253 | "[x]" |
| 1254 | } |
| 1255 | "in_progress" => "[~]", |
| 1256 | _ => "[ ]", |
| 1257 | }; |
| 1258 | lines.push(format!("{marker} {content}")); |
| 1259 | } |
| 1260 | |
| 1261 | format!( |
| 1262 | "Task list updated ({completed}/{} done):\n{}", |
| 1263 | todos.len(), |
| 1264 | lines.join("\n") |
| 1265 | ) |
| 1266 | } |
| 1267 | |
| 1268 | // ── remember ───────────────────────────────────────────────────────────────── |
| 1269 | |
| 1270 | /// Appends a durable note to the project's instruction file so it persists |
| 1271 | /// across sessions (the always-on counterpart to a one-off chat message). |
| 1272 | fn exec_remember(arguments: &str) -> String { |
| 1273 | let args: Value = match serde_json::from_str(arguments) { |
| 1274 | Ok(v) => v, |
| 1275 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1276 | }; |
| 1277 | |
| 1278 | let note = match args.get("note").and_then(Value::as_str) { |
| 1279 | Some(n) if !n.trim().is_empty() => n.trim(), |
| 1280 | Some(_) => return "Error: \"note\" must not be empty".to_string(), |
| 1281 | None => return "Error: missing required parameter \"note\"".to_string(), |
| 1282 | }; |
| 1283 | |
| 1284 | let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); |
| 1285 | remember_at(&cwd, note) |
| 1286 | } |
| 1287 | |
| 1288 | /// Core of `remember`, parameterized on the working directory so it can be |
| 1289 | /// tested without mutating the process-global current directory. |
| 1290 | fn remember_at(cwd: &Path, note: &str) -> String { |
| 1291 | let target = crate::instructions::memory_file(cwd); |
| 1292 | let target_str = target.display().to_string(); |
| 1293 | |
| 1294 | let existed = target.exists(); |
| 1295 | let mut body = if existed { |
| 1296 | match fs::read_to_string(&target) { |
| 1297 | Ok(c) => c, |
| 1298 | Err(err) => return format!("Error: could not read {target_str}: {err}"), |
| 1299 | } |
| 1300 | } else { |
| 1301 | if let Some(parent) = target.parent() |
| 1302 | && !parent.as_os_str().is_empty() |
| 1303 | && !parent.exists() |
| 1304 | && let Err(err) = fs::create_dir_all(parent) |
| 1305 | { |
| 1306 | return format!("Error: could not create parent directories: {err}"); |
| 1307 | } |
| 1308 | String::new() |
| 1309 | }; |
| 1310 | |
| 1311 | // Keep remembered notes grouped under one heading so the file stays tidy. |
| 1312 | const HEADING: &str = "## Remembered notes"; |
| 1313 | if !body.contains(HEADING) { |
| 1314 | if !body.is_empty() && !body.ends_with('\n') { |
| 1315 | body.push('\n'); |
| 1316 | } |
| 1317 | if !body.is_empty() { |
| 1318 | body.push('\n'); |
| 1319 | } |
| 1320 | body.push_str(HEADING); |
| 1321 | body.push('\n'); |
| 1322 | } |
| 1323 | if !body.ends_with('\n') { |
| 1324 | body.push('\n'); |
| 1325 | } |
| 1326 | body.push_str("- "); |
| 1327 | body.push_str(note); |
| 1328 | body.push('\n'); |
| 1329 | |
| 1330 | match fs::write(&target, &body) { |
| 1331 | Ok(()) => { |
| 1332 | let verb = if existed { "Appended to" } else { "Created" }; |
| 1333 | format!("{verb} {target_str}: remembered \"{note}\"") |
| 1334 | } |
| 1335 | Err(err) => format!("Error: could not write {target_str}: {err}"), |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | // ── delete_file ────────────────────────────────────────────────────────────── |
| 1340 | |
| 1341 | /// only removes files or *empty* directories — no recursive deletes. |
| 1342 | fn exec_delete_file(arguments: &str) -> String { |
| 1343 | let args: Value = match serde_json::from_str(arguments) { |
| 1344 | Ok(v) => v, |
| 1345 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1346 | }; |
| 1347 | |
| 1348 | let path_str = match args.get("path").and_then(Value::as_str) { |
| 1349 | Some(p) => p, |
| 1350 | None => return "Error: missing required parameter \"path\"".to_string(), |
| 1351 | }; |
| 1352 | |
| 1353 | let path = Path::new(path_str); |
| 1354 | let absolute_path = absolute_path(path); |
| 1355 | let absolute_path_str = absolute_path.display().to_string(); |
| 1356 | |
| 1357 | if !absolute_path.exists() { |
| 1358 | return format!("Error: path does not exist: {absolute_path_str}"); |
| 1359 | } |
| 1360 | |
| 1361 | if absolute_path.is_dir() { |
| 1362 | match fs::remove_dir(&absolute_path) { |
| 1363 | Ok(()) => format!("Deleted empty directory: {absolute_path_str}"), |
| 1364 | Err(err) => format!( |
| 1365 | "Error: could not delete directory: {err}. \ |
| 1366 | Only empty directories can be deleted." |
| 1367 | ), |
| 1368 | } |
| 1369 | } else { |
| 1370 | match fs::remove_file(&absolute_path) { |
| 1371 | Ok(()) => format!("Deleted file: {absolute_path_str}"), |
| 1372 | Err(err) => format!("Error: could not delete file: {err}"), |
| 1373 | } |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | // ── run_command ────────────────────────────────────────────────────────────── |
| 1378 | |
| 1379 | const COMMAND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); |
| 1380 | const COMMAND_OUTPUT_LIMIT: usize = 50_000; |
| 1381 | |
| 1382 | /// runs via `sh -c` / `cmd /C`; killed after COMMAND_TIMEOUT. |
| 1383 | fn exec_run_command(arguments: &str) -> String { |
| 1384 | let args: Value = match serde_json::from_str(arguments) { |
| 1385 | Ok(v) => v, |
| 1386 | Err(err) => return format!("Error: failed to parse arguments: {err}"), |
| 1387 | }; |
| 1388 | |
| 1389 | let command_str = match args.get("command").and_then(Value::as_str) { |
| 1390 | Some(c) => c, |
| 1391 | None => return "Error: missing required parameter \"command\"".to_string(), |
| 1392 | }; |
| 1393 | |
| 1394 | let default_cwd = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); |
| 1395 | let cwd = args |
| 1396 | .get("cwd") |
| 1397 | .and_then(Value::as_str) |
| 1398 | .unwrap_or(&default_cwd); |
| 1399 | let cwd_path = absolute_path(Path::new(cwd)); |
| 1400 | let cwd_str = cwd_path.display().to_string(); |
| 1401 | |
| 1402 | if !cwd_path.exists() { |
| 1403 | return format!("Error: working directory does not exist: {cwd_str}"); |
| 1404 | } |
| 1405 | |
| 1406 | log::info!("run_command: `{command_str}` in `{cwd_str}`"); |
| 1407 | |
| 1408 | #[cfg(unix)] |
| 1409 | let mut child = match Command::new("sh") |
| 1410 | .arg("-c") |
| 1411 | .arg(command_str) |
| 1412 | .current_dir(&cwd_path) |
| 1413 | .stdout(std::process::Stdio::piped()) |
| 1414 | .stderr(std::process::Stdio::piped()) |
| 1415 | .spawn() |
| 1416 | { |
| 1417 | Ok(c) => c, |
| 1418 | Err(err) => return format!("Error: failed to spawn command: {err}"), |
| 1419 | }; |
| 1420 | |
| 1421 | #[cfg(windows)] |
| 1422 | let mut child = match Command::new("cmd") |
| 1423 | .arg("/C") |
| 1424 | .arg(command_str) |
| 1425 | .current_dir(&cwd_path) |
| 1426 | .stdout(std::process::Stdio::piped()) |
| 1427 | .stderr(std::process::Stdio::piped()) |
| 1428 | .spawn() |
| 1429 | { |
| 1430 | Ok(c) => c, |
| 1431 | Err(err) => return format!("Error: failed to spawn command: {err}"), |
| 1432 | }; |
| 1433 | |
| 1434 | let start = std::time::Instant::now(); |
| 1435 | loop { |
| 1436 | match child.try_wait() { |
| 1437 | Ok(Some(_status)) => break, |
| 1438 | Ok(None) => { |
| 1439 | if start.elapsed() >= COMMAND_TIMEOUT { |
| 1440 | let _ = child.kill(); |
| 1441 | return format!( |
| 1442 | "Error: command timed out after {} seconds and was killed.", |
| 1443 | COMMAND_TIMEOUT.as_secs() |
| 1444 | ); |
| 1445 | } |
| 1446 | std::thread::sleep(std::time::Duration::from_millis(100)); |
| 1447 | } |
| 1448 | Err(err) => return format!("Error: failed to wait on command: {err}"), |
| 1449 | } |
| 1450 | } |
| 1451 | |
| 1452 | let output = match child.wait_with_output() { |
| 1453 | Ok(o) => o, |
| 1454 | Err(err) => return format!("Error: failed to read command output: {err}"), |
| 1455 | }; |
| 1456 | |
| 1457 | let exit_code = output.status.code().unwrap_or(-1); |
| 1458 | let mut combined = String::new(); |
| 1459 | combined.push_str(&String::from_utf8_lossy(&output.stdout)); |
| 1460 | combined.push_str(&String::from_utf8_lossy(&output.stderr)); |
| 1461 | |
| 1462 | let truncated = if combined.len() > COMMAND_OUTPUT_LIMIT { |
| 1463 | let truncated_str = &combined[..COMMAND_OUTPUT_LIMIT]; |
| 1464 | format!("{truncated_str}\n\n… (output truncated at {COMMAND_OUTPUT_LIMIT} bytes)") |
| 1465 | } else { |
| 1466 | combined |
| 1467 | }; |
| 1468 | |
| 1469 | if output.status.success() { |
| 1470 | if truncated.is_empty() { |
| 1471 | format!("Command succeeded (exit code {exit_code}) with no output.") |
| 1472 | } else { |
| 1473 | format!("Exit code {exit_code}:\n{truncated}") |
| 1474 | } |
| 1475 | } else { |
| 1476 | format!("Command failed (exit code {exit_code}):\n{truncated}") |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | #[cfg(test)] |
| 1481 | mod tests { |
| 1482 | use super::*; |
| 1483 | use std::fs; |
| 1484 | |
| 1485 | #[tokio::test] |
| 1486 | async fn test_execute_unknown_tool() { |
| 1487 | let result = execute_tool("nonexistent", "{}").await; |
| 1488 | assert!(result.starts_with("Unknown tool:")); |
| 1489 | } |
| 1490 | |
| 1491 | #[test] |
| 1492 | fn test_read_file_missing_path_param() { |
| 1493 | let result = exec_read_file("{}"); |
| 1494 | assert!(result.contains("missing required parameter")); |
| 1495 | } |
| 1496 | |
| 1497 | #[test] |
| 1498 | fn test_read_file_nonexistent() { |
| 1499 | let result = exec_read_file(r#"{"path": "/tmp/__sigit_no_such_file_42__"}"#); |
| 1500 | assert!(result.contains("does not exist")); |
| 1501 | } |
| 1502 | |
| 1503 | #[test] |
| 1504 | fn test_read_file_success() { |
| 1505 | let dir = std::env::temp_dir().join("sigit_test_read_file"); |
| 1506 | let _ = fs::create_dir_all(&dir); |
| 1507 | let file_path = dir.join("hello.txt"); |
| 1508 | fs::write(&file_path, "hello world").unwrap(); |
| 1509 | |
| 1510 | let args = serde_json::json!({ "path": file_path }).to_string(); |
| 1511 | let result = exec_read_file(&args); |
| 1512 | assert_eq!(result, "hello world"); |
| 1513 | |
| 1514 | let _ = fs::remove_dir_all(&dir); |
| 1515 | } |
| 1516 | |
| 1517 | #[test] |
| 1518 | fn test_list_directory_missing_path_param() { |
| 1519 | let result = exec_list_directory("{}"); |
| 1520 | assert!(result.contains("missing required parameter")); |
| 1521 | } |
| 1522 | |
| 1523 | #[test] |
| 1524 | fn test_list_directory_success() { |
| 1525 | let dir = std::env::temp_dir().join("sigit_test_list_dir"); |
| 1526 | let _ = fs::remove_dir_all(&dir); |
| 1527 | fs::create_dir_all(dir.join("subdir")).unwrap(); |
| 1528 | fs::write(dir.join("aaa.txt"), "").unwrap(); |
| 1529 | fs::write(dir.join("bbb.rs"), "").unwrap(); |
| 1530 | |
| 1531 | let args = serde_json::json!({ "path": dir }).to_string(); |
| 1532 | let result = exec_list_directory(&args); |
| 1533 | |
| 1534 | assert!(result.contains("[DIR] subdir")); |
| 1535 | assert!(result.contains("[FILE] aaa.txt")); |
| 1536 | assert!(result.contains("[FILE] bbb.rs")); |
| 1537 | |
| 1538 | // Directories should appear before files. |
| 1539 | let dir_pos = result.find("[DIR]").unwrap(); |
| 1540 | let file_pos = result.find("[FILE]").unwrap(); |
| 1541 | assert!(dir_pos < file_pos); |
| 1542 | |
| 1543 | let _ = fs::remove_dir_all(&dir); |
| 1544 | } |
| 1545 | |
| 1546 | #[test] |
| 1547 | fn test_search_files_invalid_regex() { |
| 1548 | let result = exec_search_files(r#"{"pattern": "[invalid", "path": "."}"#); |
| 1549 | assert!(result.contains("invalid regex")); |
| 1550 | } |
| 1551 | |
| 1552 | #[test] |
| 1553 | fn test_search_files_success() { |
| 1554 | let dir = std::env::temp_dir().join("sigit_test_search"); |
| 1555 | let _ = fs::remove_dir_all(&dir); |
| 1556 | fs::create_dir_all(&dir).unwrap(); |
| 1557 | fs::write( |
| 1558 | dir.join("code.rs"), |
| 1559 | "fn main() {\n println!(\"hello\");\n}\n", |
| 1560 | ) |
| 1561 | .unwrap(); |
| 1562 | fs::write(dir.join("other.txt"), "no match here\n").unwrap(); |
| 1563 | |
| 1564 | let args = serde_json::json!({ |
| 1565 | "pattern": "println", |
| 1566 | "path": dir |
| 1567 | }) |
| 1568 | .to_string(); |
| 1569 | let result = exec_search_files(&args); |
| 1570 | |
| 1571 | assert!(result.contains("code.rs:2:")); |
| 1572 | assert!(result.contains("println")); |
| 1573 | assert!(!result.contains("other.txt")); |
| 1574 | |
| 1575 | let _ = fs::remove_dir_all(&dir); |
| 1576 | } |
| 1577 | |
| 1578 | #[test] |
| 1579 | fn test_search_files_no_matches() { |
| 1580 | let dir = std::env::temp_dir().join("sigit_test_search_none"); |
| 1581 | let _ = fs::remove_dir_all(&dir); |
| 1582 | fs::create_dir_all(&dir).unwrap(); |
| 1583 | fs::write(dir.join("empty.txt"), "nothing special").unwrap(); |
| 1584 | |
| 1585 | let args = serde_json::json!({ |
| 1586 | "pattern": "zzz_will_not_match_42", |
| 1587 | "path": dir |
| 1588 | }) |
| 1589 | .to_string(); |
| 1590 | let result = exec_search_files(&args); |
| 1591 | assert!(result.contains("No matches found")); |
| 1592 | |
| 1593 | let _ = fs::remove_dir_all(&dir); |
| 1594 | } |
| 1595 | |
| 1596 | #[test] |
| 1597 | fn test_all_tools_count() { |
| 1598 | let tools = all_tools(); |
| 1599 | assert_eq!(tools.len(), 13); |
| 1600 | assert_eq!(tools[0].name, "read_file"); |
| 1601 | assert_eq!(tools[1].name, "create_directory"); |
| 1602 | assert_eq!(tools[2].name, "list_directory"); |
| 1603 | assert_eq!(tools[3].name, "search_files"); |
| 1604 | assert_eq!(tools[4].name, "read_website"); |
| 1605 | assert_eq!(tools[5].name, "create_file"); |
| 1606 | assert_eq!(tools[6].name, "edit_file"); |
| 1607 | assert_eq!(tools[7].name, "delete_file"); |
| 1608 | assert_eq!(tools[8].name, "run_command"); |
| 1609 | assert_eq!(tools[9].name, "multi_edit"); |
| 1610 | assert_eq!(tools[10].name, "glob"); |
| 1611 | assert_eq!(tools[11].name, "write_todos"); |
| 1612 | assert_eq!(tools[12].name, "remember"); |
| 1613 | } |
| 1614 | |
| 1615 | #[test] |
| 1616 | fn test_edit_file_replace_all() { |
| 1617 | let dir = std::env::temp_dir().join("sigit_test_edit_replace_all"); |
| 1618 | let _ = fs::remove_dir_all(&dir); |
| 1619 | fs::create_dir_all(&dir).unwrap(); |
| 1620 | let file = dir.join("f.txt"); |
| 1621 | fs::write(&file, "foo foo foo").unwrap(); |
| 1622 | |
| 1623 | // Without replace_all an ambiguous match is rejected. |
| 1624 | let args = |
| 1625 | serde_json::json!({ "path": &file, "old_text": "foo", "new_text": "bar" }).to_string(); |
| 1626 | let result = exec_edit_file(&args); |
| 1627 | assert!(result.contains("appears 3 times"), "{result}"); |
| 1628 | |
| 1629 | // With replace_all every occurrence is changed. |
| 1630 | let args = serde_json::json!({ |
| 1631 | "path": &file, "old_text": "foo", "new_text": "bar", "replace_all": true |
| 1632 | }) |
| 1633 | .to_string(); |
| 1634 | let result = exec_edit_file(&args); |
| 1635 | assert!(result.starts_with("Edited file:"), "{result}"); |
| 1636 | assert_eq!(fs::read_to_string(&file).unwrap(), "bar bar bar"); |
| 1637 | |
| 1638 | let _ = fs::remove_dir_all(&dir); |
| 1639 | } |
| 1640 | |
| 1641 | #[test] |
| 1642 | fn test_edit_file_whitespace_hint() { |
| 1643 | let dir = std::env::temp_dir().join("sigit_test_edit_hint"); |
| 1644 | let _ = fs::remove_dir_all(&dir); |
| 1645 | fs::create_dir_all(&dir).unwrap(); |
| 1646 | let file = dir.join("f.txt"); |
| 1647 | fs::write(&file, "line one\n indented\nline three\n").unwrap(); |
| 1648 | |
| 1649 | // old_text has more indentation than the file, so it isn't a substring, |
| 1650 | // but its trimmed content still locates the intended line. |
| 1651 | let args = serde_json::json!({ |
| 1652 | "path": &file, "old_text": " indented", "new_text": "x" |
| 1653 | }) |
| 1654 | .to_string(); |
| 1655 | let result = exec_edit_file(&args); |
| 1656 | assert!(result.contains("line 2"), "{result}"); |
| 1657 | assert!(result.contains("whitespace"), "{result}"); |
| 1658 | |
| 1659 | let _ = fs::remove_dir_all(&dir); |
| 1660 | } |
| 1661 | |
| 1662 | #[test] |
| 1663 | fn test_multi_edit_atomic_on_failure() { |
| 1664 | let dir = std::env::temp_dir().join("sigit_test_multi_edit"); |
| 1665 | let _ = fs::remove_dir_all(&dir); |
| 1666 | fs::create_dir_all(&dir).unwrap(); |
| 1667 | let file = dir.join("f.txt"); |
| 1668 | fs::write(&file, "alpha beta gamma").unwrap(); |
| 1669 | |
| 1670 | // Second edit can't match -> nothing should be written. |
| 1671 | let args = serde_json::json!({ |
| 1672 | "path": &file, |
| 1673 | "edits": [ |
| 1674 | { "old_text": "alpha", "new_text": "ALPHA" }, |
| 1675 | { "old_text": "nope", "new_text": "x" } |
| 1676 | ] |
| 1677 | }) |
| 1678 | .to_string(); |
| 1679 | let result = exec_multi_edit(&args); |
| 1680 | assert!(result.contains("edit #2 failed"), "{result}"); |
| 1681 | assert_eq!(fs::read_to_string(&file).unwrap(), "alpha beta gamma"); |
| 1682 | |
| 1683 | // All-matching batch applies in sequence. |
| 1684 | let args = serde_json::json!({ |
| 1685 | "path": &file, |
| 1686 | "edits": [ |
| 1687 | { "old_text": "alpha", "new_text": "ALPHA" }, |
| 1688 | { "old_text": "gamma", "new_text": "GAMMA" } |
| 1689 | ] |
| 1690 | }) |
| 1691 | .to_string(); |
| 1692 | let result = exec_multi_edit(&args); |
| 1693 | assert!(result.contains("Applied 2 edits"), "{result}"); |
| 1694 | assert_eq!(fs::read_to_string(&file).unwrap(), "ALPHA beta GAMMA"); |
| 1695 | |
| 1696 | let _ = fs::remove_dir_all(&dir); |
| 1697 | } |
| 1698 | |
| 1699 | #[test] |
| 1700 | fn test_glob_to_regex() { |
| 1701 | let re = Regex::new(&glob_to_regex("**/*.rs")).unwrap(); |
| 1702 | assert!(re.is_match("src/tools.rs")); |
| 1703 | assert!(re.is_match("main.rs")); // `**/` matches zero directories too |
| 1704 | assert!(!re.is_match("src/tools.txt")); |
| 1705 | |
| 1706 | let re = Regex::new(&glob_to_regex("*.{ts,tsx}")).unwrap(); |
| 1707 | assert!(re.is_match("app.ts")); |
| 1708 | assert!(re.is_match("app.tsx")); |
| 1709 | assert!(!re.is_match("app.js")); |
| 1710 | } |
| 1711 | |
| 1712 | #[test] |
| 1713 | fn test_glob_tool_success() { |
| 1714 | let dir = std::env::temp_dir().join("sigit_test_glob"); |
| 1715 | let _ = fs::remove_dir_all(&dir); |
| 1716 | fs::create_dir_all(dir.join("src")).unwrap(); |
| 1717 | fs::write(dir.join("Cargo.toml"), "").unwrap(); |
| 1718 | fs::write(dir.join("src/main.rs"), "").unwrap(); |
| 1719 | fs::write(dir.join("src/lib.rs"), "").unwrap(); |
| 1720 | |
| 1721 | let args = serde_json::json!({ "pattern": "**/*.rs", "path": &dir }).to_string(); |
| 1722 | let result = exec_glob(&args); |
| 1723 | assert!(result.contains("main.rs"), "{result}"); |
| 1724 | assert!(result.contains("lib.rs"), "{result}"); |
| 1725 | assert!(!result.contains("Cargo.toml"), "{result}"); |
| 1726 | |
| 1727 | let _ = fs::remove_dir_all(&dir); |
| 1728 | } |
| 1729 | |
| 1730 | #[test] |
| 1731 | fn test_search_files_file_glob_filter() { |
| 1732 | let dir = std::env::temp_dir().join("sigit_test_search_glob"); |
| 1733 | let _ = fs::remove_dir_all(&dir); |
| 1734 | fs::create_dir_all(&dir).unwrap(); |
| 1735 | fs::write(dir.join("code.rs"), "needle here\n").unwrap(); |
| 1736 | fs::write(dir.join("notes.txt"), "needle here\n").unwrap(); |
| 1737 | |
| 1738 | let args = serde_json::json!({ |
| 1739 | "pattern": "needle", "path": &dir, "file_glob": "*.rs" |
| 1740 | }) |
| 1741 | .to_string(); |
| 1742 | let result = exec_search_files(&args); |
| 1743 | assert!(result.contains("code.rs"), "{result}"); |
| 1744 | assert!(!result.contains("notes.txt"), "{result}"); |
| 1745 | |
| 1746 | let _ = fs::remove_dir_all(&dir); |
| 1747 | } |
| 1748 | |
| 1749 | #[test] |
| 1750 | fn test_write_todos_renders_checklist() { |
| 1751 | let args = serde_json::json!({ |
| 1752 | "todos": [ |
| 1753 | { "content": "Read code", "status": "completed" }, |
| 1754 | { "content": "Make change", "status": "in_progress" }, |
| 1755 | { "content": "Run tests", "status": "pending" } |
| 1756 | ] |
| 1757 | }) |
| 1758 | .to_string(); |
| 1759 | let result = exec_write_todos(&args); |
| 1760 | assert!(result.contains("1/3 done"), "{result}"); |
| 1761 | assert!(result.contains("[x] Read code"), "{result}"); |
| 1762 | assert!(result.contains("[~] Make change"), "{result}"); |
| 1763 | assert!(result.contains("[ ] Run tests"), "{result}"); |
| 1764 | } |
| 1765 | |
| 1766 | #[test] |
| 1767 | fn test_remember_appends_to_instruction_file() { |
| 1768 | let dir = std::env::temp_dir().join("sigit_test_remember"); |
| 1769 | let _ = fs::remove_dir_all(&dir); |
| 1770 | fs::create_dir_all(dir.join(".git")).unwrap(); |
| 1771 | let claude_md = dir.join("CLAUDE.md"); |
| 1772 | fs::write(&claude_md, "# Project\n").unwrap(); |
| 1773 | |
| 1774 | let target = crate::instructions::memory_file(&dir); |
| 1775 | // Should pick the existing CLAUDE.md at the repo root. |
| 1776 | assert_eq!( |
| 1777 | target.canonicalize().unwrap(), |
| 1778 | claude_md.canonicalize().unwrap() |
| 1779 | ); |
| 1780 | |
| 1781 | let result = remember_at(&dir, "remembered text"); |
| 1782 | assert!(result.contains("remembered"), "{result}"); |
| 1783 | |
| 1784 | let updated = fs::read_to_string(&claude_md).unwrap(); |
| 1785 | assert!(updated.contains("## Remembered notes"), "{updated}"); |
| 1786 | assert!(updated.contains("- remembered text"), "{updated}"); |
| 1787 | |
| 1788 | let _ = fs::remove_dir_all(&dir); |
| 1789 | } |
| 1790 | |
| 1791 | #[test] |
| 1792 | fn test_all_tools_schemas_are_valid_json_objects() { |
| 1793 | for tool in all_tools() { |
| 1794 | assert!( |
| 1795 | tool.parameters_schema.is_object(), |
| 1796 | "schema for {} is not an object", |
| 1797 | tool.name |
| 1798 | ); |
| 1799 | let obj = tool.parameters_schema.as_object().unwrap(); |
| 1800 | assert!(obj.contains_key("type")); |
| 1801 | assert!(obj.contains_key("properties")); |
| 1802 | assert!(obj.contains_key("required")); |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | // ── read_website tests ─────────────────────────────────────────────── |
| 1807 | |
| 1808 | #[test] |
| 1809 | fn test_read_website_missing_url() { |
| 1810 | let result = exec_read_website("{}"); |
| 1811 | assert!(result.contains("missing required parameter")); |
| 1812 | } |
| 1813 | |
| 1814 | #[test] |
| 1815 | fn test_read_website_invalid_scheme() { |
| 1816 | let result = exec_read_website(r#"{"url": "file:///tmp/test.html"}"#); |
| 1817 | assert!(result.contains("url must start with http:// or https://")); |
| 1818 | } |
| 1819 | |
| 1820 | #[test] |
| 1821 | fn test_read_website_extracts_title_from_html() { |
| 1822 | let body = r#" |
| 1823 | <html> |
| 1824 | <head> |
| 1825 | <title>Qwen 3.6 27B</title> |
| 1826 | </head> |
| 1827 | <body> |
| 1828 | <h1>Model card</h1> |
| 1829 | <p>Large language model.</p> |
| 1830 | </body> |
| 1831 | </html> |
| 1832 | "#; |
| 1833 | |
| 1834 | let title = Regex::new(r"(?is)<title[^>]*>(.*?)</title>") |
| 1835 | .unwrap() |
| 1836 | .captures(body) |
| 1837 | .and_then(|captures| captures.get(1)) |
| 1838 | .map(|m| { |
| 1839 | Regex::new(r"\s+") |
| 1840 | .unwrap() |
| 1841 | .replace_all(m.as_str(), " ") |
| 1842 | .trim() |
| 1843 | .to_string() |
| 1844 | }) |
| 1845 | .filter(|title| !title.is_empty()); |
| 1846 | |
| 1847 | assert_eq!(title.as_deref(), Some("Qwen 3.6 27B")); |
| 1848 | } |
| 1849 | |
| 1850 | #[test] |
| 1851 | fn test_read_website_metadata_includes_final_url_header() { |
| 1852 | let final_url = "https://huggingface.co/Qwen/Qwen3.6-27B"; |
| 1853 | let title = Some("Qwen 3.6 27B".to_string()); |
| 1854 | let cleaned = "Model card\nLarge language model.".to_string(); |
| 1855 | |
| 1856 | let mut metadata = vec![format!("URL: {final_url}")]; |
| 1857 | if let Some(title) = &title { |
| 1858 | metadata.push(format!("Title: {title}")); |
| 1859 | } |
| 1860 | |
| 1861 | let body_text = match title { |
| 1862 | Some(_) => cleaned, |
| 1863 | None => cleaned, |
| 1864 | }; |
| 1865 | |
| 1866 | let output = format!("{}\n\n{}", metadata.join("\n"), body_text); |
| 1867 | |
| 1868 | assert!(output.starts_with("URL: https://huggingface.co/Qwen/Qwen3.6-27B")); |
| 1869 | assert!(output.contains("\nTitle: Qwen 3.6 27B\n\n")); |
| 1870 | } |
| 1871 | |
| 1872 | // ── create_directory tests ─────────────────────────────────────────── |
| 1873 | |
| 1874 | #[test] |
| 1875 | fn test_create_directory_missing_path() { |
| 1876 | let result = exec_create_directory("{}"); |
| 1877 | assert!(result.contains("missing required parameter")); |
| 1878 | } |
| 1879 | |
| 1880 | #[test] |
| 1881 | fn test_create_directory_success() { |
| 1882 | let dir = std::env::temp_dir() |
| 1883 | .join("sigit_test_create_directory") |
| 1884 | .join("nested") |
| 1885 | .join("child"); |
| 1886 | let _ = fs::remove_dir_all(dir.parent().unwrap()); |
| 1887 | |
| 1888 | let args = serde_json::json!({ "path": dir }).to_string(); |
| 1889 | let result = exec_create_directory(&args); |
| 1890 | assert!(result.starts_with("Created directory:"), "got: {result}"); |
| 1891 | assert!(dir.exists()); |
| 1892 | assert!(dir.is_dir()); |
| 1893 | |
| 1894 | let _ = fs::remove_dir_all(dir.parent().unwrap().parent().unwrap()); |
| 1895 | } |
| 1896 | |
| 1897 | #[test] |
| 1898 | fn test_create_directory_already_exists() { |
| 1899 | let dir = std::env::temp_dir().join("sigit_test_create_directory_exists"); |
| 1900 | let _ = fs::remove_dir_all(&dir); |
| 1901 | fs::create_dir_all(&dir).unwrap(); |
| 1902 | |
| 1903 | let args = serde_json::json!({ "path": dir }).to_string(); |
| 1904 | let result = exec_create_directory(&args); |
| 1905 | assert!(result.contains("Directory already exists"), "got: {result}"); |
| 1906 | |
| 1907 | let _ = fs::remove_dir_all(&dir); |
| 1908 | } |
| 1909 | |
| 1910 | // ── create_file tests ──────────────────────────────────────────────── |
| 1911 | |
| 1912 | #[test] |
| 1913 | fn test_create_file_missing_path() { |
| 1914 | let result = exec_create_file(r#"{"content": "hello"}"#); |
| 1915 | assert!(result.contains("missing required parameter")); |
| 1916 | } |
| 1917 | |
| 1918 | #[test] |
| 1919 | fn test_create_file_missing_content() { |
| 1920 | let result = exec_create_file(r#"{"path": "/tmp/sigit_test_nope.txt"}"#); |
| 1921 | assert!(result.contains("missing required parameter")); |
| 1922 | } |
| 1923 | |
| 1924 | #[test] |
| 1925 | fn test_create_file_success() { |
| 1926 | let dir = std::env::temp_dir().join("sigit_test_create_file"); |
| 1927 | let _ = fs::remove_dir_all(&dir); |
| 1928 | |
| 1929 | let file_path = dir.join("sub").join("new_file.txt"); |
| 1930 | let args = serde_json::json!({ |
| 1931 | "path": file_path, |
| 1932 | "content": "hello world" |
| 1933 | }) |
| 1934 | .to_string(); |
| 1935 | |
| 1936 | let result = exec_create_file(&args); |
| 1937 | assert!(result.starts_with("Created file:"), "got: {result}"); |
| 1938 | assert!(file_path.exists()); |
| 1939 | assert_eq!(fs::read_to_string(&file_path).unwrap(), "hello world"); |
| 1940 | |
| 1941 | let _ = fs::remove_dir_all(&dir); |
| 1942 | } |
| 1943 | |
| 1944 | #[test] |
| 1945 | fn test_create_file_already_exists() { |
| 1946 | let dir = std::env::temp_dir().join("sigit_test_create_exists"); |
| 1947 | let _ = fs::remove_dir_all(&dir); |
| 1948 | fs::create_dir_all(&dir).unwrap(); |
| 1949 | |
| 1950 | let file_path = dir.join("existing.txt"); |
| 1951 | fs::write(&file_path, "original").unwrap(); |
| 1952 | |
| 1953 | let args = serde_json::json!({ |
| 1954 | "path": file_path, |
| 1955 | "content": "overwrite attempt" |
| 1956 | }) |
| 1957 | .to_string(); |
| 1958 | |
| 1959 | let result = exec_create_file(&args); |
| 1960 | assert!(result.contains("already exists"), "got: {result}"); |
| 1961 | // Original content untouched. |
| 1962 | assert_eq!(fs::read_to_string(&file_path).unwrap(), "original"); |
| 1963 | |
| 1964 | let _ = fs::remove_dir_all(&dir); |
| 1965 | } |
| 1966 | |
| 1967 | // ── edit_file tests ────────────────────────────────────────────────── |
| 1968 | |
| 1969 | #[test] |
| 1970 | fn test_edit_file_missing_params() { |
| 1971 | let result = exec_edit_file(r#"{"path": "x"}"#); |
| 1972 | assert!(result.contains("missing required parameter")); |
| 1973 | |
| 1974 | let result = exec_edit_file(r#"{"path": "x", "old_text": "a"}"#); |
| 1975 | assert!(result.contains("missing required parameter")); |
| 1976 | } |
| 1977 | |
| 1978 | #[test] |
| 1979 | fn test_edit_file_nonexistent() { |
| 1980 | let result = exec_edit_file( |
| 1981 | r#"{"path": "/tmp/__sigit_no_such__", "old_text": "a", "new_text": "b"}"#, |
| 1982 | ); |
| 1983 | assert!(result.contains("does not exist")); |
| 1984 | } |
| 1985 | |
| 1986 | #[test] |
| 1987 | fn test_edit_file_success() { |
| 1988 | let dir = std::env::temp_dir().join("sigit_test_edit_file"); |
| 1989 | let _ = fs::remove_dir_all(&dir); |
| 1990 | fs::create_dir_all(&dir).unwrap(); |
| 1991 | |
| 1992 | let file_path = dir.join("code.rs"); |
| 1993 | fs::write(&file_path, "fn main() {\n println!(\"hello\");\n}\n").unwrap(); |
| 1994 | |
| 1995 | let args = serde_json::json!({ |
| 1996 | "path": file_path, |
| 1997 | "old_text": "println!(\"hello\")", |
| 1998 | "new_text": "println!(\"world\")" |
| 1999 | }) |
| 2000 | .to_string(); |
| 2001 | |
| 2002 | let result = exec_edit_file(&args); |
| 2003 | assert!(result.starts_with("Edited file:"), "got: {result}"); |
| 2004 | |
| 2005 | let updated = fs::read_to_string(&file_path).unwrap(); |
| 2006 | assert!(updated.contains("println!(\"world\")")); |
| 2007 | assert!(!updated.contains("println!(\"hello\")")); |
| 2008 | |
| 2009 | let _ = fs::remove_dir_all(&dir); |
| 2010 | } |
| 2011 | |
| 2012 | #[test] |
| 2013 | fn test_edit_file_old_text_not_found() { |
| 2014 | let dir = std::env::temp_dir().join("sigit_test_edit_notfound"); |
| 2015 | let _ = fs::remove_dir_all(&dir); |
| 2016 | fs::create_dir_all(&dir).unwrap(); |
| 2017 | |
| 2018 | let file_path = dir.join("data.txt"); |
| 2019 | fs::write(&file_path, "aaa bbb ccc").unwrap(); |
| 2020 | |
| 2021 | let args = serde_json::json!({ |
| 2022 | "path": file_path, |
| 2023 | "old_text": "zzz", |
| 2024 | "new_text": "yyy" |
| 2025 | }) |
| 2026 | .to_string(); |
| 2027 | |
| 2028 | let result = exec_edit_file(&args); |
| 2029 | assert!(result.contains("old_text not found"), "got: {result}"); |
| 2030 | |
| 2031 | let _ = fs::remove_dir_all(&dir); |
| 2032 | } |
| 2033 | |
| 2034 | #[test] |
| 2035 | fn test_edit_file_ambiguous_match() { |
| 2036 | let dir = std::env::temp_dir().join("sigit_test_edit_ambiguous"); |
| 2037 | let _ = fs::remove_dir_all(&dir); |
| 2038 | fs::create_dir_all(&dir).unwrap(); |
| 2039 | |
| 2040 | let file_path = dir.join("repeat.txt"); |
| 2041 | fs::write(&file_path, "foo bar foo bar foo").unwrap(); |
| 2042 | |
| 2043 | let args = serde_json::json!({ |
| 2044 | "path": file_path, |
| 2045 | "old_text": "foo", |
| 2046 | "new_text": "baz" |
| 2047 | }) |
| 2048 | .to_string(); |
| 2049 | |
| 2050 | let result = exec_edit_file(&args); |
| 2051 | assert!(result.contains("appears 3 times"), "got: {result}"); |
| 2052 | // File should be unchanged. |
| 2053 | assert_eq!( |
| 2054 | fs::read_to_string(&file_path).unwrap(), |
| 2055 | "foo bar foo bar foo" |
| 2056 | ); |
| 2057 | |
| 2058 | let _ = fs::remove_dir_all(&dir); |
| 2059 | } |
| 2060 | |
| 2061 | // ── delete_file tests ──────────────────────────────────────────────── |
| 2062 | |
| 2063 | #[test] |
| 2064 | fn test_delete_file_missing_path() { |
| 2065 | let result = exec_delete_file("{}"); |
| 2066 | assert!( |
| 2067 | result.contains("missing required parameter"), |
| 2068 | "got: {result}" |
| 2069 | ); |
| 2070 | } |
| 2071 | |
| 2072 | #[test] |
| 2073 | fn test_delete_file_nonexistent() { |
| 2074 | let result = exec_delete_file(r#"{"path": "/tmp/sigit_test_no_such_file_xyz"}"#); |
| 2075 | assert!(result.contains("does not exist"), "got: {result}"); |
| 2076 | } |
| 2077 | |
| 2078 | #[test] |
| 2079 | fn test_delete_file_success() { |
| 2080 | let dir = std::env::temp_dir().join("sigit_test_delete_file"); |
| 2081 | let _ = fs::remove_dir_all(&dir); |
| 2082 | fs::create_dir_all(&dir).unwrap(); |
| 2083 | |
| 2084 | let file_path = dir.join("to_delete.txt"); |
| 2085 | fs::write(&file_path, "bye").unwrap(); |
| 2086 | assert!(file_path.exists()); |
| 2087 | |
| 2088 | let args = serde_json::json!({ "path": file_path }).to_string(); |
| 2089 | let result = exec_delete_file(&args); |
| 2090 | assert!(result.contains("Deleted file"), "got: {result}"); |
| 2091 | assert!(!file_path.exists()); |
| 2092 | |
| 2093 | let _ = fs::remove_dir_all(&dir); |
| 2094 | } |
| 2095 | |
| 2096 | #[test] |
| 2097 | fn test_delete_empty_directory() { |
| 2098 | let dir = std::env::temp_dir().join("sigit_test_delete_empty_dir"); |
| 2099 | let _ = fs::remove_dir_all(&dir); |
| 2100 | fs::create_dir_all(&dir).unwrap(); |
| 2101 | |
| 2102 | let args = serde_json::json!({ "path": dir }).to_string(); |
| 2103 | let result = exec_delete_file(&args); |
| 2104 | assert!(result.contains("Deleted empty directory"), "got: {result}"); |
| 2105 | assert!(!dir.exists()); |
| 2106 | } |
| 2107 | |
| 2108 | #[test] |
| 2109 | fn test_delete_nonempty_directory() { |
| 2110 | let dir = std::env::temp_dir().join("sigit_test_delete_nonempty_dir"); |
| 2111 | let _ = fs::remove_dir_all(&dir); |
| 2112 | fs::create_dir_all(&dir).unwrap(); |
| 2113 | fs::write(dir.join("child.txt"), "content").unwrap(); |
| 2114 | |
| 2115 | let args = serde_json::json!({ "path": dir }).to_string(); |
| 2116 | let result = exec_delete_file(&args); |
| 2117 | assert!(result.contains("Error"), "got: {result}"); |
| 2118 | assert!(dir.exists(), "directory should not have been deleted"); |
| 2119 | |
| 2120 | let _ = fs::remove_dir_all(&dir); |
| 2121 | } |
| 2122 | |
| 2123 | // ── run_command tests ──────────────────────────────────────────────── |
| 2124 | |
| 2125 | #[test] |
| 2126 | fn test_run_command_missing_command() { |
| 2127 | let result = exec_run_command("{}"); |
| 2128 | assert!( |
| 2129 | result.contains("missing required parameter"), |
| 2130 | "got: {result}" |
| 2131 | ); |
| 2132 | } |
| 2133 | |
| 2134 | #[test] |
| 2135 | fn test_run_command_success() { |
| 2136 | let result = exec_run_command(r#"{"command": "echo hello"}"#); |
| 2137 | assert!(result.contains("hello"), "got: {result}"); |
| 2138 | assert!(result.contains("Exit code 0"), "got: {result}"); |
| 2139 | } |
| 2140 | |
| 2141 | #[test] |
| 2142 | fn test_run_command_failure() { |
| 2143 | #[cfg(unix)] |
| 2144 | let command = "false"; |
| 2145 | #[cfg(windows)] |
| 2146 | let command = "exit /b 1"; |
| 2147 | |
| 2148 | let args = serde_json::json!({ "command": command }).to_string(); |
| 2149 | let result = exec_run_command(&args); |
| 2150 | assert!(result.contains("failed"), "got: {result}"); |
| 2151 | } |
| 2152 | |
| 2153 | #[test] |
| 2154 | fn test_run_command_with_cwd() { |
| 2155 | let dir = std::env::temp_dir().join("sigit_test_run_cmd_cwd"); |
| 2156 | let _ = fs::remove_dir_all(&dir); |
| 2157 | fs::create_dir_all(&dir).unwrap(); |
| 2158 | |
| 2159 | #[cfg(unix)] |
| 2160 | let command = "pwd"; |
| 2161 | #[cfg(windows)] |
| 2162 | let command = "cd"; |
| 2163 | |
| 2164 | let args = serde_json::json!({ |
| 2165 | "command": command, |
| 2166 | "cwd": dir |
| 2167 | }) |
| 2168 | .to_string(); |
| 2169 | let result = exec_run_command(&args); |
| 2170 | // The output should contain the temp dir path. |
| 2171 | assert!( |
| 2172 | result.contains(&dir.to_string_lossy().to_string()), |
| 2173 | "got: {result}" |
| 2174 | ); |
| 2175 | |
| 2176 | let _ = fs::remove_dir_all(&dir); |
| 2177 | } |
| 2178 | |
| 2179 | #[test] |
| 2180 | fn test_run_command_bad_cwd() { |
| 2181 | let missing_dir = std::env::temp_dir().join("sigit_no_such_dir_xyz"); |
| 2182 | let _ = fs::remove_dir_all(&missing_dir); |
| 2183 | |
| 2184 | let args = serde_json::json!({ |
| 2185 | "command": "echo hi", |
| 2186 | "cwd": missing_dir |
| 2187 | }) |
| 2188 | .to_string(); |
| 2189 | let result = exec_run_command(&args); |
| 2190 | assert!(result.contains("does not exist"), "got: {result}"); |
| 2191 | } |
| 2192 | |
| 2193 | #[test] |
| 2194 | fn test_run_command_captures_stderr() { |
| 2195 | #[cfg(unix)] |
| 2196 | let command = "echo err >&2"; |
| 2197 | #[cfg(windows)] |
| 2198 | let command = "echo err 1>&2"; |
| 2199 | |
| 2200 | let args = serde_json::json!({ "command": command }).to_string(); |
| 2201 | let result = exec_run_command(&args); |
| 2202 | assert!(result.contains("err"), "got: {result}"); |
| 2203 | } |
| 2204 | } |