| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::fs; |
| 3 | use std::io::{self, Read}; |
| 4 | use std::path::{Component, Path, PathBuf}; |
| 5 | |
| 6 | use sha2::{Digest, Sha256}; |
| 7 | |
| 8 | use super::types::PluginScope; |
| 9 | use codewhale_util::path_identity::metadata_is_link_or_reparse; |
| 10 | |
| 11 | pub const STAMP_NAME: &str = ".stamp"; |
| 12 | pub const AGENT_TEAMS_BUNDLE_NAME: &str = "agent-teams"; |
| 13 | pub const DISABLE_BUNDLED_AGENT_TEAMS_ENV: &str = "CODEWHALE_DISABLE_BUNDLED_AGENT_TEAMS"; |
| 14 | |
| 15 | const BUILTIN_DIR_NAME: &str = "builtin-plugins"; |
| 16 | const SNAPSHOTS_DIR_NAME: &str = "snapshots"; |
| 17 | |
| 18 | macro_rules! agent_teams_file { |
| 19 | ($relative:literal) => { |
| 20 | ( |
| 21 | $relative, |
| 22 | include_bytes!(concat!("../assets/agent-teams/", $relative)), |
| 23 | ) |
| 24 | }; |
| 25 | } |
| 26 | |
| 27 | const AGENT_TEAMS_FILES: &[(&str, &[u8])] = &[ |
| 28 | agent_teams_file!("LICENSE"), |
| 29 | agent_teams_file!("package.json"), |
| 30 | agent_teams_file!("plugin.json"), |
| 31 | agent_teams_file!("cordis.patch.yml"), |
| 32 | agent_teams_file!("compatibility.json"), |
| 33 | agent_teams_file!("lib/artifacts.js"), |
| 34 | agent_teams_file!("lib/capabilities.js"), |
| 35 | agent_teams_file!("lib/client.js"), |
| 36 | agent_teams_file!("lib/command.js"), |
| 37 | agent_teams_file!("lib/event-types.js"), |
| 38 | agent_teams_file!("lib/events.js"), |
| 39 | agent_teams_file!("lib/git-artifact-stamp.json"), |
| 40 | agent_teams_file!("lib/harness-compat.js"), |
| 41 | agent_teams_file!("lib/index.js"), |
| 42 | agent_teams_file!("lib/lineage.js"), |
| 43 | agent_teams_file!("lib/mailbox.js"), |
| 44 | agent_teams_file!("lib/members.js"), |
| 45 | agent_teams_file!("lib/profiles.js"), |
| 46 | agent_teams_file!("lib/quality-gates.js"), |
| 47 | agent_teams_file!("lib/scheduler.js"), |
| 48 | agent_teams_file!("lib/snapshot.js"), |
| 49 | agent_teams_file!("lib/state.js"), |
| 50 | agent_teams_file!("lib/tool-names.js"), |
| 51 | agent_teams_file!("lib/tool-policies.js"), |
| 52 | agent_teams_file!("lib/tools.js"), |
| 53 | agent_teams_file!("lib/types.js"), |
| 54 | agent_teams_file!("lib/web-routes.js"), |
| 55 | agent_teams_file!("lib/workspace-audit-service.js"), |
| 56 | agent_teams_file!("lib/workspace-audit-worker.js"), |
| 57 | agent_teams_file!("lib/workspace-audit.js"), |
| 58 | agent_teams_file!("assets/agent-teams/action-celebrating-v2.png"), |
| 59 | agent_teams_file!("assets/agent-teams/action-reporting-v2.png"), |
| 60 | agent_teams_file!("assets/agent-teams/action-sending-v2.png"), |
| 61 | agent_teams_file!("assets/agent-teams/action-sleeping-v2.png"), |
| 62 | agent_teams_file!("assets/agent-teams/action-thinking-v2.png"), |
| 63 | agent_teams_file!("assets/agent-teams/action-working-v2.png"), |
| 64 | agent_teams_file!("assets/agent-teams/member-data-v2.png"), |
| 65 | agent_teams_file!("assets/agent-teams/member-designer-v2.png"), |
| 66 | agent_teams_file!("assets/agent-teams/member-docs-v2.png"), |
| 67 | agent_teams_file!("assets/agent-teams/member-engineer-v2.png"), |
| 68 | agent_teams_file!("assets/agent-teams/member-operator-v2.png"), |
| 69 | agent_teams_file!("assets/agent-teams/member-qa-v2.png"), |
| 70 | agent_teams_file!("assets/agent-teams/member-researcher-v2.png"), |
| 71 | agent_teams_file!("assets/agent-teams/member-security-v2.png"), |
| 72 | agent_teams_file!("assets/agent-teams/team-lead-v2.png"), |
| 73 | ]; |
| 74 | |
| 75 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 76 | pub struct EmbeddedBundle { |
| 77 | pub name: &'static str, |
| 78 | pub digest: String, |
| 79 | } |
| 80 | |
| 81 | impl EmbeddedBundle { |
| 82 | pub fn snapshot_dir_name(&self) -> String { |
| 83 | format!("{}-{}", self.name, self.digest) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | #[must_use] |
| 88 | pub fn is_bundled_agent_teams(scope: PluginScope, name: &str) -> bool { |
| 89 | scope == PluginScope::Builtin && name == AGENT_TEAMS_BUNDLE_NAME |
| 90 | } |
| 91 | |
| 92 | #[must_use] |
| 93 | pub fn is_bundled_agent_teams_id(plugin_id: &str, name: &str) -> bool { |
| 94 | plugin_id.starts_with("builtin/") && name == AGENT_TEAMS_BUNDLE_NAME |
| 95 | } |
| 96 | |
| 97 | #[must_use] |
| 98 | pub fn bundled_agent_teams_default_enabled() -> bool { |
| 99 | !matches!( |
| 100 | std::env::var(DISABLE_BUNDLED_AGENT_TEAMS_ENV) |
| 101 | .ok() |
| 102 | .as_deref() |
| 103 | .map(str::trim), |
| 104 | Some("1" | "true" | "TRUE" | "yes" | "YES") |
| 105 | ) |
| 106 | } |
| 107 | |
| 108 | #[must_use] |
| 109 | pub fn embedded_bundles() -> Vec<EmbeddedBundle> { |
| 110 | vec![EmbeddedBundle { |
| 111 | name: AGENT_TEAMS_BUNDLE_NAME, |
| 112 | digest: digest(AGENT_TEAMS_FILES), |
| 113 | }] |
| 114 | } |
| 115 | |
| 116 | pub fn snapshots_dir(home: &Path) -> PathBuf { |
| 117 | home.join(BUILTIN_DIR_NAME).join(SNAPSHOTS_DIR_NAME) |
| 118 | } |
| 119 | |
| 120 | #[must_use] |
| 121 | pub fn materialized_dirs() -> Vec<PathBuf> { |
| 122 | match materialize() { |
| 123 | Ok(Some(root)) => vec![root], |
| 124 | Ok(None) => Vec::new(), |
| 125 | Err(error) => { |
| 126 | tracing::warn!( |
| 127 | target: "plugins", |
| 128 | %error, |
| 129 | "built-in plugin bundles could not be written; they will not be discovered" |
| 130 | ); |
| 131 | Vec::new() |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | fn materialize() -> io::Result<Option<PathBuf>> { |
| 137 | let home = codewhale_config::codewhale_home().map_err(io::Error::other)?; |
| 138 | materialize_at_home(&home) |
| 139 | } |
| 140 | |
| 141 | pub fn materialize_at_home(home: &Path) -> io::Result<Option<PathBuf>> { |
| 142 | let home = match home.canonicalize() { |
| 143 | Ok(home) => home, |
| 144 | Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 145 | Err(error) => return Err(error), |
| 146 | }; |
| 147 | match fs::symlink_metadata(&home) { |
| 148 | Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 149 | Err(error) => return Err(error), |
| 150 | Ok(metadata) if !metadata.is_dir() || metadata_is_link_or_reparse(&metadata) => { |
| 151 | return Err(invalid_bundle("Codewhale home must be a real directory")); |
| 152 | } |
| 153 | Ok(_) => {} |
| 154 | } |
| 155 | let root = home.join(BUILTIN_DIR_NAME); |
| 156 | reject_symlink(&root)?; |
| 157 | match fs::create_dir(&root) { |
| 158 | Ok(()) => {} |
| 159 | Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} |
| 160 | Err(error) => return Err(error), |
| 161 | } |
| 162 | reject_symlink(&root)?; |
| 163 | let snapshots = root.join(SNAPSHOTS_DIR_NAME); |
| 164 | reject_symlink(&snapshots)?; |
| 165 | super::registry::ensure_private_plugin_state_directory(&snapshots).map_err(io::Error::other)?; |
| 166 | write_bundle(&snapshots, AGENT_TEAMS_BUNDLE_NAME, AGENT_TEAMS_FILES).map(Some) |
| 167 | } |
| 168 | |
| 169 | fn digest(files: &[(&str, &[u8])]) -> String { |
| 170 | let mut hasher = Sha256::new(); |
| 171 | for (relative, contents) in files { |
| 172 | hasher.update(relative.as_bytes()); |
| 173 | hasher.update([0]); |
| 174 | hasher.update((contents.len() as u64).to_le_bytes()); |
| 175 | hasher.update(contents); |
| 176 | } |
| 177 | let digest = hasher.finalize(); |
| 178 | let mut hex = String::with_capacity(digest.len() * 2); |
| 179 | for byte in digest { |
| 180 | use std::fmt::Write as _; |
| 181 | let _ = write!(&mut hex, "{byte:02x}"); |
| 182 | } |
| 183 | hex |
| 184 | } |
| 185 | |
| 186 | fn invalid_bundle(message: &str) -> io::Error { |
| 187 | io::Error::new(io::ErrorKind::InvalidData, message) |
| 188 | } |
| 189 | |
| 190 | fn reject_symlink(path: &Path) -> io::Result<()> { |
| 191 | match fs::symlink_metadata(path) { |
| 192 | Ok(metadata) if metadata_is_link_or_reparse(&metadata) => { |
| 193 | Err(invalid_bundle("built-in plugin path must not be a symlink")) |
| 194 | } |
| 195 | Ok(_) => Ok(()), |
| 196 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), |
| 197 | Err(error) => Err(error), |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn mark_snapshot_used(snapshot: &Path) { |
| 202 | if let Ok(Some(stamp)) = |
| 203 | super::registry::open_existing_regular_file(&snapshot.join(STAMP_NAME), true) |
| 204 | { |
| 205 | let _ = stamp.set_modified(std::time::SystemTime::now()); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | pub(crate) fn write_bundle( |
| 210 | root: &Path, |
| 211 | name: &str, |
| 212 | files: &[(&str, &[u8])], |
| 213 | ) -> io::Result<PathBuf> { |
| 214 | reject_symlink(root)?; |
| 215 | if !super::agent_plugin::is_standard_plugin_name(name) || files.is_empty() { |
| 216 | return Err(invalid_bundle( |
| 217 | "invalid embedded plugin name or empty bundle", |
| 218 | )); |
| 219 | } |
| 220 | let want = digest(files); |
| 221 | let destination = root.join(format!("{name}-{want}")); |
| 222 | let mut expected = BTreeMap::from([(PathBuf::from(STAMP_NAME), want.as_bytes())]); |
| 223 | for (relative, contents) in files { |
| 224 | let path = Path::new(relative); |
| 225 | if path.as_os_str().is_empty() |
| 226 | || path |
| 227 | .components() |
| 228 | .any(|part| !matches!(part, Component::Normal(_))) |
| 229 | || expected |
| 230 | .insert(Path::new(name).join(path), *contents) |
| 231 | .is_some() |
| 232 | { |
| 233 | return Err(invalid_bundle("invalid or duplicate embedded bundle path")); |
| 234 | } |
| 235 | } |
| 236 | let mut directories = BTreeSet::from([PathBuf::new()]); |
| 237 | for path in expected.keys() { |
| 238 | let mut cursor = path.parent(); |
| 239 | while let Some(dir) = cursor { |
| 240 | if !directories.insert(dir.to_path_buf()) { |
| 241 | break; |
| 242 | } |
| 243 | cursor = dir.parent(); |
| 244 | } |
| 245 | } |
| 246 | if verify_snapshot(&destination, &directories, &expected).is_ok() { |
| 247 | mark_snapshot_used(&destination); |
| 248 | return Ok(destination); |
| 249 | } |
| 250 | let stage = tempfile::Builder::new() |
| 251 | .prefix(&format!(".stage-{name}-")) |
| 252 | .tempdir_in(root)?; |
| 253 | for dir in &directories { |
| 254 | if !dir.as_os_str().is_empty() { |
| 255 | fs::create_dir_all(stage.path().join(dir))?; |
| 256 | } |
| 257 | } |
| 258 | for (relative, contents) in &expected { |
| 259 | fs::write(stage.path().join(relative), contents)?; |
| 260 | } |
| 261 | let stage_path = stage.keep(); |
| 262 | match publish_snapshot(&stage_path, &destination) { |
| 263 | Ok(()) => { |
| 264 | verify_snapshot(&destination, &directories, &expected)?; |
| 265 | mark_snapshot_used(&destination); |
| 266 | Ok(destination) |
| 267 | } |
| 268 | Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { |
| 269 | let _ = fs::remove_dir_all(&stage_path); |
| 270 | verify_snapshot(&destination, &directories, &expected)?; |
| 271 | mark_snapshot_used(&destination); |
| 272 | Ok(destination) |
| 273 | } |
| 274 | Err(error) => { |
| 275 | let _ = fs::remove_dir_all(&stage_path); |
| 276 | Err(error) |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn verify_snapshot( |
| 282 | root: &Path, |
| 283 | directories: &BTreeSet<PathBuf>, |
| 284 | files: &BTreeMap<PathBuf, &[u8]>, |
| 285 | ) -> io::Result<()> { |
| 286 | for relative in directories { |
| 287 | let directory = if relative.as_os_str().is_empty() { |
| 288 | root.to_path_buf() |
| 289 | } else { |
| 290 | root.join(relative) |
| 291 | }; |
| 292 | let metadata = fs::symlink_metadata(&directory)?; |
| 293 | if !metadata.is_dir() || metadata_is_link_or_reparse(&metadata) { |
| 294 | return Err(invalid_bundle( |
| 295 | "built-in snapshot directory is not a real directory", |
| 296 | )); |
| 297 | } |
| 298 | for entry in fs::read_dir(&directory)? { |
| 299 | let entry = entry?; |
| 300 | let child = relative.join(entry.file_name()); |
| 301 | if !files.contains_key(&child) && !directories.contains(&child) { |
| 302 | return Err(invalid_bundle( |
| 303 | "built-in snapshot contains unexpected content", |
| 304 | )); |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | for (relative, contents) in files { |
| 309 | let path = root.join(relative); |
| 310 | let mut file = super::registry::open_existing_regular_file(&path, false) |
| 311 | .map_err(io::Error::other)? |
| 312 | .ok_or_else(|| invalid_bundle("built-in snapshot file is missing"))?; |
| 313 | let metadata = file.metadata()?; |
| 314 | if metadata.len() != contents.len() as u64 { |
| 315 | return Err(invalid_bundle("built-in snapshot content changed")); |
| 316 | } |
| 317 | let mut buffer = vec![0; 64 * 1024]; |
| 318 | for chunk in contents.chunks(buffer.len()) { |
| 319 | file.read_exact(&mut buffer[..chunk.len()])?; |
| 320 | if &buffer[..chunk.len()] != chunk { |
| 321 | return Err(invalid_bundle("built-in snapshot content changed")); |
| 322 | } |
| 323 | } |
| 324 | if file.read(&mut buffer[..1])? != 0 { |
| 325 | return Err(invalid_bundle( |
| 326 | "built-in snapshot content changed during verification", |
| 327 | )); |
| 328 | } |
| 329 | } |
| 330 | Ok(()) |
| 331 | } |
| 332 | |
| 333 | pub fn parse_snapshot_dir_name( |
| 334 | dir_name: &str, |
| 335 | bundles: &[EmbeddedBundle], |
| 336 | ) -> Option<(&'static str, String)> { |
| 337 | bundles.iter().find_map(|bundle| { |
| 338 | let digest = dir_name.strip_prefix(bundle.name)?.strip_prefix('-')?; |
| 339 | (digest.len() == 64 |
| 340 | && digest |
| 341 | .bytes() |
| 342 | .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) |
| 343 | .then(|| (bundle.name, digest.to_string())) |
| 344 | }) |
| 345 | } |
| 346 | |
| 347 | #[cfg(any(target_os = "macos", target_os = "linux", target_os = "android"))] |
| 348 | pub fn publish_snapshot(source: &Path, destination: &Path) -> io::Result<()> { |
| 349 | use std::ffi::CString; |
| 350 | use std::os::unix::ffi::OsStrExt as _; |
| 351 | |
| 352 | let source = CString::new(source.as_os_str().as_bytes())?; |
| 353 | let destination = CString::new(destination.as_os_str().as_bytes())?; |
| 354 | #[cfg(target_os = "macos")] |
| 355 | let result = |
| 356 | unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) }; |
| 357 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 358 | let result = unsafe { |
| 359 | libc::syscall( |
| 360 | libc::SYS_renameat2, |
| 361 | libc::AT_FDCWD, |
| 362 | source.as_ptr(), |
| 363 | libc::AT_FDCWD, |
| 364 | destination.as_ptr(), |
| 365 | libc::RENAME_NOREPLACE, |
| 366 | ) |
| 367 | }; |
| 368 | if result == 0 { |
| 369 | Ok(()) |
| 370 | } else { |
| 371 | Err(io::Error::last_os_error()) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | #[cfg(windows)] |
| 376 | pub fn publish_snapshot(source: &Path, destination: &Path) -> io::Result<()> { |
| 377 | use std::os::windows::ffi::OsStrExt as _; |
| 378 | use windows::Win32::Storage::FileSystem::{MOVEFILE_WRITE_THROUGH, MoveFileExW}; |
| 379 | use windows::core::PCWSTR; |
| 380 | |
| 381 | let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect(); |
| 382 | let destination: Vec<u16> = destination |
| 383 | .as_os_str() |
| 384 | .encode_wide() |
| 385 | .chain(Some(0)) |
| 386 | .collect(); |
| 387 | let mut attempt = 0; |
| 388 | loop { |
| 389 | let error = match unsafe { |
| 390 | MoveFileExW( |
| 391 | PCWSTR(source.as_ptr()), |
| 392 | PCWSTR(destination.as_ptr()), |
| 393 | MOVEFILE_WRITE_THROUGH, |
| 394 | ) |
| 395 | } { |
| 396 | Ok(()) => return Ok(()), |
| 397 | Err(_) => io::Error::last_os_error(), |
| 398 | }; |
| 399 | let Some(backoff) = codewhale_util::utils::windows_publish_retry_delay(&error, attempt) |
| 400 | else { |
| 401 | return Err(error); |
| 402 | }; |
| 403 | std::thread::sleep(backoff); |
| 404 | attempt += 1; |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | #[cfg(not(any( |
| 409 | target_os = "macos", |
| 410 | target_os = "linux", |
| 411 | target_os = "android", |
| 412 | windows |
| 413 | )))] |
| 414 | pub fn publish_snapshot(_source: &Path, _destination: &Path) -> io::Result<()> { |
| 415 | Err(io::Error::new( |
| 416 | io::ErrorKind::Unsupported, |
| 417 | "atomic built-in snapshot publication is unsupported on this platform", |
| 418 | )) |
| 419 | } |
| 420 | |
| 421 | #[cfg(test)] |
| 422 | #[path = "builtin_tests.rs"] |
| 423 | mod snapshot_tests; |
| 424 |