| 1 | //! File system engines for the lowercase `read`, `write`, and `edit` primitives |
| 2 | //! plus deferred workspace helpers such as `list_dir`. The older `read_file`, |
| 3 | //! `write_file`, and `edit_file` names remain registered but hidden for |
| 4 | //! protocol clients that call them by name. |
| 5 | //! |
| 6 | //! These tools provide safe file system operations within the workspace, |
| 7 | //! with path validation to prevent escaping the workspace boundary. |
| 8 | |
| 9 | use super::diff_format::make_unified_diff; |
| 10 | use super::rust_format::{NORMALIZED_NOTE, normalize_edit}; |
| 11 | use super::spec::{ |
| 12 | ApprovalRequirement, RichToolResult, ToolCapability, ToolContext, ToolError, ToolResult, |
| 13 | ToolSpec, optional_str, optional_u64, required_str, |
| 14 | }; |
| 15 | use super::syntax_check::guard_edit; |
| 16 | use async_trait::async_trait; |
| 17 | use codewhale_tools::param_alias::{PATH_ALIASES, ParamAlias, alias, apply_param_aliases}; |
| 18 | use serde_json::{Value, json}; |
| 19 | use std::borrow::Cow; |
| 20 | use std::collections::HashMap; |
| 21 | use std::fs; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::{Arc, Mutex, OnceLock, Weak}; |
| 24 | use std::time::Duration; |
| 25 | use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard}; |
| 26 | use tokio_util::sync::CancellationToken; |
| 27 | use unicode_normalization::UnicodeNormalization; |
| 28 | |
| 29 | // === Content-hash edit guards (#3979) === |
| 30 | |
| 31 | /// Format a file snapshot's content hash as `sha256:<hex>`. |
| 32 | /// |
| 33 | /// The prefixed shape (rather than a bare hex digest) is deliberate: it is |
| 34 | /// self-describing in the transcript, and it makes an accidentally-truncated or |
| 35 | /// hand-invented value fail the equality check instead of matching by luck. |
| 36 | /// |
| 37 | /// A file's hash is taken over its raw bytes, always before any windowing, |
| 38 | /// truncation, or rendering, so the value `read` reports is the value `write`, |
| 39 | /// `edit`, and `patch` verify. |
| 40 | pub fn content_hash(bytes: &[u8]) -> String { |
| 41 | format!("sha256:{}", codewhale_runtime::hashing::sha256_hex(bytes)) |
| 42 | } |
| 43 | |
| 44 | /// Hash a file's bytes without holding the whole file in memory. |
| 45 | /// |
| 46 | /// The read path streams a bounded window out of large files on purpose, so it |
| 47 | /// never has the full contents to hash. Digesting through a separate streaming |
| 48 | /// pass keeps that memory bound while still producing a hash over the entire |
| 49 | /// file — the only value an edit guard can verify against. |
| 50 | fn hash_reader_streaming(reader: &mut impl std::io::Read) -> std::io::Result<String> { |
| 51 | use sha2::{Digest, Sha256}; |
| 52 | |
| 53 | let mut hasher = Sha256::new(); |
| 54 | let mut buf = vec![0_u8; 64 * 1024]; |
| 55 | loop { |
| 56 | let read = reader.read(&mut buf)?; |
| 57 | if read == 0 { |
| 58 | break; |
| 59 | } |
| 60 | hasher.update(&buf[..read]); |
| 61 | } |
| 62 | Ok(format!( |
| 63 | "sha256:{}", |
| 64 | codewhale_runtime::hashing::hex_bytes(hasher.finalize()) |
| 65 | )) |
| 66 | } |
| 67 | |
| 68 | /// The one-line header that reports a snapshot hash to the model. |
| 69 | /// |
| 70 | /// This goes in `ToolResult::content`, not in `ToolResult::metadata`, and that |
| 71 | /// placement is the whole point. `metadata` never reaches the model: the wire |
| 72 | /// `ContentBlock::ToolResult` (`crates/core/src/request.rs`) has no field for |
| 73 | /// it, and the turn loop builds the tool message from `output.content` alone |
| 74 | /// (`crates/engine/src/core/engine/turn_loop.rs`). Metadata is for the TUI, |
| 75 | /// telemetry, and the approval/mutation receipts. A hash the model cannot read |
| 76 | /// is a guard the model cannot use, so it is rendered into the content — either |
| 77 | /// as an attribute on the `<file …>` envelope, or as this header line for the |
| 78 | /// unwrapped small-file read. |
| 79 | fn content_hash_header(hash: &str) -> String { |
| 80 | format!("content_hash=\"{hash}\"\n") |
| 81 | } |
| 82 | |
| 83 | /// Reject a mutation whose `expected_hash` does not describe the current file. |
| 84 | /// |
| 85 | /// Callers must run this against the exact snapshot the mutation would be |
| 86 | /// applied to, and before anything is written. `None` (parameter absent) keeps |
| 87 | /// the pre-#3979 behavior untouched — the guard is opt-in. |
| 88 | fn verify_expected_hash( |
| 89 | expected: Option<&str>, |
| 90 | current_bytes: &[u8], |
| 91 | action: &str, |
| 92 | path_str: &str, |
| 93 | ) -> Result<(), ToolError> { |
| 94 | let Some(expected) = expected else { |
| 95 | return Ok(()); |
| 96 | }; |
| 97 | let actual = content_hash(current_bytes); |
| 98 | if expected == actual { |
| 99 | return Ok(()); |
| 100 | } |
| 101 | Err(ToolError::execution_failed(format!( |
| 102 | "File `{action}` refused: {path_str} changed since it was read. \ |
| 103 | expected_hash was {expected} but the file is now {actual}, so nothing was written. \ |
| 104 | Recovery: re-read the file with `read` (path=\"{path_str}\") to get the current contents \ |
| 105 | and its content_hash, then retry with the new hash." |
| 106 | ))) |
| 107 | } |
| 108 | |
| 109 | /// Shared schema text for the optional guard parameter. |
| 110 | /// |
| 111 | /// The hidden compatibility schema still has a byte budget, so this is only the |
| 112 | /// instruction the legacy caller needs: what to pass and what happens on a |
| 113 | /// mismatch. The rationale stays in doc comments rather than schema bytes. |
| 114 | pub(super) const EXPECTED_HASH_DESCRIPTION: &str = |
| 115 | "Prior read's content_hash; refuse the write if the file has changed."; |
| 116 | |
| 117 | // === Cross-harness parameter aliases === |
| 118 | |
| 119 | /// Edit-specific spellings. Ordered most- to least-common. |
| 120 | const EDIT_ALIASES: &[ParamAlias] = &[ |
| 121 | alias("old_string", "search"), |
| 122 | alias("new_string", "replace"), |
| 123 | alias("old_str", "search"), |
| 124 | alias("new_str", "replace"), |
| 125 | alias("oldText", "search"), |
| 126 | alias("newText", "replace"), |
| 127 | alias("old_text", "search"), |
| 128 | alias("new_text", "replace"), |
| 129 | alias("replacement", "replace"), |
| 130 | ]; |
| 131 | |
| 132 | /// Read-window spellings. `offset`/`limit` and `line_offset`/`n_lines` both |
| 133 | /// name the same two numbers as CodeWhale's `start_line`/`max_lines` in widely |
| 134 | /// trained-on tool surfaces. A wrong guess here used to be ignored outright, |
| 135 | /// silently returning the head of the file instead of the window the model |
| 136 | /// asked for — a wrong answer shaped like a right one. |
| 137 | const READ_ALIASES: &[ParamAlias] = &[ |
| 138 | alias("offset", "start_line"), |
| 139 | alias("line_offset", "start_line"), |
| 140 | alias("limit", "max_lines"), |
| 141 | alias("n_lines", "max_lines"), |
| 142 | alias("num_lines", "max_lines"), |
| 143 | ]; |
| 144 | |
| 145 | /// `file_search` spellings. `grep_files` names its result cap `max_results`; |
| 146 | /// `file_search` spells the same number `limit`. Folding it here keeps the |
| 147 | /// result-count cap a model asks for the cap it gets whichever name it reaches |
| 148 | /// for. |
| 149 | pub(super) const SEARCH_NAME_ALIASES: &[ParamAlias] = &[alias("max_results", "limit")]; |
| 150 | |
| 151 | /// `grep_files` spellings, mirroring `SEARCH_NAME_ALIASES` in the other |
| 152 | /// direction: a model that carries `file_search`'s `query` and `limit` across |
| 153 | /// to a content search means `pattern` and `max_results`. |
| 154 | pub(super) const SEARCH_CONTENT_ALIASES: &[ParamAlias] = |
| 155 | &[alias("query", "pattern"), alias("limit", "max_results")]; |
| 156 | |
| 157 | // === Per-action parameter contracts === |
| 158 | |
| 159 | /// The parameter contract for one file tool. |
| 160 | /// |
| 161 | /// #5209 taught `edit` to refuse a parameter it does not implement instead of |
| 162 | /// dropping it and returning a success-shaped receipt. Only `edit` learned it. |
| 163 | /// Every other action kept silently discarding unknown keys, and for a reader |
| 164 | /// that is the same failure wearing a quieter costume: a misspelled |
| 165 | /// `start_line` on `read` is dropped, the head of the file comes back, and |
| 166 | /// nothing in the response says the requested window was never honored — a |
| 167 | /// wrong answer shaped like a right one. |
| 168 | /// |
| 169 | /// One table, one error shape, every action. |
| 170 | pub(super) struct ActionParams { |
| 171 | /// Tool name the refusal names (`read`, `grep_files`, …). |
| 172 | action: &'static str, |
| 173 | /// Every parameter the action implements, canonical spellings only. |
| 174 | /// Aliases are folded onto these by [`apply_param_aliases`] before |
| 175 | /// validation runs, so they must not be listed here. |
| 176 | allowed: &'static [&'static str], |
| 177 | /// Parameters the action cannot run without. |
| 178 | required: &'static [&'static str], |
| 179 | /// `true` when exactly one of `required` is needed rather than all of |
| 180 | /// them — `patch` accepts `patch`, `replace`, or `changes`. |
| 181 | required_is_choice: bool, |
| 182 | } |
| 183 | |
| 184 | const fn params( |
| 185 | action: &'static str, |
| 186 | allowed: &'static [&'static str], |
| 187 | required: &'static [&'static str], |
| 188 | ) -> ActionParams { |
| 189 | ActionParams { |
| 190 | action, |
| 191 | allowed, |
| 192 | required, |
| 193 | required_is_choice: false, |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | pub(super) const READ_PARAMS: ActionParams = params( |
| 198 | "read", |
| 199 | &["path", "start_line", "max_lines", "pages"], |
| 200 | &["path"], |
| 201 | ); |
| 202 | |
| 203 | pub(super) const WRITE_PARAMS: ActionParams = params( |
| 204 | "write", |
| 205 | &["path", "content", "expected_hash", "line_ending"], |
| 206 | &["path", "content"], |
| 207 | ); |
| 208 | |
| 209 | pub(super) const EDIT_PARAMS: ActionParams = params( |
| 210 | "edit", |
| 211 | &["path", "search", "replace", "expected_hash"], |
| 212 | &["path", "search", "replace"], |
| 213 | ); |
| 214 | |
| 215 | pub(super) const LIST_PARAMS: ActionParams = params("list_dir", &["path"], &[]); |
| 216 | |
| 217 | pub(super) const SEARCH_NAME_PARAMS: ActionParams = params( |
| 218 | "file_search", |
| 219 | &[ |
| 220 | "query", |
| 221 | "path", |
| 222 | "limit", |
| 223 | "extensions", |
| 224 | "exclude", |
| 225 | "replace_default_excludes", |
| 226 | ], |
| 227 | &["query"], |
| 228 | ); |
| 229 | |
| 230 | pub(super) const SEARCH_CONTENT_PARAMS: ActionParams = params( |
| 231 | "grep_files", |
| 232 | &[ |
| 233 | "pattern", |
| 234 | "path", |
| 235 | "include", |
| 236 | "exclude", |
| 237 | "replace_default_excludes", |
| 238 | "mode", |
| 239 | "context_lines", |
| 240 | "case_insensitive", |
| 241 | "max_results", |
| 242 | ], |
| 243 | &["pattern"], |
| 244 | ); |
| 245 | |
| 246 | pub(super) const PATCH_PARAMS: ActionParams = ActionParams { |
| 247 | action: "apply_patch", |
| 248 | allowed: &[ |
| 249 | "path", |
| 250 | "patch", |
| 251 | "replace", |
| 252 | "changes", |
| 253 | "fuzz", |
| 254 | "create_if_missing", |
| 255 | "expected_hash", |
| 256 | ], |
| 257 | required: &["patch", "replace", "changes"], |
| 258 | required_is_choice: true, |
| 259 | }; |
| 260 | |
| 261 | /// Render `names` as a backticked, comma-separated English list. |
| 262 | fn quoted_list(names: &[&str], conjunction: &str) -> String { |
| 263 | let quoted: Vec<String> = names.iter().map(|name| format!("`{name}`")).collect(); |
| 264 | match quoted.as_slice() { |
| 265 | [] => "none".to_string(), |
| 266 | [only] => only.clone(), |
| 267 | [first, second] => format!("{first} {conjunction} {second}"), |
| 268 | [head @ .., last] => format!("{}, {conjunction} {last}", head.join(", ")), |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | impl ActionParams { |
| 273 | /// Reject parameter names this action does not implement. |
| 274 | /// |
| 275 | /// Must run *after* [`apply_param_aliases`], exactly as the `edit` path |
| 276 | /// does. The alias lane's reasoning stands: translating an unambiguous |
| 277 | /// synonym is better than refusing it, so by the time this runs every |
| 278 | /// spelling with a known meaning has already been folded onto its |
| 279 | /// canonical name. What is left is a name with no known meaning, where |
| 280 | /// continuing would mean guessing which argument was intended — so it |
| 281 | /// hard-errors rather than dropping the argument and reporting success. |
| 282 | pub(super) fn reject_unknown(&self, input: &Value) -> Result<(), ToolError> { |
| 283 | let action = self.action; |
| 284 | let required = if self.required_is_choice { |
| 285 | format!("one of {}", quoted_list(self.required, "or")) |
| 286 | } else { |
| 287 | quoted_list(self.required, "and") |
| 288 | }; |
| 289 | |
| 290 | let Some(obj) = input.as_object() else { |
| 291 | return Err(ToolError::invalid_input(format!( |
| 292 | "{action} input must be an object. Allowed parameters are {}. Required: {required}. The call was not performed.", |
| 293 | quoted_list(self.allowed, "and"), |
| 294 | ))); |
| 295 | }; |
| 296 | |
| 297 | let unexpected: Vec<&str> = obj |
| 298 | .keys() |
| 299 | .map(String::as_str) |
| 300 | .filter(|key| !self.allowed.contains(key)) |
| 301 | .collect(); |
| 302 | if !unexpected.is_empty() { |
| 303 | return Err(ToolError::invalid_input(format!( |
| 304 | "unexpected {action} parameter(s): {}. Allowed parameters are {}. Required: {required}. The call was not performed.", |
| 305 | unexpected.join(", "), |
| 306 | quoted_list(self.allowed, "and"), |
| 307 | ))); |
| 308 | } |
| 309 | |
| 310 | Ok(()) |
| 311 | } |
| 312 | |
| 313 | /// A required parameter that is not also allowed would make the refusal |
| 314 | /// self-contradicting: it would name an argument the same check rejects. |
| 315 | #[cfg(test)] |
| 316 | pub(super) fn assert_required_is_allowed(&self) { |
| 317 | for name in self.required { |
| 318 | assert!( |
| 319 | self.allowed.contains(name), |
| 320 | "{} requires `{name}` but does not allow it", |
| 321 | self.action |
| 322 | ); |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // === ReadFileTool === |
| 328 | |
| 329 | fn canonical_path_for_credential_guard(path: &Path) -> PathBuf { |
| 330 | let absolute = if path.is_absolute() { |
| 331 | path.to_path_buf() |
| 332 | } else { |
| 333 | std::env::current_dir() |
| 334 | .unwrap_or_else(|_| PathBuf::from(".")) |
| 335 | .join(path) |
| 336 | }; |
| 337 | if let Ok(resolved) = fs::canonicalize(&absolute) { |
| 338 | return resolved; |
| 339 | } |
| 340 | let mut suffix: Vec<std::ffi::OsString> = Vec::new(); |
| 341 | let mut cursor = absolute.as_path(); |
| 342 | while let Some(parent) = cursor.parent() { |
| 343 | if let Some(name) = cursor.file_name() { |
| 344 | suffix.push(name.to_os_string()); |
| 345 | } |
| 346 | if let Ok(mut resolved) = fs::canonicalize(parent) { |
| 347 | for name in suffix.iter().rev() { |
| 348 | resolved.push(name); |
| 349 | } |
| 350 | return resolved; |
| 351 | } |
| 352 | cursor = parent; |
| 353 | } |
| 354 | absolute |
| 355 | } |
| 356 | |
| 357 | fn config_backup_path_for_credential_guard(config_path: &Path) -> PathBuf { |
| 358 | let mut file_name = config_path |
| 359 | .file_name() |
| 360 | .map(std::ffi::OsString::from) |
| 361 | .unwrap_or_else(|| std::ffi::OsString::from(codewhale_config::CONFIG_FILE_NAME)); |
| 362 | file_name.push(".bak"); |
| 363 | config_path |
| 364 | .parent() |
| 365 | .unwrap_or_else(|| Path::new(".")) |
| 366 | .join(file_name) |
| 367 | } |
| 368 | |
| 369 | fn is_config_or_backup(candidate: &Path, config_path: &Path) -> bool { |
| 370 | let config_path = canonical_path_for_credential_guard(config_path); |
| 371 | let backup_path = |
| 372 | canonical_path_for_credential_guard(&config_backup_path_for_credential_guard(&config_path)); |
| 373 | codewhale_sandbox::read_guard::paths_match(candidate, &config_path) |
| 374 | || codewhale_sandbox::read_guard::paths_match(candidate, &backup_path) |
| 375 | } |
| 376 | |
| 377 | /// Resolve a model-supplied path for an in-process read, applying every read |
| 378 | /// guard in the one safe order: the deny-list on the caller's raw spelling |
| 379 | /// (so a denial never names a symlink target), then `resolve_path`, then the |
| 380 | /// credential-store check and the deny-list again on the resolved path. |
| 381 | /// |
| 382 | /// Every tool that reads a file's content in-process and hands it (or a |
| 383 | /// derivative) to the model goes through this. |
| 384 | fn resolve_guarded_read_path( |
| 385 | context: &ToolContext, |
| 386 | raw: &str, |
| 387 | tool: &str, |
| 388 | ) -> Result<PathBuf, ToolError> { |
| 389 | guard_read_path(context, raw, tool, ToolContext::resolve_path) |
| 390 | } |
| 391 | |
| 392 | pub fn resolve_guarded_display_path( |
| 393 | context: &ToolContext, |
| 394 | raw: &str, |
| 395 | tool: &str, |
| 396 | ) -> Result<PathBuf, ToolError> { |
| 397 | guard_read_path(context, raw, tool, ToolContext::resolve_read_path) |
| 398 | } |
| 399 | |
| 400 | fn guard_read_path( |
| 401 | context: &ToolContext, |
| 402 | raw: &str, |
| 403 | tool: &str, |
| 404 | resolve: fn(&ToolContext, &str) -> Result<PathBuf, ToolError>, |
| 405 | ) -> Result<PathBuf, ToolError> { |
| 406 | let raw_path = Path::new(raw); |
| 407 | enforce_read_denylist(raw_path, tool)?; |
| 408 | if !raw_path.is_absolute() && super::spec::resolve_home_path(raw)?.is_none() { |
| 409 | let workspace_candidate = context.workspace.join(raw_path); |
| 410 | if is_codewhale_credential_path(&workspace_candidate) { |
| 411 | return Err(ToolError::permission_denied(format!( |
| 412 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 413 | ))); |
| 414 | } |
| 415 | enforce_read_denylist_with_display(&workspace_candidate, raw_path, tool)?; |
| 416 | } |
| 417 | let path = if context.strict_workspace_confinement { |
| 418 | context.resolve_path(raw)? |
| 419 | } else { |
| 420 | resolve(context, raw)? |
| 421 | }; |
| 422 | if is_codewhale_credential_path(&path) { |
| 423 | return Err(ToolError::permission_denied(format!( |
| 424 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 425 | ))); |
| 426 | } |
| 427 | enforce_read_denylist_with_display(&path, raw_path, tool)?; |
| 428 | Ok(path) |
| 429 | } |
| 430 | |
| 431 | /// Workspace-escape fallback for the read-only image tools (`read`, |
| 432 | /// `read_media`): admit `raw` only when it is exactly an image the user |
| 433 | /// attached in this session's prompts. See |
| 434 | /// [`crate::image_attach::resolve_user_attached_image`] for the admission |
| 435 | /// rule; the credential and deny-list guards still apply here. `Ok(None)` |
| 436 | /// means "not admitted" and the caller keeps its original refusal. |
| 437 | /// |
| 438 | /// Known limit: a path the user mentioned only in prose, never attached, is |
| 439 | /// not admitted; `/trust add` remains the way to open a directory. |
| 440 | pub async fn user_attached_image_read_path( |
| 441 | context: &ToolContext, |
| 442 | raw: &str, |
| 443 | tool: &str, |
| 444 | ) -> Result<Option<PathBuf>, ToolError> { |
| 445 | let Some(snapshot) = context.session_objects.as_ref() else { |
| 446 | return Ok(None); |
| 447 | }; |
| 448 | let references = crate::image_attach::user_attached_image_references(&snapshot.messages); |
| 449 | if references.is_empty() { |
| 450 | return Ok(None); |
| 451 | } |
| 452 | let raw_owned = raw.to_string(); |
| 453 | let admitted = tokio::task::spawn_blocking(move || { |
| 454 | crate::image_attach::resolve_user_attached_image(&references, &raw_owned) |
| 455 | }) |
| 456 | .await |
| 457 | .map_err(|error| ToolError::execution_failed(format!("Failed to resolve {raw}: {error}")))?; |
| 458 | let Some(path) = admitted else { |
| 459 | return Ok(None); |
| 460 | }; |
| 461 | if is_codewhale_credential_path(&path) { |
| 462 | return Err(ToolError::permission_denied(format!( |
| 463 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 464 | ))); |
| 465 | } |
| 466 | enforce_read_denylist(&path, tool)?; |
| 467 | Ok(Some(path)) |
| 468 | } |
| 469 | |
| 470 | /// Refuse a read the sandbox read deny-list blocks (S1). |
| 471 | /// |
| 472 | /// `read_file`, `read`, and `read_media` all run *in-process*: they call |
| 473 | /// `std::fs` inside the harness, so `sandbox-exec` and `bwrap` never see them |
| 474 | /// and the OS-level deny rules do not apply. This is the enforcement point for |
| 475 | /// those tools, and the refusal is always an explicit error — never an empty |
| 476 | /// result, which would read as "the file is empty" and invite the model to |
| 477 | /// probe siblings. |
| 478 | pub fn enforce_read_denylist(path: &Path, tool: &str) -> Result<(), ToolError> { |
| 479 | enforce_read_denylist_with_display(path, path, tool) |
| 480 | } |
| 481 | |
| 482 | fn enforce_read_denylist_with_display( |
| 483 | check_path: &Path, |
| 484 | display_path: &Path, |
| 485 | tool: &str, |
| 486 | ) -> Result<(), ToolError> { |
| 487 | let home_path = check_path |
| 488 | .to_str() |
| 489 | .map(super::spec::resolve_home_path) |
| 490 | .transpose()? |
| 491 | .flatten(); |
| 492 | if home_path |
| 493 | .as_deref() |
| 494 | .is_some_and(is_codewhale_credential_path) |
| 495 | { |
| 496 | return Err(ToolError::permission_denied(format!( |
| 497 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 498 | ))); |
| 499 | } |
| 500 | match codewhale_sandbox::read_guard::active().check(home_path.as_deref().unwrap_or(check_path)) |
| 501 | { |
| 502 | Ok(()) => Ok(()), |
| 503 | Err(mut denial) => { |
| 504 | denial.requested = display_path.to_path_buf(); |
| 505 | let message = denial.message(tool); |
| 506 | tracing::warn!( |
| 507 | target: "codewhale::sandbox::read_guard", |
| 508 | requested = %denial.requested.display(), |
| 509 | via_symlink = denial.via_symlink, |
| 510 | tool = tool, |
| 511 | "sandbox read deny-list refused a read" |
| 512 | ); |
| 513 | Err(ToolError::permission_denied(message)) |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | pub fn working_set_read_allowed(path: &Path) -> bool { |
| 519 | enforce_read_denylist(path, "working_set").is_ok() |
| 520 | } |
| 521 | |
| 522 | /// Return whether `read_file` must refuse a CodeWhale-owned credential file. |
| 523 | /// |
| 524 | /// This is deliberately scoped to the active config, the two conventional |
| 525 | /// config locations (including one-time backups), and CodeWhale's file-backed |
| 526 | /// secret-store directories. Other dotfiles remain readable. Model-bound |
| 527 | /// redaction is still required because shell tools can read these files and |
| 528 | /// arbitrary commands can print credentials without reading a file at all. |
| 529 | pub fn is_codewhale_credential_path(path: &Path) -> bool { |
| 530 | let candidate = canonical_path_for_credential_guard(path); |
| 531 | |
| 532 | if let Ok(active_config) = codewhale_config::resolve_config_path(None) |
| 533 | && is_config_or_backup(&candidate, &active_config) |
| 534 | { |
| 535 | return true; |
| 536 | } |
| 537 | |
| 538 | // `CODEWHALE_HOME` relocates the *runtime* home; it is not a licence to read |
| 539 | // the user's real `~/.codewhale/config.toml`. `codewhale_home()` returns the |
| 540 | // override when one is set, so relying on it alone left the ambient store |
| 541 | // unguarded whenever that variable pointed elsewhere. Keep the ambient root |
| 542 | // in the set alongside the override, mirroring the deliberately |
| 543 | // unconditional `~/.codewhale/secrets` entry in `sandbox::read_guard` |
| 544 | // (read_guard.rs:481-487). `legacy_deepseek_home()` is already ambient by |
| 545 | // construction (paths/src/lib.rs:183-185), so it needs no counterpart. |
| 546 | let mut roots: Vec<PathBuf> = Vec::with_capacity(3); |
| 547 | roots.extend(codewhale_config::codewhale_home().ok()); |
| 548 | roots.extend(codewhale_config::legacy_deepseek_home().ok()); |
| 549 | roots.extend( |
| 550 | codewhale_paths::user_home().map(|home| home.join(codewhale_config::CODEWHALE_APP_DIR)), |
| 551 | ); |
| 552 | for root in roots { |
| 553 | if is_config_or_backup(&candidate, &root.join(codewhale_config::CONFIG_FILE_NAME)) { |
| 554 | return true; |
| 555 | } |
| 556 | |
| 557 | let secrets_dir = canonical_path_for_credential_guard(&root.join("secrets")); |
| 558 | if codewhale_sandbox::read_guard::path_is_within(&candidate, &secrets_dir) { |
| 559 | return true; |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | false |
| 564 | } |
| 565 | |
| 566 | // === small-contract-compatible primitive implementation helpers === |
| 567 | |
| 568 | /// Byte cap on selected output for one `read` call. Bytes are an internal |
| 569 | /// safety valve, not a model knob: the model's only paging vocabulary is |
| 570 | /// lines (`offset`/`limit`). |
| 571 | const READ_DEFAULT_MAX_BYTES: usize = 50 * 1024; |
| 572 | /// Default and maximum number of lines returned by one `read` call. |
| 573 | const READ_LIMIT_LINES: usize = 2_000; |
| 574 | /// Maximum characters returned for a single line; overflow is truncated |
| 575 | /// with a marker suffix. |
| 576 | const READ_MAX_LINE_CHARS: usize = 2_000; |
| 577 | /// Outer bound on the operator's process-wide `[workshop] read_result_max_bytes` |
| 578 | /// override, and therefore on any read result. |
| 579 | const READ_RESULT_ABSOLUTE_MAX_BYTES: usize = 2 * 1024 * 1024; |
| 580 | |
| 581 | /// Whole-source processing bound, independent of the model-visible read budget. |
| 582 | /// Verified file readers accept only regular, single-link files. |
| 583 | const CONTRACT_FILE_MAX_BYTES: usize = 16 * 1024 * 1024; |
| 584 | |
| 585 | fn check_contract_file_size(size: usize) -> Result<(), ToolError> { |
| 586 | if size > CONTRACT_FILE_MAX_BYTES { |
| 587 | return Err(ToolError::execution_failed( |
| 588 | "File content exceeds the supported 16 MiB processing cap. Split or export a smaller file, or use an appropriate separately authorized tool.", |
| 589 | )); |
| 590 | } |
| 591 | Ok(()) |
| 592 | } |
| 593 | |
| 594 | fn check_contract_cancelled(token: Option<&CancellationToken>) -> Result<(), ToolError> { |
| 595 | if token.is_some_and(CancellationToken::is_cancelled) { |
| 596 | return Err(ToolError::cancelled("Operation aborted")); |
| 597 | } |
| 598 | Ok(()) |
| 599 | } |
| 600 | |
| 601 | /// Read at most cap+1 actual bytes, including files that grow after metadata. |
| 602 | /// Cancellation is polled between bounded reads; it cannot interrupt an OS |
| 603 | /// syscall already in progress. This worker never mutates the file. |
| 604 | pub(super) fn read_contract_source( |
| 605 | reader: &mut impl std::io::Read, |
| 606 | cancel: Option<&CancellationToken>, |
| 607 | ) -> Result<Vec<u8>, ToolError> { |
| 608 | let mut bytes = Vec::new(); |
| 609 | let mut chunk = [0_u8; 64 * 1024]; |
| 610 | loop { |
| 611 | check_contract_cancelled(cancel)?; |
| 612 | let remaining = CONTRACT_FILE_MAX_BYTES + 1 - bytes.len(); |
| 613 | let read_len = remaining.min(chunk.len()); |
| 614 | let count = match reader.read(&mut chunk[..read_len]) { |
| 615 | Ok(count) => count, |
| 616 | Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, |
| 617 | Err(error) => { |
| 618 | return Err(ToolError::execution_failed(format!( |
| 619 | "Failed to read file: {error}" |
| 620 | ))); |
| 621 | } |
| 622 | }; |
| 623 | check_contract_cancelled(cancel)?; |
| 624 | if count == 0 { |
| 625 | return Ok(bytes); |
| 626 | } |
| 627 | bytes.extend_from_slice(&chunk[..count]); |
| 628 | check_contract_file_size(bytes.len())?; |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | fn map_contract_open_error( |
| 633 | error: std::io::Error, |
| 634 | display_path: &Path, |
| 635 | writable: bool, |
| 636 | ) -> ToolError { |
| 637 | let is_eloop = { |
| 638 | #[cfg(unix)] |
| 639 | { |
| 640 | error.raw_os_error() == Some(libc::ELOOP) |
| 641 | } |
| 642 | #[cfg(not(unix))] |
| 643 | { |
| 644 | false |
| 645 | } |
| 646 | }; |
| 647 | if !is_eloop |
| 648 | && fs::symlink_metadata(display_path).is_ok_and(|meta| { |
| 649 | meta.is_dir() && !codewhale_util::path_identity::metadata_is_link_or_reparse(&meta) |
| 650 | }) |
| 651 | { |
| 652 | return if writable { |
| 653 | ToolError::execution_failed(format!( |
| 654 | "Could not edit {}: path is a directory, not a file", |
| 655 | display_path.display() |
| 656 | )) |
| 657 | } else { |
| 658 | ToolError::execution_failed(format!( |
| 659 | "Failed to read {}: path is a directory; use file_search or list_dir to see its files", |
| 660 | display_path.display() |
| 661 | )) |
| 662 | }; |
| 663 | } |
| 664 | if writable && error.kind() == std::io::ErrorKind::PermissionDenied { |
| 665 | return ToolError::execution_failed(format!( |
| 666 | "Could not edit file {}: target must be readable and writable ({error})", |
| 667 | display_path.display() |
| 668 | )); |
| 669 | } |
| 670 | if is_confined_policy_error(&error) { |
| 671 | return map_confined_io_error(error, display_path, if writable { "edit" } else { "read" }); |
| 672 | } |
| 673 | if writable { |
| 674 | ToolError::execution_failed(format!( |
| 675 | "Could not edit file {}: target must be readable and writable ({error})", |
| 676 | display_path.display() |
| 677 | )) |
| 678 | } else { |
| 679 | ToolError::execution_failed(format!( |
| 680 | "Failed to read {}: {error}", |
| 681 | display_path.display() |
| 682 | )) |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | async fn load_contract_source( |
| 687 | plan: ReadOpenPlan, |
| 688 | writable: bool, |
| 689 | context: &ToolContext, |
| 690 | ) -> Result<Option<Vec<u8>>, ToolError> { |
| 691 | check_file_operation_cancelled(context)?; |
| 692 | let cancel = context.cancel_token.clone(); |
| 693 | let mut worker = tokio::task::spawn_blocking(move || { |
| 694 | check_contract_cancelled(cancel.as_ref())?; |
| 695 | let mut file = match &plan.target { |
| 696 | ReadOpenTarget::Workspace { |
| 697 | workspace_canonical, |
| 698 | relative, |
| 699 | display_path, |
| 700 | } => { |
| 701 | if relative.as_os_str().is_empty() { |
| 702 | return Err(if writable { |
| 703 | ToolError::execution_failed(format!( |
| 704 | "Could not edit {}: path is a directory, not a file", |
| 705 | display_path.display() |
| 706 | )) |
| 707 | } else { |
| 708 | ToolError::execution_failed(format!( |
| 709 | "Failed to read {}: path is a directory; use file_search or list_dir to see its files", |
| 710 | display_path.display() |
| 711 | )) |
| 712 | }); |
| 713 | } |
| 714 | let ws = match codewhale_util::files::WorkspaceFile::open_shared( |
| 715 | workspace_canonical, |
| 716 | relative, |
| 717 | false, |
| 718 | ) { |
| 719 | Ok(ws) => ws, |
| 720 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 721 | Err(error) => { |
| 722 | return Err(map_confined_io_error( |
| 723 | error, |
| 724 | display_path, |
| 725 | if writable { "edit" } else { "read" }, |
| 726 | )); |
| 727 | } |
| 728 | }; |
| 729 | let open_result = if writable { |
| 730 | ws.open_update(false, false) |
| 731 | } else { |
| 732 | ws.open_file_shared() |
| 733 | }; |
| 734 | match open_result { |
| 735 | Ok(file) => file, |
| 736 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 737 | Err(error) => { |
| 738 | return Err(map_contract_open_error(error, display_path, writable)); |
| 739 | } |
| 740 | } |
| 741 | } |
| 742 | ReadOpenTarget::Outside { path } => { |
| 743 | match open_outside_regular_file_with_write(path, true, writable) { |
| 744 | Ok(file) => file, |
| 745 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 746 | Err(error) => return Err(map_contract_open_error(error, path, writable)), |
| 747 | } |
| 748 | } |
| 749 | }; |
| 750 | verify_opened_read_file(&file, &plan.boundary)?; |
| 751 | let metadata = file |
| 752 | .metadata() |
| 753 | .map_err(|error| map_contract_open_error(error, &plan.file_path, writable))?; |
| 754 | if metadata.len() > CONTRACT_FILE_MAX_BYTES as u64 { |
| 755 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 756 | } |
| 757 | read_contract_source(&mut file, cancel.as_ref()).map(Some) |
| 758 | }); |
| 759 | let result = if let Some(cancel) = context.cancel_token.as_ref() { |
| 760 | tokio::select! { |
| 761 | biased; |
| 762 | () = cancel.cancelled() => return Err(ToolError::cancelled("Operation aborted")), |
| 763 | result = &mut worker => result, |
| 764 | } |
| 765 | } else { |
| 766 | worker.await |
| 767 | }; |
| 768 | result.map_err(|error| ToolError::execution_failed(format!("File read task: {error}")))? |
| 769 | } |
| 770 | |
| 771 | /// Resolve the byte cap for one `read` call: the operator's process-wide |
| 772 | /// `[workshop] read_result_max_bytes` override, clamped into |
| 773 | /// `[READ_DEFAULT_MAX_BYTES, READ_RESULT_ABSOLUTE_MAX_BYTES]` (2 MiB), or |
| 774 | /// [`READ_DEFAULT_MAX_BYTES`] when unset. The model cannot move it. |
| 775 | fn effective_read_max_bytes() -> usize { |
| 776 | codewhale_runtime::active_workshop::active_read_result_max_bytes() |
| 777 | .map_or(READ_DEFAULT_MAX_BYTES, |configured| { |
| 778 | configured.clamp(READ_DEFAULT_MAX_BYTES, READ_RESULT_ABSOLUTE_MAX_BYTES) |
| 779 | }) |
| 780 | } |
| 781 | |
| 782 | type FileMutationMutex = AsyncMutex<()>; |
| 783 | |
| 784 | /// File primitives can also be invoked outside the native engine's global |
| 785 | /// execution lock (for example by an embedded host). Keep writes to one path |
| 786 | /// ordered in those hosts without exposing any locking ceremony in the tool |
| 787 | /// schema or result. |
| 788 | fn file_mutation_lock(path: &Path) -> Result<Arc<FileMutationMutex>, ToolError> { |
| 789 | static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<FileMutationMutex>>>> = OnceLock::new(); |
| 790 | let locks = LOCKS.get_or_init(|| Mutex::new(HashMap::new())); |
| 791 | let mut locks = locks.lock().map_err(|_| { |
| 792 | ToolError::execution_failed( |
| 793 | "file mutation queue is unavailable because its lock was poisoned", |
| 794 | ) |
| 795 | })?; |
| 796 | locks.retain(|_, lock| lock.strong_count() > 0); |
| 797 | if let Some(lock) = locks.get(path).and_then(Weak::upgrade) { |
| 798 | return Ok(lock); |
| 799 | } |
| 800 | let lock = Arc::new(AsyncMutex::new(())); |
| 801 | locks.insert(path.to_path_buf(), Arc::downgrade(&lock)); |
| 802 | Ok(lock) |
| 803 | } |
| 804 | |
| 805 | async fn acquire_file_mutation( |
| 806 | path: &Path, |
| 807 | context: &ToolContext, |
| 808 | ) -> Result<OwnedMutexGuard<()>, ToolError> { |
| 809 | let lock = file_mutation_lock(path)?; |
| 810 | if let Some(cancel) = context.cancel_token.as_ref() { |
| 811 | tokio::select! { |
| 812 | guard = lock.lock_owned() => Ok(guard), |
| 813 | () = cancel.cancelled() => Err(ToolError::cancelled("Operation aborted")), |
| 814 | } |
| 815 | } else { |
| 816 | Ok(lock.lock_owned().await) |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | /// Atomic workspace write on the blocking pool: temp create plus fsync plus |
| 821 | /// rename (and a retry loop on Windows) must not park a Tokio worker |
| 822 | /// (blocking-call convention, #6149). Error shape matches the historical |
| 823 | /// inline call. |
| 824 | pub(super) async fn run_blocking_write_atomic( |
| 825 | path: &Path, |
| 826 | contents: Vec<u8>, |
| 827 | ) -> Result<(), ToolError> { |
| 828 | let path = path.to_path_buf(); |
| 829 | tokio::task::spawn_blocking(move || { |
| 830 | codewhale_util::utils::write_atomic_workspace(&path, &contents).map_err(|e| { |
| 831 | ToolError::execution_failed(format!("Failed to write {}: {e}", path.display())) |
| 832 | }) |
| 833 | }) |
| 834 | .await |
| 835 | .map_err(|e| ToolError::execution_failed(format!("File write task: {e}")))??; |
| 836 | Ok(()) |
| 837 | } |
| 838 | |
| 839 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 840 | enum ConfinedFileId { |
| 841 | #[cfg(unix)] |
| 842 | Unix { dev: u64, ino: u64 }, |
| 843 | #[cfg(windows)] |
| 844 | Windows { volume: u32, index: u64 }, |
| 845 | #[cfg(all(not(unix), not(windows)))] |
| 846 | Unsupported, |
| 847 | } |
| 848 | |
| 849 | fn confined_file_id(file: &fs::File) -> std::io::Result<ConfinedFileId> { |
| 850 | #[cfg(unix)] |
| 851 | { |
| 852 | use std::os::unix::fs::MetadataExt as _; |
| 853 | let meta = file.metadata()?; |
| 854 | Ok(ConfinedFileId::Unix { |
| 855 | dev: meta.dev(), |
| 856 | ino: meta.ino(), |
| 857 | }) |
| 858 | } |
| 859 | #[cfg(windows)] |
| 860 | { |
| 861 | let identity = codewhale_util::path_identity::windows_file_identity(file)?; |
| 862 | Ok(ConfinedFileId::Windows { |
| 863 | volume: identity.volume, |
| 864 | index: identity.index, |
| 865 | }) |
| 866 | } |
| 867 | #[cfg(all(not(unix), not(windows)))] |
| 868 | { |
| 869 | let _ = file; |
| 870 | Err(std::io::ErrorKind::Unsupported.into()) |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | fn is_confined_policy_error(error: &std::io::Error) -> bool { |
| 875 | #[cfg(unix)] |
| 876 | if error.raw_os_error() == Some(libc::ELOOP) { |
| 877 | return true; |
| 878 | } |
| 879 | #[cfg(windows)] |
| 880 | if error.kind() == std::io::ErrorKind::PermissionDenied { |
| 881 | return true; |
| 882 | } |
| 883 | matches!( |
| 884 | error.kind(), |
| 885 | std::io::ErrorKind::InvalidInput |
| 886 | | std::io::ErrorKind::InvalidData |
| 887 | | std::io::ErrorKind::AlreadyExists |
| 888 | ) |
| 889 | } |
| 890 | |
| 891 | fn map_confined_io_error(error: std::io::Error, path: &Path, action: &str) -> ToolError { |
| 892 | if is_confined_policy_error(&error) { |
| 893 | return ToolError::permission_denied(format!( |
| 894 | "{action} refused symlink or confined path constraint for {}: {error}", |
| 895 | path.display() |
| 896 | )); |
| 897 | } |
| 898 | ToolError::execution_failed(format!("Failed to {action} {}: {error}", path.display())) |
| 899 | } |
| 900 | |
| 901 | enum ConfinedPrior { |
| 902 | Missing, |
| 903 | Existing { bytes: Vec<u8>, id: ConfinedFileId }, |
| 904 | } |
| 905 | |
| 906 | fn write_uses_confined_io(context: &ToolContext) -> bool { |
| 907 | context.strict_workspace_confinement |
| 908 | || (!context.trust_mode |
| 909 | && !context.follow_symlinks |
| 910 | && context.trusted_external_paths.is_empty()) |
| 911 | } |
| 912 | |
| 913 | async fn resolve_confined_target_async( |
| 914 | context: &ToolContext, |
| 915 | raw: &str, |
| 916 | allow_root_dot: bool, |
| 917 | ) -> Result<(PathBuf, PathBuf), ToolError> { |
| 918 | let workspace_canonical = |
| 919 | tokio::fs::canonicalize(&context.workspace) |
| 920 | .await |
| 921 | .map_err(|error| { |
| 922 | ToolError::execution_failed(format!( |
| 923 | "Failed to canonicalize workspace {}: {error}", |
| 924 | context.workspace.display() |
| 925 | )) |
| 926 | })?; |
| 927 | let relative = |
| 928 | super::spec::resolve_confined_target(context, &workspace_canonical, raw, allow_root_dot)?; |
| 929 | Ok((workspace_canonical, relative)) |
| 930 | } |
| 931 | |
| 932 | fn resolve_confined_target_sync( |
| 933 | context: &ToolContext, |
| 934 | raw: &str, |
| 935 | allow_root_dot: bool, |
| 936 | ) -> Result<(PathBuf, PathBuf), ToolError> { |
| 937 | let workspace_canonical = fs::canonicalize(&context.workspace).map_err(|error| { |
| 938 | ToolError::execution_failed(format!( |
| 939 | "Failed to canonicalize workspace {}: {error}", |
| 940 | context.workspace.display() |
| 941 | )) |
| 942 | })?; |
| 943 | let relative = |
| 944 | super::spec::resolve_confined_target(context, &workspace_canonical, raw, allow_root_dot)?; |
| 945 | Ok((workspace_canonical, relative)) |
| 946 | } |
| 947 | |
| 948 | async fn load_confined_prior_file( |
| 949 | workspace_canonical: &Path, |
| 950 | relative: &Path, |
| 951 | display_path: &Path, |
| 952 | tool: &'static str, |
| 953 | raw_spelling: &str, |
| 954 | max_bytes: Option<usize>, |
| 955 | context: &ToolContext, |
| 956 | ) -> Result<ConfinedPrior, ToolError> { |
| 957 | check_file_operation_cancelled(context)?; |
| 958 | let workspace = workspace_canonical.to_path_buf(); |
| 959 | let relative = relative.to_path_buf(); |
| 960 | let display = display_path.to_path_buf(); |
| 961 | let boundary = OpenedReadBoundary::from_context( |
| 962 | context, |
| 963 | tool, |
| 964 | raw_spelling, |
| 965 | workspace_canonical.to_path_buf(), |
| 966 | None, |
| 967 | false, |
| 968 | ) |
| 969 | .await; |
| 970 | let cancel = context.cancel_token.clone(); |
| 971 | let mut worker = tokio::task::spawn_blocking(move || { |
| 972 | use std::io::Read as _; |
| 973 | check_contract_cancelled(cancel.as_ref())?; |
| 974 | let ws = |
| 975 | match codewhale_util::files::WorkspaceFile::open_shared(&workspace, &relative, false) { |
| 976 | Ok(ws) => ws, |
| 977 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 978 | return Ok(ConfinedPrior::Missing); |
| 979 | } |
| 980 | Err(error) => return Err(map_confined_io_error(error, &display, "inspect")), |
| 981 | }; |
| 982 | let mut file = match ws.open_file() { |
| 983 | Ok(file) => file, |
| 984 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 985 | return Ok(ConfinedPrior::Missing); |
| 986 | } |
| 987 | Err(error) => return Err(map_confined_io_error(error, &display, "read")), |
| 988 | }; |
| 989 | verify_opened_read_file(&file, &boundary)?; |
| 990 | let id = confined_file_id(&file) |
| 991 | .map_err(|error| map_confined_io_error(error, &display, "inspect"))?; |
| 992 | let bytes = if let Some(cap) = max_bytes { |
| 993 | let meta = file |
| 994 | .metadata() |
| 995 | .map_err(|error| map_confined_io_error(error, &display, "read"))?; |
| 996 | if meta.len() > cap as u64 { |
| 997 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 998 | } |
| 999 | read_contract_source(&mut file, cancel.as_ref())? |
| 1000 | } else { |
| 1001 | let mut bytes = Vec::new(); |
| 1002 | file.read_to_end(&mut bytes) |
| 1003 | .map_err(|error| map_confined_io_error(error, &display, "read"))?; |
| 1004 | bytes |
| 1005 | }; |
| 1006 | Ok(ConfinedPrior::Existing { bytes, id }) |
| 1007 | }); |
| 1008 | let result = if let Some(cancel) = context.cancel_token.as_ref() { |
| 1009 | tokio::select! { |
| 1010 | biased; |
| 1011 | () = cancel.cancelled() => return Err(ToolError::cancelled("Operation aborted")), |
| 1012 | result = &mut worker => result, |
| 1013 | } |
| 1014 | } else { |
| 1015 | worker.await |
| 1016 | }; |
| 1017 | result.map_err(|error| ToolError::execution_failed(format!("File read task: {error}")))? |
| 1018 | } |
| 1019 | |
| 1020 | async fn commit_confined_write( |
| 1021 | workspace_canonical: &Path, |
| 1022 | relative: &Path, |
| 1023 | display_path: &Path, |
| 1024 | expected_id: Option<ConfinedFileId>, |
| 1025 | contents: Vec<u8>, |
| 1026 | ) -> Result<(), ToolError> { |
| 1027 | let workspace = workspace_canonical.to_path_buf(); |
| 1028 | let relative = relative.to_path_buf(); |
| 1029 | let display = display_path.to_path_buf(); |
| 1030 | tokio::task::spawn_blocking(move || { |
| 1031 | let create = expected_id.is_none(); |
| 1032 | let ws = codewhale_util::files::WorkspaceFile::open_shared(&workspace, &relative, create) |
| 1033 | .map_err(|error| map_confined_io_error(error, &display, "write"))?; |
| 1034 | match expected_id { |
| 1035 | None => ws |
| 1036 | .publish(&contents) |
| 1037 | .map_err(|error| map_confined_io_error(error, &display, "write")), |
| 1038 | Some(prior_id) => { |
| 1039 | let probe = ws |
| 1040 | .identity_probe() |
| 1041 | .map_err(|error| map_confined_io_error(error, &display, "write"))?; |
| 1042 | let current_id = confined_file_id(&probe) |
| 1043 | .map_err(|error| map_confined_io_error(error, &display, "write"))?; |
| 1044 | if current_id != prior_id { |
| 1045 | return Err(ToolError::permission_denied(format!( |
| 1046 | "write target changed before replacement: {}", |
| 1047 | display.display() |
| 1048 | ))); |
| 1049 | } |
| 1050 | drop(probe); |
| 1051 | ws.replace(&contents) |
| 1052 | .map_err(|error| map_confined_io_error(error, &display, "write")) |
| 1053 | } |
| 1054 | } |
| 1055 | }) |
| 1056 | .await |
| 1057 | .map_err(|error| ToolError::execution_failed(format!("File write task: {error}")))? |
| 1058 | } |
| 1059 | |
| 1060 | fn check_file_operation_cancelled(context: &ToolContext) -> Result<(), ToolError> { |
| 1061 | check_contract_cancelled(context.cancel_token.as_ref()) |
| 1062 | } |
| 1063 | |
| 1064 | /// One `mutation.files[]` receipt entry. `size` and `sha256` describe the |
| 1065 | /// exact bytes this call wrote, recorded where they were written so a turn's |
| 1066 | /// artifact reference never has to re-read (and race) the disk. `sha256` is |
| 1067 | /// plain lowercase hex: the same value `GET /v1/workspace/files/read` reports |
| 1068 | /// as `revision`. |
| 1069 | pub fn mutation_file_entry(path: &str, outcome: &str, written: Option<&[u8]>) -> Value { |
| 1070 | let mut entry = json!({ "path": path, "outcome": outcome }); |
| 1071 | if let Some(bytes) = written { |
| 1072 | entry["size"] = json!(bytes.len()); |
| 1073 | entry["sha256"] = json!(codewhale_runtime::hashing::sha256_hex(bytes)); |
| 1074 | } |
| 1075 | entry |
| 1076 | } |
| 1077 | |
| 1078 | const CONTRACT_DIFF_MAX_LINES: usize = 120; |
| 1079 | const CONTRACT_DIFF_MAX_BYTES: usize = 6 * 1024; |
| 1080 | const CONTRACT_CREATE_PREVIEW_MAX_LINES: usize = 24; |
| 1081 | const CONTRACT_CREATE_PREVIEW_MAX_BYTES: usize = 1536; |
| 1082 | |
| 1083 | fn truncate_utf8_prefix(text: &str, max_bytes: usize) -> &str { |
| 1084 | if text.len() <= max_bytes { |
| 1085 | return text; |
| 1086 | } |
| 1087 | let mut end = max_bytes; |
| 1088 | while end > 0 && !text.is_char_boundary(end) { |
| 1089 | end -= 1; |
| 1090 | } |
| 1091 | &text[..end] |
| 1092 | } |
| 1093 | |
| 1094 | fn format_contract_mutation_content( |
| 1095 | summary: &str, |
| 1096 | outcome: &str, |
| 1097 | after: &str, |
| 1098 | diff: &str, |
| 1099 | ) -> String { |
| 1100 | let trimmed = diff.trim_end_matches('\n'); |
| 1101 | if trimmed.is_empty() { |
| 1102 | return summary.to_string(); |
| 1103 | } |
| 1104 | let (max_lines, max_bytes) = if outcome == "created" { |
| 1105 | ( |
| 1106 | CONTRACT_CREATE_PREVIEW_MAX_LINES, |
| 1107 | CONTRACT_CREATE_PREVIEW_MAX_BYTES, |
| 1108 | ) |
| 1109 | } else { |
| 1110 | (CONTRACT_DIFF_MAX_LINES, CONTRACT_DIFF_MAX_BYTES) |
| 1111 | }; |
| 1112 | let mut total_lines = 0usize; |
| 1113 | let mut added = 0usize; |
| 1114 | let mut removed = 0usize; |
| 1115 | for line in trimmed.lines() { |
| 1116 | total_lines += 1; |
| 1117 | if line.starts_with('+') && !line.starts_with("+++ ") { |
| 1118 | added += 1; |
| 1119 | } else if line.starts_with('-') && !line.starts_with("--- ") { |
| 1120 | removed += 1; |
| 1121 | } |
| 1122 | } |
| 1123 | if total_lines <= max_lines && trimmed.len() <= max_bytes { |
| 1124 | return format!("{summary}\n{trimmed}"); |
| 1125 | } |
| 1126 | let mut preview = String::new(); |
| 1127 | let mut kept_lines = 0usize; |
| 1128 | for line in trimmed.lines() { |
| 1129 | if kept_lines >= max_lines { |
| 1130 | break; |
| 1131 | } |
| 1132 | let sep = usize::from(!preview.is_empty()); |
| 1133 | if preview.len() + sep + line.len() > max_bytes { |
| 1134 | if preview.is_empty() { |
| 1135 | preview.push_str(truncate_utf8_prefix(line, max_bytes)); |
| 1136 | preview.push_str("..."); |
| 1137 | kept_lines = 1; |
| 1138 | } |
| 1139 | break; |
| 1140 | } |
| 1141 | if !preview.is_empty() { |
| 1142 | preview.push('\n'); |
| 1143 | } |
| 1144 | preview.push_str(line); |
| 1145 | kept_lines += 1; |
| 1146 | } |
| 1147 | let note = if outcome == "created" { |
| 1148 | format!( |
| 1149 | "... (diff truncated: created file has {} lines, {} bytes; showing {kept_lines} of {total_lines} diff lines)", |
| 1150 | after.lines().count(), |
| 1151 | after.len() |
| 1152 | ) |
| 1153 | } else { |
| 1154 | format!( |
| 1155 | "... (diff truncated: showing {kept_lines} of {total_lines} lines; +{added}/-{removed} changed lines total)" |
| 1156 | ) |
| 1157 | }; |
| 1158 | if preview.is_empty() { |
| 1159 | format!("{summary}\n{note}") |
| 1160 | } else { |
| 1161 | format!("{summary}\n{preview}\n{note}") |
| 1162 | } |
| 1163 | } |
| 1164 | |
| 1165 | fn contract_mutation_result( |
| 1166 | requested_path: &str, |
| 1167 | before: &str, |
| 1168 | after: &str, |
| 1169 | written: &[u8], |
| 1170 | outcome: &str, |
| 1171 | summary: String, |
| 1172 | ) -> ToolResult { |
| 1173 | let diff = make_unified_diff(requested_path, before, after); |
| 1174 | let content = format_contract_mutation_content(&summary, outcome, after, &diff); |
| 1175 | ToolResult::success(content).with_metadata(json!({ |
| 1176 | "event": "file.mutation", |
| 1177 | "mutation": { |
| 1178 | "diff": diff, |
| 1179 | "files": [mutation_file_entry(requested_path, outcome, Some(written))], |
| 1180 | "renames": [] |
| 1181 | } |
| 1182 | })) |
| 1183 | } |
| 1184 | |
| 1185 | pub(super) fn reject_primitive_unknown( |
| 1186 | input: &Value, |
| 1187 | tool: &str, |
| 1188 | allowed: &[&str], |
| 1189 | ) -> Result<(), ToolError> { |
| 1190 | let object = input |
| 1191 | .as_object() |
| 1192 | .ok_or_else(|| ToolError::invalid_input(format!("{tool} input must be an object")))?; |
| 1193 | let unexpected = object |
| 1194 | .keys() |
| 1195 | .filter(|key| !allowed.contains(&key.as_str())) |
| 1196 | .cloned() |
| 1197 | .collect::<Vec<_>>(); |
| 1198 | if unexpected.is_empty() { |
| 1199 | return Ok(()); |
| 1200 | } |
| 1201 | Err(ToolError::invalid_input(format!( |
| 1202 | "unexpected {tool} parameter(s): {}", |
| 1203 | unexpected.join(", ") |
| 1204 | ))) |
| 1205 | } |
| 1206 | |
| 1207 | fn contract_nonnegative_int(input: &Value, key: &str) -> Result<Option<usize>, ToolError> { |
| 1208 | let Some(value) = input.get(key) else { |
| 1209 | return Ok(None); |
| 1210 | }; |
| 1211 | let number = codewhale_tools::json_nonnegative_integer(value) |
| 1212 | .ok_or_else(|| ToolError::invalid_input(format!("{key} must be a non-negative integer")))?; |
| 1213 | usize::try_from(number) |
| 1214 | .map(Some) |
| 1215 | .map_err(|_| ToolError::invalid_input(format!("{key} exceeds platform range"))) |
| 1216 | } |
| 1217 | |
| 1218 | fn primitive_image_mime(bytes: &[u8]) -> Option<&'static str> { |
| 1219 | crate::image_attach::sniff_media_type(bytes).or_else(|| { |
| 1220 | (bytes.starts_with(b"BM") && bytes.get(6..10) == Some(&[0; 4][..])).then_some("image/bmp") |
| 1221 | }) |
| 1222 | } |
| 1223 | |
| 1224 | #[derive(Debug)] |
| 1225 | struct ContractReadWindow { |
| 1226 | content: String, |
| 1227 | shown_lines: usize, |
| 1228 | truncated_by_bytes: bool, |
| 1229 | line_truncated: bool, |
| 1230 | } |
| 1231 | |
| 1232 | fn contract_read_window( |
| 1233 | content: &str, |
| 1234 | first_line: usize, |
| 1235 | selected_lines: usize, |
| 1236 | last_line_has_lf: bool, |
| 1237 | max_bytes: usize, |
| 1238 | ) -> ContractReadWindow { |
| 1239 | let mut window = ContractReadWindow { |
| 1240 | content: String::new(), |
| 1241 | shown_lines: 0, |
| 1242 | truncated_by_bytes: false, |
| 1243 | line_truncated: false, |
| 1244 | }; |
| 1245 | if selected_lines == 0 { |
| 1246 | return window; |
| 1247 | } |
| 1248 | let mut output_bytes = 0usize; |
| 1249 | for (idx, raw_line) in content.split('\n').take(selected_lines).enumerate() { |
| 1250 | let has_lf = idx + 1 < selected_lines || last_line_has_lf; |
| 1251 | let line = if has_lf { |
| 1252 | raw_line.strip_suffix('\r').unwrap_or(raw_line) |
| 1253 | } else { |
| 1254 | raw_line |
| 1255 | }; |
| 1256 | let (text, truncated) = truncate_read_line(line); |
| 1257 | let line_no = first_line + idx; |
| 1258 | let rendered = format!("{line_no}: {text}"); |
| 1259 | let bytes = rendered.len() + usize::from(window.shown_lines > 0); |
| 1260 | if window.shown_lines > 0 && output_bytes.saturating_add(bytes) > max_bytes { |
| 1261 | window.truncated_by_bytes = true; |
| 1262 | break; |
| 1263 | } |
| 1264 | output_bytes += bytes; |
| 1265 | if window.shown_lines > 0 { |
| 1266 | window.content.push('\n'); |
| 1267 | } |
| 1268 | window.content.push_str(&rendered); |
| 1269 | window.shown_lines += 1; |
| 1270 | window.line_truncated |= truncated; |
| 1271 | } |
| 1272 | window |
| 1273 | } |
| 1274 | |
| 1275 | fn truncate_read_line(line: &str) -> (std::borrow::Cow<'_, str>, bool) { |
| 1276 | if line.len() <= READ_MAX_LINE_CHARS { |
| 1277 | return (std::borrow::Cow::Borrowed(line), false); |
| 1278 | } |
| 1279 | match line.char_indices().nth(READ_MAX_LINE_CHARS) { |
| 1280 | Some((byte_index, _)) => ( |
| 1281 | std::borrow::Cow::Owned(format!( |
| 1282 | "{}... [line truncated at {READ_MAX_LINE_CHARS} chars]", |
| 1283 | &line[..byte_index] |
| 1284 | )), |
| 1285 | true, |
| 1286 | ), |
| 1287 | None => (std::borrow::Cow::Borrowed(line), false), |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | #[cfg(target_vendor = "apple")] |
| 1292 | fn opened_file_canonical_path(file: &fs::File) -> std::io::Result<PathBuf> { |
| 1293 | use std::ffi::{CStr, OsStr}; |
| 1294 | use std::os::fd::AsRawFd as _; |
| 1295 | use std::os::unix::ffi::OsStrExt as _; |
| 1296 | |
| 1297 | let mut buffer = [0_u8; libc::PATH_MAX as usize]; |
| 1298 | if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buffer.as_mut_ptr()) } == -1 { |
| 1299 | return Err(std::io::Error::last_os_error()); |
| 1300 | } |
| 1301 | let path = CStr::from_bytes_until_nul(&buffer).map_err(|_| { |
| 1302 | std::io::Error::new( |
| 1303 | std::io::ErrorKind::InvalidData, |
| 1304 | "opened file path was not NUL-terminated", |
| 1305 | ) |
| 1306 | })?; |
| 1307 | Ok(PathBuf::from(OsStr::from_bytes(path.to_bytes()))) |
| 1308 | } |
| 1309 | |
| 1310 | #[cfg(all(unix, not(target_vendor = "apple")))] |
| 1311 | fn opened_file_canonical_path(file: &fs::File) -> std::io::Result<PathBuf> { |
| 1312 | use std::os::fd::AsRawFd as _; |
| 1313 | |
| 1314 | fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())) |
| 1315 | } |
| 1316 | |
| 1317 | #[cfg(windows)] |
| 1318 | fn opened_file_canonical_path(file: &fs::File) -> std::io::Result<PathBuf> { |
| 1319 | use std::ffi::OsString; |
| 1320 | use std::os::windows::ffi::OsStringExt as _; |
| 1321 | use std::os::windows::io::AsRawHandle as _; |
| 1322 | use windows_sys::Win32::Storage::FileSystem::{ |
| 1323 | FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW, VOLUME_NAME_DOS, |
| 1324 | }; |
| 1325 | |
| 1326 | let handle = file.as_raw_handle(); |
| 1327 | let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS; |
| 1328 | let needed = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) }; |
| 1329 | if needed == 0 { |
| 1330 | return Err(std::io::Error::last_os_error()); |
| 1331 | } |
| 1332 | let mut buffer = vec![0_u16; needed as usize + 1]; |
| 1333 | let written = unsafe { |
| 1334 | GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags) |
| 1335 | }; |
| 1336 | if written == 0 || written as usize >= buffer.len() { |
| 1337 | return Err(std::io::Error::last_os_error()); |
| 1338 | } |
| 1339 | Ok(PathBuf::from(OsString::from_wide( |
| 1340 | &buffer[..written as usize], |
| 1341 | ))) |
| 1342 | } |
| 1343 | |
| 1344 | #[cfg(all(not(unix), not(windows)))] |
| 1345 | fn opened_file_canonical_path(_file: &fs::File) -> std::io::Result<PathBuf> { |
| 1346 | Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) |
| 1347 | } |
| 1348 | |
| 1349 | fn opened_path_candidates(fd_path: PathBuf) -> Vec<PathBuf> { |
| 1350 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 1351 | { |
| 1352 | use std::ffi::OsStr; |
| 1353 | use std::os::unix::ffi::OsStrExt as _; |
| 1354 | const DELETED_SUFFIX: &[u8] = b" (deleted)"; |
| 1355 | let bytes = fd_path.as_os_str().as_bytes(); |
| 1356 | if let Some(stripped) = bytes.strip_suffix(DELETED_SUFFIX) |
| 1357 | && !stripped.is_empty() |
| 1358 | && !fd_path.exists() |
| 1359 | { |
| 1360 | return vec![PathBuf::from(OsStr::from_bytes(stripped)), fd_path]; |
| 1361 | } |
| 1362 | } |
| 1363 | vec![fd_path] |
| 1364 | } |
| 1365 | |
| 1366 | #[derive(Clone)] |
| 1367 | pub(super) struct OpenedReadBoundary { |
| 1368 | tool: &'static str, |
| 1369 | raw_spelling: PathBuf, |
| 1370 | trust_mode: bool, |
| 1371 | strict_workspace_confinement: bool, |
| 1372 | workspace_canonical: PathBuf, |
| 1373 | allowed_roots: Vec<PathBuf>, |
| 1374 | exact_allowed_file: Option<PathBuf>, |
| 1375 | } |
| 1376 | |
| 1377 | impl OpenedReadBoundary { |
| 1378 | pub(super) async fn from_context( |
| 1379 | context: &ToolContext, |
| 1380 | tool: &'static str, |
| 1381 | raw_spelling: &str, |
| 1382 | workspace_canonical: PathBuf, |
| 1383 | exact_allowed_file: Option<PathBuf>, |
| 1384 | allow_read_only_roots: bool, |
| 1385 | ) -> Self { |
| 1386 | let mut allowed_roots = Vec::new(); |
| 1387 | if !context.strict_workspace_confinement { |
| 1388 | let extra_roots = if allow_read_only_roots { |
| 1389 | context.read_only_roots.as_slice() |
| 1390 | } else { |
| 1391 | &[] |
| 1392 | }; |
| 1393 | let roots = context |
| 1394 | .trusted_external_paths |
| 1395 | .iter() |
| 1396 | .chain(extra_roots.iter()); |
| 1397 | for root in roots { |
| 1398 | let canonical = tokio::fs::canonicalize(root) |
| 1399 | .await |
| 1400 | .unwrap_or_else(|_| root.clone()); |
| 1401 | allowed_roots.push(canonical); |
| 1402 | } |
| 1403 | } |
| 1404 | let exact_allowed_file = match exact_allowed_file { |
| 1405 | Some(path) => Some(tokio::fs::canonicalize(&path).await.unwrap_or(path)), |
| 1406 | None => None, |
| 1407 | }; |
| 1408 | Self { |
| 1409 | tool, |
| 1410 | raw_spelling: PathBuf::from(raw_spelling), |
| 1411 | trust_mode: context.trust_mode, |
| 1412 | strict_workspace_confinement: context.strict_workspace_confinement, |
| 1413 | workspace_canonical, |
| 1414 | allowed_roots, |
| 1415 | exact_allowed_file, |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | fn from_context_sync( |
| 1420 | context: &ToolContext, |
| 1421 | tool: &'static str, |
| 1422 | raw_spelling: &str, |
| 1423 | workspace_canonical: PathBuf, |
| 1424 | exact_allowed_file: Option<PathBuf>, |
| 1425 | allow_read_only_roots: bool, |
| 1426 | ) -> Self { |
| 1427 | let mut allowed_roots = Vec::new(); |
| 1428 | if !context.strict_workspace_confinement { |
| 1429 | let extra_roots = if allow_read_only_roots { |
| 1430 | context.read_only_roots.as_slice() |
| 1431 | } else { |
| 1432 | &[] |
| 1433 | }; |
| 1434 | let roots = context |
| 1435 | .trusted_external_paths |
| 1436 | .iter() |
| 1437 | .chain(extra_roots.iter()); |
| 1438 | for root in roots { |
| 1439 | let canonical = fs::canonicalize(root).unwrap_or_else(|_| root.clone()); |
| 1440 | allowed_roots.push(canonical); |
| 1441 | } |
| 1442 | } |
| 1443 | let exact_allowed_file = |
| 1444 | exact_allowed_file.map(|path| fs::canonicalize(&path).unwrap_or(path)); |
| 1445 | Self { |
| 1446 | tool, |
| 1447 | raw_spelling: PathBuf::from(raw_spelling), |
| 1448 | trust_mode: context.trust_mode, |
| 1449 | strict_workspace_confinement: context.strict_workspace_confinement, |
| 1450 | workspace_canonical, |
| 1451 | allowed_roots, |
| 1452 | exact_allowed_file, |
| 1453 | } |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | fn verify_opened_read_file( |
| 1458 | file: &fs::File, |
| 1459 | boundary: &OpenedReadBoundary, |
| 1460 | ) -> Result<PathBuf, ToolError> { |
| 1461 | let fd_path = opened_file_canonical_path(file).map_err(|error| { |
| 1462 | ToolError::permission_denied(format!( |
| 1463 | "{} could not verify opened file path for {}: {error}", |
| 1464 | boundary.tool, |
| 1465 | boundary.raw_spelling.display() |
| 1466 | )) |
| 1467 | })?; |
| 1468 | for candidate in opened_path_candidates(fd_path.clone()) { |
| 1469 | if is_codewhale_credential_path(&candidate) { |
| 1470 | return Err(ToolError::permission_denied(format!( |
| 1471 | "{} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 1472 | boundary.tool |
| 1473 | ))); |
| 1474 | } |
| 1475 | enforce_read_denylist_with_display(&candidate, &boundary.raw_spelling, boundary.tool)?; |
| 1476 | let within_workspace = !boundary.workspace_canonical.as_os_str().is_empty() |
| 1477 | && codewhale_sandbox::read_guard::path_is_within( |
| 1478 | &candidate, |
| 1479 | &boundary.workspace_canonical, |
| 1480 | ); |
| 1481 | let within_allowed_root = !boundary.strict_workspace_confinement |
| 1482 | && boundary |
| 1483 | .allowed_roots |
| 1484 | .iter() |
| 1485 | .any(|root| codewhale_sandbox::read_guard::path_is_within(&candidate, root)); |
| 1486 | let matches_exact_allowed = boundary |
| 1487 | .exact_allowed_file |
| 1488 | .as_deref() |
| 1489 | .is_some_and(|allowed| codewhale_sandbox::read_guard::paths_match(&candidate, allowed)); |
| 1490 | let trust_allowed = !boundary.strict_workspace_confinement && boundary.trust_mode; |
| 1491 | if !(within_workspace || within_allowed_root || matches_exact_allowed || trust_allowed) { |
| 1492 | return Err(ToolError::permission_denied(format!( |
| 1493 | "{} refused opened file outside allowed roots for {}", |
| 1494 | boundary.tool, |
| 1495 | boundary.raw_spelling.display() |
| 1496 | ))); |
| 1497 | } |
| 1498 | } |
| 1499 | Ok(fd_path) |
| 1500 | } |
| 1501 | |
| 1502 | #[derive(Clone)] |
| 1503 | enum ReadOpenTarget { |
| 1504 | Workspace { |
| 1505 | workspace_canonical: PathBuf, |
| 1506 | relative: PathBuf, |
| 1507 | display_path: PathBuf, |
| 1508 | }, |
| 1509 | Outside { |
| 1510 | path: PathBuf, |
| 1511 | }, |
| 1512 | } |
| 1513 | |
| 1514 | #[derive(Clone)] |
| 1515 | pub(super) struct ReadOpenPlan { |
| 1516 | target: ReadOpenTarget, |
| 1517 | pub(super) file_path: PathBuf, |
| 1518 | boundary: OpenedReadBoundary, |
| 1519 | } |
| 1520 | |
| 1521 | fn build_read_open_target(workspace_canonical: &Path, file_path: &Path) -> ReadOpenTarget { |
| 1522 | if !workspace_canonical.as_os_str().is_empty() |
| 1523 | && let Ok(relative) = file_path.strip_prefix(workspace_canonical) |
| 1524 | && (relative.as_os_str().is_empty() || codewhale_util::files::path_is_confined(relative)) |
| 1525 | { |
| 1526 | ReadOpenTarget::Workspace { |
| 1527 | workspace_canonical: workspace_canonical.to_path_buf(), |
| 1528 | relative: relative.to_path_buf(), |
| 1529 | display_path: file_path.to_path_buf(), |
| 1530 | } |
| 1531 | } else { |
| 1532 | ReadOpenTarget::Outside { |
| 1533 | path: file_path.to_path_buf(), |
| 1534 | } |
| 1535 | } |
| 1536 | } |
| 1537 | |
| 1538 | pub(super) async fn resolve_read_open_plan( |
| 1539 | context: &ToolContext, |
| 1540 | raw: &str, |
| 1541 | tool: &'static str, |
| 1542 | allow_user_attached_image: bool, |
| 1543 | allow_read_only_roots: bool, |
| 1544 | ) -> Result<ReadOpenPlan, ToolError> { |
| 1545 | if context.strict_workspace_confinement { |
| 1546 | enforce_read_denylist(Path::new(raw), tool)?; |
| 1547 | let (workspace_canonical, relative) = |
| 1548 | resolve_confined_target_async(context, raw, false).await?; |
| 1549 | let file_path = workspace_canonical.join(&relative); |
| 1550 | if is_codewhale_credential_path(&file_path) { |
| 1551 | return Err(ToolError::permission_denied(format!( |
| 1552 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1553 | ))); |
| 1554 | } |
| 1555 | enforce_read_denylist_with_display(&file_path, Path::new(raw), tool)?; |
| 1556 | let boundary = OpenedReadBoundary::from_context( |
| 1557 | context, |
| 1558 | tool, |
| 1559 | raw, |
| 1560 | workspace_canonical.clone(), |
| 1561 | None, |
| 1562 | allow_read_only_roots, |
| 1563 | ) |
| 1564 | .await; |
| 1565 | return Ok(ReadOpenPlan { |
| 1566 | target: ReadOpenTarget::Workspace { |
| 1567 | workspace_canonical, |
| 1568 | relative, |
| 1569 | display_path: file_path.clone(), |
| 1570 | }, |
| 1571 | file_path, |
| 1572 | boundary, |
| 1573 | }); |
| 1574 | } |
| 1575 | |
| 1576 | let mut exact_allowed_file = None; |
| 1577 | let resolved = if allow_read_only_roots { |
| 1578 | resolve_guarded_display_path(context, raw, tool) |
| 1579 | } else { |
| 1580 | resolve_guarded_read_path(context, raw, tool) |
| 1581 | }; |
| 1582 | let file_path = match resolved { |
| 1583 | Ok(path) => path, |
| 1584 | Err(error @ ToolError::PathEscape { .. }) if allow_user_attached_image => { |
| 1585 | let admitted = user_attached_image_read_path(context, raw, tool) |
| 1586 | .await? |
| 1587 | .ok_or(error)?; |
| 1588 | exact_allowed_file = Some(admitted.clone()); |
| 1589 | admitted |
| 1590 | } |
| 1591 | Err(error) => return Err(error), |
| 1592 | }; |
| 1593 | if exact_allowed_file.is_none() && context.follow_symlinks { |
| 1594 | exact_allowed_file = Some(file_path.clone()); |
| 1595 | } |
| 1596 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 1597 | .await |
| 1598 | .unwrap_or_else(|_| context.workspace.clone()); |
| 1599 | let target = build_read_open_target(&workspace_canonical, &file_path); |
| 1600 | let boundary = OpenedReadBoundary::from_context( |
| 1601 | context, |
| 1602 | tool, |
| 1603 | raw, |
| 1604 | workspace_canonical, |
| 1605 | exact_allowed_file, |
| 1606 | allow_read_only_roots, |
| 1607 | ) |
| 1608 | .await; |
| 1609 | Ok(ReadOpenPlan { |
| 1610 | target, |
| 1611 | file_path, |
| 1612 | boundary, |
| 1613 | }) |
| 1614 | } |
| 1615 | |
| 1616 | pub(super) fn resolve_read_open_plan_sync( |
| 1617 | context: &ToolContext, |
| 1618 | raw: &str, |
| 1619 | tool: &'static str, |
| 1620 | allow_read_only_roots: bool, |
| 1621 | ) -> Result<ReadOpenPlan, ToolError> { |
| 1622 | if context.strict_workspace_confinement { |
| 1623 | enforce_read_denylist(Path::new(raw), tool)?; |
| 1624 | let (workspace_canonical, relative) = resolve_confined_target_sync(context, raw, false)?; |
| 1625 | let file_path = workspace_canonical.join(&relative); |
| 1626 | if is_codewhale_credential_path(&file_path) { |
| 1627 | return Err(ToolError::permission_denied(format!( |
| 1628 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1629 | ))); |
| 1630 | } |
| 1631 | enforce_read_denylist_with_display(&file_path, Path::new(raw), tool)?; |
| 1632 | let boundary = OpenedReadBoundary::from_context_sync( |
| 1633 | context, |
| 1634 | tool, |
| 1635 | raw, |
| 1636 | workspace_canonical.clone(), |
| 1637 | None, |
| 1638 | allow_read_only_roots, |
| 1639 | ); |
| 1640 | return Ok(ReadOpenPlan { |
| 1641 | target: ReadOpenTarget::Workspace { |
| 1642 | workspace_canonical, |
| 1643 | relative, |
| 1644 | display_path: file_path.clone(), |
| 1645 | }, |
| 1646 | file_path, |
| 1647 | boundary, |
| 1648 | }); |
| 1649 | } |
| 1650 | |
| 1651 | let file_path = if allow_read_only_roots { |
| 1652 | resolve_guarded_display_path(context, raw, tool)? |
| 1653 | } else { |
| 1654 | resolve_guarded_read_path(context, raw, tool)? |
| 1655 | }; |
| 1656 | let exact_allowed_file = context.follow_symlinks.then(|| file_path.clone()); |
| 1657 | let workspace_canonical = |
| 1658 | fs::canonicalize(&context.workspace).unwrap_or_else(|_| context.workspace.clone()); |
| 1659 | let target = build_read_open_target(&workspace_canonical, &file_path); |
| 1660 | let boundary = OpenedReadBoundary::from_context_sync( |
| 1661 | context, |
| 1662 | tool, |
| 1663 | raw, |
| 1664 | workspace_canonical, |
| 1665 | exact_allowed_file, |
| 1666 | allow_read_only_roots, |
| 1667 | ); |
| 1668 | Ok(ReadOpenPlan { |
| 1669 | target, |
| 1670 | file_path, |
| 1671 | boundary, |
| 1672 | }) |
| 1673 | } |
| 1674 | |
| 1675 | async fn resolve_write_preread_plan( |
| 1676 | context: &ToolContext, |
| 1677 | raw: &str, |
| 1678 | tool: &'static str, |
| 1679 | ) -> Result<ReadOpenPlan, ToolError> { |
| 1680 | if context.strict_workspace_confinement { |
| 1681 | let (workspace_canonical, relative) = |
| 1682 | resolve_confined_target_async(context, raw, false).await?; |
| 1683 | let file_path = workspace_canonical.join(&relative); |
| 1684 | if is_codewhale_credential_path(&file_path) { |
| 1685 | return Err(ToolError::permission_denied(format!( |
| 1686 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1687 | ))); |
| 1688 | } |
| 1689 | let boundary = OpenedReadBoundary::from_context( |
| 1690 | context, |
| 1691 | tool, |
| 1692 | raw, |
| 1693 | workspace_canonical.clone(), |
| 1694 | None, |
| 1695 | false, |
| 1696 | ) |
| 1697 | .await; |
| 1698 | return Ok(ReadOpenPlan { |
| 1699 | target: ReadOpenTarget::Workspace { |
| 1700 | workspace_canonical, |
| 1701 | relative, |
| 1702 | display_path: file_path.clone(), |
| 1703 | }, |
| 1704 | file_path, |
| 1705 | boundary, |
| 1706 | }); |
| 1707 | } |
| 1708 | |
| 1709 | let raw_path = Path::new(raw); |
| 1710 | if !raw_path.is_absolute() && super::spec::resolve_home_path(raw)?.is_none() { |
| 1711 | let workspace_candidate = context.workspace.join(raw_path); |
| 1712 | if is_codewhale_credential_path(&workspace_candidate) { |
| 1713 | return Err(ToolError::permission_denied(format!( |
| 1714 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1715 | ))); |
| 1716 | } |
| 1717 | } |
| 1718 | let file_path = context.resolve_path(raw)?; |
| 1719 | if is_codewhale_credential_path(&file_path) { |
| 1720 | return Err(ToolError::permission_denied(format!( |
| 1721 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1722 | ))); |
| 1723 | } |
| 1724 | let exact_allowed_file = context.follow_symlinks.then(|| file_path.clone()); |
| 1725 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 1726 | .await |
| 1727 | .unwrap_or_else(|_| context.workspace.clone()); |
| 1728 | let target = build_read_open_target(&workspace_canonical, &file_path); |
| 1729 | let boundary = OpenedReadBoundary::from_context( |
| 1730 | context, |
| 1731 | tool, |
| 1732 | raw, |
| 1733 | workspace_canonical, |
| 1734 | exact_allowed_file, |
| 1735 | false, |
| 1736 | ) |
| 1737 | .await; |
| 1738 | Ok(ReadOpenPlan { |
| 1739 | target, |
| 1740 | file_path, |
| 1741 | boundary, |
| 1742 | }) |
| 1743 | } |
| 1744 | |
| 1745 | pub(super) fn resolve_write_preread_plan_sync( |
| 1746 | context: &ToolContext, |
| 1747 | raw: &str, |
| 1748 | tool: &'static str, |
| 1749 | ) -> Result<ReadOpenPlan, ToolError> { |
| 1750 | if context.strict_workspace_confinement { |
| 1751 | let (workspace_canonical, relative) = resolve_confined_target_sync(context, raw, false)?; |
| 1752 | let file_path = workspace_canonical.join(&relative); |
| 1753 | if is_codewhale_credential_path(&file_path) { |
| 1754 | return Err(ToolError::permission_denied(format!( |
| 1755 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1756 | ))); |
| 1757 | } |
| 1758 | let boundary = OpenedReadBoundary::from_context_sync( |
| 1759 | context, |
| 1760 | tool, |
| 1761 | raw, |
| 1762 | workspace_canonical.clone(), |
| 1763 | None, |
| 1764 | false, |
| 1765 | ); |
| 1766 | return Ok(ReadOpenPlan { |
| 1767 | target: ReadOpenTarget::Workspace { |
| 1768 | workspace_canonical, |
| 1769 | relative, |
| 1770 | display_path: file_path.clone(), |
| 1771 | }, |
| 1772 | file_path, |
| 1773 | boundary, |
| 1774 | }); |
| 1775 | } |
| 1776 | |
| 1777 | let raw_path = Path::new(raw); |
| 1778 | if !raw_path.is_absolute() && super::spec::resolve_home_path(raw)?.is_none() { |
| 1779 | let workspace_candidate = context.workspace.join(raw_path); |
| 1780 | if is_codewhale_credential_path(&workspace_candidate) { |
| 1781 | return Err(ToolError::permission_denied(format!( |
| 1782 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1783 | ))); |
| 1784 | } |
| 1785 | } |
| 1786 | let file_path = context.resolve_path(raw)?; |
| 1787 | if is_codewhale_credential_path(&file_path) { |
| 1788 | return Err(ToolError::permission_denied(format!( |
| 1789 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1790 | ))); |
| 1791 | } |
| 1792 | let exact_allowed_file = context.follow_symlinks.then(|| file_path.clone()); |
| 1793 | let workspace_canonical = |
| 1794 | fs::canonicalize(&context.workspace).unwrap_or_else(|_| context.workspace.clone()); |
| 1795 | let target = build_read_open_target(&workspace_canonical, &file_path); |
| 1796 | let boundary = OpenedReadBoundary::from_context_sync( |
| 1797 | context, |
| 1798 | tool, |
| 1799 | raw, |
| 1800 | workspace_canonical, |
| 1801 | exact_allowed_file, |
| 1802 | false, |
| 1803 | ); |
| 1804 | Ok(ReadOpenPlan { |
| 1805 | target, |
| 1806 | file_path, |
| 1807 | boundary, |
| 1808 | }) |
| 1809 | } |
| 1810 | |
| 1811 | pub(super) async fn resolve_guarded_search_root( |
| 1812 | context: &ToolContext, |
| 1813 | raw: &str, |
| 1814 | tool: &'static str, |
| 1815 | allow_read_only_roots: bool, |
| 1816 | ) -> Result<(PathBuf, PathBuf), ToolError> { |
| 1817 | if context.strict_workspace_confinement { |
| 1818 | enforce_read_denylist(Path::new(raw), tool)?; |
| 1819 | let (workspace_canonical, relative) = |
| 1820 | resolve_confined_target_async(context, raw, true).await?; |
| 1821 | let search_path = workspace_canonical.join(&relative); |
| 1822 | if is_codewhale_credential_path(&search_path) { |
| 1823 | return Err(ToolError::permission_denied(format!( |
| 1824 | "{tool} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection" |
| 1825 | ))); |
| 1826 | } |
| 1827 | enforce_read_denylist_with_display(&search_path, Path::new(raw), tool)?; |
| 1828 | return Ok((search_path, workspace_canonical)); |
| 1829 | } |
| 1830 | let search_path = if allow_read_only_roots { |
| 1831 | resolve_guarded_display_path(context, raw, tool)? |
| 1832 | } else { |
| 1833 | resolve_guarded_read_path(context, raw, tool)? |
| 1834 | }; |
| 1835 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 1836 | .await |
| 1837 | .unwrap_or_else(|_| context.workspace.clone()); |
| 1838 | Ok((search_path, workspace_canonical)) |
| 1839 | } |
| 1840 | |
| 1841 | pub(super) async fn resolve_read_open_plan_for_media( |
| 1842 | context: &ToolContext, |
| 1843 | raw: &str, |
| 1844 | ) -> Result<ReadOpenPlan, ToolError> { |
| 1845 | let resolve_stored = || { |
| 1846 | context |
| 1847 | .runtime |
| 1848 | .media_originals_dir |
| 1849 | .as_deref() |
| 1850 | .and_then(|dir| { |
| 1851 | codewhale_runtime::media_originals::resolve_stored_original( |
| 1852 | raw, |
| 1853 | &context.workspace, |
| 1854 | dir, |
| 1855 | ) |
| 1856 | }) |
| 1857 | }; |
| 1858 | |
| 1859 | if context.strict_workspace_confinement { |
| 1860 | enforce_read_denylist(Path::new(raw), "read_media")?; |
| 1861 | match resolve_confined_target_async(context, raw, false).await { |
| 1862 | Ok((workspace_canonical, relative)) => { |
| 1863 | let file_path = workspace_canonical.join(&relative); |
| 1864 | if is_codewhale_credential_path(&file_path) { |
| 1865 | return Err(ToolError::permission_denied( |
| 1866 | "read_media cannot read Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 1867 | )); |
| 1868 | } |
| 1869 | enforce_read_denylist_with_display(&file_path, Path::new(raw), "read_media")?; |
| 1870 | let boundary = OpenedReadBoundary::from_context( |
| 1871 | context, |
| 1872 | "read_media", |
| 1873 | raw, |
| 1874 | workspace_canonical.clone(), |
| 1875 | None, |
| 1876 | false, |
| 1877 | ) |
| 1878 | .await; |
| 1879 | return Ok(ReadOpenPlan { |
| 1880 | target: ReadOpenTarget::Workspace { |
| 1881 | workspace_canonical, |
| 1882 | relative, |
| 1883 | display_path: file_path.clone(), |
| 1884 | }, |
| 1885 | file_path, |
| 1886 | boundary, |
| 1887 | }); |
| 1888 | } |
| 1889 | Err(primary_err) => { |
| 1890 | let Some(stored) = resolve_stored() else { |
| 1891 | return Err(primary_err); |
| 1892 | }; |
| 1893 | if is_codewhale_credential_path(&stored) { |
| 1894 | return Err(ToolError::permission_denied( |
| 1895 | "read_media cannot read Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 1896 | )); |
| 1897 | } |
| 1898 | enforce_read_denylist_with_display(&stored, Path::new(raw), "read_media")?; |
| 1899 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 1900 | .await |
| 1901 | .unwrap_or_else(|_| context.workspace.clone()); |
| 1902 | let boundary = OpenedReadBoundary::from_context( |
| 1903 | context, |
| 1904 | "read_media", |
| 1905 | raw, |
| 1906 | workspace_canonical, |
| 1907 | Some(stored.clone()), |
| 1908 | false, |
| 1909 | ) |
| 1910 | .await; |
| 1911 | return Ok(ReadOpenPlan { |
| 1912 | target: ReadOpenTarget::Outside { |
| 1913 | path: stored.clone(), |
| 1914 | }, |
| 1915 | file_path: stored, |
| 1916 | boundary, |
| 1917 | }); |
| 1918 | } |
| 1919 | } |
| 1920 | } |
| 1921 | |
| 1922 | enforce_read_denylist(Path::new(raw), "read_media")?; |
| 1923 | let mut exact_allowed_file = None; |
| 1924 | let file_path = match context.resolve_path(raw) { |
| 1925 | Ok(path) => path, |
| 1926 | Err(primary_err) => match resolve_stored() { |
| 1927 | Some(stored) => { |
| 1928 | exact_allowed_file = Some(stored.clone()); |
| 1929 | stored |
| 1930 | } |
| 1931 | None if matches!(primary_err, ToolError::PathEscape { .. }) => { |
| 1932 | let admitted = user_attached_image_read_path(context, raw, "read_media") |
| 1933 | .await? |
| 1934 | .ok_or(primary_err)?; |
| 1935 | exact_allowed_file = Some(admitted.clone()); |
| 1936 | admitted |
| 1937 | } |
| 1938 | None => return Err(primary_err), |
| 1939 | }, |
| 1940 | }; |
| 1941 | if is_codewhale_credential_path(&file_path) { |
| 1942 | return Err(ToolError::permission_denied( |
| 1943 | "read_media cannot read Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 1944 | )); |
| 1945 | } |
| 1946 | enforce_read_denylist_with_display(&file_path, Path::new(raw), "read_media")?; |
| 1947 | if exact_allowed_file.is_none() && context.follow_symlinks { |
| 1948 | exact_allowed_file = Some(file_path.clone()); |
| 1949 | } |
| 1950 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 1951 | .await |
| 1952 | .unwrap_or_else(|_| context.workspace.clone()); |
| 1953 | let target = build_read_open_target(&workspace_canonical, &file_path); |
| 1954 | let boundary = OpenedReadBoundary::from_context( |
| 1955 | context, |
| 1956 | "read_media", |
| 1957 | raw, |
| 1958 | workspace_canonical, |
| 1959 | exact_allowed_file, |
| 1960 | false, |
| 1961 | ) |
| 1962 | .await; |
| 1963 | Ok(ReadOpenPlan { |
| 1964 | target, |
| 1965 | file_path, |
| 1966 | boundary, |
| 1967 | }) |
| 1968 | } |
| 1969 | |
| 1970 | fn open_outside_regular_file(path: &Path, require_single_link: bool) -> std::io::Result<fs::File> { |
| 1971 | open_outside_regular_file_with_write(path, require_single_link, false) |
| 1972 | } |
| 1973 | |
| 1974 | fn open_outside_regular_file_with_write( |
| 1975 | path: &Path, |
| 1976 | require_single_link: bool, |
| 1977 | writable: bool, |
| 1978 | ) -> std::io::Result<fs::File> { |
| 1979 | let mut options = fs::OpenOptions::new(); |
| 1980 | options.read(true).write(writable); |
| 1981 | #[cfg(unix)] |
| 1982 | { |
| 1983 | use std::os::unix::fs::OpenOptionsExt as _; |
| 1984 | options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK); |
| 1985 | } |
| 1986 | #[cfg(windows)] |
| 1987 | { |
| 1988 | use std::os::windows::fs::OpenOptionsExt as _; |
| 1989 | options.custom_flags(0x0020_0000); |
| 1990 | } |
| 1991 | let file = options.open(path)?; |
| 1992 | let metadata = file.metadata()?; |
| 1993 | if !metadata.is_file() || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) |
| 1994 | { |
| 1995 | return Err(std::io::Error::new( |
| 1996 | std::io::ErrorKind::InvalidData, |
| 1997 | "target must be a regular file", |
| 1998 | )); |
| 1999 | } |
| 2000 | if require_single_link { |
| 2001 | #[cfg(unix)] |
| 2002 | { |
| 2003 | use std::os::unix::fs::MetadataExt as _; |
| 2004 | if metadata.nlink() != 1 { |
| 2005 | return Err(std::io::Error::new( |
| 2006 | std::io::ErrorKind::InvalidData, |
| 2007 | "target must be a regular, non-hard-linked file", |
| 2008 | )); |
| 2009 | } |
| 2010 | } |
| 2011 | #[cfg(windows)] |
| 2012 | { |
| 2013 | if codewhale_util::path_identity::windows_file_identity(&file)?.links != 1 { |
| 2014 | return Err(std::io::Error::new( |
| 2015 | std::io::ErrorKind::InvalidData, |
| 2016 | "target must be a regular, non-hard-linked file", |
| 2017 | )); |
| 2018 | } |
| 2019 | } |
| 2020 | } |
| 2021 | Ok(file) |
| 2022 | } |
| 2023 | |
| 2024 | fn map_read_open_error( |
| 2025 | error: std::io::Error, |
| 2026 | display_path: &Path, |
| 2027 | confined: bool, |
| 2028 | directory_hint: bool, |
| 2029 | ) -> ToolError { |
| 2030 | if error.kind() == std::io::ErrorKind::NotFound { |
| 2031 | return ToolError::execution_failed(format!( |
| 2032 | "Failed to read {}: {error}", |
| 2033 | display_path.display() |
| 2034 | )); |
| 2035 | } |
| 2036 | let is_eloop = { |
| 2037 | #[cfg(unix)] |
| 2038 | { |
| 2039 | error.raw_os_error() == Some(libc::ELOOP) |
| 2040 | } |
| 2041 | #[cfg(not(unix))] |
| 2042 | { |
| 2043 | false |
| 2044 | } |
| 2045 | }; |
| 2046 | if !is_eloop && fs::symlink_metadata(display_path).is_ok_and(|meta| meta.is_dir()) { |
| 2047 | return if directory_hint { |
| 2048 | ToolError::execution_failed(format!( |
| 2049 | "Failed to read {}: path is a directory; use file_search or list_dir to see its files", |
| 2050 | display_path.display() |
| 2051 | )) |
| 2052 | } else { |
| 2053 | ToolError::execution_failed(format!( |
| 2054 | "Failed to read {}: path is a directory", |
| 2055 | display_path.display() |
| 2056 | )) |
| 2057 | }; |
| 2058 | } |
| 2059 | if confined || is_confined_policy_error(&error) { |
| 2060 | return map_confined_io_error(error, display_path, "read"); |
| 2061 | } |
| 2062 | ToolError::execution_failed(format!( |
| 2063 | "Failed to read {}: {error}", |
| 2064 | display_path.display() |
| 2065 | )) |
| 2066 | } |
| 2067 | |
| 2068 | pub(super) fn open_verified_read_handle( |
| 2069 | plan: &ReadOpenPlan, |
| 2070 | require_single_link: bool, |
| 2071 | not_found_as_none: bool, |
| 2072 | directory_hint: bool, |
| 2073 | ) -> Result<Option<(fs::File, PathBuf)>, ToolError> { |
| 2074 | let file = match &plan.target { |
| 2075 | ReadOpenTarget::Workspace { |
| 2076 | workspace_canonical, |
| 2077 | relative, |
| 2078 | display_path, |
| 2079 | } => { |
| 2080 | if relative.as_os_str().is_empty() { |
| 2081 | return Err(if directory_hint { |
| 2082 | ToolError::execution_failed(format!( |
| 2083 | "Failed to read {}: path is a directory; use file_search or list_dir to see its files", |
| 2084 | display_path.display() |
| 2085 | )) |
| 2086 | } else { |
| 2087 | ToolError::execution_failed(format!( |
| 2088 | "Failed to read {}: path is a directory", |
| 2089 | display_path.display() |
| 2090 | )) |
| 2091 | }); |
| 2092 | } |
| 2093 | let ws = match codewhale_util::files::WorkspaceFile::open_shared( |
| 2094 | workspace_canonical, |
| 2095 | relative, |
| 2096 | false, |
| 2097 | ) { |
| 2098 | Ok(ws) => ws, |
| 2099 | Err(error) if not_found_as_none && error.kind() == std::io::ErrorKind::NotFound => { |
| 2100 | return Ok(None); |
| 2101 | } |
| 2102 | Err(error) => { |
| 2103 | return Err(map_read_open_error( |
| 2104 | error, |
| 2105 | display_path, |
| 2106 | plan.boundary.strict_workspace_confinement, |
| 2107 | directory_hint, |
| 2108 | )); |
| 2109 | } |
| 2110 | }; |
| 2111 | match ws.open_file_shared() { |
| 2112 | Ok(file) => file, |
| 2113 | Err(error) if not_found_as_none && error.kind() == std::io::ErrorKind::NotFound => { |
| 2114 | return Ok(None); |
| 2115 | } |
| 2116 | Err(error) => { |
| 2117 | return Err(map_read_open_error( |
| 2118 | error, |
| 2119 | display_path, |
| 2120 | plan.boundary.strict_workspace_confinement, |
| 2121 | directory_hint, |
| 2122 | )); |
| 2123 | } |
| 2124 | } |
| 2125 | } |
| 2126 | ReadOpenTarget::Outside { path } => { |
| 2127 | match open_outside_regular_file(path, require_single_link) { |
| 2128 | Ok(file) => file, |
| 2129 | Err(error) if not_found_as_none && error.kind() == std::io::ErrorKind::NotFound => { |
| 2130 | return Ok(None); |
| 2131 | } |
| 2132 | Err(error) => { |
| 2133 | return Err(map_read_open_error(error, path, false, directory_hint)); |
| 2134 | } |
| 2135 | } |
| 2136 | } |
| 2137 | }; |
| 2138 | let fd_path = verify_opened_read_file(&file, &plan.boundary)?; |
| 2139 | Ok(Some((file, fd_path))) |
| 2140 | } |
| 2141 | |
| 2142 | pub(super) async fn open_and_read_verified_bytes( |
| 2143 | plan: ReadOpenPlan, |
| 2144 | max_bytes: Option<u64>, |
| 2145 | not_found_as_none: bool, |
| 2146 | error_prefix: &'static str, |
| 2147 | ) -> Result<Option<(Vec<u8>, PathBuf)>, ToolError> { |
| 2148 | let join_path = plan.file_path.clone(); |
| 2149 | tokio::task::spawn_blocking(move || -> Result<Option<(Vec<u8>, PathBuf)>, ToolError> { |
| 2150 | use std::io::Read as _; |
| 2151 | let Some((mut file, fd_path)) = |
| 2152 | open_verified_read_handle(&plan, true, not_found_as_none, false)? |
| 2153 | else { |
| 2154 | return Ok(None); |
| 2155 | }; |
| 2156 | let mut bytes = Vec::new(); |
| 2157 | let read_result = match max_bytes { |
| 2158 | Some(limit) => file.take(limit).read_to_end(&mut bytes), |
| 2159 | None => file.read_to_end(&mut bytes), |
| 2160 | }; |
| 2161 | read_result.map_err(|e| { |
| 2162 | ToolError::execution_failed(format!("{error_prefix} {}: {e}", plan.file_path.display())) |
| 2163 | })?; |
| 2164 | Ok(Some((bytes, fd_path))) |
| 2165 | }) |
| 2166 | .await |
| 2167 | .map_err(|e| { |
| 2168 | ToolError::execution_failed(format!( |
| 2169 | "{error_prefix} {}: worker failed: {e}", |
| 2170 | join_path.display() |
| 2171 | )) |
| 2172 | })? |
| 2173 | } |
| 2174 | |
| 2175 | pub(super) fn open_verified_search_file( |
| 2176 | path: &Path, |
| 2177 | boundary: &OpenedReadBoundary, |
| 2178 | follow_symlinks: bool, |
| 2179 | ) -> Result<fs::File, ToolError> { |
| 2180 | if !follow_symlinks { |
| 2181 | if !boundary.workspace_canonical.as_os_str().is_empty() |
| 2182 | && let Ok(relative) = path.strip_prefix(&boundary.workspace_canonical) |
| 2183 | { |
| 2184 | if relative.as_os_str().is_empty() || !codewhale_util::files::path_is_confined(relative) |
| 2185 | { |
| 2186 | return Err(ToolError::permission_denied(format!( |
| 2187 | "{} refused confined path constraint for {}", |
| 2188 | boundary.tool, |
| 2189 | path.display() |
| 2190 | ))); |
| 2191 | } |
| 2192 | let ws = codewhale_util::files::WorkspaceFile::open_shared( |
| 2193 | &boundary.workspace_canonical, |
| 2194 | relative, |
| 2195 | false, |
| 2196 | ) |
| 2197 | .map_err(|error| { |
| 2198 | map_read_open_error(error, path, boundary.strict_workspace_confinement, false) |
| 2199 | })?; |
| 2200 | let file = ws.open_file_shared().map_err(|error| { |
| 2201 | map_read_open_error(error, path, boundary.strict_workspace_confinement, false) |
| 2202 | })?; |
| 2203 | verify_opened_read_file(&file, boundary)?; |
| 2204 | return Ok(file); |
| 2205 | } |
| 2206 | if boundary.strict_workspace_confinement { |
| 2207 | return Err(ToolError::permission_denied(format!( |
| 2208 | "{} refused file outside workspace for {}", |
| 2209 | boundary.tool, |
| 2210 | path.display() |
| 2211 | ))); |
| 2212 | } |
| 2213 | let file = open_outside_regular_file(path, true) |
| 2214 | .map_err(|error| map_read_open_error(error, path, false, false))?; |
| 2215 | verify_opened_read_file(&file, boundary)?; |
| 2216 | return Ok(file); |
| 2217 | } |
| 2218 | |
| 2219 | if boundary.strict_workspace_confinement { |
| 2220 | return Err(ToolError::permission_denied(format!( |
| 2221 | "{} refused symlink traversal under strict workspace confinement for {}", |
| 2222 | boundary.tool, |
| 2223 | path.display() |
| 2224 | ))); |
| 2225 | } |
| 2226 | |
| 2227 | let target = |
| 2228 | fs::canonicalize(path).map_err(|error| map_read_open_error(error, path, false, false))?; |
| 2229 | if is_codewhale_credential_path(&target) { |
| 2230 | return Err(ToolError::permission_denied(format!( |
| 2231 | "{} cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 2232 | boundary.tool |
| 2233 | ))); |
| 2234 | } |
| 2235 | enforce_read_denylist_with_display(&target, path, boundary.tool)?; |
| 2236 | let file = open_outside_regular_file(&target, true) |
| 2237 | .map_err(|error| map_read_open_error(error, path, false, false))?; |
| 2238 | let mut file_boundary = boundary.clone(); |
| 2239 | file_boundary.raw_spelling = path.to_path_buf(); |
| 2240 | file_boundary.exact_allowed_file = Some(target); |
| 2241 | verify_opened_read_file(&file, &file_boundary)?; |
| 2242 | Ok(file) |
| 2243 | } |
| 2244 | |
| 2245 | async fn load_verified_contract_read_bytes( |
| 2246 | plan: ReadOpenPlan, |
| 2247 | context: &ToolContext, |
| 2248 | ) -> Result<Option<(Vec<u8>, PathBuf)>, ToolError> { |
| 2249 | check_file_operation_cancelled(context)?; |
| 2250 | let cancel = context.cancel_token.clone(); |
| 2251 | let mut worker = tokio::task::spawn_blocking(move || { |
| 2252 | check_contract_cancelled(cancel.as_ref())?; |
| 2253 | let Some((mut file, fd_path)) = open_verified_read_handle(&plan, true, true, true)? else { |
| 2254 | return Ok(None); |
| 2255 | }; |
| 2256 | let metadata = file.metadata().map_err(|error| { |
| 2257 | ToolError::execution_failed(format!( |
| 2258 | "Failed to read {}: {error}", |
| 2259 | plan.file_path.display() |
| 2260 | )) |
| 2261 | })?; |
| 2262 | if metadata.len() > CONTRACT_FILE_MAX_BYTES as u64 { |
| 2263 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 2264 | } |
| 2265 | let bytes = read_contract_source(&mut file, cancel.as_ref())?; |
| 2266 | Ok(Some((bytes, fd_path))) |
| 2267 | }); |
| 2268 | let result = if let Some(cancel) = context.cancel_token.as_ref() { |
| 2269 | tokio::select! { |
| 2270 | biased; |
| 2271 | () = cancel.cancelled() => return Err(ToolError::cancelled("Operation aborted")), |
| 2272 | result = &mut worker => result, |
| 2273 | } |
| 2274 | } else { |
| 2275 | worker.await |
| 2276 | }; |
| 2277 | result.map_err(|error| ToolError::execution_failed(format!("File read task: {error}")))? |
| 2278 | } |
| 2279 | |
| 2280 | /// Tool for reading UTF-8 files from the workspace. |
| 2281 | pub struct ReadFileTool; |
| 2282 | |
| 2283 | impl ReadFileTool { |
| 2284 | /// Execute the lowercase `read` primitive without leaking the hidden |
| 2285 | /// Codewhale hash/snapshot protocol into its small-contract-shaped model contract. |
| 2286 | pub(super) async fn execute_contract_read( |
| 2287 | input: Value, |
| 2288 | context: &ToolContext, |
| 2289 | ) -> Result<RichToolResult, ToolError> { |
| 2290 | Self::execute_contract_read_with_pdf( |
| 2291 | input, |
| 2292 | context, |
| 2293 | super::pdf::PdfTextCommand::system(Some(context)), |
| 2294 | ) |
| 2295 | .await |
| 2296 | } |
| 2297 | |
| 2298 | async fn execute_contract_read_with_pdf( |
| 2299 | input: Value, |
| 2300 | context: &ToolContext, |
| 2301 | pdf_command: super::pdf::PdfTextCommand<'_>, |
| 2302 | ) -> Result<RichToolResult, ToolError> { |
| 2303 | reject_primitive_unknown(&input, "read", &["path", "offset", "limit", "pages"])?; |
| 2304 | let path_str = required_str(&input, "path")?; |
| 2305 | let offset = contract_nonnegative_int(&input, "offset")?; |
| 2306 | let limit = contract_nonnegative_int(&input, "limit")?; |
| 2307 | let pages = optional_str(&input, "pages")?; |
| 2308 | if limit.is_some_and(|limit| limit > READ_LIMIT_LINES) { |
| 2309 | return Err(ToolError::execution_failed(format!( |
| 2310 | "limit must be less than or equal to {READ_LIMIT_LINES}" |
| 2311 | ))); |
| 2312 | } |
| 2313 | let max_bytes = effective_read_max_bytes(); |
| 2314 | let plan = resolve_read_open_plan(context, path_str, "read", true, true).await?; |
| 2315 | let planned_path = plan.file_path.clone(); |
| 2316 | check_file_operation_cancelled(context)?; |
| 2317 | let (bytes, file_path) = load_verified_contract_read_bytes(plan, context) |
| 2318 | .await? |
| 2319 | .ok_or_else(|| { |
| 2320 | ToolError::execution_failed(format!( |
| 2321 | "Failed to read {}: file not found", |
| 2322 | planned_path.display() |
| 2323 | )) |
| 2324 | })?; |
| 2325 | // #6283: every read response carries the file's byte size, line |
| 2326 | // count, and truncation flag so the caller can page deliberately |
| 2327 | // instead of discovering a huge file one window at a time. |
| 2328 | let size_bytes = bytes.len(); |
| 2329 | check_file_operation_cancelled(context)?; |
| 2330 | if let Some(mime_type) = primitive_image_mime(&bytes) { |
| 2331 | if context.route_capabilities.image_input |
| 2332 | == codewhale_config::route::CapabilityState::Unsupported |
| 2333 | { |
| 2334 | return Err(ToolError::execution_failed( |
| 2335 | "read: the active model route does not support image input. Switch to a route marked vision-capable with /model, or configure the route's image_input capability, then try again.", |
| 2336 | )); |
| 2337 | } |
| 2338 | // Decoding and any downscale are CPU-bound; keep them off the |
| 2339 | // runtime worker (#6149). |
| 2340 | let prepared = tokio::task::spawn_blocking(move || { |
| 2341 | crate::image_attach::prepare_tool_image_bytes(&bytes, mime_type) |
| 2342 | }) |
| 2343 | .await |
| 2344 | .map_err(|error| { |
| 2345 | ToolError::execution_failed(format!("Failed to prepare image: {error}")) |
| 2346 | })?; |
| 2347 | context.note_file_read(&file_path); |
| 2348 | return Ok(RichToolResult::with_content_blocks( |
| 2349 | ToolResult::success(prepared.note).with_metadata(json!({ |
| 2350 | "evidence_routing": "inline" |
| 2351 | })), |
| 2352 | prepared.block.into_iter().collect(), |
| 2353 | )); |
| 2354 | } |
| 2355 | |
| 2356 | let text: Cow<'_, str> = if has_pdf_extension(&file_path) || bytes.starts_with(b"%PDF") { |
| 2357 | Cow::Owned( |
| 2358 | extract_pdf_bytes_result(&bytes, pages, pdf_command) |
| 2359 | .await? |
| 2360 | .content, |
| 2361 | ) |
| 2362 | } else { |
| 2363 | String::from_utf8_lossy(&bytes) |
| 2364 | }; |
| 2365 | let (effective, ended_with_newline) = match text.strip_suffix('\n') { |
| 2366 | Some(without_lf) => (without_lf.strip_suffix('\r').unwrap_or(without_lf), true), |
| 2367 | None => (text.as_ref(), false), |
| 2368 | }; |
| 2369 | let line_count = if text.is_empty() { |
| 2370 | 0 |
| 2371 | } else { |
| 2372 | effective.bytes().filter(|byte| *byte == b'\n').count() + 1 |
| 2373 | }; |
| 2374 | let requested_offset = offset.unwrap_or(1); |
| 2375 | if line_count == 0 { |
| 2376 | if requested_offset > 1 { |
| 2377 | return Err(ToolError::execution_failed(format!( |
| 2378 | "Offset {requested_offset} is beyond end of file (0 lines total)" |
| 2379 | ))); |
| 2380 | } |
| 2381 | let output = format!("[lines 0-0 of 0 | {size_bytes} bytes | truncated=false]"); |
| 2382 | context.note_file_read(&file_path); |
| 2383 | return Ok(RichToolResult::plain( |
| 2384 | ToolResult::success(output).with_metadata(json!({ |
| 2385 | "evidence_routing": "inline", |
| 2386 | "read_budget_bytes": max_bytes, |
| 2387 | "size": size_bytes, |
| 2388 | "truncated": false, |
| 2389 | "line_count": 0 |
| 2390 | })), |
| 2391 | )); |
| 2392 | } |
| 2393 | let start = requested_offset.saturating_sub(1); |
| 2394 | if start >= line_count { |
| 2395 | return Err(ToolError::execution_failed(format!( |
| 2396 | "Offset {requested_offset} is beyond end of file ({line_count} lines total)" |
| 2397 | ))); |
| 2398 | } |
| 2399 | let start_byte = if start == 0 { |
| 2400 | 0 |
| 2401 | } else { |
| 2402 | effective |
| 2403 | .match_indices('\n') |
| 2404 | .nth(start - 1) |
| 2405 | .expect("line count validated offset") |
| 2406 | .0 |
| 2407 | + 1 |
| 2408 | }; |
| 2409 | let selected_lines = limit.unwrap_or(READ_LIMIT_LINES).min(line_count - start); |
| 2410 | let end_byte = if selected_lines == 0 { |
| 2411 | start_byte |
| 2412 | } else { |
| 2413 | effective[start_byte..] |
| 2414 | .match_indices('\n') |
| 2415 | .nth(selected_lines - 1) |
| 2416 | .map_or(effective.len(), |(index, _)| start_byte + index) |
| 2417 | }; |
| 2418 | let selected_content = &effective[start_byte..end_byte]; |
| 2419 | let first_display = start + 1; |
| 2420 | let last_line_has_lf = start + selected_lines < line_count || ended_with_newline; |
| 2421 | let window = contract_read_window( |
| 2422 | selected_content, |
| 2423 | first_display, |
| 2424 | selected_lines, |
| 2425 | last_line_has_lf, |
| 2426 | max_bytes, |
| 2427 | ); |
| 2428 | // Truncated means the file holds more than this response shows: the |
| 2429 | // byte cap stopped the window, a line was char-truncated, or the |
| 2430 | // selected range stopped before EOF. A whole file that fits is |
| 2431 | // never truncated. |
| 2432 | let truncated = window.truncated_by_bytes |
| 2433 | || window.line_truncated |
| 2434 | || start + selected_lines < line_count; |
| 2435 | let header = if window.shown_lines == 0 { |
| 2436 | format!("[lines 0-0 of {line_count} | {size_bytes} bytes | truncated={truncated}]") |
| 2437 | } else { |
| 2438 | let last_display = first_display + window.shown_lines - 1; |
| 2439 | format!( |
| 2440 | "[lines {first_display}-{last_display} of {line_count} | {size_bytes} bytes | truncated={truncated}]" |
| 2441 | ) |
| 2442 | }; |
| 2443 | let mut output = if window.shown_lines == 0 { |
| 2444 | header |
| 2445 | } else { |
| 2446 | format!("{header}\n{}", window.content) |
| 2447 | }; |
| 2448 | |
| 2449 | // Continuation speaks only in lines: the next offset is the whole |
| 2450 | // instruction. |
| 2451 | if window.truncated_by_bytes { |
| 2452 | let last_display = first_display + window.shown_lines.saturating_sub(1); |
| 2453 | output.push_str(&format!( |
| 2454 | "\n\n[Showing lines {first_display}-{last_display} of {line_count}; output cap reached. Continue with offset={}.]", |
| 2455 | last_display + 1 |
| 2456 | )); |
| 2457 | } else if start + selected_lines < line_count && selected_lines > 0 { |
| 2458 | let last_display = start + selected_lines; |
| 2459 | output.push_str(&format!( |
| 2460 | "\n\n[Showing lines {first_display}-{last_display} of {line_count}. Continue with offset={}.]", |
| 2461 | last_display + 1 |
| 2462 | )); |
| 2463 | } |
| 2464 | |
| 2465 | // This internal observation keeps hidden legacy edit replay working, |
| 2466 | // but no hash or read-before-edit ceremony reaches the lowercase |
| 2467 | // schema or result. |
| 2468 | context.note_file_read(&file_path); |
| 2469 | let mut metadata = json!({ |
| 2470 | "evidence_routing": "inline", |
| 2471 | // The budget this call actually enforced. The context |
| 2472 | // compactor honors it so an already-bounded read is never |
| 2473 | // truncated a second time on its way into the conversation. |
| 2474 | "read_budget_bytes": max_bytes, |
| 2475 | // #6283: paging contract. `size` is the whole file in bytes, |
| 2476 | // `line_count` its total lines, `truncated` whether the file |
| 2477 | // holds more than this response shows. |
| 2478 | "size": size_bytes, |
| 2479 | "truncated": truncated, |
| 2480 | "line_count": line_count |
| 2481 | }); |
| 2482 | if window.shown_lines != 0 |
| 2483 | && let Some(skill) = super::skill::implicit_skill_read(&file_path, context).await |
| 2484 | { |
| 2485 | metadata["skill_name"] = json!(skill); |
| 2486 | metadata["skill_invocation"] = json!("implicit_read"); |
| 2487 | } |
| 2488 | Ok(RichToolResult::plain( |
| 2489 | ToolResult::success(output).with_metadata(metadata), |
| 2490 | )) |
| 2491 | } |
| 2492 | } |
| 2493 | |
| 2494 | #[async_trait] |
| 2495 | impl ToolSpec for ReadFileTool { |
| 2496 | fn name(&self) -> &'static str { |
| 2497 | "read_file" |
| 2498 | } |
| 2499 | |
| 2500 | fn model_visible(&self) -> bool { |
| 2501 | false |
| 2502 | } |
| 2503 | |
| 2504 | fn description(&self) -> &'static str { |
| 2505 | "Read a UTF-8 file from the workspace. Compared with `cat`, `head`, `tail`, or `sed -n '..p'` in `bash`, it is faster, sandbox-aware, and needs no approval prompt. Plain text is returned as-is and records the file snapshot required before `edit` will make a narrow in-place edit. Text reads report the whole file's `content_hash=\"sha256:…\"`; pass that value back as `expected_hash` on a later `write`, `edit`, or `patch` to have the write refused if the file changed in between. Codewhale config files and file-backed credential stores cannot be read with this tool; use `codewhale config list` or `codewhale auth status` for safe inspection. PDFs are text-extracted when the optional `pdftotext` executable (Poppler) is installed. Image screenshots are OCR-extracted when local OCR is available. Cannot read other non-PDF binaries.\n\nFor large files, use `start_line` and `max_lines` to read in chunks. By default, returns up to 500 lines or 16KB, whichever comes first. If `truncated=\"true\"` and `next_start_line` is present, continue reading from there; a byte-limited window instead shows head + tail with a `[CONTENT TRUNCATED]` marker and its note says how to narrow the range. For PDFs, use `pages` instead — `start_line`/`max_lines` only apply to text files." |
| 2506 | } |
| 2507 | |
| 2508 | fn input_schema(&self) -> Value { |
| 2509 | json!({ |
| 2510 | "type": "object", |
| 2511 | "properties": { |
| 2512 | "path": { |
| 2513 | "type": "string", |
| 2514 | "description": "File path: workspace-relative, absolute or ~/. Alias: file_path" |
| 2515 | }, |
| 2516 | "start_line": { |
| 2517 | "type": "integer", |
| 2518 | "description": "Starting line (1-based, default 1). Aliases: `offset`, `line_offset`" |
| 2519 | }, |
| 2520 | "max_lines": { |
| 2521 | "type": "integer", |
| 2522 | "description": "Lines: default/max 500, also capped at 16KB. Aliases: limit, n_lines" |
| 2523 | }, |
| 2524 | "pages": { |
| 2525 | "type": "string", |
| 2526 | "description": "PDF page range, e.g. 1-5 or 10; ignored for other files." |
| 2527 | } |
| 2528 | }, |
| 2529 | "required": ["path"] |
| 2530 | }) |
| 2531 | } |
| 2532 | |
| 2533 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 2534 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 2535 | } |
| 2536 | |
| 2537 | fn supports_parallel(&self) -> bool { |
| 2538 | true |
| 2539 | } |
| 2540 | |
| 2541 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 2542 | Self::execute_legacy_read_with_pdf( |
| 2543 | input, |
| 2544 | context, |
| 2545 | super::pdf::PdfTextCommand::system(Some(context)), |
| 2546 | ) |
| 2547 | .await |
| 2548 | } |
| 2549 | } |
| 2550 | |
| 2551 | impl ReadFileTool { |
| 2552 | async fn execute_legacy_read_with_pdf( |
| 2553 | mut input: Value, |
| 2554 | context: &ToolContext, |
| 2555 | pdf_command: super::pdf::PdfTextCommand<'_>, |
| 2556 | ) -> Result<ToolResult, ToolError> { |
| 2557 | apply_param_aliases(&mut input, PATH_ALIASES, "File read")?; |
| 2558 | apply_param_aliases(&mut input, READ_ALIASES, "File read")?; |
| 2559 | READ_PARAMS.reject_unknown(&input)?; |
| 2560 | |
| 2561 | let path_str = required_str(&input, "path")?; |
| 2562 | let plan = resolve_read_open_plan(context, path_str, "read_file", false, true).await?; |
| 2563 | let pages = optional_str(&input, "pages")?; |
| 2564 | let explicit_range = input |
| 2565 | .get("start_line") |
| 2566 | .or_else(|| input.get("max_lines")) |
| 2567 | .is_some(); |
| 2568 | |
| 2569 | check_file_operation_cancelled(context)?; |
| 2570 | let cancel = context.cancel_token.clone(); |
| 2571 | let input_clone = input.clone(); |
| 2572 | let mut worker = tokio::task::spawn_blocking(move || { |
| 2573 | use std::io::{Read as _, Seek as _}; |
| 2574 | |
| 2575 | check_contract_cancelled(cancel.as_ref())?; |
| 2576 | let (mut file, fd_path) = open_verified_read_handle(&plan, true, false, false)? |
| 2577 | .expect("not_found_as_none is false"); |
| 2578 | let read_err = |error| { |
| 2579 | ToolError::execution_failed(format!( |
| 2580 | "Failed to read {}: {error}", |
| 2581 | plan.file_path.display() |
| 2582 | )) |
| 2583 | }; |
| 2584 | if is_pdf_handle(&mut file, &fd_path).map_err(read_err)? { |
| 2585 | let metadata = file.metadata().map_err(read_err)?; |
| 2586 | if metadata.len() > CONTRACT_FILE_MAX_BYTES as u64 { |
| 2587 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 2588 | } |
| 2589 | let bytes = read_contract_source(&mut file, cancel.as_ref())?; |
| 2590 | return Ok::<_, ToolError>((fd_path, LegacyReadOutput::Pdf(bytes))); |
| 2591 | } |
| 2592 | if is_image_for_ocr(&fd_path) { |
| 2593 | let metadata = file.metadata().map_err(read_err)?; |
| 2594 | if metadata.len() > CONTRACT_FILE_MAX_BYTES as u64 { |
| 2595 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 2596 | } |
| 2597 | let bytes = read_contract_source(&mut file, cancel.as_ref())?; |
| 2598 | return Ok((fd_path, LegacyReadOutput::Image(bytes))); |
| 2599 | } |
| 2600 | let file_bytes = file.metadata().map(|meta| meta.len()).unwrap_or(u64::MAX); |
| 2601 | if !explicit_range && file_bytes <= SMALL_FILE_BYTES as u64 { |
| 2602 | let mut contents = String::new(); |
| 2603 | file.read_to_string(&mut contents).map_err(read_err)?; |
| 2604 | return Ok((fd_path, LegacyReadOutput::Small(contents))); |
| 2605 | } |
| 2606 | let (start_line, max_lines) = parse_read_range(&input_clone)?; |
| 2607 | let (window, total_lines) = |
| 2608 | read_window_streaming(&file, start_line, max_lines).map_err(read_err)?; |
| 2609 | let hash = if file.seek(std::io::SeekFrom::Start(0)).is_ok() { |
| 2610 | hash_reader_streaming(&mut file).ok() |
| 2611 | } else { |
| 2612 | None |
| 2613 | }; |
| 2614 | Ok(( |
| 2615 | fd_path, |
| 2616 | LegacyReadOutput::Window { |
| 2617 | window, |
| 2618 | total_lines, |
| 2619 | start_line, |
| 2620 | max_lines, |
| 2621 | hash, |
| 2622 | }, |
| 2623 | )) |
| 2624 | }); |
| 2625 | let joined = if let Some(cancel) = context.cancel_token.as_ref() { |
| 2626 | tokio::select! { |
| 2627 | biased; |
| 2628 | () = cancel.cancelled() => return Err(ToolError::cancelled("Operation aborted")), |
| 2629 | result = &mut worker => result, |
| 2630 | } |
| 2631 | } else { |
| 2632 | worker.await |
| 2633 | }; |
| 2634 | let (file_path, output) = |
| 2635 | joined.map_err(|e| ToolError::execution_failed(format!("File read task: {e}")))??; |
| 2636 | |
| 2637 | match output { |
| 2638 | LegacyReadOutput::Pdf(bytes) => { |
| 2639 | extract_pdf_bytes_result(&bytes, pages, pdf_command).await |
| 2640 | } |
| 2641 | LegacyReadOutput::Image(bytes) => { |
| 2642 | read_image_bytes_via_ocr(bytes, &file_path, path_str, context).await |
| 2643 | } |
| 2644 | LegacyReadOutput::Small(contents) => { |
| 2645 | context.note_file_read(&file_path); |
| 2646 | let total_lines = contents.lines().count(); |
| 2647 | if total_lines <= SMALL_FILE_LINES { |
| 2648 | let hash = content_hash(contents.as_bytes()); |
| 2649 | let body = format!("{}{contents}", content_hash_header(&hash)); |
| 2650 | return Ok(ToolResult::success(body).with_metadata(json!({ |
| 2651 | "evidence_routing": "inline", |
| 2652 | "content_hash": hash |
| 2653 | }))); |
| 2654 | } |
| 2655 | let hash = content_hash(contents.as_bytes()); |
| 2656 | let window: Vec<String> = contents |
| 2657 | .lines() |
| 2658 | .take(DEFAULT_READ_LINES) |
| 2659 | .map(str::to_string) |
| 2660 | .collect(); |
| 2661 | Ok(render_line_window( |
| 2662 | path_str, |
| 2663 | &window, |
| 2664 | total_lines, |
| 2665 | 1, |
| 2666 | DEFAULT_READ_LINES, |
| 2667 | Some(hash.as_str()), |
| 2668 | )) |
| 2669 | } |
| 2670 | LegacyReadOutput::Window { |
| 2671 | window, |
| 2672 | total_lines, |
| 2673 | start_line, |
| 2674 | max_lines, |
| 2675 | hash, |
| 2676 | } => { |
| 2677 | context.note_file_read(&file_path); |
| 2678 | if start_line > total_lines { |
| 2679 | let hash_attr = hash |
| 2680 | .as_deref() |
| 2681 | .map(|hash| format!(" content_hash=\"{hash}\"")) |
| 2682 | .unwrap_or_default(); |
| 2683 | let output = format!( |
| 2684 | "<file path=\"{path_str}\" total_lines=\"{total_lines}\" shown_lines=\"none\" truncated=\"false\"{hash_attr}>\n\n[NO CONTENT] start_line {start_line} is beyond total_lines {total_lines}.\n</file>" |
| 2685 | ); |
| 2686 | return Ok(ToolResult::success(output).with_metadata(json!({ |
| 2687 | "evidence_routing": "inline", |
| 2688 | "content_hash": hash |
| 2689 | }))); |
| 2690 | } |
| 2691 | Ok(render_line_window( |
| 2692 | path_str, |
| 2693 | &window, |
| 2694 | total_lines, |
| 2695 | start_line, |
| 2696 | max_lines, |
| 2697 | hash.as_deref(), |
| 2698 | )) |
| 2699 | } |
| 2700 | } |
| 2701 | } |
| 2702 | } |
| 2703 | |
| 2704 | fn parse_read_range(input: &Value) -> Result<(usize, usize), ToolError> { |
| 2705 | let start_line = match optional_u64(input, "start_line", 1)? { |
| 2706 | 0 => { |
| 2707 | return Err(ToolError::invalid_input( |
| 2708 | "start_line must be 1-based and greater than 0".to_string(), |
| 2709 | )); |
| 2710 | } |
| 2711 | v => usize::try_from(v).map_err(|_| { |
| 2712 | ToolError::invalid_input("start_line exceeds platform addressable range".to_string()) |
| 2713 | })?, |
| 2714 | }; |
| 2715 | let max_lines = match optional_u64(input, "max_lines", DEFAULT_READ_LINES as u64)? { |
| 2716 | 0 => { |
| 2717 | return Err(ToolError::invalid_input( |
| 2718 | "max_lines must be greater than 0".to_string(), |
| 2719 | )); |
| 2720 | } |
| 2721 | v => { |
| 2722 | let converted = usize::try_from(v).map_err(|_| { |
| 2723 | ToolError::invalid_input("max_lines exceeds platform addressable range".to_string()) |
| 2724 | })?; |
| 2725 | std::cmp::min(converted, HARD_MAX_READ_LINES) |
| 2726 | } |
| 2727 | }; |
| 2728 | Ok((start_line, max_lines)) |
| 2729 | } |
| 2730 | |
| 2731 | enum LegacyReadOutput { |
| 2732 | Pdf(Vec<u8>), |
| 2733 | Image(Vec<u8>), |
| 2734 | Small(String), |
| 2735 | Window { |
| 2736 | window: Vec<String>, |
| 2737 | total_lines: usize, |
| 2738 | start_line: usize, |
| 2739 | max_lines: usize, |
| 2740 | hash: Option<String>, |
| 2741 | }, |
| 2742 | } |
| 2743 | |
| 2744 | fn is_pdf_handle(file: &mut fs::File, path: &Path) -> std::io::Result<bool> { |
| 2745 | use std::io::{Read as _, Seek as _}; |
| 2746 | if has_pdf_extension(path) { |
| 2747 | return Ok(true); |
| 2748 | } |
| 2749 | let mut buf = [0u8; 4]; |
| 2750 | let matched = file.read_exact(&mut buf).is_ok() && &buf == b"%PDF"; |
| 2751 | file.seek(std::io::SeekFrom::Start(0))?; |
| 2752 | Ok(matched) |
| 2753 | } |
| 2754 | |
| 2755 | // Bounded output for large files. The small-file fast path keeps the |
| 2756 | // historical "return contents unchanged" behavior so existing flows |
| 2757 | // (small configs, single source files, etc.) don't suddenly start |
| 2758 | // seeing wrapped output. Once a file is large or the caller asks |
| 2759 | // for an explicit range, we switch to a numbered, line-tagged |
| 2760 | // window with continuation hints so the model can page through |
| 2761 | // without re-loading the entire file on every turn. Harvested |
| 2762 | // from PR #1451 by @Oliver-ZPLiu, closes part of #1450. |
| 2763 | // One bound, not two competing ones. The real cost of a read is BYTES of |
| 2764 | // context, and `MAX_VISIBLE_BYTES` already enforces that. A separate 200-line |
| 2765 | // default fired long before the byte budget on any prose file — a 229-line, |
| 2766 | // 12 KB document truncated at line 200 with a third of the budget unspent, |
| 2767 | // costing a second round trip to fetch 29 lines. The line cap now only guards |
| 2768 | // pathologically short lines, where 500 lines is still a small read. |
| 2769 | const DEFAULT_READ_LINES: usize = HARD_MAX_READ_LINES; |
| 2770 | const HARD_MAX_READ_LINES: usize = 500; |
| 2771 | const MAX_VISIBLE_BYTES: usize = 16 * 1024; |
| 2772 | const SMALL_FILE_LINES: usize = HARD_MAX_READ_LINES; |
| 2773 | const SMALL_FILE_BYTES: usize = 16 * 1024; |
| 2774 | |
| 2775 | /// Stream a line window out of `file`: skip `start_line - 1` lines, collect |
| 2776 | /// up to `max_lines`, then keep counting (and validating UTF-8) to EOF. |
| 2777 | /// Returns the collected window plus the total line count. Only the window |
| 2778 | /// is ever held in memory. |
| 2779 | fn read_window_streaming( |
| 2780 | file: &fs::File, |
| 2781 | start_line: usize, |
| 2782 | max_lines: usize, |
| 2783 | ) -> std::io::Result<(Vec<String>, usize)> { |
| 2784 | use std::io::BufRead; |
| 2785 | |
| 2786 | let mut reader = std::io::BufReader::new(file); |
| 2787 | let mut raw: Vec<u8> = Vec::new(); |
| 2788 | let mut window: Vec<String> = Vec::new(); |
| 2789 | let mut total_lines = 0usize; |
| 2790 | let start_idx = start_line - 1; |
| 2791 | |
| 2792 | loop { |
| 2793 | raw.clear(); |
| 2794 | let n = reader.read_until(b'\n', &mut raw)?; |
| 2795 | if n == 0 { |
| 2796 | break; |
| 2797 | } |
| 2798 | // Mirror `str::lines`: strip the trailing '\n', and a '\r' only when |
| 2799 | // it directly precedes that '\n'. |
| 2800 | let mut end = raw.len(); |
| 2801 | if raw[..end].ends_with(b"\n") { |
| 2802 | end -= 1; |
| 2803 | if raw[..end].ends_with(b"\r") { |
| 2804 | end -= 1; |
| 2805 | } |
| 2806 | } |
| 2807 | // Validate every line so invalid UTF-8 anywhere in the file fails |
| 2808 | // exactly like the previous whole-file read_to_string did. |
| 2809 | let line = std::str::from_utf8(&raw[..end]).map_err(|_| { |
| 2810 | std::io::Error::new( |
| 2811 | std::io::ErrorKind::InvalidData, |
| 2812 | "stream did not contain valid UTF-8", |
| 2813 | ) |
| 2814 | })?; |
| 2815 | if total_lines >= start_idx && window.len() < max_lines { |
| 2816 | window.push(line.to_string()); |
| 2817 | } |
| 2818 | total_lines += 1; |
| 2819 | } |
| 2820 | |
| 2821 | Ok((window, total_lines)) |
| 2822 | } |
| 2823 | |
| 2824 | /// Marker placed between the retained head and tail when a read window is |
| 2825 | /// truncated by the byte budget. Mirrors qwen-code's truncation style so the |
| 2826 | /// model sees both ends of the range. |
| 2827 | const BYTE_TRUNCATION_SEPARATOR: &str = "\n\n---\n... [CONTENT TRUNCATED] ...\n---\n\n"; |
| 2828 | |
| 2829 | /// Split `content` into a head of at most `head_budget` bytes and a tail that |
| 2830 | /// fills the remainder of `total_budget` (separator accounted for). Never |
| 2831 | /// overlaps and never splits mid-codepoint. Style matches qwen-code: |
| 2832 | /// `head_budget = total_budget / 5`. |
| 2833 | fn head_tail_for_budget(content: &str, total_budget: usize) -> (String, String) { |
| 2834 | let head_budget = (total_budget / 5).max(1); |
| 2835 | let head_end = (0..=head_budget.min(content.len())) |
| 2836 | .rev() |
| 2837 | .find(|&i| content.is_char_boundary(i)) |
| 2838 | .unwrap_or(0); |
| 2839 | let sep_len = BYTE_TRUNCATION_SEPARATOR.len(); |
| 2840 | let tail_budget = total_budget |
| 2841 | .saturating_sub(head_end) |
| 2842 | .saturating_sub(sep_len) |
| 2843 | .max(1); |
| 2844 | let tail_floor = content.len().saturating_sub(tail_budget).max(head_end); |
| 2845 | let tail_start = (tail_floor..=content.len()) |
| 2846 | .find(|&i| content.is_char_boundary(i)) |
| 2847 | .unwrap_or(content.len()); |
| 2848 | ( |
| 2849 | content[..head_end].to_string(), |
| 2850 | content[tail_start..].to_string(), |
| 2851 | ) |
| 2852 | } |
| 2853 | |
| 2854 | /// Render a collected line window into the `<file …>` wrapper used for |
| 2855 | /// ranged/large reads. `window` must hold the lines for |
| 2856 | /// `start_line..start_line + max_lines` (clamped to EOF). |
| 2857 | fn render_line_window( |
| 2858 | path_str: &str, |
| 2859 | window: &[String], |
| 2860 | total_lines: usize, |
| 2861 | start_line: usize, |
| 2862 | max_lines: usize, |
| 2863 | content_hash: Option<&str>, |
| 2864 | ) -> ToolResult { |
| 2865 | let zero_based_start = start_line - 1; |
| 2866 | let zero_based_end = std::cmp::min(zero_based_start + max_lines, total_lines); |
| 2867 | let shown_first = start_line; |
| 2868 | let shown_last = zero_based_end; // 1-based inclusive line number of the last shown line |
| 2869 | |
| 2870 | let mut numbered = String::new(); |
| 2871 | for (offset, line) in window.iter().enumerate() { |
| 2872 | let line_no = start_line + offset; |
| 2873 | numbered.push_str(&format!("{line_no:>6}│ {line}\n")); |
| 2874 | } |
| 2875 | |
| 2876 | // UTF-8-safe byte truncation of the rendered range. Qwen-style: keep a |
| 2877 | // short head (budget/5) plus the matching tail so the model sees both |
| 2878 | // ends of a long range. The full file already lives at `path_str` — the |
| 2879 | // recovery note names that absolute/workspace path for a re-read. |
| 2880 | let visible_bytes = codewhale_runtime::active_workshop::active_read_result_max_bytes() |
| 2881 | .map(|n| n.clamp(MAX_VISIBLE_BYTES, READ_RESULT_ABSOLUTE_MAX_BYTES)) |
| 2882 | .unwrap_or(MAX_VISIBLE_BYTES); |
| 2883 | let truncated_by_bytes = numbered.len() > visible_bytes; |
| 2884 | let shown_content = if truncated_by_bytes { |
| 2885 | let (head, tail) = head_tail_for_budget(&numbered, visible_bytes); |
| 2886 | format!("{head}{BYTE_TRUNCATION_SEPARATOR}{tail}") |
| 2887 | } else { |
| 2888 | numbered |
| 2889 | }; |
| 2890 | |
| 2891 | let truncated_by_lines = zero_based_end < total_lines; |
| 2892 | let truncated = truncated_by_lines || truncated_by_bytes; |
| 2893 | let next_start = zero_based_end + 1; |
| 2894 | |
| 2895 | let mut attrs = format!( |
| 2896 | "path=\"{path_str}\" total_lines=\"{total_lines}\" shown_lines=\"{shown_first}-{shown_last}\" truncated=\"{truncated}\"" |
| 2897 | ); |
| 2898 | if truncated_by_lines { |
| 2899 | attrs.push_str(&format!(" next_start_line=\"{next_start}\"")); |
| 2900 | } |
| 2901 | // Hashes the whole file, not the shown window — a partial read still |
| 2902 | // yields a guard the model can pass to `edit`/`patch`. |
| 2903 | if let Some(hash) = content_hash { |
| 2904 | attrs.push_str(&format!(" content_hash=\"{hash}\"")); |
| 2905 | } |
| 2906 | |
| 2907 | let mut output = format!("<file {attrs}>\n{shown_content}"); |
| 2908 | if truncated_by_lines { |
| 2909 | output.push_str(&format!( |
| 2910 | "\n[TRUNCATED] Showing lines {shown_first}-{shown_last} of {total_lines}. To continue, call read with path=\"{path_str}\" offset={next_start} limit={max_lines}\n" |
| 2911 | )); |
| 2912 | } |
| 2913 | if truncated_by_bytes { |
| 2914 | if shown_first == shown_last { |
| 2915 | // One line alone exceeds the byte budget: no start_line/max_lines |
| 2916 | // combination can ever reveal the elided middle, so the note must |
| 2917 | // not pretend otherwise — name the escape hatch that works. |
| 2918 | output.push_str(&format!( |
| 2919 | "\n[TRUNCATED] Line {shown_first} alone exceeds the {visible_bytes}-byte output budget; showing its head + tail. No line window can reveal the middle of one line — use a searched shell slice when needed.\n" |
| 2920 | )); |
| 2921 | } else { |
| 2922 | let narrower = (shown_last - shown_first).div_ceil(2).max(1); |
| 2923 | output.push_str(&format!( |
| 2924 | "\n[TRUNCATED] The selected range exceeded the {visible_bytes}-byte output budget; showing head + tail of lines {shown_first}-{shown_last}. Re-read narrower windows to see the middle, e.g. offset={shown_first} limit={narrower}, then advance offset.\n" |
| 2925 | )); |
| 2926 | } |
| 2927 | } |
| 2928 | output.push_str("</file>"); |
| 2929 | |
| 2930 | // The file tool self-bounds at its own byte budget and carries its own continuation |
| 2931 | // contract (`next_start_line`), so the large-output spillover envelope |
| 2932 | // must never re-wrap a read result with a second, weaker truncation. |
| 2933 | ToolResult::success(output).with_metadata(json!({ |
| 2934 | "evidence_routing": "inline", |
| 2935 | "content_hash": content_hash |
| 2936 | })) |
| 2937 | } |
| 2938 | |
| 2939 | async fn read_image_bytes_via_ocr( |
| 2940 | bytes: Vec<u8>, |
| 2941 | source_path: &Path, |
| 2942 | requested_path: &str, |
| 2943 | context: &ToolContext, |
| 2944 | ) -> Result<ToolResult, ToolError> { |
| 2945 | let source_name = source_path |
| 2946 | .file_name() |
| 2947 | .and_then(|name| name.to_str()) |
| 2948 | .map(str::to_string); |
| 2949 | let text = crate::tools::image_ocr::ocr_image_bytes(bytes, source_name, context).await?; |
| 2950 | Ok(ToolResult::success(format!( |
| 2951 | "<image_ocr path=\"{requested_path}\">\n{text}\n</image_ocr>" |
| 2952 | ))) |
| 2953 | } |
| 2954 | |
| 2955 | fn has_pdf_extension(path: &Path) -> bool { |
| 2956 | path.extension() |
| 2957 | .and_then(|e| e.to_str()) |
| 2958 | .is_some_and(|ext| ext.eq_ignore_ascii_case("pdf")) |
| 2959 | } |
| 2960 | |
| 2961 | fn is_image_for_ocr(path: &Path) -> bool { |
| 2962 | path.extension() |
| 2963 | .and_then(|e| e.to_str()) |
| 2964 | .is_some_and(|ext| { |
| 2965 | matches!( |
| 2966 | ext.to_ascii_lowercase().as_str(), |
| 2967 | "png" | "jpg" | "jpeg" | "tif" | "tiff" | "bmp" |
| 2968 | ) |
| 2969 | }) |
| 2970 | } |
| 2971 | |
| 2972 | fn parse_pages_arg(spec: &str) -> Option<(u32, u32)> { |
| 2973 | let trimmed = spec.trim(); |
| 2974 | if trimmed.is_empty() { |
| 2975 | return None; |
| 2976 | } |
| 2977 | if let Some((a, b)) = trimmed.split_once('-') { |
| 2978 | let start: u32 = a.trim().parse().ok()?; |
| 2979 | let end: u32 = b.trim().parse().ok()?; |
| 2980 | if start == 0 || end < start { |
| 2981 | return None; |
| 2982 | } |
| 2983 | Some((start, end)) |
| 2984 | } else { |
| 2985 | let n: u32 = trimmed.parse().ok()?; |
| 2986 | if n == 0 { |
| 2987 | return None; |
| 2988 | } |
| 2989 | Some((n, n)) |
| 2990 | } |
| 2991 | } |
| 2992 | |
| 2993 | /// Clean PDF-extracted text for TUI display: collapse consecutive blank |
| 2994 | /// lines (more than 1 becomes 1), replace NUL bytes with U+FFFD, replace |
| 2995 | /// non-breaking spaces with regular spaces, and trim trailing whitespace |
| 2996 | /// on each line. Produces output that won't clutter the transcript with |
| 2997 | /// vertical gaps or invisible control characters. |
| 2998 | fn clean_pdf_text(raw: &str) -> String { |
| 2999 | let mut out = String::with_capacity(raw.len()); |
| 3000 | let mut blank_run = 0usize; |
| 3001 | let mut any_content = false; |
| 3002 | for line in raw.lines() { |
| 3003 | let trimmed = line.trim_end(); |
| 3004 | if trimmed.is_empty() { |
| 3005 | blank_run = blank_run.saturating_add(1); |
| 3006 | if blank_run <= 1 { |
| 3007 | out.push('\n'); |
| 3008 | } |
| 3009 | } else { |
| 3010 | blank_run = 0; |
| 3011 | any_content = true; |
| 3012 | // Push cleaned characters directly — avoids a per-line |
| 3013 | // temporary String allocation. |
| 3014 | for c in trimmed.chars() { |
| 3015 | match c { |
| 3016 | '\0' => out.push('\u{FFFD}'), |
| 3017 | '\u{A0}' => out.push(' '), |
| 3018 | other => out.push(other), |
| 3019 | } |
| 3020 | } |
| 3021 | out.push('\n'); |
| 3022 | } |
| 3023 | } |
| 3024 | // Trim leading blank lines only — don't use str::trim() which |
| 3025 | // would also strip intentional indentation (e.g. centred titles). |
| 3026 | if any_content { |
| 3027 | let start = out.find(|c: char| c != '\n').unwrap_or(0); |
| 3028 | // Walk back from end to find the last non-newline character. |
| 3029 | let end = out.rfind(|c: char| c != '\n').map_or(out.len(), |i| { |
| 3030 | i + out[i..].chars().next().map_or(1, |c| c.len_utf8()) |
| 3031 | }); |
| 3032 | out[start..end].to_string() |
| 3033 | } else { |
| 3034 | String::new() |
| 3035 | } |
| 3036 | } |
| 3037 | |
| 3038 | async fn extract_pdf_bytes_result( |
| 3039 | bytes: &[u8], |
| 3040 | pages: Option<&str>, |
| 3041 | command: super::pdf::PdfTextCommand<'_>, |
| 3042 | ) -> Result<ToolResult, ToolError> { |
| 3043 | let page_range = match pages { |
| 3044 | Some(spec) => match parse_pages_arg(spec) { |
| 3045 | Some((start, end)) => Some((start, end)), |
| 3046 | None => { |
| 3047 | return Err(ToolError::invalid_input(format!( |
| 3048 | "invalid `pages` value `{spec}` (expected `N` or `N-M`, e.g. `1-5`)" |
| 3049 | ))); |
| 3050 | } |
| 3051 | }, |
| 3052 | None => None, |
| 3053 | }; |
| 3054 | |
| 3055 | read_pdf_bytes_with_command(bytes, page_range, command).await |
| 3056 | } |
| 3057 | |
| 3058 | async fn read_pdf_bytes_with_command( |
| 3059 | bytes: &[u8], |
| 3060 | page_range: Option<(u32, u32)>, |
| 3061 | command: super::pdf::PdfTextCommand<'_>, |
| 3062 | ) -> Result<ToolResult, ToolError> { |
| 3063 | let text = super::pdf::extract_bytes(bytes, page_range, command) |
| 3064 | .await |
| 3065 | .map_err(super::pdf::into_tool_error)?; |
| 3066 | Ok(ToolResult::success(clean_pdf_text(&text))) |
| 3067 | } |
| 3068 | |
| 3069 | // === WriteFileTool === |
| 3070 | |
| 3071 | /// Tool for writing UTF-8 files to the workspace. |
| 3072 | pub struct WriteFileTool; |
| 3073 | |
| 3074 | impl WriteFileTool { |
| 3075 | /// Execute the small-contract-shaped lowercase writer. Compatibility-only hash |
| 3076 | /// arguments remain on the hidden `write_file` path. |
| 3077 | pub(super) async fn execute_contract_write( |
| 3078 | input: Value, |
| 3079 | context: &ToolContext, |
| 3080 | ) -> Result<ToolResult, ToolError> { |
| 3081 | reject_primitive_unknown(&input, "write", &["path", "content", "line_ending"])?; |
| 3082 | let line_ending = requested_line_ending(&input)?; |
| 3083 | let path_str = required_str(&input, "path")?; |
| 3084 | let file_content = required_str(&input, "content")?; |
| 3085 | check_contract_file_size(file_content.len())?; |
| 3086 | let confined_target = if write_uses_confined_io(context) { |
| 3087 | Some(resolve_confined_target_async(context, path_str, false).await?) |
| 3088 | } else { |
| 3089 | None |
| 3090 | }; |
| 3091 | let (file_path, non_strict_plan) = match confined_target.as_ref() { |
| 3092 | Some((workspace_canonical, relative)) => { |
| 3093 | let path = workspace_canonical.join(relative); |
| 3094 | if is_codewhale_credential_path(&path) { |
| 3095 | return Err(ToolError::permission_denied( |
| 3096 | "write cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 3097 | )); |
| 3098 | } |
| 3099 | (path, None) |
| 3100 | } |
| 3101 | None => { |
| 3102 | let plan = resolve_write_preread_plan(context, path_str, "write").await?; |
| 3103 | let path = plan.file_path.clone(); |
| 3104 | (path, Some(plan)) |
| 3105 | } |
| 3106 | }; |
| 3107 | let mutation_guard = acquire_file_mutation(&file_path, context).await?; |
| 3108 | check_file_operation_cancelled(context)?; |
| 3109 | |
| 3110 | let (prior_id, prior) = match confined_target.as_ref() { |
| 3111 | Some((workspace_canonical, relative)) => match load_confined_prior_file( |
| 3112 | workspace_canonical, |
| 3113 | relative, |
| 3114 | &file_path, |
| 3115 | "write", |
| 3116 | path_str, |
| 3117 | Some(CONTRACT_FILE_MAX_BYTES), |
| 3118 | context, |
| 3119 | ) |
| 3120 | .await? |
| 3121 | { |
| 3122 | ConfinedPrior::Missing => (None, None), |
| 3123 | ConfinedPrior::Existing { bytes, id } => (Some(id), Some(bytes)), |
| 3124 | }, |
| 3125 | None => ( |
| 3126 | None, |
| 3127 | load_contract_source( |
| 3128 | non_strict_plan.expect("non-strict write plan"), |
| 3129 | false, |
| 3130 | context, |
| 3131 | ) |
| 3132 | .await?, |
| 3133 | ), |
| 3134 | }; |
| 3135 | let existed_before = prior.is_some(); |
| 3136 | if existed_before { |
| 3137 | context.require_fresh_read_before_write(&file_path, path_str)?; |
| 3138 | } |
| 3139 | let prior_bytes = prior.unwrap_or_default(); |
| 3140 | let prior_contents = String::from_utf8_lossy(&prior_bytes); |
| 3141 | |
| 3142 | check_file_operation_cancelled(context)?; |
| 3143 | let mut written = write_line_endings(file_content, &prior_contents, line_ending, true)?; |
| 3144 | let kept_ending = |
| 3145 | (line_ending.is_none() && prior_contents.contains('\n') && written != file_content) |
| 3146 | .then(|| contract_line_ending(&prior_contents)); |
| 3147 | guard_edit( |
| 3148 | &file_path, |
| 3149 | path_str, |
| 3150 | existed_before.then(|| prior_contents.as_ref()), |
| 3151 | &written, |
| 3152 | )?; |
| 3153 | if existed_before |
| 3154 | && let Some(normalized) = normalize_edit(&file_path, &prior_contents, &written).await |
| 3155 | { |
| 3156 | written = normalized; |
| 3157 | } |
| 3158 | if line_ending.is_some() { |
| 3159 | written = write_line_endings(&written, "", line_ending, true)?; |
| 3160 | } |
| 3161 | check_contract_file_size(written.len())?; |
| 3162 | check_file_operation_cancelled(context)?; |
| 3163 | if let Some((workspace_canonical, relative)) = confined_target.as_ref() { |
| 3164 | commit_confined_write( |
| 3165 | workspace_canonical, |
| 3166 | relative, |
| 3167 | &file_path, |
| 3168 | prior_id, |
| 3169 | written.clone().into_bytes(), |
| 3170 | ) |
| 3171 | .await?; |
| 3172 | } else { |
| 3173 | if let Some(parent) = file_path.parent() { |
| 3174 | tokio::fs::create_dir_all(parent).await.map_err(|error| { |
| 3175 | ToolError::execution_failed(format!( |
| 3176 | "Failed to create directory {}: {error}", |
| 3177 | parent.display() |
| 3178 | )) |
| 3179 | })?; |
| 3180 | } |
| 3181 | check_file_operation_cancelled(context)?; |
| 3182 | run_blocking_write_atomic(&file_path, written.clone().into_bytes()).await?; |
| 3183 | } |
| 3184 | context.note_file_read(&file_path); |
| 3185 | drop(mutation_guard); |
| 3186 | |
| 3187 | let outcome = if existed_before { "updated" } else { "created" }; |
| 3188 | let written_bytes = written.len(); |
| 3189 | Ok(contract_mutation_result( |
| 3190 | path_str, |
| 3191 | prior_contents.as_ref(), |
| 3192 | &written, |
| 3193 | written.as_bytes(), |
| 3194 | outcome, |
| 3195 | match (line_ending, kept_ending) { |
| 3196 | (Some(ending), _) => format!( |
| 3197 | "Successfully wrote {written_bytes} bytes to {path_str}; used {} line endings", |
| 3198 | if ending == "\r\n" { "CRLF" } else { "LF" } |
| 3199 | ), |
| 3200 | (None, Some(ending)) => format!( |
| 3201 | "Successfully wrote {written_bytes} bytes to {path_str}; kept the existing file's {} line endings", |
| 3202 | if ending == "\r\n" { "CRLF" } else { "LF" } |
| 3203 | ), |
| 3204 | (None, None) => format!("Successfully wrote {written_bytes} bytes to {path_str}"), |
| 3205 | }, |
| 3206 | )) |
| 3207 | } |
| 3208 | } |
| 3209 | |
| 3210 | #[async_trait] |
| 3211 | impl ToolSpec for WriteFileTool { |
| 3212 | fn name(&self) -> &'static str { |
| 3213 | "write_file" |
| 3214 | } |
| 3215 | |
| 3216 | fn model_visible(&self) -> bool { |
| 3217 | false |
| 3218 | } |
| 3219 | |
| 3220 | fn description(&self) -> &'static str { |
| 3221 | "Write content to a UTF-8 file in the workspace. Unlike heredocs (`cat <<EOF > file`) or `echo > file` in `bash`, its diffs render inline and its approval shows the change. Creates or overwrites; parent directories are auto-created. Pass `expected_hash` (the `content_hash` from a prior `read`) to have the overwrite refused if the file changed since that read." |
| 3222 | } |
| 3223 | |
| 3224 | fn input_schema(&self) -> Value { |
| 3225 | json!({ |
| 3226 | "type": "object", |
| 3227 | "properties": { |
| 3228 | "path": { |
| 3229 | "type": "string", |
| 3230 | "description": "Path to the file. Alias: `file_path`" |
| 3231 | }, |
| 3232 | "content": { |
| 3233 | "type": "string", |
| 3234 | "description": "Content to write" |
| 3235 | }, |
| 3236 | "expected_hash": { |
| 3237 | "type": "string", |
| 3238 | "description": EXPECTED_HASH_DESCRIPTION |
| 3239 | }, |
| 3240 | "line_ending": { |
| 3241 | "type": "string", |
| 3242 | "enum": ["preserve", "lf", "crlf"], |
| 3243 | "description": "Default: preserve existing endings. Explicit lf/crlf converts CRLF and lone CR." |
| 3244 | } |
| 3245 | }, |
| 3246 | "required": ["path", "content"] |
| 3247 | }) |
| 3248 | } |
| 3249 | |
| 3250 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 3251 | vec![ |
| 3252 | ToolCapability::WritesFiles, |
| 3253 | ToolCapability::Sandboxable, |
| 3254 | ToolCapability::RequiresApproval, |
| 3255 | ] |
| 3256 | } |
| 3257 | |
| 3258 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 3259 | ApprovalRequirement::Suggest |
| 3260 | } |
| 3261 | |
| 3262 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 3263 | let mut input = input; |
| 3264 | apply_param_aliases(&mut input, PATH_ALIASES, "File write")?; |
| 3265 | WRITE_PARAMS.reject_unknown(&input)?; |
| 3266 | |
| 3267 | let path_str = required_str(&input, "path")?; |
| 3268 | let file_content = required_str(&input, "content")?; |
| 3269 | let expected_hash = optional_str(&input, "expected_hash")?; |
| 3270 | let line_ending = requested_line_ending(&input)?; |
| 3271 | |
| 3272 | let confined_target = if write_uses_confined_io(context) { |
| 3273 | Some(resolve_confined_target_async(context, path_str, false).await?) |
| 3274 | } else { |
| 3275 | None |
| 3276 | }; |
| 3277 | let (file_path, non_strict_plan) = match confined_target.as_ref() { |
| 3278 | Some((workspace_canonical, relative)) => { |
| 3279 | let path = workspace_canonical.join(relative); |
| 3280 | if is_codewhale_credential_path(&path) { |
| 3281 | return Err(ToolError::permission_denied( |
| 3282 | "write_file cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 3283 | )); |
| 3284 | } |
| 3285 | if expected_hash.is_some() { |
| 3286 | enforce_read_denylist(Path::new(path_str), "write_file")?; |
| 3287 | enforce_read_denylist_with_display(&path, Path::new(path_str), "write_file")?; |
| 3288 | } |
| 3289 | (path, None) |
| 3290 | } |
| 3291 | None => { |
| 3292 | let plan = if expected_hash.is_some() { |
| 3293 | resolve_read_open_plan(context, path_str, "write_file", false, false).await? |
| 3294 | } else { |
| 3295 | resolve_write_preread_plan(context, path_str, "write_file").await? |
| 3296 | }; |
| 3297 | let path = plan.file_path.clone(); |
| 3298 | (path, Some(plan)) |
| 3299 | } |
| 3300 | }; |
| 3301 | let mutation_guard = acquire_file_mutation(&file_path, context).await?; |
| 3302 | |
| 3303 | let (existed_before, prior_id, prior_contents) = match confined_target.as_ref() { |
| 3304 | Some((workspace_canonical, relative)) => { |
| 3305 | match load_confined_prior_file( |
| 3306 | workspace_canonical, |
| 3307 | relative, |
| 3308 | &file_path, |
| 3309 | "write_file", |
| 3310 | path_str, |
| 3311 | None, |
| 3312 | context, |
| 3313 | ) |
| 3314 | .await? |
| 3315 | { |
| 3316 | ConfinedPrior::Missing => (false, None, String::new()), |
| 3317 | ConfinedPrior::Existing { bytes, id } => { |
| 3318 | let contents = String::from_utf8(bytes).map_err(|error| { |
| 3319 | ToolError::execution_failed(format!( |
| 3320 | "Failed to read {}: {error}", |
| 3321 | file_path.display() |
| 3322 | )) |
| 3323 | })?; |
| 3324 | (true, Some(id), contents) |
| 3325 | } |
| 3326 | } |
| 3327 | } |
| 3328 | None => match open_and_read_verified_bytes( |
| 3329 | non_strict_plan.expect("non-strict write_file plan"), |
| 3330 | None, |
| 3331 | true, |
| 3332 | "Failed to read", |
| 3333 | ) |
| 3334 | .await? |
| 3335 | { |
| 3336 | Some((bytes, _fd_path)) => { |
| 3337 | let contents = String::from_utf8(bytes).map_err(|error| { |
| 3338 | ToolError::execution_failed(format!( |
| 3339 | "Failed to read {}: {error}", |
| 3340 | file_path.display() |
| 3341 | )) |
| 3342 | })?; |
| 3343 | (true, None, contents) |
| 3344 | } |
| 3345 | None => (false, None, String::new()), |
| 3346 | }, |
| 3347 | }; |
| 3348 | |
| 3349 | // Content-hash guard (#3979), checked against the same snapshot the |
| 3350 | // diff is rendered from and before any directory or file is touched. |
| 3351 | if let Some(expected) = expected_hash { |
| 3352 | if !existed_before { |
| 3353 | // A hash describes a file that was read. Guarding a create is |
| 3354 | // a contradiction, and silently creating the file anyway would |
| 3355 | // defeat the guard the caller asked for — fail closed. |
| 3356 | return Err(ToolError::execution_failed(format!( |
| 3357 | "File `write` refused: expected_hash was supplied but {path_str} does not exist, so there is no snapshot to verify and nothing was written. Recovery: drop `expected_hash` to create the file, or read the intended path first." |
| 3358 | ))); |
| 3359 | } |
| 3360 | verify_expected_hash(Some(expected), prior_contents.as_bytes(), "write", path_str)?; |
| 3361 | } else if existed_before { |
| 3362 | context.require_fresh_read_before_write(&file_path, path_str)?; |
| 3363 | } |
| 3364 | |
| 3365 | let mut written = write_line_endings(file_content, &prior_contents, line_ending, false)?; |
| 3366 | |
| 3367 | guard_edit( |
| 3368 | &file_path, |
| 3369 | path_str, |
| 3370 | existed_before.then(|| prior_contents.as_ref()), |
| 3371 | &written, |
| 3372 | )?; |
| 3373 | if existed_before |
| 3374 | && let Some(normalized) = normalize_edit(&file_path, &prior_contents, &written).await |
| 3375 | { |
| 3376 | written = normalized; |
| 3377 | } |
| 3378 | |
| 3379 | if line_ending.is_some() { |
| 3380 | written = write_line_endings(&written, "", line_ending, true)?; |
| 3381 | } |
| 3382 | if let Some((workspace_canonical, relative)) = confined_target.as_ref() { |
| 3383 | commit_confined_write( |
| 3384 | workspace_canonical, |
| 3385 | relative, |
| 3386 | &file_path, |
| 3387 | prior_id, |
| 3388 | written.clone().into_bytes(), |
| 3389 | ) |
| 3390 | .await?; |
| 3391 | } else { |
| 3392 | if let Some(parent) = file_path.parent() { |
| 3393 | tokio::fs::create_dir_all(parent).await.map_err(|error| { |
| 3394 | ToolError::execution_failed(format!( |
| 3395 | "Failed to create directory {}: {error}", |
| 3396 | parent.display() |
| 3397 | )) |
| 3398 | })?; |
| 3399 | } |
| 3400 | run_blocking_write_atomic(&file_path, written.clone().into_bytes()).await?; |
| 3401 | } |
| 3402 | context.note_file_read(&file_path); |
| 3403 | drop(mutation_guard); |
| 3404 | |
| 3405 | let display = file_path.display().to_string(); |
| 3406 | let diff = make_unified_diff(&display, &prior_contents, &written); |
| 3407 | let summary = if existed_before { |
| 3408 | format!("Wrote {} bytes to {}", written.len(), display) |
| 3409 | } else { |
| 3410 | format!("Created {} ({} bytes)", display, written.len()) |
| 3411 | }; |
| 3412 | let summary = match line_ending { |
| 3413 | Some(ending) => format!( |
| 3414 | "{summary}; used {} line endings", |
| 3415 | if ending == "\r\n" { "CRLF" } else { "LF" } |
| 3416 | ), |
| 3417 | None => summary, |
| 3418 | }; |
| 3419 | let body = if diff.is_empty() { |
| 3420 | format!("{summary}\n(no changes)") |
| 3421 | } else { |
| 3422 | format!("{diff}\n{summary}") |
| 3423 | }; |
| 3424 | |
| 3425 | let outcome = if existed_before { "updated" } else { "created" }; |
| 3426 | // Keep the execution-owned receipt workspace-relative even though the |
| 3427 | // legacy model-facing output above retains its resolved-path wording. |
| 3428 | let receipt_diff = make_unified_diff(path_str, &prior_contents, &written); |
| 3429 | Ok(ToolResult::success(body).with_metadata(json!({ |
| 3430 | "event": "file.mutation", |
| 3431 | "mutation": { |
| 3432 | "diff": receipt_diff, |
| 3433 | "files": [mutation_file_entry(path_str, outcome, Some(written.as_bytes()))], |
| 3434 | "renames": [] |
| 3435 | } |
| 3436 | }))) |
| 3437 | } |
| 3438 | } |
| 3439 | |
| 3440 | // === EditFileTool === |
| 3441 | |
| 3442 | /// Tool for search/replace editing of files. |
| 3443 | pub struct EditFileTool; |
| 3444 | |
| 3445 | #[derive(Clone, Debug)] |
| 3446 | struct ContractEdit { |
| 3447 | index: usize, |
| 3448 | old_text: String, |
| 3449 | new_text: String, |
| 3450 | } |
| 3451 | |
| 3452 | #[derive(Clone, Debug)] |
| 3453 | struct ResolvedContractEdit { |
| 3454 | index: usize, |
| 3455 | start: usize, |
| 3456 | end: usize, |
| 3457 | replacement: String, |
| 3458 | } |
| 3459 | |
| 3460 | fn requested_line_ending(input: &Value) -> Result<Option<&'static str>, ToolError> { |
| 3461 | match input.get("line_ending") { |
| 3462 | None => Ok(None), |
| 3463 | Some(Value::String(value)) if value == "preserve" => Ok(None), |
| 3464 | Some(Value::String(value)) if value == "lf" => Ok(Some("\n")), |
| 3465 | Some(Value::String(value)) if value == "crlf" => Ok(Some("\r\n")), |
| 3466 | _ => Err(ToolError::invalid_input( |
| 3467 | "line_ending must be preserve, lf, or crlf", |
| 3468 | )), |
| 3469 | } |
| 3470 | } |
| 3471 | |
| 3472 | fn write_line_endings( |
| 3473 | content: &str, |
| 3474 | prior: &str, |
| 3475 | requested: Option<&str>, |
| 3476 | bounded: bool, |
| 3477 | ) -> Result<String, ToolError> { |
| 3478 | if bounded || requested.is_some() { |
| 3479 | check_contract_file_size(content.len())?; |
| 3480 | } |
| 3481 | if !bounded && requested.is_none() { |
| 3482 | return Ok(preserve_prior_line_endings(content, prior)); |
| 3483 | } |
| 3484 | if requested.is_none() && prior.is_empty() { |
| 3485 | return Ok(content.to_string()); |
| 3486 | } |
| 3487 | let normalized = normalize_contract_line_endings(content); |
| 3488 | let ending = requested.unwrap_or_else(|| contract_line_ending(prior)); |
| 3489 | if bounded || requested.is_some() { |
| 3490 | let extra = if ending == "\r\n" { |
| 3491 | normalized.bytes().filter(|byte| *byte == b'\n').count() |
| 3492 | } else { |
| 3493 | 0 |
| 3494 | }; |
| 3495 | check_contract_file_size(normalized.len().saturating_add(extra))?; |
| 3496 | } |
| 3497 | Ok(restore_contract_line_endings(&normalized, ending)) |
| 3498 | } |
| 3499 | |
| 3500 | fn normalize_contract_line_endings(text: &str) -> String { |
| 3501 | text.replace("\r\n", "\n").replace('\r', "\n") |
| 3502 | } |
| 3503 | |
| 3504 | fn contract_line_ending(text: &str) -> &'static str { |
| 3505 | match text.find('\n') { |
| 3506 | Some(index) if index > 0 && text.as_bytes()[index - 1] == b'\r' => "\r\n", |
| 3507 | _ => "\n", |
| 3508 | } |
| 3509 | } |
| 3510 | |
| 3511 | fn restore_contract_line_endings(text: &str, ending: &str) -> String { |
| 3512 | if ending == "\r\n" { |
| 3513 | text.replace('\n', "\r\n") |
| 3514 | } else { |
| 3515 | text.to_string() |
| 3516 | } |
| 3517 | } |
| 3518 | |
| 3519 | /// First code point of the placeholder range that carries one non-UTF-8 byte |
| 3520 | /// through a text edit (Supplementary Private Use Area-A, U+F0000..=U+F00FF). |
| 3521 | const RAW_BYTE_PLACEHOLDER_BASE: u32 = 0xF_0000; |
| 3522 | |
| 3523 | fn is_raw_byte_placeholder(ch: char) -> bool { |
| 3524 | (RAW_BYTE_PLACEHOLDER_BASE..=RAW_BYTE_PLACEHOLDER_BASE + 0xFF).contains(&u32::from(ch)) |
| 3525 | } |
| 3526 | |
| 3527 | /// Decode `bytes` for a text edit without losing any of them: valid UTF-8 is |
| 3528 | /// kept as text and each invalid byte becomes a placeholder code point that |
| 3529 | /// [`encode_lossless_text`] turns back into the same byte. A file that is not |
| 3530 | /// UTF-8 and already uses the placeholder range (or edits that do) cannot be |
| 3531 | /// round-tripped, so the edit is refused rather than risk a silent rewrite. |
| 3532 | /// |
| 3533 | /// The flag is `true` only when placeholders were introduced. A valid UTF-8 |
| 3534 | /// file keeps its characters as they are, including any in the placeholder |
| 3535 | /// range (Nerd Font icons live there), and is written back as plain UTF-8. |
| 3536 | fn decode_bytes_losslessly( |
| 3537 | bytes: &[u8], |
| 3538 | edits: &[ContractEdit], |
| 3539 | path: &str, |
| 3540 | ) -> Result<(String, bool), ToolError> { |
| 3541 | if let Ok(text) = std::str::from_utf8(bytes) { |
| 3542 | return Ok((text.to_string(), false)); |
| 3543 | } |
| 3544 | let refuse = || { |
| 3545 | ToolError::execution_failed(format!( |
| 3546 | "Could not edit file {path}: it is not valid UTF-8 and uses characters Codewhale needs to keep its raw bytes intact. The file was not changed; use `apply_patch` or a shell tool for this file." |
| 3547 | )) |
| 3548 | }; |
| 3549 | if edits.iter().any(|edit| { |
| 3550 | edit.old_text.chars().any(is_raw_byte_placeholder) |
| 3551 | || edit.new_text.chars().any(is_raw_byte_placeholder) |
| 3552 | }) { |
| 3553 | return Err(refuse()); |
| 3554 | } |
| 3555 | let mut out = String::with_capacity(bytes.len()); |
| 3556 | for chunk in bytes.utf8_chunks() { |
| 3557 | if chunk.valid().chars().any(is_raw_byte_placeholder) { |
| 3558 | return Err(refuse()); |
| 3559 | } |
| 3560 | out.push_str(chunk.valid()); |
| 3561 | for &byte in chunk.invalid() { |
| 3562 | out.push( |
| 3563 | char::from_u32(RAW_BYTE_PLACEHOLDER_BASE + u32::from(byte)) |
| 3564 | .expect("placeholder range holds valid code points"), |
| 3565 | ); |
| 3566 | } |
| 3567 | } |
| 3568 | Ok((out, true)) |
| 3569 | } |
| 3570 | |
| 3571 | /// Inverse of [`decode_bytes_losslessly`] for a file it decoded with |
| 3572 | /// placeholders. Never call it on text from a valid UTF-8 file. |
| 3573 | fn encode_lossless_text(text: &str) -> Vec<u8> { |
| 3574 | if !text.chars().any(is_raw_byte_placeholder) { |
| 3575 | return text.as_bytes().to_vec(); |
| 3576 | } |
| 3577 | let mut out = Vec::with_capacity(text.len()); |
| 3578 | let mut buf = [0_u8; 4]; |
| 3579 | for ch in text.chars() { |
| 3580 | if is_raw_byte_placeholder(ch) { |
| 3581 | out.push((u32::from(ch) - RAW_BYTE_PLACEHOLDER_BASE) as u8); |
| 3582 | } else { |
| 3583 | out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); |
| 3584 | } |
| 3585 | } |
| 3586 | out |
| 3587 | } |
| 3588 | |
| 3589 | // Raw-byte placeholders use four UTF-8 bytes in memory but encode as one. |
| 3590 | fn contract_encoded_size(text: &str, has_raw_bytes: bool) -> usize { |
| 3591 | if has_raw_bytes { |
| 3592 | text.chars() |
| 3593 | .map(|ch| { |
| 3594 | if is_raw_byte_placeholder(ch) { |
| 3595 | 1 |
| 3596 | } else { |
| 3597 | ch.len_utf8() |
| 3598 | } |
| 3599 | }) |
| 3600 | .sum() |
| 3601 | } else { |
| 3602 | text.len() |
| 3603 | } |
| 3604 | } |
| 3605 | |
| 3606 | fn append_contract_text( |
| 3607 | result: &mut String, |
| 3608 | encoded_size: &mut usize, |
| 3609 | text: &str, |
| 3610 | has_raw_bytes: bool, |
| 3611 | ) -> Result<(), ToolError> { |
| 3612 | let next = encoded_size.saturating_add(contract_encoded_size(text, has_raw_bytes)); |
| 3613 | check_contract_file_size(next)?; |
| 3614 | result.push_str(text); |
| 3615 | *encoded_size = next; |
| 3616 | Ok(()) |
| 3617 | } |
| 3618 | |
| 3619 | /// The line terminator of each line in `text`, in order (`\r\n`, `\n` or a |
| 3620 | /// lone `\r`). The k-th entry ends the k-th line of the LF-normalized text. |
| 3621 | fn line_terminators(text: &str) -> Vec<&'static str> { |
| 3622 | let bytes = text.as_bytes(); |
| 3623 | let mut out = Vec::new(); |
| 3624 | let mut index = 0; |
| 3625 | while index < bytes.len() { |
| 3626 | match bytes[index] { |
| 3627 | b'\r' if bytes.get(index + 1) == Some(&b'\n') => { |
| 3628 | out.push("\r\n"); |
| 3629 | index += 2; |
| 3630 | } |
| 3631 | b'\r' => { |
| 3632 | out.push("\r"); |
| 3633 | index += 1; |
| 3634 | } |
| 3635 | b'\n' => { |
| 3636 | out.push("\n"); |
| 3637 | index += 1; |
| 3638 | } |
| 3639 | _ => index += 1, |
| 3640 | } |
| 3641 | } |
| 3642 | out |
| 3643 | } |
| 3644 | |
| 3645 | /// Give every line an edit left alone its original terminator back, and the |
| 3646 | /// file's dominant `fallback` terminator to lines the edit wrote (B6). The |
| 3647 | /// edit ran on LF-normalized text; restoring one style for the whole file |
| 3648 | /// rewrote mixed-ending files on lines nobody touched. |
| 3649 | fn restore_line_endings_per_line( |
| 3650 | original: &str, |
| 3651 | normalized_original: &str, |
| 3652 | updated: &str, |
| 3653 | fallback: &str, |
| 3654 | has_raw_bytes: bool, |
| 3655 | ) -> Result<String, ToolError> { |
| 3656 | let terminators = line_terminators(original); |
| 3657 | if terminators.iter().all(|ending| *ending == fallback) { |
| 3658 | let extra = if fallback == "\r\n" { |
| 3659 | updated.bytes().filter(|byte| *byte == b'\n').count() |
| 3660 | } else { |
| 3661 | 0 |
| 3662 | }; |
| 3663 | check_contract_file_size( |
| 3664 | contract_encoded_size(updated, has_raw_bytes).saturating_add(extra), |
| 3665 | )?; |
| 3666 | return Ok(restore_contract_line_endings(updated, fallback)); |
| 3667 | } |
| 3668 | let diff = similar::TextDiff::configure() |
| 3669 | .timeout(std::time::Duration::from_secs(1)) |
| 3670 | .diff_lines(normalized_original, updated); |
| 3671 | let mut out = String::new(); |
| 3672 | let mut encoded_size = 0; |
| 3673 | for change in diff.iter_all_changes() { |
| 3674 | let ending = match change.tag() { |
| 3675 | similar::ChangeTag::Delete => continue, |
| 3676 | similar::ChangeTag::Equal => change |
| 3677 | .old_index() |
| 3678 | .and_then(|index| terminators.get(index).copied()) |
| 3679 | .unwrap_or(fallback), |
| 3680 | similar::ChangeTag::Insert => fallback, |
| 3681 | }; |
| 3682 | let line = change.value(); |
| 3683 | match line.strip_suffix('\n') { |
| 3684 | Some(body) => { |
| 3685 | append_contract_text(&mut out, &mut encoded_size, body, has_raw_bytes)?; |
| 3686 | append_contract_text(&mut out, &mut encoded_size, ending, has_raw_bytes)?; |
| 3687 | } |
| 3688 | None => append_contract_text(&mut out, &mut encoded_size, line, has_raw_bytes)?, |
| 3689 | } |
| 3690 | } |
| 3691 | Ok(out) |
| 3692 | } |
| 3693 | |
| 3694 | /// Rewrite `content` to match the line-ending style of an existing file's |
| 3695 | /// `prior` content, so a full-file overwrite (`write_file` / contract `write`) |
| 3696 | /// does not silently flip a CRLF (Windows) file to LF — the same policy |
| 3697 | /// `edit_file` applies. A brand-new file (no prior content) is returned |
| 3698 | /// verbatim: there is no style to preserve. |
| 3699 | fn preserve_prior_line_endings(content: &str, prior: &str) -> String { |
| 3700 | if prior.is_empty() { |
| 3701 | return content.to_string(); |
| 3702 | } |
| 3703 | restore_contract_line_endings( |
| 3704 | &normalize_contract_line_endings(content), |
| 3705 | contract_line_ending(prior), |
| 3706 | ) |
| 3707 | } |
| 3708 | |
| 3709 | /// Fallback matching view used only after a literal match fails. It follows |
| 3710 | /// The small-contract normalization categories while leaving the public schema as |
| 3711 | /// exact-text replacement rather than teaching a second edit mode. |
| 3712 | fn normalize_contract_fuzzy(text: &str) -> String { |
| 3713 | let compatible = text.nfkc().collect::<String>(); |
| 3714 | let mut trimmed = String::with_capacity(compatible.len()); |
| 3715 | for (index, line) in compatible.split('\n').enumerate() { |
| 3716 | if index > 0 { |
| 3717 | trimmed.push('\n'); |
| 3718 | } |
| 3719 | trimmed.push_str(line.trim_end()); |
| 3720 | } |
| 3721 | trimmed.chars().map(contract_fuzzy_char).collect() |
| 3722 | } |
| 3723 | |
| 3724 | fn contract_fuzzy_char(ch: char) -> char { |
| 3725 | match ch { |
| 3726 | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'', |
| 3727 | '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"', |
| 3728 | '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' |
| 3729 | | '\u{2212}' => '-', |
| 3730 | '\u{00A0}' | '\u{2002}'..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' => ' ', |
| 3731 | other => other, |
| 3732 | } |
| 3733 | } |
| 3734 | |
| 3735 | fn contract_fuzzy_offsets(original: &str, normalized: &str) -> Option<Vec<(usize, usize)>> { |
| 3736 | fn trim_line(rebuilt: &mut String, line_start: usize, offsets: &mut [(usize, usize)]) { |
| 3737 | let kept = line_start + rebuilt[line_start..].trim_end().len(); |
| 3738 | rebuilt.truncate(kept); |
| 3739 | for offset in offsets.iter_mut().rev() { |
| 3740 | if offset.0 <= kept { |
| 3741 | break; |
| 3742 | } |
| 3743 | offset.0 = kept; |
| 3744 | } |
| 3745 | } |
| 3746 | let mut rebuilt = String::with_capacity(normalized.len()); |
| 3747 | let mut offsets = vec![(0, 0)]; |
| 3748 | let mut line_start = 0; |
| 3749 | for (index, ch) in original.char_indices() { |
| 3750 | if ch == '\n' { |
| 3751 | trim_line(&mut rebuilt, line_start, &mut offsets); |
| 3752 | rebuilt.push('\n'); |
| 3753 | line_start = rebuilt.len(); |
| 3754 | } else { |
| 3755 | rebuilt.extend(std::iter::once(ch).nfkc().map(contract_fuzzy_char)); |
| 3756 | } |
| 3757 | offsets.push((rebuilt.len(), index + ch.len_utf8())); |
| 3758 | } |
| 3759 | trim_line(&mut rebuilt, line_start, &mut offsets); |
| 3760 | (rebuilt == normalized).then_some(offsets) |
| 3761 | } |
| 3762 | |
| 3763 | fn remap_single_fuzzy_edit( |
| 3764 | original: &str, |
| 3765 | normalized: &str, |
| 3766 | fuzzy_start: usize, |
| 3767 | fuzzy_end: usize, |
| 3768 | norm_offset: usize, |
| 3769 | orig_offset: usize, |
| 3770 | ) -> Option<(usize, usize, usize)> { |
| 3771 | let offsets = contract_fuzzy_offsets(original, normalized)?; |
| 3772 | let (rel_start, rel_end) = (fuzzy_start - norm_offset, fuzzy_end - norm_offset); |
| 3773 | let first_start = offsets.partition_point(|entry| entry.0 < rel_start); |
| 3774 | let first_end = offsets.partition_point(|entry| entry.0 < rel_end); |
| 3775 | let last_end = offsets.partition_point(|entry| entry.0 <= rel_end); |
| 3776 | let start = offsets |
| 3777 | .get(first_start) |
| 3778 | .filter(|entry| entry.0 == rel_start)? |
| 3779 | .1; |
| 3780 | let tight_end = offsets.get(first_end).filter(|entry| entry.0 == rel_end)?.1; |
| 3781 | let greedy_end = offsets[..last_end] |
| 3782 | .last() |
| 3783 | .filter(|entry| entry.0 == rel_end)? |
| 3784 | .1; |
| 3785 | Some(( |
| 3786 | orig_offset + start, |
| 3787 | orig_offset + tight_end, |
| 3788 | orig_offset + greedy_end, |
| 3789 | )) |
| 3790 | } |
| 3791 | |
| 3792 | fn text_matches(haystack: &str, needle: &str) -> Vec<(usize, usize)> { |
| 3793 | if needle.is_empty() { |
| 3794 | return Vec::new(); |
| 3795 | } |
| 3796 | haystack |
| 3797 | .match_indices(needle) |
| 3798 | .map(|(start, matched)| (start, start + matched.len())) |
| 3799 | .collect() |
| 3800 | } |
| 3801 | |
| 3802 | fn contract_edit_not_found( |
| 3803 | base: &str, |
| 3804 | old_text: &str, |
| 3805 | path: &str, |
| 3806 | index: usize, |
| 3807 | total: usize, |
| 3808 | has_raw_bytes: bool, |
| 3809 | ) -> ToolError { |
| 3810 | let header = if total == 1 { |
| 3811 | format!( |
| 3812 | "Could not find the exact text in {path}. The old text must match exactly including all whitespace and newlines." |
| 3813 | ) |
| 3814 | } else { |
| 3815 | format!( |
| 3816 | "Could not find edits[{index}] in {path}. The oldText must match exactly including all whitespace and newlines." |
| 3817 | ) |
| 3818 | }; |
| 3819 | let display_base: Cow<'_, str> = if has_raw_bytes { |
| 3820 | Cow::Owned( |
| 3821 | base.chars() |
| 3822 | .map(|ch| { |
| 3823 | if is_raw_byte_placeholder(ch) { |
| 3824 | '\u{FFFD}' |
| 3825 | } else { |
| 3826 | ch |
| 3827 | } |
| 3828 | }) |
| 3829 | .collect(), |
| 3830 | ) |
| 3831 | } else { |
| 3832 | Cow::Borrowed(base) |
| 3833 | }; |
| 3834 | let hint = nearest_match_hint(display_base.as_ref(), old_text, false, false); |
| 3835 | if hint.is_empty() { |
| 3836 | ToolError::execution_failed(header) |
| 3837 | } else { |
| 3838 | ToolError::execution_failed(format!("{header}\n{}", hint.trim_end())) |
| 3839 | } |
| 3840 | } |
| 3841 | |
| 3842 | fn contract_edit_duplicate(path: &str, index: usize, total: usize, matches: usize) -> ToolError { |
| 3843 | if total == 1 { |
| 3844 | ToolError::execution_failed(format!( |
| 3845 | "Found {matches} occurrences of the text in {path}. The text must be unique. Please provide more context to make it unique." |
| 3846 | )) |
| 3847 | } else { |
| 3848 | ToolError::execution_failed(format!( |
| 3849 | "Found {matches} occurrences of edits[{index}] in {path}. Each oldText must be unique. Please provide more context to make it unique." |
| 3850 | )) |
| 3851 | } |
| 3852 | } |
| 3853 | |
| 3854 | fn prepare_contract_edit_input(mut input: Value) -> Result<Value, ToolError> { |
| 3855 | for key in ["oldText", "newText"] { |
| 3856 | if let Some(text) = input.get(key).and_then(Value::as_str) { |
| 3857 | check_contract_file_size(text.len())?; |
| 3858 | } |
| 3859 | } |
| 3860 | if let Some(encoded) = input.get("edits").and_then(Value::as_str) { |
| 3861 | check_contract_file_size(encoded.len())?; |
| 3862 | } |
| 3863 | let object = input |
| 3864 | .as_object_mut() |
| 3865 | .ok_or_else(|| ToolError::invalid_input("edit input must be an object"))?; |
| 3866 | if let Some(Value::String(encoded)) = object.get("edits") |
| 3867 | && let Ok(decoded) = serde_json::from_str::<Value>(encoded) |
| 3868 | && decoded.is_array() |
| 3869 | { |
| 3870 | object.insert("edits".to_string(), decoded); |
| 3871 | } |
| 3872 | |
| 3873 | let legacy_old = object |
| 3874 | .get("oldText") |
| 3875 | .and_then(Value::as_str) |
| 3876 | .map(str::to_string); |
| 3877 | let legacy_new = object |
| 3878 | .get("newText") |
| 3879 | .and_then(Value::as_str) |
| 3880 | .map(str::to_string); |
| 3881 | if let (Some(old_text), Some(new_text)) = (legacy_old, legacy_new) { |
| 3882 | let legacy = json!({"oldText": old_text, "newText": new_text}); |
| 3883 | let mut edits = match object.remove("edits") { |
| 3884 | Some(Value::Array(edits)) => edits, |
| 3885 | _ => Vec::new(), |
| 3886 | }; |
| 3887 | edits.push(legacy); |
| 3888 | object.insert("edits".to_string(), Value::Array(edits)); |
| 3889 | object.remove("oldText"); |
| 3890 | object.remove("newText"); |
| 3891 | } |
| 3892 | Ok(input) |
| 3893 | } |
| 3894 | |
| 3895 | fn parse_contract_edits(input: &Value) -> Result<Vec<ContractEdit>, ToolError> { |
| 3896 | let raw = input |
| 3897 | .get("edits") |
| 3898 | .and_then(Value::as_array) |
| 3899 | .ok_or_else(|| ToolError::invalid_input("edits must be an array"))?; |
| 3900 | if raw.is_empty() { |
| 3901 | return Err(ToolError::invalid_input( |
| 3902 | "edit requires at least one replacement in edits", |
| 3903 | )); |
| 3904 | } |
| 3905 | let mut replacement_bytes = 0usize; |
| 3906 | raw.iter() |
| 3907 | .enumerate() |
| 3908 | .map(|(index, edit)| { |
| 3909 | reject_primitive_unknown(edit, &format!("edits[{index}]"), &["oldText", "newText"])?; |
| 3910 | let old_text = required_str(edit, "oldText")?; |
| 3911 | let new_text = required_str(edit, "newText")?; |
| 3912 | check_contract_file_size(old_text.len())?; |
| 3913 | check_contract_file_size(new_text.len())?; |
| 3914 | // All non-overlapping replacements survive into the output. Count |
| 3915 | // normalized bytes before copying another large replacement. |
| 3916 | replacement_bytes = replacement_bytes |
| 3917 | .saturating_add(new_text.len() - new_text.match_indices("\r\n").count()); |
| 3918 | check_contract_file_size(replacement_bytes)?; |
| 3919 | if old_text.is_empty() { |
| 3920 | return Err(ToolError::invalid_input(format!( |
| 3921 | "edits[{index}].oldText must not be empty" |
| 3922 | ))); |
| 3923 | } |
| 3924 | Ok(ContractEdit { |
| 3925 | index, |
| 3926 | old_text: normalize_contract_line_endings(old_text), |
| 3927 | new_text: normalize_contract_line_endings(new_text), |
| 3928 | }) |
| 3929 | }) |
| 3930 | .collect() |
| 3931 | } |
| 3932 | |
| 3933 | fn apply_resolved_edits( |
| 3934 | base: &str, |
| 3935 | edits: &[ResolvedContractEdit], |
| 3936 | offset: usize, |
| 3937 | has_raw_bytes: bool, |
| 3938 | ) -> Result<String, ToolError> { |
| 3939 | let mut encoded_size = contract_encoded_size(base, has_raw_bytes); |
| 3940 | check_contract_file_size(encoded_size)?; |
| 3941 | let mut updated = base.to_string(); |
| 3942 | for edit in edits.iter().rev() { |
| 3943 | let range = edit.start.saturating_sub(offset)..edit.end.saturating_sub(offset); |
| 3944 | let removed = &updated[range.clone()]; |
| 3945 | let projected_string_size = updated |
| 3946 | .len() |
| 3947 | .saturating_sub(removed.len()) |
| 3948 | .saturating_add(edit.replacement.len()); |
| 3949 | encoded_size = encoded_size |
| 3950 | .saturating_sub(contract_encoded_size(removed, has_raw_bytes)) |
| 3951 | .saturating_add(contract_encoded_size(&edit.replacement, has_raw_bytes)); |
| 3952 | // Reject each intermediate replacement before String::replace_range |
| 3953 | // allocates; raw-byte placeholders are at most four bytes in memory. |
| 3954 | check_contract_file_size(encoded_size)?; |
| 3955 | if projected_string_size > CONTRACT_FILE_MAX_BYTES * if has_raw_bytes { 4 } else { 1 } { |
| 3956 | check_contract_file_size(CONTRACT_FILE_MAX_BYTES + 1)?; |
| 3957 | } |
| 3958 | updated.replace_range(range, &edit.replacement); |
| 3959 | } |
| 3960 | Ok(updated) |
| 3961 | } |
| 3962 | |
| 3963 | fn lines_with_endings(text: &str) -> Vec<&str> { |
| 3964 | if text.is_empty() { |
| 3965 | Vec::new() |
| 3966 | } else { |
| 3967 | text.split_inclusive('\n').collect() |
| 3968 | } |
| 3969 | } |
| 3970 | |
| 3971 | fn line_spans(text: &str) -> Vec<(usize, usize)> { |
| 3972 | let mut offset = 0usize; |
| 3973 | lines_with_endings(text) |
| 3974 | .into_iter() |
| 3975 | .map(|line| { |
| 3976 | let span = (offset, offset + line.len()); |
| 3977 | offset = span.1; |
| 3978 | span |
| 3979 | }) |
| 3980 | .collect() |
| 3981 | } |
| 3982 | |
| 3983 | fn touched_line_range( |
| 3984 | spans: &[(usize, usize)], |
| 3985 | match_start: usize, |
| 3986 | match_end: usize, |
| 3987 | ) -> Result<(usize, usize), ToolError> { |
| 3988 | let start = spans |
| 3989 | .iter() |
| 3990 | .position(|(line_start, line_end)| match_start >= *line_start && match_start < *line_end) |
| 3991 | .ok_or_else(|| ToolError::execution_failed("edit match fell outside the file"))?; |
| 3992 | let mut end = start; |
| 3993 | while end < spans.len() && spans[end].1 < match_end { |
| 3994 | end += 1; |
| 3995 | } |
| 3996 | if end >= spans.len() { |
| 3997 | return Err(ToolError::execution_failed( |
| 3998 | "edit match fell outside the file", |
| 3999 | )); |
| 4000 | } |
| 4001 | Ok((start, end + 1)) |
| 4002 | } |
| 4003 | |
| 4004 | struct MappedContractEdit { |
| 4005 | index: usize, |
| 4006 | start: usize, |
| 4007 | end: usize, |
| 4008 | tight_end: usize, |
| 4009 | replacement: String, |
| 4010 | } |
| 4011 | |
| 4012 | enum ResolvedEditKind { |
| 4013 | Exact { |
| 4014 | start: usize, |
| 4015 | end: usize, |
| 4016 | }, |
| 4017 | Fuzzy { |
| 4018 | fuzzy_start: usize, |
| 4019 | fuzzy_end: usize, |
| 4020 | }, |
| 4021 | } |
| 4022 | |
| 4023 | struct PendingContractEdit { |
| 4024 | index: usize, |
| 4025 | replacement: String, |
| 4026 | kind: ResolvedEditKind, |
| 4027 | } |
| 4028 | |
| 4029 | fn normalized_offset_in_original(original: &str, byte_offset: usize) -> usize { |
| 4030 | let prefix = &original[..byte_offset]; |
| 4031 | let rest_of_line = original[byte_offset..] |
| 4032 | .split('\n') |
| 4033 | .next() |
| 4034 | .unwrap_or_default(); |
| 4035 | if rest_of_line.trim_end().is_empty() { |
| 4036 | normalize_contract_fuzzy(prefix).len() |
| 4037 | } else { |
| 4038 | let mut with_sentinel = String::with_capacity(prefix.len() + 1); |
| 4039 | with_sentinel.push_str(prefix); |
| 4040 | with_sentinel.push('a'); |
| 4041 | normalize_contract_fuzzy(&with_sentinel) |
| 4042 | .len() |
| 4043 | .saturating_sub(1) |
| 4044 | } |
| 4045 | } |
| 4046 | |
| 4047 | fn finalize_mapped_edits( |
| 4048 | mut edits: Vec<MappedContractEdit>, |
| 4049 | path: &str, |
| 4050 | ) -> Result<Vec<ResolvedContractEdit>, ToolError> { |
| 4051 | edits.sort_by_key(|edit| (edit.start, edit.tight_end, edit.end)); |
| 4052 | for index in 1..edits.len() { |
| 4053 | let next_start = edits[index].start; |
| 4054 | let next_index = edits[index].index; |
| 4055 | let previous = &mut edits[index - 1]; |
| 4056 | if previous.tight_end > next_start { |
| 4057 | return Err(ToolError::execution_failed(format!( |
| 4058 | "edits[{}] and edits[{}] overlap in {path}; merge them or target separate regions", |
| 4059 | previous.index, next_index |
| 4060 | ))); |
| 4061 | } |
| 4062 | if previous.end > next_start { |
| 4063 | previous.end = next_start; |
| 4064 | } |
| 4065 | } |
| 4066 | Ok(edits |
| 4067 | .into_iter() |
| 4068 | .map(|edit| ResolvedContractEdit { |
| 4069 | index: edit.index, |
| 4070 | start: edit.start, |
| 4071 | end: edit.end, |
| 4072 | replacement: edit.replacement, |
| 4073 | }) |
| 4074 | .collect()) |
| 4075 | } |
| 4076 | |
| 4077 | fn apply_mixed_contract_edits( |
| 4078 | base: &str, |
| 4079 | fuzzy_base: &str, |
| 4080 | pending: Vec<PendingContractEdit>, |
| 4081 | path: &str, |
| 4082 | has_raw_bytes: bool, |
| 4083 | ) -> Result<String, ToolError> { |
| 4084 | let original_lines = lines_with_endings(base); |
| 4085 | let original_spans = line_spans(base); |
| 4086 | let fuzzy_spans = line_spans(fuzzy_base); |
| 4087 | if original_lines.len() != fuzzy_spans.len() { |
| 4088 | return Err(ToolError::execution_failed( |
| 4089 | "fuzzy edit could not preserve the file's untouched lines", |
| 4090 | )); |
| 4091 | } |
| 4092 | |
| 4093 | struct PlacedEdit { |
| 4094 | start_line: usize, |
| 4095 | end_line: usize, |
| 4096 | sort_pos: usize, |
| 4097 | pending: PendingContractEdit, |
| 4098 | mapped: Option<MappedContractEdit>, |
| 4099 | } |
| 4100 | |
| 4101 | let mut placed = Vec::with_capacity(pending.len()); |
| 4102 | let mut all_mapped = true; |
| 4103 | for item in pending { |
| 4104 | match item.kind { |
| 4105 | ResolvedEditKind::Exact { start, end } => { |
| 4106 | let (start_line, end_line) = touched_line_range(&original_spans, start, end)?; |
| 4107 | let mapped = MappedContractEdit { |
| 4108 | index: item.index, |
| 4109 | start, |
| 4110 | end, |
| 4111 | tight_end: end, |
| 4112 | replacement: item.replacement.clone(), |
| 4113 | }; |
| 4114 | placed.push(PlacedEdit { |
| 4115 | start_line, |
| 4116 | end_line, |
| 4117 | sort_pos: start, |
| 4118 | pending: item, |
| 4119 | mapped: Some(mapped), |
| 4120 | }); |
| 4121 | } |
| 4122 | ResolvedEditKind::Fuzzy { |
| 4123 | fuzzy_start, |
| 4124 | fuzzy_end, |
| 4125 | } => { |
| 4126 | let (start_line, end_line) = |
| 4127 | touched_line_range(&fuzzy_spans, fuzzy_start, fuzzy_end)?; |
| 4128 | let orig_start = original_spans[start_line].0; |
| 4129 | let orig_end = original_spans[end_line - 1].1; |
| 4130 | let norm_start = fuzzy_spans[start_line].0; |
| 4131 | let norm_end = fuzzy_spans[end_line - 1].1; |
| 4132 | let mapped = remap_single_fuzzy_edit( |
| 4133 | &base[orig_start..orig_end], |
| 4134 | &fuzzy_base[norm_start..norm_end], |
| 4135 | fuzzy_start, |
| 4136 | fuzzy_end, |
| 4137 | norm_start, |
| 4138 | orig_start, |
| 4139 | ) |
| 4140 | .map(|(start, tight_end, end)| MappedContractEdit { |
| 4141 | index: item.index, |
| 4142 | start, |
| 4143 | end, |
| 4144 | tight_end, |
| 4145 | replacement: item.replacement.clone(), |
| 4146 | }); |
| 4147 | if mapped.is_none() { |
| 4148 | all_mapped = false; |
| 4149 | } |
| 4150 | let sort_pos = mapped.as_ref().map_or(fuzzy_start, |m| m.start); |
| 4151 | placed.push(PlacedEdit { |
| 4152 | start_line, |
| 4153 | end_line, |
| 4154 | sort_pos, |
| 4155 | pending: item, |
| 4156 | mapped, |
| 4157 | }); |
| 4158 | } |
| 4159 | } |
| 4160 | } |
| 4161 | |
| 4162 | if all_mapped { |
| 4163 | let mapped = placed |
| 4164 | .into_iter() |
| 4165 | .filter_map(|item| item.mapped) |
| 4166 | .collect::<Vec<_>>(); |
| 4167 | let resolved = finalize_mapped_edits(mapped, path)?; |
| 4168 | return apply_resolved_edits(base, &resolved, 0, has_raw_bytes); |
| 4169 | } |
| 4170 | |
| 4171 | placed.sort_by_key(|item| (item.start_line, item.end_line, item.sort_pos)); |
| 4172 | |
| 4173 | struct Group { |
| 4174 | start_line: usize, |
| 4175 | end_line: usize, |
| 4176 | items: Vec<PlacedEdit>, |
| 4177 | } |
| 4178 | |
| 4179 | let mut groups: Vec<Group> = Vec::new(); |
| 4180 | for item in placed { |
| 4181 | if let Some(group) = groups.last_mut() |
| 4182 | && item.start_line < group.end_line |
| 4183 | { |
| 4184 | group.end_line = group.end_line.max(item.end_line); |
| 4185 | group.items.push(item); |
| 4186 | } else { |
| 4187 | groups.push(Group { |
| 4188 | start_line: item.start_line, |
| 4189 | end_line: item.end_line, |
| 4190 | items: vec![item], |
| 4191 | }); |
| 4192 | } |
| 4193 | } |
| 4194 | |
| 4195 | let mut result = String::new(); |
| 4196 | let mut encoded_size = 0; |
| 4197 | let mut original_line = 0usize; |
| 4198 | for group in groups { |
| 4199 | for line in &original_lines[original_line..group.start_line] { |
| 4200 | append_contract_text(&mut result, &mut encoded_size, line, has_raw_bytes)?; |
| 4201 | } |
| 4202 | let group_orig_start = original_spans[group.start_line].0; |
| 4203 | let group_orig_end = original_spans[group.end_line - 1].1; |
| 4204 | let group_original = &base[group_orig_start..group_orig_end]; |
| 4205 | let replacement = if group.items.iter().all(|item| item.mapped.is_some()) { |
| 4206 | let mapped = group |
| 4207 | .items |
| 4208 | .into_iter() |
| 4209 | .filter_map(|item| item.mapped) |
| 4210 | .collect::<Vec<_>>(); |
| 4211 | let resolved = finalize_mapped_edits(mapped, path)?; |
| 4212 | apply_resolved_edits(group_original, &resolved, group_orig_start, has_raw_bytes)? |
| 4213 | } else { |
| 4214 | let group_norm_start = fuzzy_spans[group.start_line].0; |
| 4215 | let group_norm_end = fuzzy_spans[group.end_line - 1].1; |
| 4216 | let group_normalized = &fuzzy_base[group_norm_start..group_norm_end]; |
| 4217 | let mut resolved = group |
| 4218 | .items |
| 4219 | .into_iter() |
| 4220 | .map(|item| match item.pending.kind { |
| 4221 | ResolvedEditKind::Fuzzy { |
| 4222 | fuzzy_start, |
| 4223 | fuzzy_end, |
| 4224 | } => Ok(ResolvedContractEdit { |
| 4225 | index: item.pending.index, |
| 4226 | start: fuzzy_start - group_norm_start, |
| 4227 | end: fuzzy_end - group_norm_start, |
| 4228 | replacement: item.pending.replacement, |
| 4229 | }), |
| 4230 | ResolvedEditKind::Exact { start, end } => { |
| 4231 | let norm_start = |
| 4232 | normalized_offset_in_original(group_original, start - group_orig_start); |
| 4233 | let norm_end = |
| 4234 | normalized_offset_in_original(group_original, end - group_orig_start); |
| 4235 | if norm_start > norm_end |
| 4236 | || norm_end > group_normalized.len() |
| 4237 | || !group_normalized.is_char_boundary(norm_start) |
| 4238 | || !group_normalized.is_char_boundary(norm_end) |
| 4239 | { |
| 4240 | return Err(ToolError::execution_failed( |
| 4241 | "fuzzy edit could not preserve the file's untouched lines", |
| 4242 | )); |
| 4243 | } |
| 4244 | Ok(ResolvedContractEdit { |
| 4245 | index: item.pending.index, |
| 4246 | start: norm_start, |
| 4247 | end: norm_end, |
| 4248 | replacement: item.pending.replacement, |
| 4249 | }) |
| 4250 | } |
| 4251 | }) |
| 4252 | .collect::<Result<Vec<_>, ToolError>>()?; |
| 4253 | resolved.sort_by_key(|edit| (edit.start, edit.end)); |
| 4254 | for pair in resolved.windows(2) { |
| 4255 | if pair[0].end > pair[1].start { |
| 4256 | return Err(ToolError::execution_failed(format!( |
| 4257 | "edits[{}] and edits[{}] overlap in {path}; merge them or target separate regions", |
| 4258 | pair[0].index, pair[1].index |
| 4259 | ))); |
| 4260 | } |
| 4261 | } |
| 4262 | apply_resolved_edits(group_normalized, &resolved, 0, has_raw_bytes)? |
| 4263 | }; |
| 4264 | append_contract_text(&mut result, &mut encoded_size, &replacement, has_raw_bytes)?; |
| 4265 | original_line = group.end_line; |
| 4266 | } |
| 4267 | for line in &original_lines[original_line..] { |
| 4268 | append_contract_text(&mut result, &mut encoded_size, line, has_raw_bytes)?; |
| 4269 | } |
| 4270 | Ok(result) |
| 4271 | } |
| 4272 | |
| 4273 | fn apply_contract_edits( |
| 4274 | base: &str, |
| 4275 | edits: &[ContractEdit], |
| 4276 | path: &str, |
| 4277 | has_raw_bytes: bool, |
| 4278 | ) -> Result<String, ToolError> { |
| 4279 | let mut fuzzy_base: Option<String> = None; |
| 4280 | let mut pending = Vec::with_capacity(edits.len()); |
| 4281 | let mut any_fuzzy = false; |
| 4282 | |
| 4283 | for edit in edits { |
| 4284 | let exact = text_matches(base, &edit.old_text); |
| 4285 | if exact.len() == 1 { |
| 4286 | let (start, end) = exact[0]; |
| 4287 | pending.push(PendingContractEdit { |
| 4288 | index: edit.index, |
| 4289 | replacement: edit.new_text.clone(), |
| 4290 | kind: ResolvedEditKind::Exact { start, end }, |
| 4291 | }); |
| 4292 | continue; |
| 4293 | } |
| 4294 | if exact.len() > 1 { |
| 4295 | return Err(contract_edit_duplicate( |
| 4296 | path, |
| 4297 | edit.index, |
| 4298 | edits.len(), |
| 4299 | exact.len(), |
| 4300 | )); |
| 4301 | } |
| 4302 | |
| 4303 | let fuzzy = fuzzy_base.get_or_insert_with(|| normalize_contract_fuzzy(base)); |
| 4304 | let fuzzy_old = normalize_contract_fuzzy(&edit.old_text); |
| 4305 | let fuzzy_matches = text_matches(fuzzy, &fuzzy_old); |
| 4306 | let Some(&(fuzzy_start, fuzzy_end)) = fuzzy_matches.first() else { |
| 4307 | return Err(contract_edit_not_found( |
| 4308 | base, |
| 4309 | &edit.old_text, |
| 4310 | path, |
| 4311 | edit.index, |
| 4312 | edits.len(), |
| 4313 | has_raw_bytes, |
| 4314 | )); |
| 4315 | }; |
| 4316 | if fuzzy_matches.len() > 1 { |
| 4317 | return Err(contract_edit_duplicate( |
| 4318 | path, |
| 4319 | edit.index, |
| 4320 | edits.len(), |
| 4321 | fuzzy_matches.len(), |
| 4322 | )); |
| 4323 | } |
| 4324 | any_fuzzy = true; |
| 4325 | pending.push(PendingContractEdit { |
| 4326 | index: edit.index, |
| 4327 | replacement: edit.new_text.clone(), |
| 4328 | kind: ResolvedEditKind::Fuzzy { |
| 4329 | fuzzy_start, |
| 4330 | fuzzy_end, |
| 4331 | }, |
| 4332 | }); |
| 4333 | } |
| 4334 | |
| 4335 | let updated = if any_fuzzy { |
| 4336 | apply_mixed_contract_edits( |
| 4337 | base, |
| 4338 | fuzzy_base.as_deref().unwrap_or_default(), |
| 4339 | pending, |
| 4340 | path, |
| 4341 | has_raw_bytes, |
| 4342 | )? |
| 4343 | } else { |
| 4344 | let mut resolved = pending |
| 4345 | .into_iter() |
| 4346 | .map(|item| match item.kind { |
| 4347 | ResolvedEditKind::Exact { start, end } => ResolvedContractEdit { |
| 4348 | index: item.index, |
| 4349 | start, |
| 4350 | end, |
| 4351 | replacement: item.replacement, |
| 4352 | }, |
| 4353 | ResolvedEditKind::Fuzzy { .. } => unreachable!(), |
| 4354 | }) |
| 4355 | .collect::<Vec<_>>(); |
| 4356 | resolved.sort_by_key(|edit| (edit.start, edit.end)); |
| 4357 | for pair in resolved.windows(2) { |
| 4358 | if pair[0].end > pair[1].start { |
| 4359 | return Err(ToolError::execution_failed(format!( |
| 4360 | "edits[{}] and edits[{}] overlap in {path}; merge them or target separate regions", |
| 4361 | pair[0].index, pair[1].index |
| 4362 | ))); |
| 4363 | } |
| 4364 | } |
| 4365 | apply_resolved_edits(base, &resolved, 0, has_raw_bytes)? |
| 4366 | }; |
| 4367 | if updated == base { |
| 4368 | return Err(ToolError::execution_failed(format!( |
| 4369 | "No changes made to {path}; the replacement produced identical content." |
| 4370 | ))); |
| 4371 | } |
| 4372 | Ok(updated) |
| 4373 | } |
| 4374 | |
| 4375 | impl EditFileTool { |
| 4376 | pub(super) async fn execute_contract_edits( |
| 4377 | input: Value, |
| 4378 | context: &ToolContext, |
| 4379 | ) -> Result<ToolResult, ToolError> { |
| 4380 | let input = prepare_contract_edit_input(input)?; |
| 4381 | reject_primitive_unknown(&input, "edit", &["path", "edits"])?; |
| 4382 | let path_str = required_str(&input, "path")?; |
| 4383 | let edits = parse_contract_edits(&input)?; |
| 4384 | let read_plan = resolve_read_open_plan(context, path_str, "edit", false, false).await?; |
| 4385 | let file_path = read_plan.file_path.clone(); |
| 4386 | let mutation_guard = acquire_file_mutation(&file_path, context).await?; |
| 4387 | check_file_operation_cancelled(context)?; |
| 4388 | |
| 4389 | let raw_bytes = load_contract_source(read_plan, true, context) |
| 4390 | .await? |
| 4391 | .ok_or_else(|| { |
| 4392 | ToolError::execution_failed(format!( |
| 4393 | "Could not edit file {path_str}: file not found" |
| 4394 | )) |
| 4395 | })?; |
| 4396 | check_file_operation_cancelled(context)?; |
| 4397 | // Bytes that are not UTF-8 ride through the edit as placeholders and |
| 4398 | // are written back unchanged (B6), instead of becoming U+FFFD. |
| 4399 | let (raw, has_raw_bytes) = decode_bytes_losslessly(&raw_bytes, &edits, path_str)?; |
| 4400 | let (bom, without_bom) = raw |
| 4401 | .strip_prefix('\u{FEFF}') |
| 4402 | .map_or(("", raw.as_str()), |text| ("\u{FEFF}", text)); |
| 4403 | let ending = contract_line_ending(without_bom); |
| 4404 | let normalized = normalize_contract_line_endings(without_bom); |
| 4405 | let updated = apply_contract_edits(&normalized, &edits, path_str, has_raw_bytes)?; |
| 4406 | check_file_operation_cancelled(context)?; |
| 4407 | let restored = restore_line_endings_per_line( |
| 4408 | without_bom, |
| 4409 | &normalized, |
| 4410 | &updated, |
| 4411 | ending, |
| 4412 | has_raw_bytes, |
| 4413 | )?; |
| 4414 | check_contract_file_size( |
| 4415 | bom.len() |
| 4416 | .saturating_add(contract_encoded_size(&restored, has_raw_bytes)), |
| 4417 | )?; |
| 4418 | let mut final_content = format!("{bom}{restored}"); |
| 4419 | guard_edit(&file_path, path_str, Some(&raw), &final_content)?; |
| 4420 | if let Some(normalized) = normalize_edit(&file_path, &raw, &final_content).await { |
| 4421 | final_content = normalized; |
| 4422 | } |
| 4423 | |
| 4424 | check_contract_file_size(contract_encoded_size(&final_content, has_raw_bytes))?; |
| 4425 | check_file_operation_cancelled(context)?; |
| 4426 | let bytes = if has_raw_bytes { |
| 4427 | encode_lossless_text(&final_content) |
| 4428 | } else { |
| 4429 | final_content.clone().into_bytes() |
| 4430 | }; |
| 4431 | check_contract_file_size(bytes.len())?; |
| 4432 | check_file_operation_cancelled(context)?; |
| 4433 | // The mutation worker owns completion after atomic replacement starts. |
| 4434 | run_blocking_write_atomic(&file_path, bytes.clone()).await?; |
| 4435 | context.note_file_read(&file_path); |
| 4436 | drop(mutation_guard); |
| 4437 | |
| 4438 | Ok(contract_mutation_result( |
| 4439 | path_str, |
| 4440 | &raw, |
| 4441 | &final_content, |
| 4442 | &bytes, |
| 4443 | "updated", |
| 4444 | format!( |
| 4445 | "Successfully replaced {} block(s) in {path_str}.", |
| 4446 | edits.len() |
| 4447 | ), |
| 4448 | )) |
| 4449 | } |
| 4450 | } |
| 4451 | |
| 4452 | #[async_trait] |
| 4453 | impl ToolSpec for EditFileTool { |
| 4454 | fn name(&self) -> &'static str { |
| 4455 | "edit_file" |
| 4456 | } |
| 4457 | |
| 4458 | fn model_visible(&self) -> bool { |
| 4459 | false |
| 4460 | } |
| 4461 | |
| 4462 | fn description(&self) -> &'static str { |
| 4463 | "Replace text in a single file via exact search/replace after the file has been read with `read` in this session. It makes one unambiguous in-place edit, the counterpart of `sed -i` in `bash`. `search` must match exactly one location by default; when no exact match is found the tool retries with leading-whitespace-tolerant fuzzy matching automatically. Returns a compact unified diff, not the full file. Pass `expected_hash` (the `content_hash` from that `read`) to have the edit refused, with the file untouched, if it changed in between. `apply_patch` handles structural, multi-block, or cross-file changes, and `write` replaces a whole file." |
| 4464 | } |
| 4465 | |
| 4466 | fn input_schema(&self) -> Value { |
| 4467 | json!({ |
| 4468 | "type": "object", |
| 4469 | "properties": { |
| 4470 | "path": { |
| 4471 | "type": "string", |
| 4472 | "description": "Path to the file. Alias: `file_path`" |
| 4473 | }, |
| 4474 | "search": { |
| 4475 | "type": "string", |
| 4476 | "description": "Exact text to search for, including whitespace, indentation, and newlines. Aliases: `old_string`, `old_str`, `oldText`" |
| 4477 | }, |
| 4478 | "replace": { |
| 4479 | "type": "string", |
| 4480 | "description": "Text to replace with. Aliases: `new_string`, `new_str`, `newText`" |
| 4481 | }, |
| 4482 | "expected_hash": { |
| 4483 | "type": "string", |
| 4484 | "description": EXPECTED_HASH_DESCRIPTION |
| 4485 | } |
| 4486 | }, |
| 4487 | "required": ["path", "search", "replace"] |
| 4488 | }) |
| 4489 | } |
| 4490 | |
| 4491 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 4492 | vec![ |
| 4493 | ToolCapability::WritesFiles, |
| 4494 | ToolCapability::Sandboxable, |
| 4495 | ToolCapability::RequiresApproval, |
| 4496 | ] |
| 4497 | } |
| 4498 | |
| 4499 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 4500 | ApprovalRequirement::Suggest |
| 4501 | } |
| 4502 | |
| 4503 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 4504 | // Translate known cross-harness spellings (`old_string`/`new_string`, |
| 4505 | // `old_str`/`new_str`, …) onto `search`/`replace` first, then reject |
| 4506 | // whatever is left that we do not implement. #5209 required that a |
| 4507 | // mis-named edit never produce a success-shaped receipt for a file |
| 4508 | // that did not change; performing the edit the model unambiguously |
| 4509 | // asked for satisfies that more directly than refusing it did. |
| 4510 | let mut input = input; |
| 4511 | apply_param_aliases(&mut input, PATH_ALIASES, "File edit")?; |
| 4512 | apply_param_aliases(&mut input, EDIT_ALIASES, "File edit")?; |
| 4513 | EDIT_PARAMS.reject_unknown(&input)?; |
| 4514 | |
| 4515 | let path_str = required_str(&input, "path")?; |
| 4516 | let search = required_str(&input, "search")?; |
| 4517 | let replace = required_str(&input, "replace")?; |
| 4518 | let expected_hash = optional_str(&input, "expected_hash")?; |
| 4519 | |
| 4520 | if search == replace { |
| 4521 | // #5003 — long-text edits repeatedly failed here because the model |
| 4522 | // generated a `replace` identical to `search`. A bare "no change" |
| 4523 | // message gave no hint of the root cause, so the model retried the |
| 4524 | // same broken call. Spell out the failure and the recovery path. |
| 4525 | let char_count = search.chars().count(); |
| 4526 | let line_count = search.lines().count(); |
| 4527 | return Err(ToolError::invalid_input(format!( |
| 4528 | "search and replace are identical ({char_count} chars, {line_count} lines), so no change is possible. This usually means `replace` was copied verbatim from `search` instead of carrying the intended edits. Recovery: re-read the file with `read`, then retry with a `replace` that is genuinely different from `search`; for large multi-line rewrites prefer apply_patch with a unified diff." |
| 4529 | ))); |
| 4530 | } |
| 4531 | if search.is_empty() { |
| 4532 | return Err(ToolError::invalid_input("search must not be empty")); |
| 4533 | } |
| 4534 | if let Some(reason) = edit_payload_looks_corrupted(search, replace) { |
| 4535 | return Err(ToolError::invalid_input(format!( |
| 4536 | "edit_file refused corrupted payload: {reason}. Recovery: re-read the file and retry with a complete replace (or use apply_patch for brace-heavy multi-line edits)." |
| 4537 | ))); |
| 4538 | } |
| 4539 | |
| 4540 | let read_plan = |
| 4541 | resolve_read_open_plan(context, path_str, "edit_file", false, false).await?; |
| 4542 | let file_path = read_plan.file_path.clone(); |
| 4543 | context.require_fresh_file_read(&file_path, path_str)?; |
| 4544 | |
| 4545 | let (content_bytes, _fd_path) = |
| 4546 | open_and_read_verified_bytes(read_plan.clone(), None, false, "Failed to read") |
| 4547 | .await? |
| 4548 | .ok_or_else(|| { |
| 4549 | ToolError::execution_failed(format!( |
| 4550 | "Failed to read {}: file not found", |
| 4551 | file_path.display() |
| 4552 | )) |
| 4553 | })?; |
| 4554 | let contents = String::from_utf8(content_bytes).map_err(|e| { |
| 4555 | ToolError::execution_failed(format!("Failed to read {}: {}", file_path.display(), e)) |
| 4556 | })?; |
| 4557 | |
| 4558 | // Content-hash guard (#3979). Verified against `contents` — the exact |
| 4559 | // snapshot every match below is computed from and that the write is |
| 4560 | // derived from — and before any search/replace work, so a stale hash |
| 4561 | // can never reach the filesystem regardless of what the search would |
| 4562 | // have matched. |
| 4563 | verify_expected_hash(expected_hash, contents.as_bytes(), "edit", path_str)?; |
| 4564 | |
| 4565 | // Models provide LF newlines even when the file on disk uses CRLF. |
| 4566 | // Match in a newline-normalized view, while retaining the sparse |
| 4567 | // positions where CR bytes were removed so only the original span is |
| 4568 | // replaced and the rest of the file stays byte-for-byte untouched. |
| 4569 | let (normalized_contents, crlf_positions) = normalize_crlf_with_positions(&contents); |
| 4570 | let normalized_search = normalize_crlf(search); |
| 4571 | let mut exact_ranges = normalized_contents |
| 4572 | .match_indices(normalized_search.as_ref()) |
| 4573 | .map(|(start, matched)| (start, start + matched.len())); |
| 4574 | let first_exact_match = exact_ranges |
| 4575 | .next() |
| 4576 | .map(|range| map_normalized_range(range, crlf_positions.as_deref())); |
| 4577 | let exact_count = usize::from(first_exact_match.is_some()) + exact_ranges.count(); |
| 4578 | |
| 4579 | let ((match_start, match_end), fuzz_kind) = if exact_count == 0 { |
| 4580 | // First fallback: tolerate indentation differences. |
| 4581 | let indent_matches = map_normalized_ranges( |
| 4582 | leading_whitespace_fuzzy_matches( |
| 4583 | normalized_contents.as_ref(), |
| 4584 | normalized_search.as_ref(), |
| 4585 | ), |
| 4586 | crlf_positions.as_deref(), |
| 4587 | ); |
| 4588 | match indent_matches.as_slice() { |
| 4589 | [(start, end)] => ((*start, *end), Some("indentation")), |
| 4590 | [] => { |
| 4591 | // Second fallback: tolerate typographic-punctuation |
| 4592 | // drift (smart quotes, em-dashes, NBSP). Picks up the |
| 4593 | // copy-paste failure mode where a browser/chat client |
| 4594 | // silently substituted Unicode punctuation in for the |
| 4595 | // ASCII the file actually contains. |
| 4596 | let punct_matches = map_normalized_ranges( |
| 4597 | punctuation_normalized_matches( |
| 4598 | normalized_contents.as_ref(), |
| 4599 | normalized_search.as_ref(), |
| 4600 | ), |
| 4601 | crlf_positions.as_deref(), |
| 4602 | ); |
| 4603 | match punct_matches.as_slice() { |
| 4604 | [] => { |
| 4605 | // #5003 — the model could not tell why its search |
| 4606 | // missed; show the first lines of the search text |
| 4607 | // so it can compare against the file's contents. |
| 4608 | return Err(ToolError::execution_failed(format!( |
| 4609 | "Search string not found in {}. The search text starts with:\n{}\n{}Recovery: retry with the search copied from the lines above, or call `read` with path=\"{path_str}\" to inspect the current contents.", |
| 4610 | file_path.display(), |
| 4611 | preview_search_for_error(search), |
| 4612 | nearest_match_hint( |
| 4613 | normalized_contents.as_ref(), |
| 4614 | normalized_search.as_ref(), |
| 4615 | crlf_positions.is_some(), |
| 4616 | search.contains('\r'), |
| 4617 | ), |
| 4618 | ))); |
| 4619 | } |
| 4620 | [(start, end)] => ((*start, *end), Some("punctuation")), |
| 4621 | _ => { |
| 4622 | return Err(ToolError::execution_failed(format!( |
| 4623 | "File `edit` search is non-unique after punctuation normalization: matched {} locations in {}. Recovery: call `read` with path=\"{path_str}\" and retry with surrounding lines that make the search unique.", |
| 4624 | punct_matches.len(), |
| 4625 | file_path.display() |
| 4626 | ))); |
| 4627 | } |
| 4628 | } |
| 4629 | } |
| 4630 | _ => { |
| 4631 | return Err(ToolError::execution_failed(format!( |
| 4632 | "File `edit` search is non-unique after indentation normalization: matched {} locations in {}. Recovery: call `read` with path=\"{path_str}\" and retry with surrounding lines that make the search unique.", |
| 4633 | indent_matches.len(), |
| 4634 | file_path.display() |
| 4635 | ))); |
| 4636 | } |
| 4637 | } |
| 4638 | } else if exact_count > 1 { |
| 4639 | return Err(ToolError::execution_failed(format!( |
| 4640 | "File `edit` search is non-unique: matched {} locations in {}. \ |
| 4641 | Recovery: call `read` with path=\"{path_str}\" and retry with surrounding lines that make the search unique.", |
| 4642 | exact_count, |
| 4643 | file_path.display() |
| 4644 | ))); |
| 4645 | } else { |
| 4646 | let Some((start, end)) = first_exact_match else { |
| 4647 | return Err(ToolError::execution_failed( |
| 4648 | "edit_file internal range accounting failed — refusing write", |
| 4649 | )); |
| 4650 | }; |
| 4651 | let fuzz_kind = (&contents[start..end] != search).then_some("line endings"); |
| 4652 | ((start, end), fuzz_kind) |
| 4653 | }; |
| 4654 | |
| 4655 | let effective_replace = |
| 4656 | normalize_replacement_line_endings(replace, crlf_positions.is_some()); |
| 4657 | let mut updated = contents.clone(); |
| 4658 | updated.replace_range(match_start..match_end, &effective_replace); |
| 4659 | if updated == contents { |
| 4660 | return Err(ToolError::invalid_input( |
| 4661 | "search and replace resolve to identical file contents after line-ending normalization, no change intended", |
| 4662 | )); |
| 4663 | } |
| 4664 | |
| 4665 | if let Some(reason) = invalid_preprocessor_edit(&file_path, &contents, &updated) { |
| 4666 | return Err(ToolError::invalid_input(format!( |
| 4667 | "edit_file refused corrupted payload: {reason}. Recovery: re-read the file and retry with a complete replace (or use apply_patch for brace-heavy multi-line edits)." |
| 4668 | ))); |
| 4669 | } |
| 4670 | |
| 4671 | // Fidelity: the intended replace text must appear in the updated buffer |
| 4672 | // (empty replace is a valid deletion). Catches host/tool bridges that |
| 4673 | // claim success after mangling the payload. |
| 4674 | if !effective_replace.is_empty() && !updated.contains(&effective_replace) { |
| 4675 | return Err(ToolError::execution_failed( |
| 4676 | "edit_file internal fidelity check failed: replace text missing from updated buffer — refusing write", |
| 4677 | )); |
| 4678 | } |
| 4679 | |
| 4680 | guard_edit(&file_path, path_str, Some(&contents), &updated)?; |
| 4681 | |
| 4682 | // #6205 — normalize after the syntax gate so the next turn's anchors |
| 4683 | // match the bytes on disk rather than the text the model emitted. |
| 4684 | let normalized_formatting = match normalize_edit(&file_path, &contents, &updated).await { |
| 4685 | Some(normalized) => { |
| 4686 | updated = normalized; |
| 4687 | true |
| 4688 | } |
| 4689 | None => false, |
| 4690 | }; |
| 4691 | |
| 4692 | run_blocking_write_atomic(&file_path, updated.clone().into_bytes()).await?; |
| 4693 | |
| 4694 | // #5209 — never emit a success receipt unless the on-disk write |
| 4695 | // actually applied. A fabricated "Replaced 1 occurrence" + diff is |
| 4696 | // worse than a hard error: models trust it and re-edit the same |
| 4697 | // span 3–5× before noticing nothing changed. |
| 4698 | let (on_disk_bytes, _fd_path) = |
| 4699 | open_and_read_verified_bytes(read_plan, None, false, "Failed to verify write to") |
| 4700 | .await? |
| 4701 | .ok_or_else(|| { |
| 4702 | ToolError::execution_failed(format!( |
| 4703 | "Failed to verify write to {}: file not found", |
| 4704 | file_path.display() |
| 4705 | )) |
| 4706 | })?; |
| 4707 | let on_disk = String::from_utf8(on_disk_bytes).map_err(|e| { |
| 4708 | ToolError::execution_failed(format!( |
| 4709 | "Failed to verify write to {}: {}", |
| 4710 | file_path.display(), |
| 4711 | e |
| 4712 | )) |
| 4713 | })?; |
| 4714 | if on_disk != updated { |
| 4715 | return Err(ToolError::execution_failed(format!( |
| 4716 | "edit_file write verification failed for {}: on-disk contents do not match the applied edit — refusing success receipt", |
| 4717 | file_path.display() |
| 4718 | ))); |
| 4719 | } |
| 4720 | |
| 4721 | context.note_file_read(&file_path); |
| 4722 | |
| 4723 | let display = file_path.display().to_string(); |
| 4724 | let diff = make_unified_diff(&display, &contents, &updated); |
| 4725 | let fuzz_note = match fuzz_kind { |
| 4726 | Some("indentation") => " (fuzzy indentation match)", |
| 4727 | Some("punctuation") => { |
| 4728 | " (fuzzy punctuation match — typographic quotes/dashes normalized)" |
| 4729 | } |
| 4730 | Some("line endings") => " (CRLF/LF-normalized match)", |
| 4731 | Some(other) => other, |
| 4732 | None => "", |
| 4733 | }; |
| 4734 | let format_note = if normalized_formatting { |
| 4735 | NORMALIZED_NOTE |
| 4736 | } else { |
| 4737 | "" |
| 4738 | }; |
| 4739 | let summary = format!("Replaced 1 occurrence in {display}{fuzz_note}{format_note}"); |
| 4740 | let body = if diff.is_empty() { |
| 4741 | format!("{summary}\n(no textual changes)") |
| 4742 | } else { |
| 4743 | format!("{diff}\n{summary}") |
| 4744 | }; |
| 4745 | |
| 4746 | // The structured receipt uses the requested workspace path instead of |
| 4747 | // the resolved host path retained by the legacy model-facing body. |
| 4748 | let receipt_diff = make_unified_diff(path_str, &contents, &updated); |
| 4749 | Ok(ToolResult::success(body).with_metadata(json!({ |
| 4750 | "event": "file.mutation", |
| 4751 | "mutation": { |
| 4752 | "diff": receipt_diff, |
| 4753 | "files": [mutation_file_entry(path_str, "updated", Some(updated.as_bytes()))], |
| 4754 | "renames": [] |
| 4755 | } |
| 4756 | }))) |
| 4757 | } |
| 4758 | } |
| 4759 | |
| 4760 | /// Detect catastrophic argument corruption of brace-structured edits. |
| 4761 | /// |
| 4762 | /// Models (and some host XML/JSON bridges) occasionally deliver a `replace` |
| 4763 | /// payload where a multi-line `{ ... }` block collapsed to empty `[]` or `{}` |
| 4764 | /// while `search` still contains the full structured original. Writing that |
| 4765 | /// would brick Rust match arms / JSON objects. Fail closed with recovery text |
| 4766 | /// instead of applying the mangled payload (dogfood 2026-07-24). |
| 4767 | /// |
| 4768 | /// Unbalanced-to-unbalanced edits with the **same** brace/bracket delta are |
| 4769 | /// legitimate (e.g. adding `});` inside a nested fragment). Only a *change* |
| 4770 | /// in balance is treated as truncation/mangling. Empty-bracket collapse and |
| 4771 | /// extreme-shrinkage guards remain. |
| 4772 | fn edit_payload_looks_corrupted(search: &str, replace: &str) -> Option<&'static str> { |
| 4773 | let search_curly_open = search.matches('{').count(); |
| 4774 | let search_curly_close = search.matches('}').count(); |
| 4775 | let replace_curly_open = replace.matches('{').count(); |
| 4776 | let replace_curly_close = replace.matches('}').count(); |
| 4777 | let search_square_open = search.matches('[').count(); |
| 4778 | let search_square_close = search.matches(']').count(); |
| 4779 | let replace_square_open = replace.matches('[').count(); |
| 4780 | let replace_square_close = replace.matches(']').count(); |
| 4781 | |
| 4782 | let search_curly_delta = search_curly_open as i32 - search_curly_close as i32; |
| 4783 | let replace_curly_delta = replace_curly_open as i32 - replace_curly_close as i32; |
| 4784 | let search_square_delta = search_square_open as i32 - search_square_close as i32; |
| 4785 | let replace_square_delta = replace_square_open as i32 - replace_square_close as i32; |
| 4786 | |
| 4787 | // Same delta on both sides (including both unbalanced the same way) is |
| 4788 | // normal for fragment edits. Divergent deltas usually mean truncation. |
| 4789 | if search_curly_delta != replace_curly_delta { |
| 4790 | return Some( |
| 4791 | "search/replace change `{`/`}` brace balance — the tool-call arguments were likely truncated or mangled before apply", |
| 4792 | ); |
| 4793 | } |
| 4794 | if search_square_delta != replace_square_delta { |
| 4795 | return Some( |
| 4796 | "search/replace change `[`/`]` bracket balance — the tool-call arguments were likely truncated or mangled before apply", |
| 4797 | ); |
| 4798 | } |
| 4799 | |
| 4800 | // Dogfood 2026-07-24: multi-line Rust `{ ... }` search collapsed into an |
| 4801 | // empty `[ ... ]` placeholder (host/XML arg bridge ate the brace body). |
| 4802 | // Count non-whitespace, non-bracket payload chars; a near-empty bracket |
| 4803 | // husk with a tiny tail like `=> {},` is the signature of that failure. |
| 4804 | if search_curly_open >= 1 && replace_square_open >= 1 { |
| 4805 | let significant = replace |
| 4806 | .chars() |
| 4807 | .filter(|c| !c.is_whitespace() && *c != '[' && *c != ']') |
| 4808 | .count(); |
| 4809 | if significant <= 12 { |
| 4810 | return Some( |
| 4811 | "replace collapsed a brace-structured search block into an empty/placeholder bracket span — refusing to brick the file; re-send the full replace text (prefer apply_patch for multi-line match arms)", |
| 4812 | ); |
| 4813 | } |
| 4814 | } |
| 4815 | |
| 4816 | // Extreme shrinkage with lost braces (e.g. 200-char match arm -> tiny stub). |
| 4817 | // Balanced-to-balanced nesting changes that shrink hard still look like |
| 4818 | // mangling; keep this guard even when deltas match. |
| 4819 | if search.len() >= 80 |
| 4820 | && replace.len() * 8 < search.len() |
| 4821 | && search_curly_open >= 1 |
| 4822 | && replace_curly_open < search_curly_open |
| 4823 | { |
| 4824 | return Some( |
| 4825 | "replace is drastically shorter than search and lost brace structure — likely argument mangling; refuse apply", |
| 4826 | ); |
| 4827 | } |
| 4828 | |
| 4829 | None |
| 4830 | } |
| 4831 | |
| 4832 | const PREPROCESSOR_CONDITIONAL_ERROR: &str = "replace would change the C/C++ preprocessor conditional balance (#if/#ifdef/#ifndef vs #endif) — the search or replace text is missing a matching directive; copy the complete block including both its opening and closing directives"; |
| 4833 | |
| 4834 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 4835 | struct PreprocessorConditionalDebt { |
| 4836 | orphaned_closes: usize, |
| 4837 | unclosed_opens: usize, |
| 4838 | } |
| 4839 | |
| 4840 | impl PreprocessorConditionalDebt { |
| 4841 | fn total(self) -> usize { |
| 4842 | self.orphaned_closes + self.unclosed_opens |
| 4843 | } |
| 4844 | } |
| 4845 | |
| 4846 | /// Reject an edit only when it introduces new conditional-structure damage in |
| 4847 | /// a file whose extension identifies it as C-family source. The whole file is |
| 4848 | /// checked before and after the edit: complete block insertion/removal is safe, |
| 4849 | /// while an orphaned opener or closer increases the structural debt. Existing |
| 4850 | /// debt may be preserved or reduced so this guard never prevents a repair. |
| 4851 | fn invalid_preprocessor_edit(path: &Path, before: &str, after: &str) -> Option<&'static str> { |
| 4852 | if !is_c_family_source(path) { |
| 4853 | return None; |
| 4854 | } |
| 4855 | |
| 4856 | let before_debt = preprocessor_conditional_debt(before); |
| 4857 | let after_debt = preprocessor_conditional_debt(after); |
| 4858 | let safe = after_debt == before_debt |
| 4859 | || after_debt.total() == 0 |
| 4860 | || after_debt.total() < before_debt.total(); |
| 4861 | |
| 4862 | (!safe).then_some(PREPROCESSOR_CONDITIONAL_ERROR) |
| 4863 | } |
| 4864 | |
| 4865 | fn is_c_family_source(path: &Path) -> bool { |
| 4866 | const EXTENSIONS: &[&str] = &[ |
| 4867 | "c", "cc", "cp", "cpp", "cxx", "h", "h++", "hh", "hpp", "hxx", "inl", "ipp", "ixx", "m", |
| 4868 | "mm", "tpp", "cu", "cuh", "cppm", |
| 4869 | ]; |
| 4870 | |
| 4871 | path.extension() |
| 4872 | .and_then(|extension| extension.to_str()) |
| 4873 | .is_some_and(|extension| { |
| 4874 | EXTENSIONS |
| 4875 | .iter() |
| 4876 | .any(|candidate| extension.eq_ignore_ascii_case(candidate)) |
| 4877 | }) |
| 4878 | } |
| 4879 | |
| 4880 | /// Measure unmatched preprocessor conditionals across an entire source file. |
| 4881 | /// Tracking nesting (instead of comparing span-level tuple counts) also catches |
| 4882 | /// an `#endif` moved before its opener. Whitespace between `#` and the directive |
| 4883 | /// name is accepted, as it is by C preprocessors. |
| 4884 | fn preprocessor_conditional_debt(text: &str) -> PreprocessorConditionalDebt { |
| 4885 | let mut depth = 0usize; |
| 4886 | let mut orphaned_closes = 0usize; |
| 4887 | |
| 4888 | for line in text.lines() { |
| 4889 | match preprocessor_directive(line) { |
| 4890 | Some("if" | "ifdef" | "ifndef") => depth += 1, |
| 4891 | Some("endif") if depth == 0 => orphaned_closes += 1, |
| 4892 | Some("endif") => depth -= 1, |
| 4893 | _ => {} |
| 4894 | } |
| 4895 | } |
| 4896 | |
| 4897 | PreprocessorConditionalDebt { |
| 4898 | orphaned_closes, |
| 4899 | unclosed_opens: depth, |
| 4900 | } |
| 4901 | } |
| 4902 | |
| 4903 | fn preprocessor_directive(line: &str) -> Option<&str> { |
| 4904 | let rest = line.trim_start().strip_prefix('#')?.trim_start(); |
| 4905 | let name_end = rest |
| 4906 | .find(|character: char| !character.is_ascii_alphabetic()) |
| 4907 | .unwrap_or(rest.len()); |
| 4908 | (name_end > 0).then_some(&rest[..name_end]) |
| 4909 | } |
| 4910 | |
| 4911 | /// Build a short, line-truncated preview of a (possibly very long) search |
| 4912 | /// payload for error messages, so the model can compare what it searched for |
| 4913 | /// against the file's actual contents without the error message ballooning. |
| 4914 | /// The file region most like a search that did not match (#6542), with |
| 4915 | /// 1-based line numbers and a note on whitespace / line-ending differences, |
| 4916 | /// so the next edit can copy the real text instead of re-reading the file. |
| 4917 | fn nearest_match_hint( |
| 4918 | contents: &str, |
| 4919 | search: &str, |
| 4920 | file_has_crlf: bool, |
| 4921 | search_has_cr: bool, |
| 4922 | ) -> String { |
| 4923 | const MAX_SCANNED_LINES: usize = 50_000; |
| 4924 | const MAX_EXCERPT_LINES: usize = 12; |
| 4925 | const MAX_EXCERPT_LINE_LEN: usize = 200; |
| 4926 | const MIN_SCORE: f32 = 0.5; |
| 4927 | |
| 4928 | let line_ratio = |a: &str, b: &str| -> f32 { |
| 4929 | let (a, b) = (a.trim(), b.trim()); |
| 4930 | if a == b { |
| 4931 | 1.0 |
| 4932 | } else { |
| 4933 | similar::TextDiff::from_chars(a, b).ratio() |
| 4934 | } |
| 4935 | }; |
| 4936 | let file_lines: Vec<&str> = contents.lines().take(MAX_SCANNED_LINES).collect(); |
| 4937 | let search_lines: Vec<&str> = search.lines().collect(); |
| 4938 | let Some(anchor) = search_lines.iter().position(|line| !line.trim().is_empty()) else { |
| 4939 | return String::new(); |
| 4940 | }; |
| 4941 | let window = search_lines.len().min(file_lines.len()).max(1); |
| 4942 | |
| 4943 | let mut anchor_indices = vec![anchor]; |
| 4944 | if let Some(longest) = search_lines |
| 4945 | .iter() |
| 4946 | .enumerate() |
| 4947 | .filter(|(idx, line)| *idx != anchor && !line.trim().is_empty()) |
| 4948 | .max_by_key(|(_, line)| line.trim().len()) |
| 4949 | .map(|(idx, _)| idx) |
| 4950 | { |
| 4951 | anchor_indices.push(longest); |
| 4952 | } |
| 4953 | |
| 4954 | let mut candidate_starts = std::collections::BTreeSet::new(); |
| 4955 | for anchor_idx in anchor_indices { |
| 4956 | let mut anchors: Vec<(f32, usize)> = file_lines |
| 4957 | .iter() |
| 4958 | .enumerate() |
| 4959 | .filter(|(index, line)| *index >= anchor_idx && !line.trim().is_empty()) |
| 4960 | .map(|(index, line)| { |
| 4961 | ( |
| 4962 | line_ratio(search_lines[anchor_idx], line), |
| 4963 | index - anchor_idx, |
| 4964 | ) |
| 4965 | }) |
| 4966 | .collect(); |
| 4967 | anchors.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); |
| 4968 | for (_, start) in anchors.into_iter().take(8) { |
| 4969 | candidate_starts.insert(start); |
| 4970 | } |
| 4971 | } |
| 4972 | let best = candidate_starts |
| 4973 | .into_iter() |
| 4974 | .map(|start| { |
| 4975 | let end = (start + window).min(file_lines.len()); |
| 4976 | let score = search_lines |
| 4977 | .iter() |
| 4978 | .zip(&file_lines[start..end]) |
| 4979 | .map(|(want, have)| line_ratio(want, have)) |
| 4980 | .sum::<f32>() |
| 4981 | / window as f32; |
| 4982 | (score, start, end) |
| 4983 | }) |
| 4984 | .max_by(|a, b| a.0.total_cmp(&b.0).then(b.1.cmp(&a.1))); |
| 4985 | |
| 4986 | let mut notes = Vec::new(); |
| 4987 | if search_has_cr && !file_has_crlf { |
| 4988 | notes.push( |
| 4989 | "the search contains carriage returns (CRLF) but the file uses LF line endings" |
| 4990 | .to_string(), |
| 4991 | ); |
| 4992 | } |
| 4993 | let Some((score, start, end)) = best.filter(|(score, ..)| *score >= MIN_SCORE) else { |
| 4994 | let mut hint = String::from("No similar region found in the file.\n"); |
| 4995 | for note in notes { |
| 4996 | hint.push_str(&format!("Note: {note}.\n")); |
| 4997 | } |
| 4998 | return hint; |
| 4999 | }; |
| 5000 | let region = &file_lines[start..end]; |
| 5001 | if let Some(offset) = search_lines |
| 5002 | .iter() |
| 5003 | .zip(region.iter()) |
| 5004 | .position(|(want, have)| want != have) |
| 5005 | { |
| 5006 | notes.push(format!( |
| 5007 | "first differing line is line {}", |
| 5008 | start + offset + 1 |
| 5009 | )); |
| 5010 | } |
| 5011 | let strip_trailing = |lines: &[&str]| -> Vec<String> { |
| 5012 | lines |
| 5013 | .iter() |
| 5014 | .map(|line| line.trim_end().to_string()) |
| 5015 | .collect() |
| 5016 | }; |
| 5017 | let collapse = |lines: &[&str]| -> String { |
| 5018 | lines |
| 5019 | .iter() |
| 5020 | .flat_map(|line| line.split_whitespace()) |
| 5021 | .collect::<Vec<_>>() |
| 5022 | .join(" ") |
| 5023 | }; |
| 5024 | if strip_trailing(region) == strip_trailing(&search_lines) { |
| 5025 | notes.push("the closest region differs only in trailing whitespace".to_string()); |
| 5026 | } else if collapse(region) == collapse(&search_lines) { |
| 5027 | let tabs = |lines: &[&str]| lines.iter().any(|line| line.starts_with('\t')); |
| 5028 | if tabs(region) != tabs(&search_lines) { |
| 5029 | notes |
| 5030 | .push("the closest region differs only in whitespace (tabs vs spaces)".to_string()); |
| 5031 | } else { |
| 5032 | notes.push("the closest region differs only in whitespace".to_string()); |
| 5033 | } |
| 5034 | } |
| 5035 | if file_has_crlf { |
| 5036 | notes.push("the file uses CRLF line endings; LF in the search is fine".to_string()); |
| 5037 | } |
| 5038 | |
| 5039 | let width = end.to_string().len(); |
| 5040 | let mut hint = format!( |
| 5041 | "Closest match (lines {}-{}, {:.0}% similar):\n", |
| 5042 | start + 1, |
| 5043 | end, |
| 5044 | score * 100.0 |
| 5045 | ); |
| 5046 | for (offset, line) in region.iter().take(MAX_EXCERPT_LINES).enumerate() { |
| 5047 | let mut shown: String = line.chars().take(MAX_EXCERPT_LINE_LEN).collect(); |
| 5048 | if line.chars().count() > MAX_EXCERPT_LINE_LEN { |
| 5049 | shown.push_str("..."); |
| 5050 | } |
| 5051 | hint.push_str(&format!("{:>width$}\t{shown}\n", start + offset + 1)); |
| 5052 | } |
| 5053 | if region.len() > MAX_EXCERPT_LINES { |
| 5054 | hint.push_str(&format!( |
| 5055 | "... ({} more lines)\n", |
| 5056 | region.len() - MAX_EXCERPT_LINES |
| 5057 | )); |
| 5058 | } |
| 5059 | for note in notes { |
| 5060 | hint.push_str(&format!("Note: {note}.\n")); |
| 5061 | } |
| 5062 | hint |
| 5063 | } |
| 5064 | |
| 5065 | fn preview_search_for_error(search: &str) -> String { |
| 5066 | const MAX_PREVIEW_LINES: usize = 3; |
| 5067 | const MAX_PREVIEW_LINE_LEN: usize = 80; |
| 5068 | search |
| 5069 | .lines() |
| 5070 | .take(MAX_PREVIEW_LINES) |
| 5071 | .map(|line| { |
| 5072 | if line.chars().count() > MAX_PREVIEW_LINE_LEN { |
| 5073 | let mut truncated: String = line.chars().take(MAX_PREVIEW_LINE_LEN).collect(); |
| 5074 | truncated.push_str("..."); |
| 5075 | truncated |
| 5076 | } else { |
| 5077 | line.to_string() |
| 5078 | } |
| 5079 | }) |
| 5080 | .collect::<Vec<_>>() |
| 5081 | .join("\n") |
| 5082 | } |
| 5083 | |
| 5084 | /// Normalize Windows CRLF pairs to LF while retaining the normalized byte |
| 5085 | /// positions where a `\r` was removed. Lone carriage returns are preserved. |
| 5086 | /// Inputs without CRLF are borrowed and use identity offsets. |
| 5087 | /// |
| 5088 | /// A normalized boundary maps back to the original by adding the number of |
| 5089 | /// removed CR bytes strictly before it. At the normalized newline itself that |
| 5090 | /// excludes the current CR, so the start maps to `\r`; after the newline (or |
| 5091 | /// at EOF) it includes that CR and spans the full pair. |
| 5092 | fn normalize_crlf(input: &str) -> Cow<'_, str> { |
| 5093 | if input.contains("\r\n") { |
| 5094 | Cow::Owned(input.replace("\r\n", "\n")) |
| 5095 | } else { |
| 5096 | Cow::Borrowed(input) |
| 5097 | } |
| 5098 | } |
| 5099 | |
| 5100 | fn normalize_crlf_with_positions(input: &str) -> (Cow<'_, str>, Option<Vec<usize>>) { |
| 5101 | if !input.contains("\r\n") { |
| 5102 | return (Cow::Borrowed(input), None); |
| 5103 | } |
| 5104 | |
| 5105 | let mut normalized = String::with_capacity(input.len()); |
| 5106 | let mut crlf_positions = Vec::new(); |
| 5107 | let mut chars = input.char_indices().peekable(); |
| 5108 | |
| 5109 | while let Some((_, ch)) = chars.next() { |
| 5110 | if ch == '\r' && matches!(chars.peek(), Some((_, '\n'))) { |
| 5111 | let _ = chars.next(); |
| 5112 | crlf_positions.push(normalized.len()); |
| 5113 | normalized.push('\n'); |
| 5114 | continue; |
| 5115 | } |
| 5116 | |
| 5117 | normalized.push(ch); |
| 5118 | } |
| 5119 | |
| 5120 | (Cow::Owned(normalized), Some(crlf_positions)) |
| 5121 | } |
| 5122 | |
| 5123 | fn map_normalized_range( |
| 5124 | (start, end): (usize, usize), |
| 5125 | crlf_positions: Option<&[usize]>, |
| 5126 | ) -> (usize, usize) { |
| 5127 | let Some(crlf_positions) = crlf_positions else { |
| 5128 | return (start, end); |
| 5129 | }; |
| 5130 | let map_boundary = |
| 5131 | |offset| offset + crlf_positions.partition_point(|position| *position < offset); |
| 5132 | (map_boundary(start), map_boundary(end)) |
| 5133 | } |
| 5134 | |
| 5135 | fn map_normalized_ranges( |
| 5136 | ranges: impl IntoIterator<Item = (usize, usize)>, |
| 5137 | crlf_positions: Option<&[usize]>, |
| 5138 | ) -> Vec<(usize, usize)> { |
| 5139 | ranges |
| 5140 | .into_iter() |
| 5141 | .map(|range| map_normalized_range(range, crlf_positions)) |
| 5142 | .collect() |
| 5143 | } |
| 5144 | |
| 5145 | /// Convert model-provided replacement newlines to the base file's convention. |
| 5146 | /// Fold CRLF first so an already-CRLF payload never becomes `\r\r\n`. |
| 5147 | fn normalize_replacement_line_endings(replace: &str, use_crlf: bool) -> String { |
| 5148 | let lf = replace.replace("\r\n", "\n"); |
| 5149 | if use_crlf { |
| 5150 | lf.replace('\n', "\r\n") |
| 5151 | } else { |
| 5152 | lf |
| 5153 | } |
| 5154 | } |
| 5155 | |
| 5156 | fn strip_line_leading_whitespace_with_map(input: &str) -> (String, Vec<usize>) { |
| 5157 | let mut normalized = String::with_capacity(input.len()); |
| 5158 | let mut byte_map = Vec::with_capacity(input.len()); |
| 5159 | let mut at_line_start = true; |
| 5160 | for (idx, ch) in input.char_indices() { |
| 5161 | if at_line_start && matches!(ch, ' ' | '\t') { |
| 5162 | continue; |
| 5163 | } |
| 5164 | normalized.push(ch); |
| 5165 | for _ in 0..ch.len_utf8() { |
| 5166 | byte_map.push(idx); |
| 5167 | } |
| 5168 | at_line_start = ch == '\n'; |
| 5169 | } |
| 5170 | (normalized, byte_map) |
| 5171 | } |
| 5172 | |
| 5173 | fn line_start_before(input: &str, idx: usize) -> usize { |
| 5174 | input[..idx] |
| 5175 | .rfind('\n') |
| 5176 | .map_or(0, |newline| newline.saturating_add(1)) |
| 5177 | } |
| 5178 | |
| 5179 | fn next_char_boundary(input: &str, idx: usize) -> usize { |
| 5180 | if idx >= input.len() { |
| 5181 | return input.len(); |
| 5182 | } |
| 5183 | |
| 5184 | let mut next = idx.saturating_add(1); |
| 5185 | while next < input.len() && !input.is_char_boundary(next) { |
| 5186 | next = next.saturating_add(1); |
| 5187 | } |
| 5188 | next |
| 5189 | } |
| 5190 | |
| 5191 | fn leading_whitespace_fuzzy_matches(contents: &str, search: &str) -> Vec<(usize, usize)> { |
| 5192 | let (normalized_contents, byte_map) = strip_line_leading_whitespace_with_map(contents); |
| 5193 | let (normalized_search, _) = strip_line_leading_whitespace_with_map(search); |
| 5194 | if normalized_search.is_empty() { |
| 5195 | return Vec::new(); |
| 5196 | } |
| 5197 | |
| 5198 | let mut matches = Vec::new(); |
| 5199 | let mut cursor = 0; |
| 5200 | while let Some(rel_idx) = normalized_contents[cursor..].find(&normalized_search) { |
| 5201 | let norm_start = cursor + rel_idx; |
| 5202 | let norm_end = norm_start + normalized_search.len(); |
| 5203 | let Some(&mapped_start) = byte_map.get(norm_start) else { |
| 5204 | break; |
| 5205 | }; |
| 5206 | // Use the actual match start position, expanding to line start only |
| 5207 | // when the match begins at a line boundary in the normalized text. |
| 5208 | // This prevents destroying preceding text on the same line when |
| 5209 | // the match starts mid-line after whitespace stripping. |
| 5210 | let original_start = |
| 5211 | if norm_start == 0 || normalized_contents.as_bytes()[norm_start - 1] == b'\n' { |
| 5212 | // Match starts at a line boundary — use line start for full-line replacement. |
| 5213 | line_start_before(contents, mapped_start) |
| 5214 | } else { |
| 5215 | // Match starts mid-line — use the exact mapped position. |
| 5216 | mapped_start |
| 5217 | }; |
| 5218 | let original_end = byte_map.get(norm_end).copied().unwrap_or(contents.len()); |
| 5219 | matches.push((original_start, original_end)); |
| 5220 | cursor = next_char_boundary(&normalized_contents, norm_start); |
| 5221 | } |
| 5222 | matches |
| 5223 | } |
| 5224 | |
| 5225 | /// Normalize typographic punctuation to its ASCII counterpart: |
| 5226 | /// |
| 5227 | /// * `"` `"` / U+201C U+201D → `"` |
| 5228 | /// * `'` `'` / U+2018 U+2019 → `'` |
| 5229 | /// * `–` `—` / U+2013 U+2014 → `-` |
| 5230 | /// * U+00A0 (non-breaking space) → ASCII space |
| 5231 | /// |
| 5232 | /// Returns the normalized string plus a byte-map sized to |
| 5233 | /// `normalized.len()` whose i-th entry is the original byte offset of |
| 5234 | /// the character that produced normalized byte i. Used to recover the |
| 5235 | /// original-byte range after finding a match in normalized space. |
| 5236 | fn punctuation_normalized_with_map(input: &str) -> (String, Vec<usize>) { |
| 5237 | let mut normalized = String::with_capacity(input.len()); |
| 5238 | let mut byte_map = Vec::with_capacity(input.len()); |
| 5239 | for (idx, ch) in input.char_indices() { |
| 5240 | let replacement: Option<char> = match ch { |
| 5241 | '\u{201C}' | '\u{201D}' => Some('"'), |
| 5242 | '\u{2018}' | '\u{2019}' => Some('\''), |
| 5243 | '\u{2013}' | '\u{2014}' => Some('-'), |
| 5244 | '\u{00A0}' => Some(' '), |
| 5245 | _ => None, |
| 5246 | }; |
| 5247 | let written = replacement.unwrap_or(ch); |
| 5248 | normalized.push(written); |
| 5249 | for _ in 0..written.len_utf8() { |
| 5250 | byte_map.push(idx); |
| 5251 | } |
| 5252 | } |
| 5253 | (normalized, byte_map) |
| 5254 | } |
| 5255 | |
| 5256 | /// Try to find `search` inside `contents` after normalizing typographic |
| 5257 | /// punctuation in both. Catches the copy-paste failure mode where a |
| 5258 | /// browser, word processor, or chat client silently converted ASCII |
| 5259 | /// quotes/dashes to their Unicode "pretty" forms. |
| 5260 | fn punctuation_normalized_matches(contents: &str, search: &str) -> Vec<(usize, usize)> { |
| 5261 | let (norm_contents, byte_map) = punctuation_normalized_with_map(contents); |
| 5262 | let (norm_search, _) = punctuation_normalized_with_map(search); |
| 5263 | if norm_search.is_empty() { |
| 5264 | return Vec::new(); |
| 5265 | } |
| 5266 | // If normalization didn't change anything, the exact-match pass |
| 5267 | // already considered this case — skip to avoid double-reporting. |
| 5268 | if norm_contents == contents && norm_search == search { |
| 5269 | return Vec::new(); |
| 5270 | } |
| 5271 | |
| 5272 | let mut matches = Vec::new(); |
| 5273 | let mut cursor = 0; |
| 5274 | while let Some(rel_idx) = norm_contents[cursor..].find(&norm_search) { |
| 5275 | let norm_start = cursor + rel_idx; |
| 5276 | let norm_end = norm_start + norm_search.len(); |
| 5277 | let Some(&original_start) = byte_map.get(norm_start) else { |
| 5278 | break; |
| 5279 | }; |
| 5280 | let original_end = byte_map.get(norm_end).copied().unwrap_or(contents.len()); |
| 5281 | matches.push((original_start, original_end)); |
| 5282 | cursor = next_char_boundary(&norm_contents, norm_start); |
| 5283 | } |
| 5284 | matches |
| 5285 | } |
| 5286 | |
| 5287 | // === ListDirTool === |
| 5288 | |
| 5289 | /// Tool for listing directory contents. |
| 5290 | pub struct ListDirTool; |
| 5291 | |
| 5292 | const LIST_DIR_TIMEOUT: Duration = Duration::from_secs(30); |
| 5293 | |
| 5294 | /// Cap on entries returned by a single `list_dir` call so a huge directory |
| 5295 | /// (node_modules, build output, photo dumps) can't balloon the tool result. |
| 5296 | /// Mirrors the bounded-output idiom of `read_file`'s `HARD_MAX_READ_LINES`. |
| 5297 | /// Directories at or under the cap keep the historical plain-array response; |
| 5298 | /// larger ones return an object with truncation metadata. |
| 5299 | const LIST_DIR_MAX_ENTRIES: usize = 500; |
| 5300 | |
| 5301 | #[async_trait] |
| 5302 | impl ToolSpec for ListDirTool { |
| 5303 | fn name(&self) -> &'static str { |
| 5304 | "list_dir" |
| 5305 | } |
| 5306 | |
| 5307 | fn model_visible(&self) -> bool { |
| 5308 | true |
| 5309 | } |
| 5310 | |
| 5311 | fn description(&self) -> &'static str { |
| 5312 | "List entries in a workspace directory, bounded and sandbox-aware." |
| 5313 | } |
| 5314 | |
| 5315 | fn input_schema(&self) -> Value { |
| 5316 | json!({ |
| 5317 | "type": "object", |
| 5318 | "properties": { |
| 5319 | "path": { |
| 5320 | "type": "string", |
| 5321 | "description": "Path to inspect (relative to workspace, absolute, or ~/ home-relative; default: .)" |
| 5322 | } |
| 5323 | }, |
| 5324 | "required": [] |
| 5325 | }) |
| 5326 | } |
| 5327 | |
| 5328 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 5329 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 5330 | } |
| 5331 | |
| 5332 | fn supports_parallel(&self) -> bool { |
| 5333 | true |
| 5334 | } |
| 5335 | |
| 5336 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 5337 | let mut input = input; |
| 5338 | apply_param_aliases(&mut input, PATH_ALIASES, "File list")?; |
| 5339 | LIST_PARAMS.reject_unknown(&input)?; |
| 5340 | |
| 5341 | let path_str = optional_str(&input, "path")?.unwrap_or("."); |
| 5342 | let plan = resolve_dir_open_plan(context, path_str).await?; |
| 5343 | let cancel_token = context.cancel_token.clone(); |
| 5344 | let worker_cancel_token = cancel_token.clone(); |
| 5345 | let entries = run_blocking_list_dir(LIST_DIR_TIMEOUT, cancel_token, move || { |
| 5346 | list_dir_from_plan(&plan, worker_cancel_token.as_ref()) |
| 5347 | }) |
| 5348 | .await?; |
| 5349 | |
| 5350 | ToolResult::json(&entries).map_err(|e| ToolError::execution_failed(e.to_string())) |
| 5351 | } |
| 5352 | } |
| 5353 | |
| 5354 | enum DirOpenTarget { |
| 5355 | Workspace { |
| 5356 | workspace_canonical: PathBuf, |
| 5357 | relative: PathBuf, |
| 5358 | display_path: PathBuf, |
| 5359 | }, |
| 5360 | Outside { |
| 5361 | path: PathBuf, |
| 5362 | }, |
| 5363 | } |
| 5364 | |
| 5365 | struct DirOpenPlan { |
| 5366 | target: DirOpenTarget, |
| 5367 | display_path: PathBuf, |
| 5368 | boundary: OpenedReadBoundary, |
| 5369 | } |
| 5370 | |
| 5371 | async fn resolve_dir_open_plan( |
| 5372 | context: &ToolContext, |
| 5373 | path_str: &str, |
| 5374 | ) -> Result<DirOpenPlan, ToolError> { |
| 5375 | enforce_read_denylist(Path::new(path_str), "list_dir")?; |
| 5376 | if context.strict_workspace_confinement { |
| 5377 | let (workspace_canonical, relative) = |
| 5378 | resolve_confined_target_async(context, path_str, true).await?; |
| 5379 | let dir_path = if relative.as_os_str().is_empty() { |
| 5380 | workspace_canonical.clone() |
| 5381 | } else { |
| 5382 | workspace_canonical.join(&relative) |
| 5383 | }; |
| 5384 | enforce_read_denylist_with_display(&dir_path, Path::new(path_str), "list_dir")?; |
| 5385 | let boundary = OpenedReadBoundary::from_context( |
| 5386 | context, |
| 5387 | "list_dir", |
| 5388 | path_str, |
| 5389 | workspace_canonical.clone(), |
| 5390 | None, |
| 5391 | true, |
| 5392 | ) |
| 5393 | .await; |
| 5394 | return Ok(DirOpenPlan { |
| 5395 | target: DirOpenTarget::Workspace { |
| 5396 | workspace_canonical, |
| 5397 | relative, |
| 5398 | display_path: dir_path.clone(), |
| 5399 | }, |
| 5400 | display_path: dir_path, |
| 5401 | boundary, |
| 5402 | }); |
| 5403 | } |
| 5404 | |
| 5405 | let dir_path = context.resolve_read_path(path_str)?; |
| 5406 | enforce_read_denylist_with_display(&dir_path, Path::new(path_str), "list_dir")?; |
| 5407 | let workspace_canonical = tokio::fs::canonicalize(&context.workspace) |
| 5408 | .await |
| 5409 | .unwrap_or_else(|_| context.workspace.clone()); |
| 5410 | let target = if !context.follow_symlinks |
| 5411 | && !workspace_canonical.as_os_str().is_empty() |
| 5412 | && let Ok(relative) = dir_path.strip_prefix(&workspace_canonical) |
| 5413 | && (relative.as_os_str().is_empty() || codewhale_util::files::path_is_confined(relative)) |
| 5414 | { |
| 5415 | DirOpenTarget::Workspace { |
| 5416 | workspace_canonical: workspace_canonical.clone(), |
| 5417 | relative: relative.to_path_buf(), |
| 5418 | display_path: dir_path.clone(), |
| 5419 | } |
| 5420 | } else { |
| 5421 | DirOpenTarget::Outside { |
| 5422 | path: dir_path.clone(), |
| 5423 | } |
| 5424 | }; |
| 5425 | let exact_allowed_dir = context.follow_symlinks.then(|| dir_path.clone()); |
| 5426 | let boundary = OpenedReadBoundary::from_context( |
| 5427 | context, |
| 5428 | "list_dir", |
| 5429 | path_str, |
| 5430 | workspace_canonical, |
| 5431 | exact_allowed_dir, |
| 5432 | true, |
| 5433 | ) |
| 5434 | .await; |
| 5435 | Ok(DirOpenPlan { |
| 5436 | target, |
| 5437 | display_path: dir_path, |
| 5438 | boundary, |
| 5439 | }) |
| 5440 | } |
| 5441 | |
| 5442 | fn open_outside_dir(path: &Path) -> std::io::Result<fs::File> { |
| 5443 | let mut options = fs::OpenOptions::new(); |
| 5444 | options.read(true); |
| 5445 | #[cfg(unix)] |
| 5446 | { |
| 5447 | use std::os::unix::fs::OpenOptionsExt as _; |
| 5448 | options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC); |
| 5449 | } |
| 5450 | #[cfg(windows)] |
| 5451 | { |
| 5452 | use std::os::windows::fs::OpenOptionsExt as _; |
| 5453 | options.share_mode(1).custom_flags(0x0220_0000); |
| 5454 | } |
| 5455 | let file = match options.open(path) { |
| 5456 | Ok(file) => file, |
| 5457 | Err(error) => { |
| 5458 | #[cfg(unix)] |
| 5459 | if matches!( |
| 5460 | error.raw_os_error(), |
| 5461 | Some(libc::ENOTDIR) | Some(libc::ELOOP) |
| 5462 | ) && fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) |
| 5463 | { |
| 5464 | return Err(std::io::Error::from_raw_os_error(libc::ELOOP)); |
| 5465 | } |
| 5466 | return Err(error); |
| 5467 | } |
| 5468 | }; |
| 5469 | let metadata = file.metadata()?; |
| 5470 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) { |
| 5471 | return Err(std::io::Error::new( |
| 5472 | std::io::ErrorKind::InvalidData, |
| 5473 | "target must not be a symlink or reparse point", |
| 5474 | )); |
| 5475 | } |
| 5476 | if !metadata.is_dir() { |
| 5477 | return Err(std::io::Error::new( |
| 5478 | std::io::ErrorKind::NotADirectory, |
| 5479 | "target must be a directory", |
| 5480 | )); |
| 5481 | } |
| 5482 | Ok(file) |
| 5483 | } |
| 5484 | |
| 5485 | fn map_list_dir_open_error(error: std::io::Error, display_path: &Path) -> ToolError { |
| 5486 | if matches!( |
| 5487 | error.kind(), |
| 5488 | std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory |
| 5489 | ) { |
| 5490 | return ToolError::execution_failed(format!( |
| 5491 | "Failed to read directory {}: {error}", |
| 5492 | display_path.display() |
| 5493 | )); |
| 5494 | } |
| 5495 | if is_confined_policy_error(&error) { |
| 5496 | return ToolError::permission_denied(format!( |
| 5497 | "list refused symlink or confined path constraint for {}: {error}", |
| 5498 | display_path.display() |
| 5499 | )); |
| 5500 | } |
| 5501 | ToolError::execution_failed(format!( |
| 5502 | "Failed to read directory {}: {error}", |
| 5503 | display_path.display() |
| 5504 | )) |
| 5505 | } |
| 5506 | |
| 5507 | #[cfg(unix)] |
| 5508 | fn list_outside_dir_entries( |
| 5509 | dir_file: &fs::File, |
| 5510 | verified_path: &Path, |
| 5511 | plan: &DirOpenPlan, |
| 5512 | cancel_token: Option<&CancellationToken>, |
| 5513 | ) -> Result<codewhale_util::files::ConfinedDirListing, ToolError> { |
| 5514 | let _ = verified_path; |
| 5515 | codewhale_util::files::read_dir_from_fd(dir_file, LIST_DIR_MAX_ENTRIES, || { |
| 5516 | cancel_token.is_some_and(CancellationToken::is_cancelled) |
| 5517 | }) |
| 5518 | .map_err(|error| { |
| 5519 | if error.kind() == std::io::ErrorKind::Interrupted |
| 5520 | && cancel_token.is_some_and(CancellationToken::is_cancelled) |
| 5521 | { |
| 5522 | return list_dir_cancelled(); |
| 5523 | } |
| 5524 | map_list_dir_open_error(error, &plan.display_path) |
| 5525 | }) |
| 5526 | } |
| 5527 | |
| 5528 | #[cfg(windows)] |
| 5529 | fn list_outside_dir_entries( |
| 5530 | dir_file: &fs::File, |
| 5531 | verified_path: &Path, |
| 5532 | plan: &DirOpenPlan, |
| 5533 | cancel_token: Option<&CancellationToken>, |
| 5534 | ) -> Result<codewhale_util::files::ConfinedDirListing, ToolError> { |
| 5535 | let fence = codewhale_util::files::WindowsDirectory::open(verified_path) |
| 5536 | .map_err(|error| map_list_dir_open_error(error, &plan.display_path))?; |
| 5537 | let fence_handle = fence |
| 5538 | .acl_handle() |
| 5539 | .map_err(|error| map_list_dir_open_error(error, &plan.display_path))?; |
| 5540 | if !codewhale_util::files::same_handle(dir_file, fence_handle) |
| 5541 | .map_err(|error| map_list_dir_open_error(error, &plan.display_path))? |
| 5542 | { |
| 5543 | return Err(ToolError::permission_denied(format!( |
| 5544 | "list_dir refused swapped directory for {}", |
| 5545 | plan.boundary.raw_spelling.display() |
| 5546 | ))); |
| 5547 | } |
| 5548 | let mut entries = Vec::new(); |
| 5549 | let mut total_entries = 0usize; |
| 5550 | for entry in fs::read_dir(verified_path).map_err(|e| { |
| 5551 | ToolError::execution_failed(format!( |
| 5552 | "Failed to read directory {}: {}", |
| 5553 | plan.display_path.display(), |
| 5554 | e |
| 5555 | )) |
| 5556 | })? { |
| 5557 | check_list_dir_cancelled(cancel_token)?; |
| 5558 | let entry = entry.map_err(|e| ToolError::execution_failed(e.to_string()))?; |
| 5559 | total_entries += 1; |
| 5560 | if entries.len() >= LIST_DIR_MAX_ENTRIES { |
| 5561 | continue; |
| 5562 | } |
| 5563 | let file_type = entry |
| 5564 | .file_type() |
| 5565 | .map_err(|e| ToolError::execution_failed(e.to_string()))?; |
| 5566 | let is_reparse = file_type.is_symlink() |
| 5567 | || fs::symlink_metadata(entry.path()).ok().is_some_and(|meta| { |
| 5568 | codewhale_util::path_identity::metadata_is_link_or_reparse(&meta) |
| 5569 | }); |
| 5570 | entries.push(codewhale_util::files::ConfinedDirEntry { |
| 5571 | name: entry.file_name().to_string_lossy().into_owned(), |
| 5572 | is_dir: file_type.is_dir() && !is_reparse, |
| 5573 | }); |
| 5574 | } |
| 5575 | let _keep_fence = fence; |
| 5576 | Ok(codewhale_util::files::ConfinedDirListing { |
| 5577 | entries, |
| 5578 | total_entries, |
| 5579 | }) |
| 5580 | } |
| 5581 | |
| 5582 | #[cfg(all(not(unix), not(windows)))] |
| 5583 | fn list_outside_dir_entries( |
| 5584 | _dir_file: &fs::File, |
| 5585 | _verified_path: &Path, |
| 5586 | plan: &DirOpenPlan, |
| 5587 | _cancel_token: Option<&CancellationToken>, |
| 5588 | ) -> Result<codewhale_util::files::ConfinedDirListing, ToolError> { |
| 5589 | Err(ToolError::execution_failed(format!( |
| 5590 | "Failed to read directory {}: unsupported platform", |
| 5591 | plan.display_path.display() |
| 5592 | ))) |
| 5593 | } |
| 5594 | |
| 5595 | fn list_dir_from_plan( |
| 5596 | plan: &DirOpenPlan, |
| 5597 | cancel_token: Option<&CancellationToken>, |
| 5598 | ) -> Result<Value, ToolError> { |
| 5599 | check_list_dir_cancelled(cancel_token)?; |
| 5600 | let listing = match &plan.target { |
| 5601 | DirOpenTarget::Workspace { |
| 5602 | workspace_canonical, |
| 5603 | relative, |
| 5604 | display_path, |
| 5605 | } => { |
| 5606 | let rel = (!relative.as_os_str().is_empty()).then_some(relative.as_path()); |
| 5607 | codewhale_util::files::read_confined_dir(workspace_canonical, rel, LIST_DIR_MAX_ENTRIES) |
| 5608 | .map_err(|error| map_list_dir_open_error(error, display_path))? |
| 5609 | } |
| 5610 | DirOpenTarget::Outside { path } => { |
| 5611 | let dir_file = open_outside_dir(path) |
| 5612 | .map_err(|error| map_list_dir_open_error(error, &plan.display_path))?; |
| 5613 | let verified_path = verify_opened_read_file(&dir_file, &plan.boundary)?; |
| 5614 | list_outside_dir_entries(&dir_file, &verified_path, plan, cancel_token)? |
| 5615 | } |
| 5616 | }; |
| 5617 | check_list_dir_cancelled(cancel_token)?; |
| 5618 | let entries = listing |
| 5619 | .entries |
| 5620 | .into_iter() |
| 5621 | .map(|entry| { |
| 5622 | json!({ |
| 5623 | "name": entry.name, |
| 5624 | "is_dir": entry.is_dir, |
| 5625 | }) |
| 5626 | }) |
| 5627 | .collect::<Vec<_>>(); |
| 5628 | if listing.total_entries > entries.len() { |
| 5629 | Ok(json!({ |
| 5630 | "entries": entries, |
| 5631 | "listed_entries": LIST_DIR_MAX_ENTRIES, |
| 5632 | "total_entries": listing.total_entries, |
| 5633 | "truncated": true, |
| 5634 | })) |
| 5635 | } else { |
| 5636 | Ok(Value::Array(entries)) |
| 5637 | } |
| 5638 | } |
| 5639 | |
| 5640 | async fn run_blocking_list_dir<F>( |
| 5641 | timeout: Duration, |
| 5642 | cancel_token: Option<CancellationToken>, |
| 5643 | list_dir: F, |
| 5644 | ) -> Result<Value, ToolError> |
| 5645 | where |
| 5646 | F: FnOnce() -> Result<Value, ToolError> + Send + 'static, |
| 5647 | { |
| 5648 | if cancel_token |
| 5649 | .as_ref() |
| 5650 | .is_some_and(CancellationToken::is_cancelled) |
| 5651 | { |
| 5652 | return Err(list_dir_cancelled()); |
| 5653 | } |
| 5654 | |
| 5655 | let task = tokio::task::spawn_blocking(list_dir); |
| 5656 | let result = match cancel_token { |
| 5657 | Some(token) => { |
| 5658 | tokio::select! { |
| 5659 | biased; |
| 5660 | () = token.cancelled() => return Err(list_dir_cancelled()), |
| 5661 | result = tokio::time::timeout(timeout, task) => result, |
| 5662 | } |
| 5663 | } |
| 5664 | None => tokio::time::timeout(timeout, task).await, |
| 5665 | }; |
| 5666 | |
| 5667 | let joined = result.map_err(|_| list_dir_timeout(timeout))?; |
| 5668 | joined.map_err(|err| { |
| 5669 | ToolError::execution_failed(format!("list_dir worker failed before completion: {err}")) |
| 5670 | })? |
| 5671 | } |
| 5672 | |
| 5673 | fn check_list_dir_cancelled(cancel_token: Option<&CancellationToken>) -> Result<(), ToolError> { |
| 5674 | if cancel_token.is_some_and(CancellationToken::is_cancelled) { |
| 5675 | return Err(list_dir_cancelled()); |
| 5676 | } |
| 5677 | Ok(()) |
| 5678 | } |
| 5679 | |
| 5680 | fn list_dir_cancelled() -> ToolError { |
| 5681 | ToolError::cancelled("list_dir cancelled before completion") |
| 5682 | } |
| 5683 | |
| 5684 | fn list_dir_timeout(timeout: Duration) -> ToolError { |
| 5685 | ToolError::Timeout { |
| 5686 | seconds: timeout.as_secs().max(1), |
| 5687 | } |
| 5688 | } |
| 5689 | |
| 5690 | // === Unit Tests === |
| 5691 | |
| 5692 | #[cfg(test)] |
| 5693 | #[path = "file/tests.rs"] |
| 5694 | mod pdf_tests; |
| 5695 | |
| 5696 | #[cfg(test)] |
| 5697 | #[path = "file/tests/tools.rs"] |
| 5698 | mod tests; |
| 5699 |