| 1 | use std::collections::HashSet; |
| 2 | use std::path::PathBuf; |
| 3 | |
| 4 | use async_trait::async_trait; |
| 5 | use serde_json::{Value, json}; |
| 6 | use sha2::{Digest, Sha256}; |
| 7 | |
| 8 | use super::spec::{ |
| 9 | ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_str, type_mismatch, |
| 10 | }; |
| 11 | |
| 12 | const MAX_FILES: usize = 32; |
| 13 | const READ_BUFFER_BYTES: usize = 64 * 1024; |
| 14 | |
| 15 | pub struct PresentTool; |
| 16 | |
| 17 | #[async_trait] |
| 18 | impl ToolSpec for PresentTool { |
| 19 | fn name(&self) -> &'static str { |
| 20 | "present" |
| 21 | } |
| 22 | |
| 23 | fn description(&self) -> &'static str { |
| 24 | "Declare existing workspace files as final deliverables and return a handoff receipt. \ |
| 25 | Read-only: the files are not modified, moved, copied, or uploaded. For each of 1-32 \ |
| 26 | workspace-relative paths it records the display path, byte length, and SHA-256. Call \ |
| 27 | it after finishing an artifact so the tool call is the presentation point. It does \ |
| 28 | not create a delivery folder or a second artifact store." |
| 29 | } |
| 30 | |
| 31 | fn input_schema(&self) -> Value { |
| 32 | json!({ |
| 33 | "type": "object", |
| 34 | "properties": { |
| 35 | "files": { |
| 36 | "type": "array", |
| 37 | "description": "Workspace-relative paths of existing regular files to present (1-32, no duplicates).", |
| 38 | "items": { "type": "string", "minLength": 1 }, |
| 39 | "minItems": 1, |
| 40 | "maxItems": MAX_FILES |
| 41 | }, |
| 42 | "note": { |
| 43 | "type": "string", |
| 44 | "description": "Optional short note about the presented artifacts." |
| 45 | } |
| 46 | }, |
| 47 | "required": ["files"] |
| 48 | }) |
| 49 | } |
| 50 | |
| 51 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 52 | vec![ToolCapability::ReadOnly] |
| 53 | } |
| 54 | |
| 55 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 56 | let paths = match input.get("files") { |
| 57 | Some(Value::Array(paths)) => paths, |
| 58 | Some(other) => { |
| 59 | return Err(type_mismatch("files", other, "an array of paths")); |
| 60 | } |
| 61 | None => return Err(ToolError::missing_field("files")), |
| 62 | }; |
| 63 | if paths.is_empty() { |
| 64 | return Err(ToolError::invalid_input( |
| 65 | "`files` must contain at least one path", |
| 66 | )); |
| 67 | } |
| 68 | if paths.len() > MAX_FILES { |
| 69 | return Err(ToolError::invalid_input(format!( |
| 70 | "`files` contains {} paths; present at most {MAX_FILES} per call", |
| 71 | paths.len() |
| 72 | ))); |
| 73 | } |
| 74 | let note = optional_str(&input, "note")? |
| 75 | .map(str::trim) |
| 76 | .filter(|note| !note.is_empty()); |
| 77 | let workspace = tokio::fs::canonicalize(&context.workspace) |
| 78 | .await |
| 79 | .unwrap_or_else(|_| context.workspace.clone()); |
| 80 | let mut seen = HashSet::with_capacity(paths.len()); |
| 81 | let mut presented = Vec::with_capacity(paths.len()); |
| 82 | |
| 83 | for (index, value) in paths.iter().enumerate() { |
| 84 | let Some(raw) = value.as_str() else { |
| 85 | let field = format!("files[{index}]"); |
| 86 | return Err(type_mismatch(&field, value, "a path string")); |
| 87 | }; |
| 88 | if raw.trim().is_empty() { |
| 89 | return Err(ToolError::invalid_input(format!( |
| 90 | "`files[{index}]` must not be empty" |
| 91 | ))); |
| 92 | } |
| 93 | let plan = |
| 94 | crate::tools::file::resolve_read_open_plan(context, raw, "present", false, false) |
| 95 | .await?; |
| 96 | let resolved = plan.file_path.clone(); |
| 97 | if !seen.insert(resolved.clone()) { |
| 98 | return Err(ToolError::invalid_input(format!( |
| 99 | "`files` names the same file more than once: {raw}" |
| 100 | ))); |
| 101 | } |
| 102 | let display = resolved |
| 103 | .strip_prefix(&workspace) |
| 104 | .unwrap_or(resolved.as_path()) |
| 105 | .to_string_lossy() |
| 106 | .into_owned(); |
| 107 | let (bytes, sha256, fd_path) = hash_verified_file(plan, display.clone()).await?; |
| 108 | if fd_path != resolved && !seen.insert(fd_path) { |
| 109 | return Err(ToolError::invalid_input(format!( |
| 110 | "`files` names the same file more than once: {raw}" |
| 111 | ))); |
| 112 | } |
| 113 | presented.push((display, bytes, sha256)); |
| 114 | } |
| 115 | |
| 116 | let entries = presented |
| 117 | .iter() |
| 118 | .map(|(path, bytes, sha256)| json!({ "path": path, "bytes": bytes, "sha256": sha256 })) |
| 119 | .collect::<Vec<_>>(); |
| 120 | let mut metadata = json!({ "presented": entries }); |
| 121 | if let Some(note) = note { |
| 122 | metadata["note"] = Value::String(note.to_string()); |
| 123 | } |
| 124 | |
| 125 | let mut summary = format!( |
| 126 | "Presented {} file{}. Handoff receipt only; nothing was written, moved, copied, or uploaded.", |
| 127 | presented.len(), |
| 128 | if presented.len() == 1 { "" } else { "s" } |
| 129 | ); |
| 130 | for (path, bytes, sha256) in &presented { |
| 131 | summary.push_str(&format!("\n- {path} ({bytes} bytes, sha256 {sha256})")); |
| 132 | } |
| 133 | if let Some(note) = note { |
| 134 | summary.push_str(&format!("\nNote: {note}")); |
| 135 | } |
| 136 | |
| 137 | Ok(ToolResult::success(summary).with_metadata(metadata)) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | async fn hash_verified_file( |
| 142 | plan: crate::tools::file::ReadOpenPlan, |
| 143 | display: String, |
| 144 | ) -> Result<(u64, String, PathBuf), ToolError> { |
| 145 | let display_for_join = display.clone(); |
| 146 | tokio::task::spawn_blocking(move || -> Result<(u64, String, PathBuf), ToolError> { |
| 147 | use std::io::Read as _; |
| 148 | |
| 149 | let (mut file, fd_path) = |
| 150 | match crate::tools::file::open_verified_read_handle(&plan, true, true, false) { |
| 151 | Ok(Some(opened)) => opened, |
| 152 | Ok(None) => { |
| 153 | return Err(ToolError::invalid_input(format!( |
| 154 | "cannot present {display}: file not found" |
| 155 | ))); |
| 156 | } |
| 157 | Err(ToolError::ExecutionFailed { message, .. }) |
| 158 | if message.contains("path is a directory") => |
| 159 | { |
| 160 | return Err(ToolError::invalid_input(format!( |
| 161 | "cannot present {display}: not a regular file" |
| 162 | ))); |
| 163 | } |
| 164 | Err(error) => return Err(error), |
| 165 | }; |
| 166 | let metadata = file.metadata().map_err(|error| { |
| 167 | ToolError::execution_failed(format!("failed to inspect {display}: {error}")) |
| 168 | })?; |
| 169 | if !metadata.is_file() { |
| 170 | return Err(ToolError::invalid_input(format!( |
| 171 | "cannot present {display}: not a regular file" |
| 172 | ))); |
| 173 | } |
| 174 | let mut hasher = Sha256::new(); |
| 175 | let mut bytes = 0_u64; |
| 176 | let mut buffer = vec![0_u8; READ_BUFFER_BYTES]; |
| 177 | loop { |
| 178 | let read = file.read(&mut buffer).map_err(|error| { |
| 179 | ToolError::execution_failed(format!("failed to read {display}: {error}")) |
| 180 | })?; |
| 181 | if read == 0 { |
| 182 | break; |
| 183 | } |
| 184 | hasher.update(&buffer[..read]); |
| 185 | bytes += read as u64; |
| 186 | } |
| 187 | Ok(( |
| 188 | bytes, |
| 189 | codewhale_runtime::hashing::hex_bytes(hasher.finalize()), |
| 190 | fd_path, |
| 191 | )) |
| 192 | }) |
| 193 | .await |
| 194 | .map_err(|error| { |
| 195 | ToolError::execution_failed(format!( |
| 196 | "failed to read {display_for_join}: worker failed: {error}" |
| 197 | )) |
| 198 | })? |
| 199 | } |
| 200 | |
| 201 | #[cfg(test)] |
| 202 | mod tests { |
| 203 | use super::*; |
| 204 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 205 | use std::fs; |
| 206 | use tempfile::tempdir; |
| 207 | |
| 208 | #[allow(clippy::await_holding_lock)] |
| 209 | #[tokio::test] |
| 210 | async fn present_hashes_regular_file_and_refuses_denied_credential_ro_and_hardlink() { |
| 211 | let _lock = lock_test_env(); |
| 212 | let workspace = tempdir().expect("workspace"); |
| 213 | let ws_canon = workspace.path().canonicalize().expect("canon ws"); |
| 214 | let cw_home = ws_canon.join("cw-home"); |
| 215 | fs::create_dir_all(&cw_home).expect("mkdir cw-home"); |
| 216 | fs::create_dir_all(ws_canon.join("subdir")).expect("mkdir subdir"); |
| 217 | let _cw_home_guard = EnvVarGuard::set("CODEWHALE_HOME", &cw_home); |
| 218 | let _cfg_guard = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 219 | let _legacy_cfg_guard = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 220 | |
| 221 | fs::write(ws_canon.join("report.txt"), "hello world\n").expect("write report"); |
| 222 | fs::write(ws_canon.join(".env"), "SECRET=1\n").expect("write .env"); |
| 223 | fs::write(cw_home.join("config.toml"), "api_key = \"secret\"\n").expect("write config"); |
| 224 | |
| 225 | let ctx = ToolContext::new(&ws_canon); |
| 226 | let ok = PresentTool |
| 227 | .execute(json!({"files": ["report.txt"]}), &ctx) |
| 228 | .await |
| 229 | .expect("regular workspace file succeeds"); |
| 230 | assert!(ok.success); |
| 231 | let entry = &ok.metadata.as_ref().expect("metadata")["presented"][0]; |
| 232 | assert_eq!(entry["bytes"], json!(12)); |
| 233 | assert_eq!( |
| 234 | entry["sha256"], |
| 235 | json!(codewhale_runtime::hashing::sha256_hex(b"hello world\n")) |
| 236 | ); |
| 237 | |
| 238 | let missing_err = PresentTool |
| 239 | .execute(json!({"files": ["missing.txt"]}), &ctx) |
| 240 | .await |
| 241 | .expect_err("missing file must fail"); |
| 242 | assert!( |
| 243 | matches!(missing_err, ToolError::InvalidInput { .. }) |
| 244 | && missing_err.to_string().contains("cannot present"), |
| 245 | "{missing_err:?}" |
| 246 | ); |
| 247 | |
| 248 | let dir_err = PresentTool |
| 249 | .execute(json!({"files": ["subdir"]}), &ctx) |
| 250 | .await |
| 251 | .expect_err("directory must fail"); |
| 252 | assert!( |
| 253 | matches!(dir_err, ToolError::InvalidInput { .. }) |
| 254 | && dir_err.to_string().contains("not a regular file"), |
| 255 | "{dir_err:?}" |
| 256 | ); |
| 257 | |
| 258 | let env_err = PresentTool |
| 259 | .execute(json!({"files": [".env"]}), &ctx) |
| 260 | .await |
| 261 | .expect_err(".env must be refused"); |
| 262 | assert!( |
| 263 | matches!(env_err, ToolError::PermissionDenied { .. }), |
| 264 | "{env_err:?}" |
| 265 | ); |
| 266 | |
| 267 | let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true); |
| 268 | let cred_err = PresentTool |
| 269 | .execute( |
| 270 | json!({"files": [cw_home.join("config.toml").to_string_lossy()]}), |
| 271 | &trusted_ctx, |
| 272 | ) |
| 273 | .await |
| 274 | .expect_err("credential file must be refused"); |
| 275 | assert!( |
| 276 | matches!(cred_err, ToolError::PermissionDenied { .. }), |
| 277 | "{cred_err:?}" |
| 278 | ); |
| 279 | |
| 280 | let ro_root = tempdir().expect("ro_root"); |
| 281 | let ro_file = ro_root.path().join("ro.txt"); |
| 282 | fs::write(&ro_file, "readonly\n").expect("write ro"); |
| 283 | let ro_canon = ro_root.path().canonicalize().expect("canon ro"); |
| 284 | let ro_ctx = ToolContext::new(&ws_canon).with_read_only_roots(vec![ro_canon]); |
| 285 | let ro_err = PresentTool |
| 286 | .execute(json!({"files": [ro_file.to_string_lossy()]}), &ro_ctx) |
| 287 | .await |
| 288 | .expect_err("present must not read read_only_roots"); |
| 289 | assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}"); |
| 290 | |
| 291 | #[cfg(unix)] |
| 292 | { |
| 293 | let outside = tempdir().expect("outside"); |
| 294 | let orig = outside.path().join("orig.txt"); |
| 295 | let linked = outside.path().join("alias.txt"); |
| 296 | fs::write(&orig, "secret\n").expect("write orig"); |
| 297 | fs::hard_link(&orig, &linked).expect("hardlink"); |
| 298 | let link_err = PresentTool |
| 299 | .execute(json!({"files": [linked.to_string_lossy()]}), &trusted_ctx) |
| 300 | .await |
| 301 | .expect_err("outside hardlink must be refused"); |
| 302 | assert!( |
| 303 | matches!(link_err, ToolError::PermissionDenied { .. }), |
| 304 | "{link_err:?}" |
| 305 | ); |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 |