| 1 | //! Tool specification traits for the CodeWhale agent system. |
| 2 | //! |
| 3 | //! This module defines the core abstractions for tools: |
| 4 | //! - `ToolSpec`: The main trait that all tools must implement |
| 5 | //! - `ToolContext`: Execution context passed to tools |
| 6 | //! - `ToolResult`: Unified result type for tool execution |
| 7 | //! - `ToolCapability`: Capabilities and requirements of tools |
| 8 | |
| 9 | use std::collections::HashMap; |
| 10 | use std::fs; |
| 11 | use std::path::{Component, Path, PathBuf}; |
| 12 | use std::sync::{Arc, Mutex, OnceLock}; |
| 13 | use std::time::SystemTime; |
| 14 | |
| 15 | use async_trait::async_trait; |
| 16 | use serde::{Deserialize, Serialize}; |
| 17 | use serde_json::Value; |
| 18 | use tokio_util::sync::CancellationToken; |
| 19 | use unicode_normalization::UnicodeNormalization; |
| 20 | |
| 21 | use codewhale_execpolicy::ApprovalMode; |
| 22 | |
| 23 | use crate::rlm::session::SessionObjectSnapshot; |
| 24 | use crate::rlm::session::{SharedRlmSessionStore, new_shared_rlm_session_store}; |
| 25 | use crate::tools::handle::{SharedHandleStore, new_shared_handle_store}; |
| 26 | use crate::tools::shell::{SharedShellManager, new_shared_shell_manager}; |
| 27 | use codewhale_agent_contract::worker_profile::ShellPolicy; |
| 28 | use codewhale_lsp::LspManager; |
| 29 | use codewhale_net::network_policy::NetworkPolicyDecider; |
| 30 | use codewhale_runtime::features::Features; |
| 31 | use codewhale_sandbox::backend::SandboxBackend; |
| 32 | #[allow(unused_imports)] |
| 33 | pub use codewhale_tools::{ |
| 34 | ApprovalRequirement, PreparedToolCall, ResourceClaim, ToolCapability, ToolError, |
| 35 | ToolExecutionOutcome, ToolResult, ToolResultContentBlock, ToolTerminalStatus, optional_bool, |
| 36 | optional_bool_opt, optional_str, optional_u64, required_str, required_u64, |
| 37 | schedule_non_conflicting, type_mismatch, |
| 38 | }; |
| 39 | |
| 40 | /// Text plus provider-neutral rich blocks at the conversation boundary. |
| 41 | #[derive(Debug, Clone)] |
| 42 | pub struct RichToolResult { |
| 43 | pub result: ToolResult, |
| 44 | pub content_blocks: Vec<ToolResultContentBlock>, |
| 45 | } |
| 46 | |
| 47 | impl RichToolResult { |
| 48 | #[must_use] |
| 49 | pub fn plain(result: ToolResult) -> Self { |
| 50 | Self { |
| 51 | result, |
| 52 | content_blocks: Vec::new(), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | #[must_use] |
| 57 | pub fn with_content_blocks( |
| 58 | result: ToolResult, |
| 59 | content_blocks: Vec<ToolResultContentBlock>, |
| 60 | ) -> Self { |
| 61 | Self { |
| 62 | result, |
| 63 | content_blocks, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | #[must_use] |
| 68 | pub fn into_result(self) -> ToolResult { |
| 69 | self.result |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | impl std::ops::Deref for RichToolResult { |
| 74 | type Target = ToolResult; |
| 75 | |
| 76 | fn deref(&self) -> &Self::Target { |
| 77 | &self.result |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | #[async_trait] |
| 82 | pub trait DynamicToolExecutor: Send + Sync { |
| 83 | async fn execute_dynamic_tool( |
| 84 | &self, |
| 85 | thread_id: Option<String>, |
| 86 | namespace: Option<String>, |
| 87 | name: String, |
| 88 | input: Value, |
| 89 | ) -> Result<ToolResult, ToolError>; |
| 90 | } |
| 91 | |
| 92 | /// Optional durable runtime services made available to model-visible tools. |
| 93 | /// |
| 94 | /// These are intentionally optional so existing unit tests and one-off tool |
| 95 | /// contexts keep working. Tools that need durable task/automation state fail |
| 96 | /// closed with a clear "not available" error when the relevant service is not |
| 97 | /// attached. |
| 98 | pub type OwnerAccountingOriginLookup = |
| 99 | Arc<dyn Fn(&str) -> Option<crate::cost_status::NativeUsageOrigin> + Send + Sync>; |
| 100 | |
| 101 | #[derive(Clone)] |
| 102 | pub struct RuntimeToolServices { |
| 103 | pub accounting_origin: Option<crate::cost_status::NativeUsageOrigin>, |
| 104 | pub owner_accounting_origin: Option<OwnerAccountingOriginLookup>, |
| 105 | pub runtime_mcp_servers: Option<(PathBuf, crate::mcp::SharedRuntimeMcpServers)>, |
| 106 | pub shell_manager: Option<SharedShellManager>, |
| 107 | /// True only for the real headless exec host after it has established the |
| 108 | /// explicit authority required to transfer `persist:true` services. |
| 109 | pub persist_services_enabled: bool, |
| 110 | pub task_manager: Option<crate::task_manager::SharedTaskManager>, |
| 111 | pub automations: Option<crate::automation_manager::SharedAutomationManager>, |
| 112 | pub task_data_dir: Option<PathBuf>, |
| 113 | pub active_task_id: Option<String>, |
| 114 | pub active_thread_id: Option<String>, |
| 115 | pub dynamic_tool_executor: Option<Arc<dyn DynamicToolExecutor>>, |
| 116 | /// Active-session Work Graph authority plus its legacy Plan/To-do views. |
| 117 | pub work: Option<crate::work_graph::SharedWorkRuntime>, |
| 118 | /// Hook executor for `shell_env` injection (#456) and any future |
| 119 | /// tool-side hook events. `None` outside the live engine — test |
| 120 | /// contexts that don't care about hooks get a no-op. |
| 121 | pub hook_executor: Option<std::sync::Arc<crate::hooks::HookExecutor>>, |
| 122 | /// Per-session backing store for `var_handle` payloads. Cloned tool |
| 123 | /// contexts share this Arc so handles survive across turns. |
| 124 | pub handle_store: SharedHandleStore, |
| 125 | /// Per-session persistent RLM kernels, keyed by caller-chosen context name. |
| 126 | pub rlm_sessions: SharedRlmSessionStore, |
| 127 | /// Directory for `read_media`'s content-addressed store of |
| 128 | /// pre-compression image originals. `None` (tests and one-off contexts) |
| 129 | /// disables persistence so unit tests never touch the real state dir; |
| 130 | /// production wiring points it at `<codewhale home>/media-originals`. |
| 131 | pub media_originals_dir: Option<PathBuf>, |
| 132 | } |
| 133 | |
| 134 | impl Default for RuntimeToolServices { |
| 135 | fn default() -> Self { |
| 136 | Self { |
| 137 | accounting_origin: None, |
| 138 | owner_accounting_origin: None, |
| 139 | runtime_mcp_servers: None, |
| 140 | shell_manager: None, |
| 141 | persist_services_enabled: false, |
| 142 | task_manager: None, |
| 143 | automations: None, |
| 144 | task_data_dir: None, |
| 145 | active_task_id: None, |
| 146 | active_thread_id: None, |
| 147 | dynamic_tool_executor: None, |
| 148 | work: None, |
| 149 | hook_executor: None, |
| 150 | handle_store: new_shared_handle_store(), |
| 151 | rlm_sessions: new_shared_rlm_session_store(), |
| 152 | media_originals_dir: None, |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | impl std::fmt::Debug for RuntimeToolServices { |
| 158 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 159 | f.debug_struct("RuntimeToolServices") |
| 160 | .field("accounting_origin", &self.accounting_origin.is_some()) |
| 161 | .field("runtime_mcp_servers", &self.runtime_mcp_servers.is_some()) |
| 162 | .field("shell_manager", &self.shell_manager.is_some()) |
| 163 | .field("persist_services_enabled", &self.persist_services_enabled) |
| 164 | .field("task_manager", &self.task_manager.is_some()) |
| 165 | .field("automations", &self.automations.is_some()) |
| 166 | .field("task_data_dir", &self.task_data_dir) |
| 167 | .field("active_task_id", &self.active_task_id) |
| 168 | .field("active_thread_id", &self.active_thread_id) |
| 169 | .field( |
| 170 | "dynamic_tool_executor", |
| 171 | &self.dynamic_tool_executor.is_some(), |
| 172 | ) |
| 173 | .field("work", &self.work.is_some()) |
| 174 | .field("hook_executor", &self.hook_executor.is_some()) |
| 175 | .field("handle_store", &true) |
| 176 | .field("rlm_sessions", &true) |
| 177 | .field("media_originals_dir", &self.media_originals_dir) |
| 178 | .finish() |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 183 | struct FileReadSnapshot { |
| 184 | len: u64, |
| 185 | modified: Option<SystemTime>, |
| 186 | } |
| 187 | |
| 188 | #[derive(Debug, Default)] |
| 189 | pub struct FileReadTracker { |
| 190 | reads: HashMap<PathBuf, FileReadSnapshot>, |
| 191 | } |
| 192 | |
| 193 | pub type SharedFileReadTracker = Arc<Mutex<FileReadTracker>>; |
| 194 | |
| 195 | pub fn new_shared_file_read_tracker() -> SharedFileReadTracker { |
| 196 | Arc::new(Mutex::new(FileReadTracker::default())) |
| 197 | } |
| 198 | |
| 199 | fn file_read_snapshot(path: &Path) -> Result<FileReadSnapshot, ToolError> { |
| 200 | let metadata = fs::metadata(path).map_err(|e| { |
| 201 | ToolError::execution_failed(format!("Failed to inspect {}: {e}", path.display())) |
| 202 | })?; |
| 203 | Ok(FileReadSnapshot { |
| 204 | len: metadata.len(), |
| 205 | modified: metadata.modified().ok(), |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | /// Machine-readable mutation boundary for a headless worker process. |
| 210 | /// |
| 211 | /// Fleet serializes this envelope onto the exact `codewhale exec` argv. The |
| 212 | /// child installs it before constructing its engine, and every ToolContext in |
| 213 | /// that process inherits the same outer cap. Nested agents may narrow this |
| 214 | /// boundary, but cannot remove or expand it. |
| 215 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 216 | #[serde(deny_unknown_fields)] |
| 217 | pub struct ToolAuthorityEnvelope { |
| 218 | pub schema_version: u32, |
| 219 | pub owner: String, |
| 220 | pub authority: ToolMutationAuthority, |
| 221 | /// Optional outer network cap for headless workers. `None` preserves the |
| 222 | /// behavior of v1 envelopes written before this field existed; new Fleet |
| 223 | /// launches always carry the resolved worker permission explicitly. |
| 224 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 225 | pub network_access: Option<bool>, |
| 226 | /// Explicit shell cap for a headless worker. Older v1 envelopes omit this |
| 227 | /// field and therefore remain shell-less; mutation authority is never |
| 228 | /// treated as an implicit shell grant. |
| 229 | #[serde(default, skip_serializing_if = "ToolShellAuthority::is_none")] |
| 230 | pub shell: ToolShellAuthority, |
| 231 | /// Narrow process-start authority for the built-in verification surface. |
| 232 | /// This is separate from both mutation and shell authority: a verifier may |
| 233 | /// run classifier-bounded workspace checks, but that never grants Bash or |
| 234 | /// an operator-supplied command line. |
| 235 | #[serde(default, skip_serializing_if = "ToolVerificationAuthority::is_none")] |
| 236 | pub verification: ToolVerificationAuthority, |
| 237 | #[serde(default)] |
| 238 | pub writable_roots: Vec<String>, |
| 239 | #[serde(default)] |
| 240 | pub writable_files: Vec<String>, |
| 241 | #[serde(default)] |
| 242 | pub coordination_contracts: Vec<String>, |
| 243 | } |
| 244 | |
| 245 | /// Shell authority carried across the Fleet subprocess boundary. |
| 246 | /// |
| 247 | /// Full/arbitrary shell is intentionally not representable here. Fleet can |
| 248 | /// opt a Scout/Reviewer worker into the classifier-proven read subset, while every |
| 249 | /// other headless role keeps the historical shell-less posture. |
| 250 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] |
| 251 | #[serde(rename_all = "snake_case")] |
| 252 | pub enum ToolShellAuthority { |
| 253 | #[default] |
| 254 | None, |
| 255 | ReadOnly, |
| 256 | } |
| 257 | |
| 258 | impl ToolShellAuthority { |
| 259 | #[must_use] |
| 260 | pub const fn is_none(&self) -> bool { |
| 261 | matches!(self, Self::None) |
| 262 | } |
| 263 | |
| 264 | #[must_use] |
| 265 | const fn shell_policy(self) -> ShellPolicy { |
| 266 | match self { |
| 267 | Self::None => ShellPolicy::None, |
| 268 | Self::ReadOnly => ShellPolicy::ReadOnly, |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Process authority for Fleet's dedicated verifier role. |
| 274 | /// |
| 275 | /// Arbitrary execution is intentionally not representable. The registry and |
| 276 | /// dispatch boundary admit only calls that the shared verification classifier |
| 277 | /// proves are default workspace checks or pure test selection. |
| 278 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] |
| 279 | #[serde(rename_all = "snake_case")] |
| 280 | pub enum ToolVerificationAuthority { |
| 281 | #[default] |
| 282 | None, |
| 283 | Bounded, |
| 284 | } |
| 285 | |
| 286 | impl ToolVerificationAuthority { |
| 287 | #[must_use] |
| 288 | pub const fn is_none(&self) -> bool { |
| 289 | matches!(self, Self::None) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// Whether a headless Fleet process should register the one read-only Bash |
| 294 | /// surface after intersecting the transported cap with explicit tool denies. |
| 295 | #[must_use] |
| 296 | pub fn fleet_exec_shell_enabled( |
| 297 | fleet_authority_active: bool, |
| 298 | shell_authority: ToolShellAuthority, |
| 299 | disallowed_tools: Option<&[String]>, |
| 300 | ) -> bool { |
| 301 | fleet_authority_active |
| 302 | && shell_authority == ToolShellAuthority::ReadOnly |
| 303 | && !disallowed_tools.is_some_and(|rules| { |
| 304 | rules.iter().any(|rule| { |
| 305 | let rule = rule.trim().to_ascii_lowercase(); |
| 306 | rule.strip_suffix('*') |
| 307 | .map_or_else(|| rule == "bash", |prefix| "bash".starts_with(prefix)) |
| 308 | }) |
| 309 | }) |
| 310 | } |
| 311 | |
| 312 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 313 | #[serde(rename_all = "snake_case")] |
| 314 | pub enum ToolMutationAuthority { |
| 315 | ReadOnly, |
| 316 | ScopedWrite, |
| 317 | } |
| 318 | |
| 319 | static PROCESS_TOOL_AUTHORITY: OnceLock<Arc<ToolAuthorityEnvelope>> = OnceLock::new(); |
| 320 | |
| 321 | impl ToolAuthorityEnvelope { |
| 322 | pub fn normalized(mut self) -> Result<Self, String> { |
| 323 | if self.schema_version != 1 { |
| 324 | return Err(format!( |
| 325 | "unsupported tool authority schema version {}", |
| 326 | self.schema_version |
| 327 | )); |
| 328 | } |
| 329 | self.owner = bounded_authority_value("owner", &self.owner, 128)?; |
| 330 | self.writable_roots = normalize_authority_paths(&self.writable_roots, "writable_roots")?; |
| 331 | self.writable_files = normalize_authority_paths(&self.writable_files, "writable_files")?; |
| 332 | self.coordination_contracts = normalize_authority_values( |
| 333 | &self.coordination_contracts, |
| 334 | "coordination_contracts", |
| 335 | 16, |
| 336 | 128, |
| 337 | )?; |
| 338 | if self.authority == ToolMutationAuthority::ScopedWrite |
| 339 | && self.writable_roots.is_empty() |
| 340 | && self.writable_files.is_empty() |
| 341 | && self.coordination_contracts.is_empty() |
| 342 | { |
| 343 | return Err( |
| 344 | "scoped_write authority requires a writable root, exact file, or coordination contract" |
| 345 | .to_string(), |
| 346 | ); |
| 347 | } |
| 348 | if self.authority == ToolMutationAuthority::ReadOnly |
| 349 | && (!self.writable_roots.is_empty() |
| 350 | || !self.writable_files.is_empty() |
| 351 | || !self.coordination_contracts.is_empty()) |
| 352 | { |
| 353 | return Err("read_only authority cannot carry mutation scope".to_string()); |
| 354 | } |
| 355 | if self.verification == ToolVerificationAuthority::Bounded |
| 356 | && (self.authority != ToolMutationAuthority::ReadOnly |
| 357 | || self.shell != ToolShellAuthority::None) |
| 358 | { |
| 359 | return Err( |
| 360 | "bounded verification requires read_only mutation authority and no Bash authority" |
| 361 | .to_string(), |
| 362 | ); |
| 363 | } |
| 364 | Ok(self) |
| 365 | } |
| 366 | |
| 367 | pub fn from_json(raw: &str) -> Result<Self, String> { |
| 368 | serde_json::from_str::<Self>(raw) |
| 369 | .map_err(|error| format!("invalid tool authority envelope: {error}"))? |
| 370 | .normalized() |
| 371 | } |
| 372 | |
| 373 | #[cfg(any(test, feature = "test-support"))] |
| 374 | fn is_within(&self, outer: &Self) -> bool { |
| 375 | if self.shell > outer.shell |
| 376 | || self.verification > outer.verification |
| 377 | || (outer.network_access == Some(false) && self.network_access != Some(false)) |
| 378 | { |
| 379 | return false; |
| 380 | } |
| 381 | if self.authority == ToolMutationAuthority::ReadOnly { |
| 382 | return true; |
| 383 | } |
| 384 | if outer.authority != ToolMutationAuthority::ScopedWrite { |
| 385 | return false; |
| 386 | } |
| 387 | self.writable_roots.iter().all(|path| { |
| 388 | outer |
| 389 | .writable_roots |
| 390 | .iter() |
| 391 | .any(|root| authority_path_is_within_root(path, root)) |
| 392 | }) && self.writable_files.iter().all(|path| { |
| 393 | outer.writable_files.contains(path) |
| 394 | || outer |
| 395 | .writable_roots |
| 396 | .iter() |
| 397 | .any(|root| authority_path_is_within_root(path, root)) |
| 398 | }) && self |
| 399 | .coordination_contracts |
| 400 | .iter() |
| 401 | .all(|contract| outer.coordination_contracts.contains(contract)) |
| 402 | } |
| 403 | |
| 404 | pub fn permits_mutation_path( |
| 405 | &self, |
| 406 | context: &ToolContext, |
| 407 | raw_path: &str, |
| 408 | ) -> Result<bool, ToolError> { |
| 409 | if self.authority == ToolMutationAuthority::ReadOnly { |
| 410 | return Ok(false); |
| 411 | } |
| 412 | let target = resolve_strict_authority_path(context, raw_path)?; |
| 413 | for file in &self.writable_files { |
| 414 | if resolve_strict_authority_path(context, file)? == target { |
| 415 | return Ok(true); |
| 416 | } |
| 417 | } |
| 418 | for root in &self.writable_roots { |
| 419 | if target.starts_with(resolve_strict_authority_path(context, root)?) { |
| 420 | return Ok(true); |
| 421 | } |
| 422 | } |
| 423 | Ok(false) |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | #[cfg(any(test, feature = "test-support"))] |
| 428 | fn authority_path_is_within_root(path: &str, root: &str) -> bool { |
| 429 | root == "." |
| 430 | || path == root |
| 431 | || path |
| 432 | .strip_prefix(root) |
| 433 | .is_some_and(|suffix| suffix.starts_with('/')) |
| 434 | } |
| 435 | |
| 436 | pub fn install_process_tool_authority(envelope: ToolAuthorityEnvelope) -> Result<(), String> { |
| 437 | let envelope = Arc::new(envelope.normalized()?); |
| 438 | if let Some(existing) = PROCESS_TOOL_AUTHORITY.get() { |
| 439 | return if existing.as_ref() == envelope.as_ref() { |
| 440 | Ok(()) |
| 441 | } else { |
| 442 | Err("tool authority envelope was already installed for this process".to_string()) |
| 443 | }; |
| 444 | } |
| 445 | PROCESS_TOOL_AUTHORITY |
| 446 | .set(envelope) |
| 447 | .map_err(|_| "tool authority envelope was already installed for this process".to_string()) |
| 448 | } |
| 449 | |
| 450 | fn process_tool_authority() -> Option<Arc<ToolAuthorityEnvelope>> { |
| 451 | PROCESS_TOOL_AUTHORITY.get().cloned() |
| 452 | } |
| 453 | |
| 454 | fn bounded_authority_value(field: &str, value: &str, max_chars: usize) -> Result<String, String> { |
| 455 | let value = value.trim().nfc().collect::<String>(); |
| 456 | if value.is_empty() |
| 457 | || value.chars().count() > max_chars |
| 458 | || value.chars().any(|ch| matches!(ch, '\0' | '\r' | '\n')) |
| 459 | { |
| 460 | return Err(format!( |
| 461 | "tool authority {field} must be one non-empty line of at most {max_chars} characters" |
| 462 | )); |
| 463 | } |
| 464 | Ok(value) |
| 465 | } |
| 466 | |
| 467 | fn normalize_authority_paths(values: &[String], field: &str) -> Result<Vec<String>, String> { |
| 468 | if values.len() > 32 { |
| 469 | return Err(format!("tool authority {field} accepts at most 32 entries")); |
| 470 | } |
| 471 | let mut normalized = Vec::new(); |
| 472 | for raw in values { |
| 473 | let raw = bounded_authority_value(field, raw, 512)?.replace('\\', "/"); |
| 474 | let windows_drive = raw.as_bytes().get(1) == Some(&b':') |
| 475 | && raw.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); |
| 476 | if raw.starts_with('/') || raw.starts_with("//") || windows_drive { |
| 477 | return Err(format!( |
| 478 | "tool authority {field} entries must be repo-relative" |
| 479 | )); |
| 480 | } |
| 481 | let mut segments = Vec::new(); |
| 482 | for segment in raw.split('/') { |
| 483 | match segment { |
| 484 | "" | "." => {} |
| 485 | ".." => { |
| 486 | return Err(format!( |
| 487 | "tool authority {field} cannot contain parent traversal" |
| 488 | )); |
| 489 | } |
| 490 | value => segments.push(value), |
| 491 | } |
| 492 | } |
| 493 | let path = if segments.is_empty() { |
| 494 | ".".to_string() |
| 495 | } else { |
| 496 | segments.join("/") |
| 497 | }; |
| 498 | if !normalized.contains(&path) { |
| 499 | normalized.push(path); |
| 500 | } |
| 501 | } |
| 502 | Ok(normalized) |
| 503 | } |
| 504 | |
| 505 | fn normalize_authority_values( |
| 506 | values: &[String], |
| 507 | field: &str, |
| 508 | max_entries: usize, |
| 509 | max_chars: usize, |
| 510 | ) -> Result<Vec<String>, String> { |
| 511 | if values.len() > max_entries { |
| 512 | return Err(format!( |
| 513 | "tool authority {field} accepts at most {max_entries} entries" |
| 514 | )); |
| 515 | } |
| 516 | let mut normalized = Vec::new(); |
| 517 | for value in values { |
| 518 | let value = bounded_authority_value(field, value, max_chars)?; |
| 519 | if !normalized.contains(&value) { |
| 520 | normalized.push(value); |
| 521 | } |
| 522 | } |
| 523 | Ok(normalized) |
| 524 | } |
| 525 | |
| 526 | pub fn resolve_strict_authority_path( |
| 527 | context: &ToolContext, |
| 528 | raw_path: &str, |
| 529 | ) -> Result<PathBuf, ToolError> { |
| 530 | let normalized = normalize_authority_paths(&[raw_path.to_string()], "mutation_path") |
| 531 | .map_err(ToolError::permission_denied)? |
| 532 | .into_iter() |
| 533 | .next() |
| 534 | .ok_or_else(|| ToolError::permission_denied("mutation path cannot be empty"))?; |
| 535 | let workspace = context.workspace.canonicalize().map_err(|error| { |
| 536 | ToolError::execution_failed(format!( |
| 537 | "Failed to canonicalize authority workspace {}: {error}", |
| 538 | context.workspace.display() |
| 539 | )) |
| 540 | })?; |
| 541 | let mut current = workspace.clone(); |
| 542 | if normalized != "." { |
| 543 | for segment in normalized.split('/') { |
| 544 | current.push(segment); |
| 545 | match fs::symlink_metadata(¤t) { |
| 546 | Ok(metadata) |
| 547 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) => |
| 548 | { |
| 549 | return Err(ToolError::permission_denied(format!( |
| 550 | "machine-readable authority paths must not traverse symlinks: {}", |
| 551 | current.display() |
| 552 | ))); |
| 553 | } |
| 554 | Ok(_) => {} |
| 555 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 556 | Err(error) => { |
| 557 | return Err(ToolError::execution_failed(format!( |
| 558 | "Failed to inspect authority path {}: {error}", |
| 559 | current.display() |
| 560 | ))); |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | if !current.starts_with(&workspace) { |
| 566 | return Err(ToolError::permission_denied(format!( |
| 567 | "machine-readable authority path escapes workspace: {}", |
| 568 | current.display() |
| 569 | ))); |
| 570 | } |
| 571 | Ok(current) |
| 572 | } |
| 573 | |
| 574 | /// Context passed to tools during execution. |
| 575 | #[derive(Clone)] |
| 576 | pub struct ToolContext { |
| 577 | /// The workspace root directory |
| 578 | pub workspace: PathBuf, |
| 579 | /// Per-turn policy and attached services. Kept behind one owned group so |
| 580 | /// cloning a context preserves the historical value semantics while the |
| 581 | /// top-level context remains small and stable as services evolve. |
| 582 | pub execution: Box<ToolExecutionState>, |
| 583 | } |
| 584 | |
| 585 | /// Policy and service state attached to one tool-execution context. |
| 586 | /// |
| 587 | /// `ToolContext` dereferences to this group for source compatibility with |
| 588 | /// existing tools. New code can use `context.execution` when the grouping is |
| 589 | /// useful, without growing the top-level context by another field per feature. |
| 590 | #[derive(Clone)] |
| 591 | pub struct ToolExecutionState { |
| 592 | /// Actual Core caller admission for per-round Python RPCs. Kernels do not |
| 593 | /// retain it; unattached tool contexts cannot make model calls. |
| 594 | pub rlm_caller: Option<Arc<crate::core::engine::rlm_host::CapturedRlmCaller>>, |
| 595 | pub accounting_origin: Option<crate::cost_status::NativeUsageOrigin>, |
| 596 | /// Effective session/ancestor tool ceiling, carried to MCP dispatch and runtime registration. |
| 597 | pub disallowed_tools: Vec<String>, |
| 598 | /// Trusted local host narrowing; inherited by every alias/nested context. |
| 599 | pub acp_host: Option<codewhale_config::AppMode>, |
| 600 | /// Captured child grant; retained through aliases and context overrides. |
| 601 | pub child_host: Option<Arc<crate::tools::subagent::engine::ChildAuthority>>, |
| 602 | /// Set only on the context of one call a person approved on a card. |
| 603 | pub human_decision: Option<crate::core::engine::HumanDecision>, |
| 604 | /// Carried authorization for a changing `plugin_manager` call. |
| 605 | pub creator_decision: Option<crate::extension_host::creator_policy::CreatorDecisionCarrier>, |
| 606 | pub mcp_always_binding: Option<u64>, |
| 607 | pub account_fence: Option<Arc<crate::profile_constitution::AccountFence>>, |
| 608 | /// Shared shell manager for background tasks and streaming IO. |
| 609 | pub shell_manager: SharedShellManager, |
| 610 | /// Per-session snapshots for files successfully observed by `read_file`. |
| 611 | /// Mutation tools use this to reject narrow edits against unread or stale |
| 612 | /// content. |
| 613 | pub file_read_tracker: SharedFileReadTracker, |
| 614 | /// Sub-agent that owns tool work started through this context. Root user |
| 615 | /// turns leave this unset; child contexts stamp it so long-running shell |
| 616 | /// jobs can be attributed in UI surfaces. |
| 617 | pub owner_agent_id: Option<String>, |
| 618 | pub owner_agent_name: Option<String>, |
| 619 | /// Tool call and engine turn that created long-running work through this |
| 620 | /// context. Hosts use these stable identities to reconcile later updates |
| 621 | /// with the originating transcript position. |
| 622 | pub origin_tool_call_id: Option<String>, |
| 623 | pub origin_turn_id: Option<String>, |
| 624 | /// Outer process authority cap installed by Fleet/headless dispatch. |
| 625 | /// `None` for ordinary interactive/root sessions. |
| 626 | pub tool_authority: Option<Arc<ToolAuthorityEnvelope>>, |
| 627 | /// Whether to allow paths outside workspace |
| 628 | pub trust_mode: bool, |
| 629 | /// Explicit skills directory used for model-visible skill discovery. |
| 630 | pub skills_dir: Option<PathBuf>, |
| 631 | /// Session-pinned skill discovery, bundle policy and ambient index limits. |
| 632 | pub skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>, |
| 633 | /// Immutable registry snapshot for this workspace/engine context. |
| 634 | pub plugin_registry: Option<Arc<codewhale_plugins::PluginRegistry>>, |
| 635 | /// Elevated sandbox policy override (used when retrying after sandbox denial). |
| 636 | /// This overrides the default sandbox behavior for shell commands. |
| 637 | pub elevated_sandbox_policy: Option<codewhale_sandbox::SandboxPolicy>, |
| 638 | /// Whether the enclosing host is the real headless `codewhale exec` |
| 639 | /// process. `persist:true` background services are only permitted there; |
| 640 | /// interactive TUI, desktop/app-server, and hosted runtime-thread engines |
| 641 | /// leave this false so the feature fails closed. |
| 642 | pub persist_services_enabled: bool, |
| 643 | /// Optional user-facing hint for shell commands that fail because the |
| 644 | /// active sandbox policy intentionally denies outbound network access. |
| 645 | pub shell_network_denied_hint: Option<String>, |
| 646 | /// Whether tools should auto-approve without safety checks (YOLO mode). |
| 647 | /// When true, command safety analysis is skipped for shell execution. |
| 648 | pub auto_approve: bool, |
| 649 | /// Effective approval posture for this execution context. A turn stamps the |
| 650 | /// posture it resolved here; a context built from the legacy bit alone |
| 651 | /// folds it with [`codewhale_execpolicy::ApprovalMode::from_auto_approve`]. |
| 652 | /// Tools that create work of their own (a durable task) pin it, so the work |
| 653 | /// inherits the authority the caller was granted rather than re-deriving |
| 654 | /// one from a legacy bit. |
| 655 | pub approval_mode: ApprovalMode, |
| 656 | pub owner_present: bool, |
| 657 | /// Effective shell policy for this execution context. |
| 658 | pub shell_policy: ShellPolicy, |
| 659 | /// Effective feature flag set for the running session. |
| 660 | pub features: Features, |
| 661 | /// Namespace for tool state that should be scoped to the current session/thread. |
| 662 | pub state_namespace: String, |
| 663 | /// Effective context window for the active provider/model route. Web tools |
| 664 | /// use this to keep inline page content below three percent of the route. |
| 665 | pub route_context_window: Option<u32>, |
| 666 | /// User-trusted external paths the agent may read/write even when they |
| 667 | /// fall outside `workspace`. Loaded from `~/.deepseek/workspace-trust.json` |
| 668 | /// and refreshed when the user runs `/trust add <path>`. Distinct from |
| 669 | /// `trust_mode`, which is the all-or-nothing legacy switch (#29). |
| 670 | pub trusted_external_paths: Vec<PathBuf>, |
| 671 | pub read_only_roots: Vec<PathBuf>, |
| 672 | /// Whether to follow symbolic links during file discovery and tool |
| 673 | /// operations. When `true`, symlinked directories are traversed and |
| 674 | /// symlinked paths that resolve outside the workspace are still allowed |
| 675 | /// (the symlink itself must be inside the workspace). Mirrors the |
| 676 | /// `workspace_follow_symlinks` setting. |
| 677 | pub follow_symlinks: bool, |
| 678 | /// Per-domain network policy (#135). When `None`, network tools fall back |
| 679 | /// to a permissive default that mirrors pre-v0.7.0 behavior so tests and |
| 680 | /// other contexts that don't construct a real policy keep working. |
| 681 | pub network_policy: Option<NetworkPolicyDecider>, |
| 682 | /// Durable runtime services for task, gate, PR-attempt, GitHub evidence, |
| 683 | /// and automation tools. |
| 684 | pub runtime: RuntimeToolServices, |
| 685 | /// Snapshot of the active prompt/session/history exposed as symbolic RLM |
| 686 | /// objects. Tools only receive compact cards unless explicitly opening a |
| 687 | /// bounded object through `rlm_open`. |
| 688 | pub session_objects: Option<SessionObjectSnapshot>, |
| 689 | /// Cancellation token for the active engine turn. Tools that may wait on |
| 690 | /// external work should observe this so UI cancel can interrupt them. |
| 691 | pub cancel_token: Option<CancellationToken>, |
| 692 | /// Absolute deadline inherited from the active Engine turn after approval. |
| 693 | /// Nested model/code work may narrow this bound but must never reset it. |
| 694 | pub turn_deadline: Option<tokio::time::Instant>, |
| 695 | /// Optional external sandbox backend for shell execution. |
| 696 | /// When set, exec_shell routes commands through this instead of spawning |
| 697 | /// a local process. |
| 698 | pub sandbox_backend: Option<std::sync::Arc<dyn SandboxBackend>>, |
| 699 | /// Path to the user memory file. `None` when the user-memory feature |
| 700 | /// (#489) is disabled — tools that read or write the file should |
| 701 | /// short-circuit on `None` rather than fall back to a workspace-local |
| 702 | /// default. |
| 703 | pub memory_path: Option<PathBuf>, |
| 704 | /// LSP manager for post-edit diagnostics injection (#428). `None` when |
| 705 | /// LSP is disabled or the context is constructed in a test that does not |
| 706 | /// need diagnostics. Edit tools append a `<diagnostics>` block to their |
| 707 | /// result when this is present and the manager is enabled. |
| 708 | pub lsp_manager: Option<Arc<LspManager>>, |
| 709 | |
| 710 | /// Adaptive evidence router (#4619). Consulted only when |
| 711 | /// `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` opts the process in; under the |
| 712 | /// default classic lane this field is inert and bounding happens at the |
| 713 | /// engine/subagent completion boundary. `None` in sub-agents and test |
| 714 | /// contexts. |
| 715 | pub large_output_router: Option<crate::tools::large_output_router::LargeOutputRouter>, |
| 716 | |
| 717 | /// Which search backend `web_search` should use. Default: Firecrawl. Set via |
| 718 | /// `[search] provider` in config.toml. |
| 719 | pub search_provider: codewhale_runtime::config::SearchProvider, |
| 720 | /// Optional Firecrawl key, or required key for other API search providers. |
| 721 | /// Metaso also falls back to the `METASO_API_KEY` env var. |
| 722 | /// Baidu also falls back to `BAIDU_SEARCH_API_KEY`. |
| 723 | pub search_api_key: Option<String>, |
| 724 | /// Optional DuckDuckGo-compatible HTML endpoint override for `web_search`. |
| 725 | pub search_base_url: Option<String>, |
| 726 | pub third_party_search: crate::tools::web::consent::ThirdPartySearchPermit, |
| 727 | /// Opaque client for the active route's documented first-party search |
| 728 | /// tool. It owns provider authentication internally and is attached only |
| 729 | /// when the exact route capability says server-side search is supported. |
| 730 | pub provider_native_search: Option<crate::client::ProviderNativeSearchClient>, |
| 731 | /// Exact active route capability facts. Unknown stays fail-closed. |
| 732 | pub route_capabilities: codewhale_config::route::RouteCapabilities, |
| 733 | /// Engine-served gate for calls nested inside an `execute_tools` program. |
| 734 | /// Set only on the context of one `execute_tools` call by the turn loop; |
| 735 | /// every nested call is planned and approved through the same gate a |
| 736 | /// direct call gets. `None` everywhere else (sub-agents, tests, exec |
| 737 | /// hosts without an engine turn), where code mode keeps its read-only, |
| 738 | /// auto-approved profile. |
| 739 | pub nested_call_gate: Option<crate::tools::codemode::NestedCallGate>, |
| 740 | /// Where the session's live permission posture lives. Set by the engine; |
| 741 | /// every agent call re-reads it (`None` keeps the posture above as is). |
| 742 | pub live_posture: Option<crate::core::engine::LivePosture>, |
| 743 | pub browser_tool: Option<String>, |
| 744 | pub child_activation: Option<Arc<crate::tools::subagent::ChildActivationRequest>>, |
| 745 | pub strict_workspace_confinement: bool, |
| 746 | } |
| 747 | |
| 748 | impl std::ops::Deref for ToolContext { |
| 749 | type Target = ToolExecutionState; |
| 750 | |
| 751 | fn deref(&self) -> &Self::Target { |
| 752 | &self.execution |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | impl std::ops::DerefMut for ToolContext { |
| 757 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 758 | &mut self.execution |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | impl ToolContext { |
| 763 | /// Create an inert context for a registry that intentionally has no tools. |
| 764 | /// |
| 765 | /// Empty paths are deliberate: isolated Runtime Chat must not retain the |
| 766 | /// host workspace or derive project notes and MCP paths. Isolation comes |
| 767 | /// from callers pairing this context with an empty registry and allow-list |
| 768 | /// plus a zero tool-call budget; this constructor is not a security |
| 769 | /// boundary by itself. |
| 770 | #[must_use] |
| 771 | pub fn for_empty_registry() -> Self { |
| 772 | Self::with_options(PathBuf::new(), false) |
| 773 | } |
| 774 | |
| 775 | /// Create a new `ToolContext` with default settings. |
| 776 | #[must_use] |
| 777 | pub fn new(workspace: impl Into<PathBuf>) -> Self { |
| 778 | Self::with_options(workspace, false) |
| 779 | } |
| 780 | |
| 781 | /// Create a `ToolContext` with all settings specified. |
| 782 | pub fn with_options(workspace: impl Into<PathBuf>, trust_mode: bool) -> Self { |
| 783 | let workspace = workspace.into(); |
| 784 | let shell_manager = new_shared_shell_manager(workspace.clone()); |
| 785 | let tool_authority = process_tool_authority(); |
| 786 | let shell_policy = match tool_authority.as_deref() { |
| 787 | Some(cap) => cap.shell.shell_policy(), |
| 788 | None => ShellPolicy::Full, |
| 789 | }; |
| 790 | Self { |
| 791 | workspace, |
| 792 | execution: Box::new(ToolExecutionState { |
| 793 | rlm_caller: None, |
| 794 | accounting_origin: None, |
| 795 | disallowed_tools: Vec::new(), |
| 796 | acp_host: None, |
| 797 | child_host: None, |
| 798 | human_decision: None, |
| 799 | creator_decision: None, |
| 800 | mcp_always_binding: None, |
| 801 | account_fence: None, |
| 802 | shell_manager, |
| 803 | file_read_tracker: new_shared_file_read_tracker(), |
| 804 | owner_agent_id: None, |
| 805 | owner_agent_name: None, |
| 806 | origin_tool_call_id: None, |
| 807 | origin_turn_id: None, |
| 808 | tool_authority, |
| 809 | trust_mode, |
| 810 | skills_dir: None, |
| 811 | skills_config: Default::default(), |
| 812 | plugin_registry: None, |
| 813 | elevated_sandbox_policy: None, |
| 814 | persist_services_enabled: false, |
| 815 | shell_network_denied_hint: None, |
| 816 | auto_approve: false, |
| 817 | approval_mode: ApprovalMode::Suggest, |
| 818 | owner_present: false, |
| 819 | shell_policy, |
| 820 | features: Features::with_defaults(), |
| 821 | state_namespace: "workspace".to_string(), |
| 822 | route_context_window: None, |
| 823 | trusted_external_paths: Vec::new(), |
| 824 | read_only_roots: Vec::new(), |
| 825 | follow_symlinks: false, |
| 826 | network_policy: None, |
| 827 | runtime: RuntimeToolServices::default(), |
| 828 | session_objects: None, |
| 829 | cancel_token: None, |
| 830 | turn_deadline: None, |
| 831 | sandbox_backend: None, |
| 832 | memory_path: None, |
| 833 | lsp_manager: None, |
| 834 | large_output_router: None, |
| 835 | search_provider: codewhale_runtime::config::SearchProvider::default(), |
| 836 | search_api_key: None, |
| 837 | search_base_url: None, |
| 838 | third_party_search: crate::tools::web::consent::ThirdPartySearchPermit::default(), |
| 839 | provider_native_search: None, |
| 840 | route_capabilities: codewhale_config::route::RouteCapabilities::default(), |
| 841 | nested_call_gate: None, |
| 842 | live_posture: None, |
| 843 | browser_tool: None, |
| 844 | child_activation: None, |
| 845 | strict_workspace_confinement: false, |
| 846 | }), |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | /// Create a `ToolContext` with auto-approve mode (YOLO). |
| 851 | pub fn with_auto_approve( |
| 852 | workspace: impl Into<PathBuf>, |
| 853 | trust_mode: bool, |
| 854 | auto_approve: bool, |
| 855 | ) -> Self { |
| 856 | let mut context = Self::with_options(workspace, trust_mode); |
| 857 | context.auto_approve = auto_approve; |
| 858 | // The bit stands for a posture, so fold it here rather than leaving the |
| 859 | // two fields to disagree. A turn-level builder overwrites this with the |
| 860 | // session's resolved posture, which is the authority that counts. |
| 861 | context.approval_mode = codewhale_execpolicy::ApprovalMode::from_auto_approve(auto_approve); |
| 862 | context |
| 863 | } |
| 864 | |
| 865 | /// Attach a per-domain network policy to this context (#135). |
| 866 | #[must_use] |
| 867 | pub fn with_network_policy(mut self, policy: NetworkPolicyDecider) -> Self { |
| 868 | self.network_policy = Some(policy); |
| 869 | self |
| 870 | } |
| 871 | |
| 872 | /// Attach durable runtime services to tools. |
| 873 | #[must_use] |
| 874 | pub fn with_runtime_services(mut self, runtime: RuntimeToolServices) -> Self { |
| 875 | self.runtime = runtime; |
| 876 | self |
| 877 | } |
| 878 | |
| 879 | /// Re-read the session's live permission posture (see `live_posture`) and |
| 880 | /// return what was read; `None` when this context has no live source. |
| 881 | pub fn refresh_live_posture(&mut self) -> Option<crate::core::engine::LiveRuntimeAuthority> { |
| 882 | let live = self.live_posture.clone()?; |
| 883 | let authority = live.apply(self); |
| 884 | if let Some(child) = self.child_host.as_ref() { |
| 885 | self.shell_policy = self.shell_policy.min_with(child.grant.shell_policy()); |
| 886 | } |
| 887 | Some(authority) |
| 888 | } |
| 889 | |
| 890 | /// Stamp tool work with the sub-agent that owns it. |
| 891 | #[must_use] |
| 892 | pub fn with_owner_agent( |
| 893 | mut self, |
| 894 | agent_id: impl Into<String>, |
| 895 | agent_name: impl Into<String>, |
| 896 | ) -> Self { |
| 897 | let agent_id = agent_id.into(); |
| 898 | let agent_name = agent_name.into(); |
| 899 | self.owner_agent_id = (!agent_id.trim().is_empty()).then_some(agent_id); |
| 900 | self.owner_agent_name = (!agent_name.trim().is_empty()).then_some(agent_name); |
| 901 | self |
| 902 | } |
| 903 | |
| 904 | /// Bind long-running work to the engine turn that created it. |
| 905 | #[must_use] |
| 906 | pub fn with_origin_turn_id(mut self, turn_id: impl Into<String>) -> Self { |
| 907 | self.origin_turn_id = Some(turn_id.into()); |
| 908 | self |
| 909 | } |
| 910 | |
| 911 | /// Bind long-running work to the tool call that created it. |
| 912 | #[must_use] |
| 913 | pub fn with_origin_tool_call_id(mut self, tool_call_id: impl Into<String>) -> Self { |
| 914 | self.origin_tool_call_id = Some(tool_call_id.into()); |
| 915 | self |
| 916 | } |
| 917 | |
| 918 | #[cfg(any(test, feature = "test-support"))] |
| 919 | pub fn with_tool_authority(mut self, envelope: ToolAuthorityEnvelope) -> Result<Self, String> { |
| 920 | let envelope = envelope.normalized()?; |
| 921 | if let Some(outer) = self.tool_authority.as_ref() |
| 922 | && !envelope.is_within(outer) |
| 923 | { |
| 924 | return Err( |
| 925 | "nested tool authority cannot expand its process authority cap".to_string(), |
| 926 | ); |
| 927 | } |
| 928 | self.tool_authority = Some(Arc::new(envelope)); |
| 929 | self.shell_policy = self.authority_clamped_shell_policy(self.shell_policy); |
| 930 | Ok(self) |
| 931 | } |
| 932 | |
| 933 | /// Attach skill discovery settings for tools that need to resolve |
| 934 | /// model-visible skills by name. |
| 935 | #[must_use] |
| 936 | pub fn with_skills_config( |
| 937 | mut self, |
| 938 | skills_dir: impl Into<PathBuf>, |
| 939 | config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>, |
| 940 | ) -> Self { |
| 941 | self.skills_dir = Some(skills_dir.into()); |
| 942 | self.skills_config = config; |
| 943 | self |
| 944 | } |
| 945 | |
| 946 | #[must_use] |
| 947 | pub fn with_plugin_registry( |
| 948 | mut self, |
| 949 | registry: Arc<codewhale_plugins::PluginRegistry>, |
| 950 | ) -> Self { |
| 951 | self.plugin_registry = Some(registry); |
| 952 | self |
| 953 | } |
| 954 | |
| 955 | /// Attach active prompt/history/session symbolic objects for RLM tools. |
| 956 | #[must_use] |
| 957 | pub fn with_session_objects(mut self, snapshot: SessionObjectSnapshot) -> Self { |
| 958 | self.session_objects = Some(snapshot); |
| 959 | self |
| 960 | } |
| 961 | |
| 962 | /// Attach the active engine cancellation token. |
| 963 | #[must_use] |
| 964 | pub fn with_cancel_token(mut self, cancel_token: CancellationToken) -> Self { |
| 965 | self.cancel_token = Some(cancel_token); |
| 966 | self |
| 967 | } |
| 968 | |
| 969 | /// Attach the effective shell policy for this turn. |
| 970 | #[must_use] |
| 971 | pub fn with_shell_policy(mut self, policy: ShellPolicy) -> Self { |
| 972 | self.shell_policy = self.authority_clamped_shell_policy(policy); |
| 973 | self |
| 974 | } |
| 975 | |
| 976 | /// Replace the turn shell policy while retaining the process authority as |
| 977 | /// an outer ceiling. Live mode changes rebuild this value on every tool |
| 978 | /// call, so the clamp belongs here rather than only at engine startup. |
| 979 | pub fn set_shell_policy(&mut self, policy: ShellPolicy) { |
| 980 | self.shell_policy = self.authority_clamped_shell_policy(policy); |
| 981 | } |
| 982 | |
| 983 | fn authority_clamped_shell_policy(&self, policy: ShellPolicy) -> ShellPolicy { |
| 984 | let policy = match self.tool_authority.as_deref() { |
| 985 | Some(cap) => policy.min_with(cap.shell.shell_policy()), |
| 986 | None => policy, |
| 987 | }; |
| 988 | self.child_host |
| 989 | .as_ref() |
| 990 | .map_or(policy, |child| policy.min_with(child.grant.shell_policy())) |
| 991 | } |
| 992 | |
| 993 | /// Attach an external sandbox backend for remote shell execution. |
| 994 | #[must_use] |
| 995 | pub fn with_sandbox_backend(mut self, backend: std::sync::Arc<dyn SandboxBackend>) -> Self { |
| 996 | self.sandbox_backend = Some(backend); |
| 997 | self |
| 998 | } |
| 999 | |
| 1000 | /// Set the user's trusted external paths (loaded from |
| 1001 | /// `~/.deepseek/workspace-trust.json`). See [`Self::resolve_path`] for |
| 1002 | /// how the list is consulted. |
| 1003 | #[must_use] |
| 1004 | pub fn with_trusted_external_paths(mut self, paths: Vec<PathBuf>) -> Self { |
| 1005 | self.trusted_external_paths = paths; |
| 1006 | self |
| 1007 | } |
| 1008 | |
| 1009 | #[must_use] |
| 1010 | pub fn with_read_only_roots(mut self, roots: Vec<PathBuf>) -> Self { |
| 1011 | self.read_only_roots = roots; |
| 1012 | self |
| 1013 | } |
| 1014 | |
| 1015 | pub fn resolve_read_path(&self, raw: &str) -> Result<PathBuf, ToolError> { |
| 1016 | let escape = match self.resolve_path(raw) { |
| 1017 | Err(error @ ToolError::PathEscape { .. }) if !self.read_only_roots.is_empty() => error, |
| 1018 | other => return other, |
| 1019 | }; |
| 1020 | self.read_only_root_path(raw).ok_or(escape) |
| 1021 | } |
| 1022 | |
| 1023 | fn read_only_root_path(&self, raw: &str) -> Option<PathBuf> { |
| 1024 | let candidate = resolve_home_path(raw) |
| 1025 | .ok() |
| 1026 | .flatten() |
| 1027 | .unwrap_or_else(|| PathBuf::from(raw)); |
| 1028 | if !candidate.is_absolute() { |
| 1029 | return None; |
| 1030 | } |
| 1031 | let canonical = candidate.canonicalize().ok()?; |
| 1032 | self.read_only_roots |
| 1033 | .iter() |
| 1034 | .any(|root| canonical.starts_with(root)) |
| 1035 | .then_some(canonical) |
| 1036 | } |
| 1037 | |
| 1038 | /// Set whether tools should follow symbolic links. When `true`, |
| 1039 | /// `resolve_path` allows symlinked paths that resolve outside the |
| 1040 | /// workspace, and walk-based tools traverse symlinked directories. |
| 1041 | /// Mirrors the `workspace_follow_symlinks` setting. |
| 1042 | #[must_use] |
| 1043 | pub fn with_follow_symlinks(mut self, follow: bool) -> Self { |
| 1044 | self.follow_symlinks = follow; |
| 1045 | self |
| 1046 | } |
| 1047 | |
| 1048 | /// Attach an LSP manager so the `lsp` tool can query language intelligence |
| 1049 | /// and diagnostics. |
| 1050 | #[must_use] |
| 1051 | pub fn with_lsp_manager(mut self, manager: Arc<LspManager>) -> Self { |
| 1052 | self.lsp_manager = Some(manager); |
| 1053 | self |
| 1054 | } |
| 1055 | |
| 1056 | /// Remember that the caller has observed the current on-disk state of a |
| 1057 | /// file. This is intentionally best-effort so successful reads/writes do |
| 1058 | /// not fail after completing only because a post-operation metadata lookup |
| 1059 | /// raced with filesystem changes. |
| 1060 | pub fn note_file_read(&self, path: &Path) { |
| 1061 | let Ok(snapshot) = file_read_snapshot(path) else { |
| 1062 | return; |
| 1063 | }; |
| 1064 | let Ok(mut tracker) = self.file_read_tracker.lock() else { |
| 1065 | return; |
| 1066 | }; |
| 1067 | tracker.reads.insert(path.to_path_buf(), snapshot); |
| 1068 | } |
| 1069 | |
| 1070 | /// Require a successful, still-fresh `read_file` snapshot before a narrow |
| 1071 | /// in-place edit. This catches model edits made against guessed or stale |
| 1072 | /// content while leaving transactional patch preflight separate. |
| 1073 | pub fn require_fresh_file_read( |
| 1074 | &self, |
| 1075 | path: &Path, |
| 1076 | requested_path: &str, |
| 1077 | ) -> Result<(), ToolError> { |
| 1078 | self.require_fresh_read_for(path, requested_path, "edit", "read", "read") |
| 1079 | } |
| 1080 | |
| 1081 | pub fn require_fresh_read_before_write( |
| 1082 | &self, |
| 1083 | path: &Path, |
| 1084 | requested_path: &str, |
| 1085 | ) -> Result<(), ToolError> { |
| 1086 | self.require_fresh_read_for(path, requested_path, "write", "read", "read") |
| 1087 | } |
| 1088 | |
| 1089 | fn require_fresh_read_for( |
| 1090 | &self, |
| 1091 | path: &Path, |
| 1092 | requested_path: &str, |
| 1093 | mutation: &str, |
| 1094 | read_call: &str, |
| 1095 | read: &str, |
| 1096 | ) -> Result<(), ToolError> { |
| 1097 | let prior = { |
| 1098 | let tracker = self.file_read_tracker.lock().map_err(|_| { |
| 1099 | ToolError::execution_failed( |
| 1100 | "Failed to check read-before-edit state: tracker lock poisoned".to_string(), |
| 1101 | ) |
| 1102 | })?; |
| 1103 | tracker.reads.get(path).cloned() |
| 1104 | }; |
| 1105 | |
| 1106 | let Some(prior) = prior else { |
| 1107 | return Err(ToolError::execution_failed(format!( |
| 1108 | "Refusing {mutation} for {} because it has not been read in this session. \ |
| 1109 | Recovery: call {read_call} path=\"{requested_path}\" to inspect the current contents, \ |
| 1110 | then retry {mutation}.", |
| 1111 | path.display() |
| 1112 | ))); |
| 1113 | }; |
| 1114 | |
| 1115 | let current = file_read_snapshot(path).map_err(|e| { |
| 1116 | ToolError::execution_failed(format!( |
| 1117 | "Refusing {mutation} for {} because the file could not be checked for staleness ({e}). \ |
| 1118 | Recovery: call {read_call} path=\"{requested_path}\" again, then retry {mutation}.", |
| 1119 | path.display() |
| 1120 | )) |
| 1121 | })?; |
| 1122 | |
| 1123 | if current != prior { |
| 1124 | return Err(ToolError::execution_failed(format!( |
| 1125 | "Refusing {mutation} for {} because it changed since the last {read} call. \ |
| 1126 | Recovery: call {read_call} path=\"{requested_path}\" again and retry with the current contents.", |
| 1127 | path.display() |
| 1128 | ))); |
| 1129 | } |
| 1130 | |
| 1131 | Ok(()) |
| 1132 | } |
| 1133 | |
| 1134 | /// Cap the authority a tool call asks for on work it hands off (a durable |
| 1135 | /// task or a scheduled automation) at what this session holds. Requested |
| 1136 | /// `allow_shell`, `trust_mode` and `auto_approve` bits are declarations |
| 1137 | /// from the model; each survives only when this session already has that |
| 1138 | /// authority, so delegated work never runs with more than its creator. |
| 1139 | pub fn cap_delegated_authority( |
| 1140 | &self, |
| 1141 | allow_shell: Option<bool>, |
| 1142 | trust_mode: Option<bool>, |
| 1143 | auto_approve: Option<bool>, |
| 1144 | ) -> (Option<bool>, Option<bool>, Option<bool>) { |
| 1145 | let holds_shell = self.shell_policy == ShellPolicy::Full; |
| 1146 | ( |
| 1147 | // An omitted flag falls back to the host's configured default, so |
| 1148 | // a session without full shell must say "no" for it rather than |
| 1149 | // leave it unset. |
| 1150 | match allow_shell { |
| 1151 | Some(requested) => Some(requested && holds_shell), |
| 1152 | None if holds_shell => None, |
| 1153 | None => Some(false), |
| 1154 | }, |
| 1155 | trust_mode.map(|requested| requested && self.trust_mode), |
| 1156 | auto_approve.map(|requested| requested && self.approval_mode == ApprovalMode::Bypass), |
| 1157 | ) |
| 1158 | } |
| 1159 | |
| 1160 | /// Resolve a path relative to workspace, validating it doesn't escape. |
| 1161 | /// |
| 1162 | /// This handles both existing files (using canonicalize) and non-existent files |
| 1163 | /// (for write operations) by canonicalizing the parent directory and appending |
| 1164 | /// the filename. |
| 1165 | /// Resolve a path relative to workspace, validating it doesn't escape. |
| 1166 | /// |
| 1167 | /// # Examples |
| 1168 | /// |
| 1169 | /// ```ignore |
| 1170 | /// # use crate::tools::spec::ToolContext; |
| 1171 | /// let ctx = ToolContext::new("."); |
| 1172 | /// let path = ctx.resolve_path("README.md")?; |
| 1173 | /// # Ok::<(), crate::tools::spec::ToolError>(()) |
| 1174 | /// ``` |
| 1175 | pub fn resolve_path(&self, raw: &str) -> Result<PathBuf, ToolError> { |
| 1176 | let candidate = if let Some(home_path) = resolve_home_path(raw)? { |
| 1177 | home_path |
| 1178 | } else if std::path::Path::new(raw).is_absolute() { |
| 1179 | PathBuf::from(raw) |
| 1180 | } else { |
| 1181 | self.workspace.join(raw) |
| 1182 | }; |
| 1183 | |
| 1184 | // In trust mode, allow any path without validation |
| 1185 | if self.trust_mode { |
| 1186 | // Still try to canonicalize for consistency, but don't require it |
| 1187 | return Ok(candidate.canonicalize().unwrap_or(candidate)); |
| 1188 | } |
| 1189 | |
| 1190 | // Try to canonicalize the workspace |
| 1191 | let workspace_canonical = self |
| 1192 | .workspace |
| 1193 | .canonicalize() |
| 1194 | .unwrap_or_else(|_| self.workspace.clone()); |
| 1195 | |
| 1196 | // When follow_symlinks is enabled, check the non-canonical (symlink) |
| 1197 | // path against the workspace first. A symlink inside the workspace |
| 1198 | // that resolves outside is allowed — the symlink itself is the gate. |
| 1199 | if self.follow_symlinks { |
| 1200 | let candidate_normalized = normalize_path(&candidate); |
| 1201 | let workspace_normalized = normalize_path(&self.workspace); |
| 1202 | let workspace_canonical_normalized = normalize_path(&workspace_canonical); |
| 1203 | |
| 1204 | if candidate_normalized.starts_with(&workspace_normalized) |
| 1205 | || candidate_normalized.starts_with(&workspace_canonical_normalized) |
| 1206 | { |
| 1207 | // The symlink (or plain path) is inside the workspace. |
| 1208 | // Return the canonicalized target so file I/O works correctly. |
| 1209 | if candidate.exists() { |
| 1210 | return Ok(candidate.canonicalize().unwrap_or(candidate)); |
| 1211 | } |
| 1212 | // Non-existent path: canonicalize the deepest existing ancestor |
| 1213 | return self.resolve_nonexistent_path(candidate, &workspace_canonical); |
| 1214 | } |
| 1215 | |
| 1216 | // Path is outside workspace even before resolving symlinks. |
| 1217 | // Fall through to the standard escape check. |
| 1218 | } |
| 1219 | |
| 1220 | // For the initial check, also try to canonicalize the candidate if possible |
| 1221 | // This handles symlinks like /var -> /private/var on macOS |
| 1222 | let candidate_canonical = candidate |
| 1223 | .canonicalize() |
| 1224 | .unwrap_or_else(|_| normalize_path(&candidate)); |
| 1225 | let workspace_normalized = normalize_path(&workspace_canonical); |
| 1226 | |
| 1227 | // Check if the candidate is under the workspace (comparing canonical paths) |
| 1228 | if !candidate_canonical.starts_with(&workspace_normalized) { |
| 1229 | // Also try with non-canonical workspace for cases where workspace itself |
| 1230 | // hasn't been canonicalized yet |
| 1231 | let workspace_plain = normalize_path(&self.workspace); |
| 1232 | let candidate_normalized = normalize_path(&candidate); |
| 1233 | if !candidate_normalized.starts_with(&workspace_plain) |
| 1234 | && !self.is_trusted_external_path(&candidate_canonical) |
| 1235 | && !self.is_trusted_external_path(&candidate_normalized) |
| 1236 | { |
| 1237 | return Err(ToolError::PathEscape { |
| 1238 | path: candidate_canonical, |
| 1239 | }); |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | // For existing paths, use canonicalize directly |
| 1244 | if candidate.exists() { |
| 1245 | let canonical = candidate.canonicalize().map_err(|e| { |
| 1246 | ToolError::execution_failed(format!( |
| 1247 | "Failed to canonicalize {}: {}", |
| 1248 | candidate.display(), |
| 1249 | e |
| 1250 | )) |
| 1251 | })?; |
| 1252 | |
| 1253 | if !canonical.starts_with(&workspace_canonical) |
| 1254 | && !self.is_trusted_external_path(&canonical) |
| 1255 | { |
| 1256 | return Err(ToolError::PathEscape { path: canonical }); |
| 1257 | } |
| 1258 | |
| 1259 | return Ok(canonical); |
| 1260 | } |
| 1261 | |
| 1262 | self.resolve_nonexistent_path(candidate, &workspace_canonical) |
| 1263 | } |
| 1264 | |
| 1265 | /// Resolve `raw` against the workspace and require an existing directory. |
| 1266 | /// |
| 1267 | /// Tools that scope execution to a subdirectory (Run `cwd`) resolve |
| 1268 | /// through here so containment, existence, and the refusal wording have |
| 1269 | /// one owner. A workspace escape keeps the typed `PathEscape`; a missing |
| 1270 | /// or non-directory path names the fallback (drop the field to run in |
| 1271 | /// the workspace root). |
| 1272 | pub fn resolve_existing_dir(&self, raw: &str, field: &str) -> Result<PathBuf, ToolError> { |
| 1273 | let resolved = self.resolve_path(raw)?; |
| 1274 | if resolved.is_dir() { |
| 1275 | Ok(resolved) |
| 1276 | } else { |
| 1277 | Err(ToolError::invalid_input(format!( |
| 1278 | "{field} '{raw}' is not an existing directory inside the workspace; drop `{field}` to run in the workspace root" |
| 1279 | ))) |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | /// Resolve a non-existent path by canonicalizing its deepest existing |
| 1284 | /// ancestor and validating the result is under the workspace or a |
| 1285 | /// trusted external path. |
| 1286 | fn resolve_nonexistent_path( |
| 1287 | &self, |
| 1288 | candidate: PathBuf, |
| 1289 | workspace_canonical: &Path, |
| 1290 | ) -> Result<PathBuf, ToolError> { |
| 1291 | let workspace_normalized = normalize_path(workspace_canonical); |
| 1292 | let workspace_plain = normalize_path(&self.workspace); |
| 1293 | let mut existing_ancestor = candidate.clone(); |
| 1294 | let mut suffix_parts: Vec<std::ffi::OsString> = Vec::new(); |
| 1295 | |
| 1296 | while fs::symlink_metadata(&existing_ancestor).is_err() { |
| 1297 | if let Some(file_name) = existing_ancestor.file_name() { |
| 1298 | suffix_parts.push(file_name.to_owned()); |
| 1299 | } |
| 1300 | match existing_ancestor.parent() { |
| 1301 | Some(parent) if !parent.as_os_str().is_empty() => { |
| 1302 | existing_ancestor = parent.to_path_buf(); |
| 1303 | } |
| 1304 | _ => { |
| 1305 | // No existing parent found; fall back to simple check |
| 1306 | break; |
| 1307 | } |
| 1308 | } |
| 1309 | } |
| 1310 | let ancestor_normalized = normalize_path(&existing_ancestor); |
| 1311 | let follows_in_workspace = self.follow_symlinks |
| 1312 | && (ancestor_normalized.starts_with(&workspace_plain) |
| 1313 | || ancestor_normalized.starts_with(&workspace_normalized)); |
| 1314 | |
| 1315 | let canonical_ancestor = if fs::symlink_metadata(&existing_ancestor).is_ok() { |
| 1316 | match existing_ancestor.canonicalize() { |
| 1317 | Ok(canonical) => canonical, |
| 1318 | Err(_) if follows_in_workspace => existing_ancestor, |
| 1319 | Err(_) => { |
| 1320 | let mut landing = |
| 1321 | resolve_unresolvable_link(&existing_ancestor).map_err(|_| { |
| 1322 | ToolError::PathEscape { |
| 1323 | path: existing_ancestor.clone(), |
| 1324 | } |
| 1325 | })?; |
| 1326 | landing.extend(suffix_parts.iter().rev()); |
| 1327 | if !landing.starts_with(workspace_canonical) |
| 1328 | && !landing.starts_with(&workspace_normalized) |
| 1329 | && !self.is_trusted_external_path(&landing) |
| 1330 | { |
| 1331 | return Err(ToolError::PathEscape { path: landing }); |
| 1332 | } |
| 1333 | let spelled = match ( |
| 1334 | existing_ancestor.parent().map(Path::canonicalize), |
| 1335 | existing_ancestor.file_name(), |
| 1336 | ) { |
| 1337 | (Some(Ok(parent)), Some(name)) => Some(parent.join(name)), |
| 1338 | _ => None, |
| 1339 | }; |
| 1340 | spelled.unwrap_or(existing_ancestor) |
| 1341 | } |
| 1342 | } |
| 1343 | } else { |
| 1344 | existing_ancestor |
| 1345 | }; |
| 1346 | |
| 1347 | // Rebuild the full path from canonicalized ancestor |
| 1348 | let mut canonical = canonical_ancestor; |
| 1349 | for part in suffix_parts.into_iter().rev() { |
| 1350 | canonical.push(part); |
| 1351 | } |
| 1352 | let canonical = normalize_path(&canonical); |
| 1353 | |
| 1354 | if follows_in_workspace { |
| 1355 | return Ok(canonical); |
| 1356 | } |
| 1357 | |
| 1358 | // Validate it's under workspace, OR is under a user-trusted external |
| 1359 | // path (`/trust add <path>` from the slash command, persisted in |
| 1360 | // `~/.deepseek/workspace-trust.json`). |
| 1361 | if !canonical.starts_with(workspace_canonical) |
| 1362 | && !canonical.starts_with(&workspace_normalized) |
| 1363 | && !self.is_trusted_external_path(&canonical) |
| 1364 | { |
| 1365 | return Err(ToolError::PathEscape { path: canonical }); |
| 1366 | } |
| 1367 | |
| 1368 | Ok(canonical) |
| 1369 | } |
| 1370 | |
| 1371 | /// Whether `path` is under any of the user-trusted external roots. The |
| 1372 | /// caller should pass an already-canonicalized (or normalized) path. |
| 1373 | fn is_trusted_external_path(&self, path: &Path) -> bool { |
| 1374 | self.trusted_external_paths |
| 1375 | .iter() |
| 1376 | .any(|trusted| path.starts_with(trusted)) |
| 1377 | } |
| 1378 | |
| 1379 | /// Set the trust mode. |
| 1380 | #[cfg(any(test, feature = "test-support"))] |
| 1381 | pub fn with_trust_mode(mut self, trust: bool) -> Self { |
| 1382 | self.trust_mode = trust; |
| 1383 | self |
| 1384 | } |
| 1385 | |
| 1386 | /// Set feature flags for tool execution. |
| 1387 | pub fn with_features(mut self, features: Features) -> Self { |
| 1388 | self.features = features; |
| 1389 | self |
| 1390 | } |
| 1391 | |
| 1392 | /// Override the shared shell manager. |
| 1393 | pub fn with_shell_manager(mut self, shell_manager: SharedShellManager) -> Self { |
| 1394 | self.shell_manager = shell_manager; |
| 1395 | self |
| 1396 | } |
| 1397 | |
| 1398 | /// Reuse the engine's session-scoped read snapshots across tool-context |
| 1399 | /// rebuilds. A fresh context is assembled for each turn, but successful |
| 1400 | /// reads must remain authoritative until the observed file changes. |
| 1401 | pub fn with_file_read_tracker(mut self, tracker: SharedFileReadTracker) -> Self { |
| 1402 | self.file_read_tracker = tracker; |
| 1403 | self |
| 1404 | } |
| 1405 | |
| 1406 | /// Set the elevated sandbox policy override. |
| 1407 | /// |
| 1408 | /// This is used when retrying a tool after a sandbox denial, to run |
| 1409 | /// with elevated permissions. |
| 1410 | pub fn with_elevated_sandbox_policy( |
| 1411 | mut self, |
| 1412 | policy: codewhale_sandbox::SandboxPolicy, |
| 1413 | ) -> Self { |
| 1414 | self.elevated_sandbox_policy = Some(policy); |
| 1415 | self |
| 1416 | } |
| 1417 | |
| 1418 | /// Carry a person's card decision to the one call it approved. |
| 1419 | #[must_use] |
| 1420 | pub fn with_human_decision(mut self, decision: crate::core::engine::HumanDecision) -> Self { |
| 1421 | self.human_decision = Some(decision); |
| 1422 | self |
| 1423 | } |
| 1424 | |
| 1425 | /// Carry the turn loop's `plugin_manager` admission decision onto the tool context. |
| 1426 | #[must_use] |
| 1427 | pub fn with_creator_decision( |
| 1428 | mut self, |
| 1429 | decision: crate::extension_host::creator_policy::CreatorDecisionCarrier, |
| 1430 | ) -> Self { |
| 1431 | self.creator_decision = Some(decision); |
| 1432 | self |
| 1433 | } |
| 1434 | |
| 1435 | /// Set the shell network-denial hint used by network-restricted modes. |
| 1436 | pub fn with_shell_network_denied_hint(mut self, hint: impl Into<String>) -> Self { |
| 1437 | self.shell_network_denied_hint = Some(hint.into()); |
| 1438 | self |
| 1439 | } |
| 1440 | |
| 1441 | /// Set the namespace used for session-scoped tool state. |
| 1442 | pub fn with_state_namespace(mut self, namespace: impl Into<String>) -> Self { |
| 1443 | self.state_namespace = namespace.into(); |
| 1444 | self |
| 1445 | } |
| 1446 | |
| 1447 | /// Attach the active route's effective context window. |
| 1448 | #[must_use] |
| 1449 | pub fn with_route_context_window(mut self, context_window: u32) -> Self { |
| 1450 | self.route_context_window = (context_window > 0).then_some(context_window); |
| 1451 | self |
| 1452 | } |
| 1453 | |
| 1454 | /// Attach the adaptive evidence router (#4619). Consulted only under the |
| 1455 | /// `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` opt-in. |
| 1456 | #[must_use] |
| 1457 | pub fn with_large_output_router( |
| 1458 | mut self, |
| 1459 | router: crate::tools::large_output_router::LargeOutputRouter, |
| 1460 | ) -> Self { |
| 1461 | self.large_output_router = Some(router); |
| 1462 | self |
| 1463 | } |
| 1464 | } |
| 1465 | |
| 1466 | const MAX_LINK_HOPS: usize = 40; |
| 1467 | |
| 1468 | fn resolve_unresolvable_link(link: &Path) -> std::io::Result<PathBuf> { |
| 1469 | let mut link = link.to_path_buf(); |
| 1470 | let mut tail: Vec<std::ffi::OsString> = Vec::new(); |
| 1471 | for _ in 0..MAX_LINK_HOPS { |
| 1472 | let target = fs::read_link(&link)?; |
| 1473 | let parent = link |
| 1474 | .parent() |
| 1475 | .filter(|parent| !parent.as_os_str().is_empty()) |
| 1476 | .unwrap_or_else(|| Path::new(".")) |
| 1477 | .canonicalize()?; |
| 1478 | let joined = parent.join(&target); |
| 1479 | let mut ancestor = PathBuf::new(); |
| 1480 | let mut suffix: Vec<std::ffi::OsString> = Vec::new(); |
| 1481 | let mut missing = false; |
| 1482 | for component in joined.components() { |
| 1483 | match component { |
| 1484 | Component::Prefix(prefix) => { |
| 1485 | if missing { |
| 1486 | return Err(std::io::Error::new( |
| 1487 | std::io::ErrorKind::InvalidInput, |
| 1488 | "parent traversal in unresolved link target", |
| 1489 | )); |
| 1490 | } |
| 1491 | ancestor.push(prefix.as_os_str()); |
| 1492 | } |
| 1493 | Component::RootDir => { |
| 1494 | if missing { |
| 1495 | return Err(std::io::Error::new( |
| 1496 | std::io::ErrorKind::InvalidInput, |
| 1497 | "parent traversal in unresolved link target", |
| 1498 | )); |
| 1499 | } |
| 1500 | ancestor.push(component.as_os_str()); |
| 1501 | } |
| 1502 | Component::CurDir => {} |
| 1503 | Component::ParentDir => { |
| 1504 | if missing { |
| 1505 | return Err(std::io::Error::new( |
| 1506 | std::io::ErrorKind::InvalidInput, |
| 1507 | "parent traversal in unresolved link target", |
| 1508 | )); |
| 1509 | } |
| 1510 | let next_candidate = ancestor.join(component.as_os_str()); |
| 1511 | if fs::symlink_metadata(&next_candidate).is_err() { |
| 1512 | return Err(std::io::Error::new( |
| 1513 | std::io::ErrorKind::InvalidInput, |
| 1514 | "parent traversal in unresolved link target", |
| 1515 | )); |
| 1516 | } |
| 1517 | ancestor = next_candidate; |
| 1518 | } |
| 1519 | Component::Normal(name) => { |
| 1520 | if missing { |
| 1521 | suffix.push(name.to_owned()); |
| 1522 | } else { |
| 1523 | let next_candidate = ancestor.join(name); |
| 1524 | if fs::symlink_metadata(&next_candidate).is_ok() { |
| 1525 | ancestor = next_candidate; |
| 1526 | } else { |
| 1527 | missing = true; |
| 1528 | suffix.push(name.to_owned()); |
| 1529 | } |
| 1530 | } |
| 1531 | } |
| 1532 | } |
| 1533 | } |
| 1534 | if fs::symlink_metadata(&ancestor).is_err() { |
| 1535 | let mut landing = normalize_path(&joined); |
| 1536 | landing.extend(tail.iter()); |
| 1537 | return Ok(landing); |
| 1538 | } |
| 1539 | match ancestor.canonicalize() { |
| 1540 | Ok(mut landing) => { |
| 1541 | landing.extend(suffix); |
| 1542 | landing.extend(tail); |
| 1543 | return Ok(landing); |
| 1544 | } |
| 1545 | Err(_) => { |
| 1546 | let mut rest = suffix; |
| 1547 | rest.extend(tail); |
| 1548 | tail = rest; |
| 1549 | link = ancestor; |
| 1550 | } |
| 1551 | } |
| 1552 | } |
| 1553 | Err(std::io::Error::other("too many levels of symbolic links")) |
| 1554 | } |
| 1555 | |
| 1556 | pub fn normalize_path(path: &Path) -> PathBuf { |
| 1557 | let mut prefix: Option<std::ffi::OsString> = None; |
| 1558 | let mut is_root = false; |
| 1559 | let mut stack: Vec<std::ffi::OsString> = Vec::new(); |
| 1560 | |
| 1561 | for component in path.components() { |
| 1562 | match component { |
| 1563 | Component::Prefix(prefix_component) => { |
| 1564 | prefix = Some(prefix_component.as_os_str().to_owned()); |
| 1565 | } |
| 1566 | Component::RootDir => { |
| 1567 | is_root = true; |
| 1568 | } |
| 1569 | Component::CurDir => {} |
| 1570 | Component::ParentDir => { |
| 1571 | let parent = Component::ParentDir.as_os_str(); |
| 1572 | if let Some(last) = stack.pop() { |
| 1573 | if last == parent { |
| 1574 | stack.push(last); |
| 1575 | stack.push(parent.to_owned()); |
| 1576 | } |
| 1577 | } else if !is_root { |
| 1578 | stack.push(parent.to_owned()); |
| 1579 | } |
| 1580 | } |
| 1581 | Component::Normal(part) => { |
| 1582 | stack.push(part.to_owned()); |
| 1583 | } |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | let mut normalized = PathBuf::new(); |
| 1588 | if let Some(prefix) = prefix { |
| 1589 | normalized.push(prefix); |
| 1590 | } |
| 1591 | if is_root { |
| 1592 | normalized.push(Path::new(std::path::MAIN_SEPARATOR_STR)); |
| 1593 | } |
| 1594 | for part in stack { |
| 1595 | normalized.push(part); |
| 1596 | } |
| 1597 | normalized |
| 1598 | } |
| 1599 | |
| 1600 | pub(crate) fn has_forbidden_windows_colon(raw: &str, windows: bool) -> bool { |
| 1601 | if !windows { |
| 1602 | return false; |
| 1603 | } |
| 1604 | let bytes = raw.as_bytes(); |
| 1605 | let rest = if raw.starts_with(r"\\?\") |
| 1606 | || raw.starts_with("//?/") |
| 1607 | || raw.starts_with(r"\\.\") |
| 1608 | || raw.starts_with("//./") |
| 1609 | { |
| 1610 | if bytes.get(4).is_some_and(u8::is_ascii_alphabetic) |
| 1611 | && bytes.get(5) == Some(&b':') |
| 1612 | && matches!(bytes.get(6), Some(b'\\') | Some(b'/')) |
| 1613 | { |
| 1614 | &raw[6..] |
| 1615 | } else { |
| 1616 | raw |
| 1617 | } |
| 1618 | } else if bytes.first().is_some_and(u8::is_ascii_alphabetic) |
| 1619 | && bytes.get(1) == Some(&b':') |
| 1620 | && matches!(bytes.get(2), Some(b'\\') | Some(b'/')) |
| 1621 | { |
| 1622 | &raw[2..] |
| 1623 | } else { |
| 1624 | raw |
| 1625 | }; |
| 1626 | rest.contains(':') |
| 1627 | } |
| 1628 | |
| 1629 | pub(crate) fn is_windows_short_name_segment(segment: &str) -> bool { |
| 1630 | for (idx, _) in segment.match_indices('~') { |
| 1631 | let after = &segment[idx + 1..]; |
| 1632 | let digits = after.split('.').next().unwrap_or(after); |
| 1633 | if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) { |
| 1634 | return true; |
| 1635 | } |
| 1636 | } |
| 1637 | false |
| 1638 | } |
| 1639 | |
| 1640 | pub(crate) fn has_windows_trailing_dot_or_space(segment: &str, windows: bool) -> bool { |
| 1641 | windows && segment != "." && segment != ".." && segment.ends_with(['.', ' ']) |
| 1642 | } |
| 1643 | |
| 1644 | pub(crate) fn is_protected_workspace_metadata_segment(segment: &str, windows: bool) -> bool { |
| 1645 | if codewhale_util::git_metadata::git_metadata_name(segment, windows) { |
| 1646 | return true; |
| 1647 | } |
| 1648 | let trimmed = if windows { |
| 1649 | segment |
| 1650 | .split(':') |
| 1651 | .next() |
| 1652 | .unwrap_or_default() |
| 1653 | .trim_end_matches(['.', ' ']) |
| 1654 | } else { |
| 1655 | segment |
| 1656 | }; |
| 1657 | if trimmed.eq_ignore_ascii_case(".codewhale") { |
| 1658 | return true; |
| 1659 | } |
| 1660 | if windows { |
| 1661 | let stem = trimmed.split('.').next().unwrap_or(trimmed); |
| 1662 | if let Some((prefix, digits)) = stem.rsplit_once('~') |
| 1663 | && !digits.is_empty() |
| 1664 | && digits.bytes().all(|byte| byte.is_ascii_digit()) |
| 1665 | { |
| 1666 | let prefix = prefix.strip_prefix('.').unwrap_or(prefix); |
| 1667 | let upper = prefix.to_ascii_uppercase(); |
| 1668 | if !upper.is_empty() && "CODEWHALE".starts_with(&upper) { |
| 1669 | return true; |
| 1670 | } |
| 1671 | } |
| 1672 | } |
| 1673 | false |
| 1674 | } |
| 1675 | |
| 1676 | pub(crate) fn validate_windows_relative_segments( |
| 1677 | relative: &str, |
| 1678 | windows: bool, |
| 1679 | ) -> Result<(), String> { |
| 1680 | if !windows { |
| 1681 | return Ok(()); |
| 1682 | } |
| 1683 | if has_forbidden_windows_colon(relative, true) { |
| 1684 | return Err("windows colons and alternate data streams are not allowed".to_string()); |
| 1685 | } |
| 1686 | for segment in relative.replace('\\', "/").split('/') { |
| 1687 | if segment.is_empty() || segment == "." { |
| 1688 | continue; |
| 1689 | } |
| 1690 | if has_windows_trailing_dot_or_space(segment, true) { |
| 1691 | return Err(format!( |
| 1692 | "trailing dots or spaces are not allowed: {segment}" |
| 1693 | )); |
| 1694 | } |
| 1695 | if is_windows_short_name_segment(segment) { |
| 1696 | return Err(format!( |
| 1697 | "windows short-name aliases are not allowed: {segment}" |
| 1698 | )); |
| 1699 | } |
| 1700 | } |
| 1701 | Ok(()) |
| 1702 | } |
| 1703 | |
| 1704 | fn strip_windows_verbatim_slashes(raw: &str) -> String { |
| 1705 | let mut normalized = raw.replace('\\', "/"); |
| 1706 | if let Some(rest) = normalized |
| 1707 | .strip_prefix("//?/UNC/") |
| 1708 | .or_else(|| normalized.strip_prefix("//?/unc/")) |
| 1709 | { |
| 1710 | normalized = format!("//{rest}"); |
| 1711 | } else if let Some(rest) = normalized |
| 1712 | .strip_prefix("//?/") |
| 1713 | .or_else(|| normalized.strip_prefix("//./")) |
| 1714 | { |
| 1715 | normalized = rest.to_string(); |
| 1716 | } |
| 1717 | while normalized.len() > 1 && normalized.ends_with('/') { |
| 1718 | if normalized.len() == 3 && normalized.as_bytes().get(1) == Some(&b':') { |
| 1719 | break; |
| 1720 | } |
| 1721 | normalized.pop(); |
| 1722 | } |
| 1723 | normalized |
| 1724 | } |
| 1725 | |
| 1726 | pub(crate) fn has_windows_drive_or_unc_prefix(raw: &str) -> bool { |
| 1727 | raw.starts_with(r"\\") |
| 1728 | || raw.starts_with("//") |
| 1729 | || (raw.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) |
| 1730 | && raw.as_bytes().get(1) == Some(&b':')) |
| 1731 | } |
| 1732 | |
| 1733 | pub(crate) fn strip_workspace_root_str( |
| 1734 | workspace_raw: &str, |
| 1735 | workspace_canonical: Option<&str>, |
| 1736 | raw: &str, |
| 1737 | windows: bool, |
| 1738 | ) -> Option<String> { |
| 1739 | if !windows { |
| 1740 | let candidate = Path::new(raw); |
| 1741 | let rest = candidate |
| 1742 | .strip_prefix(Path::new(workspace_raw)) |
| 1743 | .ok() |
| 1744 | .or_else(|| { |
| 1745 | workspace_canonical.and_then(|root| candidate.strip_prefix(Path::new(root)).ok()) |
| 1746 | })?; |
| 1747 | let mut clean = PathBuf::new(); |
| 1748 | for component in rest.components() { |
| 1749 | match component { |
| 1750 | Component::Normal(part) => clean.push(part), |
| 1751 | Component::CurDir => {} |
| 1752 | _ => return None, |
| 1753 | } |
| 1754 | } |
| 1755 | let shown = clean.to_str()?; |
| 1756 | return Some(if shown.is_empty() { |
| 1757 | ".".to_string() |
| 1758 | } else { |
| 1759 | shown.to_string() |
| 1760 | }); |
| 1761 | } |
| 1762 | |
| 1763 | let cand = strip_windows_verbatim_slashes(raw); |
| 1764 | for root in std::iter::once(workspace_raw).chain(workspace_canonical) { |
| 1765 | let root_norm = strip_windows_verbatim_slashes(root); |
| 1766 | if cand.eq_ignore_ascii_case(&root_norm) { |
| 1767 | return Some(".".to_string()); |
| 1768 | } |
| 1769 | let cand_bytes = cand.as_bytes(); |
| 1770 | let root_len = root_norm.len(); |
| 1771 | if cand_bytes.len() > root_len |
| 1772 | && cand[..root_len].eq_ignore_ascii_case(&root_norm) |
| 1773 | && (root_norm.ends_with('/') || cand_bytes[root_len] == b'/') |
| 1774 | { |
| 1775 | let tail = &cand[if root_norm.ends_with('/') { |
| 1776 | root_len |
| 1777 | } else { |
| 1778 | root_len + 1 |
| 1779 | }..]; |
| 1780 | let mut segments = Vec::new(); |
| 1781 | for segment in tail.split('/') { |
| 1782 | match segment { |
| 1783 | "" | "." => {} |
| 1784 | ".." => return None, |
| 1785 | part => segments.push(part), |
| 1786 | } |
| 1787 | } |
| 1788 | return Some(if segments.is_empty() { |
| 1789 | ".".to_string() |
| 1790 | } else { |
| 1791 | segments.join("/") |
| 1792 | }); |
| 1793 | } |
| 1794 | } |
| 1795 | None |
| 1796 | } |
| 1797 | |
| 1798 | pub(crate) fn resolve_confined_target( |
| 1799 | context: &ToolContext, |
| 1800 | workspace_canonical: &Path, |
| 1801 | raw: &str, |
| 1802 | allow_root_dot: bool, |
| 1803 | ) -> Result<PathBuf, ToolError> { |
| 1804 | if context.workspace.as_os_str().is_empty() || raw.is_empty() { |
| 1805 | return Err(ToolError::permission_denied( |
| 1806 | "workspace path cannot be empty".to_string(), |
| 1807 | )); |
| 1808 | } |
| 1809 | if has_forbidden_windows_colon(raw, cfg!(windows)) { |
| 1810 | return Err(ToolError::permission_denied( |
| 1811 | "workspace path cannot contain a colon outside a Windows drive prefix".to_string(), |
| 1812 | )); |
| 1813 | } |
| 1814 | if context.strict_workspace_confinement |
| 1815 | && (raw == "~" || raw.starts_with("~/") || (cfg!(windows) && raw.starts_with("~\\"))) |
| 1816 | { |
| 1817 | return Err(ToolError::permission_denied( |
| 1818 | "workspace path cannot use home shorthand".to_string(), |
| 1819 | )); |
| 1820 | } |
| 1821 | let home_resolved = if !context.strict_workspace_confinement { |
| 1822 | resolve_home_path(raw)? |
| 1823 | } else { |
| 1824 | None |
| 1825 | }; |
| 1826 | let check_path = home_resolved.as_deref().unwrap_or_else(|| Path::new(raw)); |
| 1827 | if check_path |
| 1828 | .components() |
| 1829 | .any(|component| matches!(component, Component::ParentDir)) |
| 1830 | { |
| 1831 | return Err(ToolError::PathEscape { |
| 1832 | path: normalize_path(&context.workspace.join(check_path)), |
| 1833 | }); |
| 1834 | } |
| 1835 | let relative = if let Some(home_path) = home_resolved.as_deref() { |
| 1836 | let home_str = home_path.to_str().ok_or_else(|| { |
| 1837 | ToolError::permission_denied("workspace path must be valid UTF-8".to_string()) |
| 1838 | })?; |
| 1839 | let ws_plain = normalize_path(&context.workspace); |
| 1840 | let ws_str = ws_plain.to_string_lossy(); |
| 1841 | let can_str = workspace_canonical.to_string_lossy(); |
| 1842 | let rel = strip_workspace_root_str(&ws_str, Some(&can_str), home_str, cfg!(windows)) |
| 1843 | .ok_or_else(|| ToolError::PathEscape { |
| 1844 | path: normalize_path(home_path), |
| 1845 | })?; |
| 1846 | if rel == "." { |
| 1847 | PathBuf::new() |
| 1848 | } else { |
| 1849 | PathBuf::from(rel) |
| 1850 | } |
| 1851 | } else if check_path.is_absolute() |
| 1852 | || check_path.has_root() |
| 1853 | || (cfg!(windows) && has_windows_drive_or_unc_prefix(raw)) |
| 1854 | { |
| 1855 | let ws_str = context.workspace.to_string_lossy(); |
| 1856 | let can_str = workspace_canonical.to_string_lossy(); |
| 1857 | let rel = strip_workspace_root_str(&ws_str, Some(&can_str), raw, cfg!(windows)) |
| 1858 | .ok_or_else(|| ToolError::PathEscape { |
| 1859 | path: PathBuf::from(raw), |
| 1860 | })?; |
| 1861 | if rel == "." { |
| 1862 | PathBuf::new() |
| 1863 | } else { |
| 1864 | PathBuf::from(rel) |
| 1865 | } |
| 1866 | } else { |
| 1867 | let mut rel = PathBuf::new(); |
| 1868 | for component in check_path.components() { |
| 1869 | match component { |
| 1870 | Component::Normal(part) => rel.push(part), |
| 1871 | Component::CurDir => {} |
| 1872 | _ => { |
| 1873 | return Err(ToolError::PathEscape { |
| 1874 | path: PathBuf::from(raw), |
| 1875 | }); |
| 1876 | } |
| 1877 | } |
| 1878 | } |
| 1879 | rel |
| 1880 | }; |
| 1881 | |
| 1882 | if relative.as_os_str().is_empty() { |
| 1883 | if !allow_root_dot { |
| 1884 | return Err(ToolError::permission_denied( |
| 1885 | "workspace path must name an entry inside the workspace".to_string(), |
| 1886 | )); |
| 1887 | } |
| 1888 | } else { |
| 1889 | validate_windows_relative_segments(&relative.to_string_lossy(), cfg!(windows)) |
| 1890 | .map_err(ToolError::permission_denied)?; |
| 1891 | } |
| 1892 | |
| 1893 | Ok(relative) |
| 1894 | } |
| 1895 | |
| 1896 | /// Resolve an exact `~` or `~/` path prefix to the current user's home directory. |
| 1897 | /// |
| 1898 | /// Only exact `~` and `~/` (or `~\` on Windows) prefixes are resolved. Prefixes like |
| 1899 | /// `~otheruser`, shell variables (`$VAR`), command substitution, and globs are not |
| 1900 | /// expanded. Literal paths like `./~/file` stay literal. |
| 1901 | /// |
| 1902 | /// Returns: |
| 1903 | /// - `Ok(Some(path))` if `raw` has an exact home prefix and home was determined. |
| 1904 | /// - `Ok(None)` if `raw` does not have an exact home prefix. |
| 1905 | /// - `Err(ToolError)` if `raw` has an exact home prefix but user home could not be determined. |
| 1906 | pub fn resolve_home_path(raw: &str) -> Result<Option<PathBuf>, ToolError> { |
| 1907 | resolve_home_path_with(raw, codewhale_paths::user_home) |
| 1908 | } |
| 1909 | |
| 1910 | pub fn resolve_home_path_with( |
| 1911 | raw: &str, |
| 1912 | home_lookup: impl FnOnce() -> Option<PathBuf>, |
| 1913 | ) -> Result<Option<PathBuf>, ToolError> { |
| 1914 | let suffix = if raw == "~" { |
| 1915 | "" |
| 1916 | } else if let Some(rest) = raw.strip_prefix("~/") { |
| 1917 | rest.trim_start_matches(|c| c == '/' || (cfg!(windows) && c == '\\')) |
| 1918 | } else { |
| 1919 | #[cfg(windows)] |
| 1920 | if let Some(rest) = raw.strip_prefix(r"~\") { |
| 1921 | rest.trim_start_matches(['/', '\\']) |
| 1922 | } else { |
| 1923 | return Ok(None); |
| 1924 | } |
| 1925 | #[cfg(not(windows))] |
| 1926 | return Ok(None); |
| 1927 | }; |
| 1928 | |
| 1929 | // A drive prefix is not a home-relative suffix. `PathBuf::join` would |
| 1930 | // otherwise replace the home on Windows (for example `~/C:\file`). |
| 1931 | #[cfg(windows)] |
| 1932 | if Path::new(suffix) |
| 1933 | .components() |
| 1934 | .any(|part| matches!(part, std::path::Component::Prefix(_))) |
| 1935 | { |
| 1936 | return Err(ToolError::invalid_input( |
| 1937 | "a home-relative path cannot contain a drive prefix", |
| 1938 | )); |
| 1939 | } |
| 1940 | let home = home_lookup().ok_or_else(|| { |
| 1941 | ToolError::execution_failed(format!( |
| 1942 | "Failed to resolve path '{raw}': user home directory could not be determined" |
| 1943 | )) |
| 1944 | })?; |
| 1945 | |
| 1946 | if suffix.is_empty() { |
| 1947 | Ok(Some(home)) |
| 1948 | } else { |
| 1949 | Ok(Some(home.join(suffix))) |
| 1950 | } |
| 1951 | } |
| 1952 | |
| 1953 | /// The core trait that all tools must implement. |
| 1954 | #[async_trait] |
| 1955 | pub trait ToolSpec: Send + Sync { |
| 1956 | fn delegated_mcp_read(&self) -> Option<Arc<crate::mcp::DelegatedMcpRead>> { |
| 1957 | None |
| 1958 | } |
| 1959 | |
| 1960 | /// Returns the unique name of this tool (used in API calls). |
| 1961 | fn name(&self) -> &str; |
| 1962 | |
| 1963 | /// Identifies the implementation in local registration diagnostics only. |
| 1964 | /// Adapters should use their existing source identity, never credentials, |
| 1965 | /// command arguments, descriptions, or other execution payloads. |
| 1966 | fn registration_origin(&self) -> std::borrow::Cow<'_, str> { |
| 1967 | std::any::type_name::<Self>().into() |
| 1968 | } |
| 1969 | |
| 1970 | /// Returns a human-readable description of what this tool does. |
| 1971 | fn description(&self) -> &str; |
| 1972 | |
| 1973 | /// Returns the JSON Schema for the tool's input parameters. |
| 1974 | fn input_schema(&self) -> Value; |
| 1975 | |
| 1976 | /// Returns the capabilities this tool has. |
| 1977 | fn capabilities(&self) -> Vec<ToolCapability>; |
| 1978 | |
| 1979 | /// Returns the approval requirement for this tool. |
| 1980 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 1981 | let caps = self.capabilities(); |
| 1982 | if caps.contains(&ToolCapability::ExecutesCode) { |
| 1983 | ApprovalRequirement::Required |
| 1984 | } else if caps.contains(&ToolCapability::WritesFiles) { |
| 1985 | ApprovalRequirement::Suggest |
| 1986 | } else { |
| 1987 | ApprovalRequirement::Auto |
| 1988 | } |
| 1989 | } |
| 1990 | |
| 1991 | /// Returns the approval requirement for this concrete tool input. |
| 1992 | fn approval_requirement_for(&self, _input: &Value) -> ApprovalRequirement { |
| 1993 | self.approval_requirement() |
| 1994 | } |
| 1995 | |
| 1996 | /// Returns whether this tool is sandboxable. |
| 1997 | #[cfg(any(test, feature = "test-support"))] |
| 1998 | fn is_sandboxable(&self) -> bool { |
| 1999 | self.capabilities().contains(&ToolCapability::Sandboxable) |
| 2000 | } |
| 2001 | |
| 2002 | /// Returns whether this tool is read-only. |
| 2003 | fn is_read_only(&self) -> bool { |
| 2004 | let caps = self.capabilities(); |
| 2005 | caps.contains(&ToolCapability::ReadOnly) |
| 2006 | && !caps.contains(&ToolCapability::WritesFiles) |
| 2007 | && !caps.contains(&ToolCapability::ExecutesCode) |
| 2008 | } |
| 2009 | |
| 2010 | /// Returns whether this concrete tool input is read-only. |
| 2011 | fn is_read_only_for(&self, _input: &Value) -> bool { |
| 2012 | self.is_read_only() |
| 2013 | } |
| 2014 | |
| 2015 | /// Returns whether this tool can be executed in parallel with others. |
| 2016 | fn supports_parallel(&self) -> bool { |
| 2017 | false |
| 2018 | } |
| 2019 | |
| 2020 | /// Returns whether this concrete tool input can run in parallel. |
| 2021 | fn supports_parallel_for(&self, _input: &Value) -> bool { |
| 2022 | self.supports_parallel() |
| 2023 | } |
| 2024 | |
| 2025 | /// Returns whether this input starts durable/detached work and returns |
| 2026 | /// immediately. Detached starts are not read-only, but in auto-approved |
| 2027 | /// turns they do not need to block neighboring read-only inspections. |
| 2028 | fn starts_detached_for(&self, _input: &Value) -> bool { |
| 2029 | false |
| 2030 | } |
| 2031 | |
| 2032 | fn refusal_before_approval( |
| 2033 | &self, |
| 2034 | _input: &Value, |
| 2035 | _context: &ToolContext, |
| 2036 | ) -> Option<ToolResult> { |
| 2037 | None |
| 2038 | } |
| 2039 | |
| 2040 | /// Resolve input-specific policy without performing external side effects. |
| 2041 | /// |
| 2042 | /// Resource claims deliberately default to global exclusivity until a |
| 2043 | /// first-party tool opts into narrower, canonicalized claims. The initial |
| 2044 | /// seam records this decision but leaves the existing scheduler unchanged. |
| 2045 | fn prepare(&self, input: Value, _context: &ToolContext) -> Result<PreparedToolCall, ToolError> { |
| 2046 | Ok(PreparedToolCall { |
| 2047 | name: self.name().to_string(), |
| 2048 | description: self.description().to_string(), |
| 2049 | read_only: self.is_read_only_for(&input), |
| 2050 | supports_parallel: self.supports_parallel_for(&input), |
| 2051 | starts_detached: self.starts_detached_for(&input), |
| 2052 | approval: self.approval_requirement_for(&input), |
| 2053 | resources: vec![ResourceClaim::GlobalExclusive], |
| 2054 | input, |
| 2055 | }) |
| 2056 | } |
| 2057 | |
| 2058 | /// The approval-grant scope this tool's calls are keyed under instead of |
| 2059 | /// the name-derived key families, if it has one. `None` (every built-in, |
| 2060 | /// script and MCP tool) keeps [`crate::tools::approval_cache`]'s keys. |
| 2061 | /// |
| 2062 | /// Extension tools return `ext:<plugin_id>@<content_hash>`, so a session |
| 2063 | /// grant covers one reviewed plugin build: an updated plugin, or another |
| 2064 | /// plugin that later registers the same name, is asked again. |
| 2065 | fn approval_scope(&self) -> Option<String> { |
| 2066 | None |
| 2067 | } |
| 2068 | |
| 2069 | /// Who this tool is, if it is an extension tool: composed by Rust from its |
| 2070 | /// registration. `Some` makes the turn loop serve a permission gate for |
| 2071 | /// the tool's call, through which its `core/call`s are planned and |
| 2072 | /// approved like a model's, and makes the tool unreachable from any other |
| 2073 | /// extension's `core/call` (no recursion). `None` (every built-in, script |
| 2074 | /// and MCP tool) changes nothing. |
| 2075 | fn extension_caller(&self) -> Option<crate::tools::codemode::ExtensionCaller> { |
| 2076 | None |
| 2077 | } |
| 2078 | |
| 2079 | /// Returns whether this tool should be excluded from the model-visible |
| 2080 | /// tool catalog (deferred loading). Tools marked `true` are registered |
| 2081 | /// but not sent to the model until explicitly activated via tool search. |
| 2082 | fn defer_loading(&self) -> bool { |
| 2083 | false |
| 2084 | } |
| 2085 | |
| 2086 | /// Returns whether this tool should be advertised in the model-facing |
| 2087 | /// catalog. Hidden compatibility tools remain registered and executable |
| 2088 | /// by name so saved transcripts can replay without teaching new sessions |
| 2089 | /// the deprecated spelling. |
| 2090 | fn model_visible(&self) -> bool { |
| 2091 | true |
| 2092 | } |
| 2093 | |
| 2094 | /// Execute the tool with the given input and context. |
| 2095 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError>; |
| 2096 | |
| 2097 | /// Execute with rich result blocks. Existing tools inherit text-only |
| 2098 | /// behavior; tools such as lowercase `read` can opt in without changing |
| 2099 | /// the published `ToolResult` struct. |
| 2100 | async fn execute_rich( |
| 2101 | &self, |
| 2102 | input: Value, |
| 2103 | context: &ToolContext, |
| 2104 | ) -> Result<RichToolResult, ToolError> { |
| 2105 | self.execute(input, context) |
| 2106 | .await |
| 2107 | .map(RichToolResult::plain) |
| 2108 | } |
| 2109 | } |
| 2110 | |
| 2111 | #[cfg(test)] |
| 2112 | mod tests; |
| 2113 |