| 1 | //! Tool registry for managing and executing tools. |
| 2 | //! |
| 3 | //! The registry provides: |
| 4 | //! - Dynamic tool registration |
| 5 | //! - Tool lookup by name |
| 6 | //! - Conversion to API Tool format |
| 7 | //! - Filtering by capability |
| 8 | |
| 9 | use std::collections::HashMap; |
| 10 | use std::sync::{Arc, OnceLock}; |
| 11 | |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | |
| 14 | use codewhale_app_server_protocol::runtime::DynamicToolSpec; |
| 15 | use serde_json::Value; |
| 16 | |
| 17 | use crate::client::CodewhaleClient; |
| 18 | use crate::tools::goal::SharedGoalState; |
| 19 | use codewhale_models::Tool; |
| 20 | |
| 21 | use super::spec::{ |
| 22 | ApprovalRequirement, RichToolResult, ToolCapability, ToolContext, ToolError, ToolResult, |
| 23 | ToolResultContentBlock, ToolSpec, |
| 24 | }; |
| 25 | use codewhale_models::schema_canonicalize; |
| 26 | use codewhale_models::schema_sanitize; |
| 27 | |
| 28 | // === Types === |
| 29 | |
| 30 | /// Registry that holds all available tools. |
| 31 | pub struct ToolRegistry { |
| 32 | tools: HashMap<String, Arc<dyn ToolSpec>>, |
| 33 | context: ToolContext, |
| 34 | read_only_shell: bool, |
| 35 | /// Memoised serialised tool catalog. Rebuilt lazily on first |
| 36 | /// `to_api_tools` call after a mutation; pinned across reads so the |
| 37 | /// description and schema bytes stay byte-stable for DeepSeek's KV |
| 38 | /// prefix cache. Invalidated on `register` / `remove_tool`. |
| 39 | api_cache: OnceLock<Vec<Tool>>, |
| 40 | } |
| 41 | |
| 42 | /// The one sentence naming a `[tools.overrides]` entry that D4 refused, shared |
| 43 | /// by the runtime log and the engine's user-facing status line. |
| 44 | pub fn override_refusal_notice(tool_name: &str) -> String { |
| 45 | format!( |
| 46 | "Refused [tools.overrides.{name}]: a script or command override cannot replace the built-in tool '{name}', which stays active. Set type = \"disabled\" to turn it off, or key the override by a new tool name.", |
| 47 | name = codewhale_runtime::safe_label::SafeLabel::identifier(tool_name) |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | impl ToolRegistry { |
| 52 | /// Create a new empty registry with the given context. |
| 53 | #[must_use] |
| 54 | pub fn new(context: ToolContext) -> Self { |
| 55 | Self { |
| 56 | tools: HashMap::new(), |
| 57 | context, |
| 58 | read_only_shell: false, |
| 59 | api_cache: OnceLock::new(), |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Register a tool in the registry. |
| 64 | pub fn register(&mut self, tool: Arc<dyn ToolSpec>) { |
| 65 | let name = tool.name().to_string(); |
| 66 | if let Some(previous) = self.tools.get(&name) { |
| 67 | tracing::warn!( |
| 68 | previous_origin = ?previous.registration_origin(), |
| 69 | replacement_origin = ?tool.registration_origin(), |
| 70 | "Overwriting existing tool: {}", codewhale_runtime::safe_label::SafeLabel::identifier(&name) |
| 71 | ); |
| 72 | } |
| 73 | self.tools.insert(name, tool); |
| 74 | self.invalidate_api_cache(); |
| 75 | } |
| 76 | |
| 77 | /// Register multiple tools at once. |
| 78 | pub fn register_all(&mut self, tools: Vec<Arc<dyn ToolSpec>>) { |
| 79 | for tool in tools { |
| 80 | self.register(tool); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | pub(crate) fn delegated_mcp_read( |
| 85 | &self, |
| 86 | name: &str, |
| 87 | ) -> Option<Arc<crate::mcp::DelegatedMcpRead>> { |
| 88 | self.get(name)?.delegated_mcp_read() |
| 89 | } |
| 90 | |
| 91 | /// Get a tool by name. |
| 92 | #[must_use] |
| 93 | pub fn get(&self, name: &str) -> Option<Arc<dyn ToolSpec>> { |
| 94 | self.tools.get(name).cloned() |
| 95 | } |
| 96 | |
| 97 | /// Check if a tool exists. |
| 98 | #[must_use] |
| 99 | pub fn contains(&self, name: &str) -> bool { |
| 100 | self.tools.contains_key(name) |
| 101 | } |
| 102 | |
| 103 | /// Get all registered tool names. |
| 104 | #[must_use] |
| 105 | pub fn names(&self) -> Vec<&str> { |
| 106 | self.tools.keys().map(std::string::String::as_str).collect() |
| 107 | } |
| 108 | |
| 109 | /// Get all registered tools. |
| 110 | #[must_use] |
| 111 | pub fn all(&self) -> Vec<Arc<dyn ToolSpec>> { |
| 112 | self.tools.values().cloned().collect() |
| 113 | } |
| 114 | |
| 115 | /// Execute a tool by name, returning the full `ToolResult`. |
| 116 | #[cfg(any(test, feature = "test-support"))] |
| 117 | pub async fn execute_full(&self, name: &str, input: Value) -> Result<ToolResult, ToolError> { |
| 118 | self.execute_rich_full(name, input) |
| 119 | .await |
| 120 | .map(RichToolResult::into_result) |
| 121 | } |
| 122 | |
| 123 | #[cfg(any(test, feature = "test-support"))] |
| 124 | pub async fn execute_rich_full( |
| 125 | &self, |
| 126 | name: &str, |
| 127 | input: Value, |
| 128 | ) -> Result<RichToolResult, ToolError> { |
| 129 | let tool = self |
| 130 | .get(name) |
| 131 | .ok_or_else(|| ToolError::not_available(format!("tool '{name}' is not registered")))?; |
| 132 | |
| 133 | crate::extension_host::validate_caller_plugins(self.context.plugin_registry.as_deref()) |
| 134 | .map_err(ToolError::not_available)?; |
| 135 | let child = self.admit_child_call(name, &input, &self.context).await?; |
| 136 | enforce_tool_authority(name, &input, tool.as_ref(), &self.context)?; |
| 137 | let rich = tool |
| 138 | .execute_rich(input, &self.context) |
| 139 | .await |
| 140 | .map(crate::image_attach::bound_rich_tool_result)?; |
| 141 | if rich.result.success |
| 142 | && let Some((authority, writes)) = child |
| 143 | { |
| 144 | authority.record_settled_writes(writes).await; |
| 145 | } |
| 146 | Ok(rich) |
| 147 | } |
| 148 | |
| 149 | pub async fn execute_rich_full_with_context<'a, F>( |
| 150 | &self, |
| 151 | name: &str, |
| 152 | input: Value, |
| 153 | context_override: Option<&ToolContext>, |
| 154 | on_admitted: F, |
| 155 | ) -> Result<RichToolResult, ToolError> |
| 156 | where |
| 157 | F: FnOnce() -> Result< |
| 158 | Option<crate::core::engine::tool_execution::OperationSpanGuard<'a>>, |
| 159 | ToolError, |
| 160 | > + Send, |
| 161 | { |
| 162 | let tool = self |
| 163 | .get(name) |
| 164 | .ok_or_else(|| ToolError::not_available(format!("tool '{name}' is not registered")))?; |
| 165 | |
| 166 | let ctx = context_override.unwrap_or(&self.context); |
| 167 | crate::extension_host::validate_caller_plugins(ctx.plugin_registry.as_deref()) |
| 168 | .map_err(ToolError::not_available)?; |
| 169 | let child = self.admit_child_call(name, &input, ctx).await?; |
| 170 | enforce_tool_authority(name, &input, tool.as_ref(), ctx)?; |
| 171 | let operation_span = on_admitted()?; |
| 172 | let outcome = tool.execute_rich(input.clone(), ctx).await; |
| 173 | if let Some(operation_span) = operation_span { |
| 174 | operation_span |
| 175 | .complete(super::activity::operation_outcome( |
| 176 | &outcome, |
| 177 | ctx.cancel_token |
| 178 | .as_ref() |
| 179 | .is_some_and(tokio_util::sync::CancellationToken::is_cancelled), |
| 180 | )) |
| 181 | .await; |
| 182 | } |
| 183 | let mut rich = crate::image_attach::bound_rich_tool_result(outcome?); |
| 184 | if rich.result.success |
| 185 | && let Some((authority, writes)) = child |
| 186 | { |
| 187 | authority.record_settled_writes(writes).await; |
| 188 | } |
| 189 | let result = &mut rich.result; |
| 190 | |
| 191 | // Adaptive evidence routing (#4619) is an explicit opt-in |
| 192 | // (`CODEWHALE_ADAPTIVE_OUTPUT_ROUTING`) and is storage-free here |
| 193 | // because this layer does not own a call id. The engine/subagent |
| 194 | // completion boundary publishes the exact artifact. Under the default |
| 195 | // classic lane nothing happens at this layer — the same boundary owns |
| 196 | // the bounded spillover preview. |
| 197 | if crate::tools::large_output_router::adaptive_output_routing_enabled() |
| 198 | && let Some(router) = ctx.large_output_router.as_ref() |
| 199 | { |
| 200 | use crate::tools::large_output_router::EvidenceRouting; |
| 201 | let (estimated_routing, estimated_tokens, threshold) = |
| 202 | router.evidence_routing(name, result); |
| 203 | let metadata = result.metadata.get_or_insert_with(|| serde_json::json!({})); |
| 204 | if let Some(object) = metadata.as_object_mut() { |
| 205 | // A tool that self-bounds its output behind its own |
| 206 | // recovery contract (e.g. read_file's `next_start_line` |
| 207 | // paging) declares its routing itself; the size estimate |
| 208 | // must not override that and double-wrap the result. |
| 209 | let routing = object |
| 210 | .get("evidence_routing") |
| 211 | .cloned() |
| 212 | .and_then(|value| serde_json::from_value::<EvidenceRouting>(value).ok()) |
| 213 | .unwrap_or(estimated_routing); |
| 214 | object.insert( |
| 215 | "evidence_routing".to_string(), |
| 216 | serde_json::to_value(routing).unwrap_or_else(|_| serde_json::json!("inline")), |
| 217 | ); |
| 218 | object.insert( |
| 219 | "evidence_estimated_tokens".to_string(), |
| 220 | estimated_tokens.into(), |
| 221 | ); |
| 222 | object.insert("evidence_threshold_tokens".to_string(), threshold.into()); |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | Ok(rich) |
| 227 | } |
| 228 | |
| 229 | pub async fn admit_child_call( |
| 230 | &self, |
| 231 | name: &str, |
| 232 | input: &Value, |
| 233 | context: &ToolContext, |
| 234 | ) -> Result<Option<(Arc<super::subagent::engine::ChildAuthority>, Vec<String>)>, ToolError> |
| 235 | { |
| 236 | let child = self |
| 237 | .context |
| 238 | .child_host |
| 239 | .as_ref() |
| 240 | .or(context.child_host.as_ref()); |
| 241 | let Some(child) = child else { |
| 242 | return Ok(None); |
| 243 | }; |
| 244 | if self |
| 245 | .context |
| 246 | .child_host |
| 247 | .as_ref() |
| 248 | .zip(context.child_host.as_ref()) |
| 249 | .is_some_and(|(expected, actual)| !Arc::ptr_eq(expected, actual)) |
| 250 | { |
| 251 | return Err(ToolError::permission_denied( |
| 252 | "child context cannot replace its captured grant", |
| 253 | )); |
| 254 | } |
| 255 | child.validate_context(context)?; |
| 256 | let writes = child |
| 257 | .validate_claim(self, name, input) |
| 258 | .await |
| 259 | .map_err(super::subagent::engine::ChildAuthority::typed_error)?; |
| 260 | // Claim lookup may wait; current caller liveness and immutable child ceiling are rechecked before effects. |
| 261 | child.validate_context(context)?; |
| 262 | crate::extension_host::validate_caller_plugins(context.plugin_registry.as_deref()) |
| 263 | .map_err(ToolError::not_available)?; |
| 264 | child |
| 265 | .validate(self, name, input) |
| 266 | .map_err(super::subagent::engine::ChildAuthority::typed_error)?; |
| 267 | Ok(Some((child.clone(), writes))) |
| 268 | } |
| 269 | |
| 270 | /// Get the current tool context. |
| 271 | #[must_use] |
| 272 | pub fn context(&self) -> &ToolContext { |
| 273 | &self.context |
| 274 | } |
| 275 | |
| 276 | pub fn set_plugin_registry( |
| 277 | &mut self, |
| 278 | plugins: Option<std::sync::Arc<codewhale_plugins::PluginRegistry>>, |
| 279 | ) { |
| 280 | self.context.plugin_registry = plugins; |
| 281 | } |
| 282 | |
| 283 | /// Convert all tools to API Tool format for sending to the model. |
| 284 | /// |
| 285 | /// Output is sorted by tool name for **prefix-cache stability** (#263). |
| 286 | /// Rust's `HashMap` uses a randomly-seeded hasher per process, so a raw |
| 287 | /// `self.tools.values()` iteration emits tools in a different order on |
| 288 | /// every `deepseek` launch, invalidating DeepSeek's KV prefix cache for |
| 289 | /// every cross-session resume. Sorting here matches the way Claude Code |
| 290 | /// stabilises its tool array (`assembleToolPool` in their reference). |
| 291 | /// |
| 292 | /// The serialised catalog is memoised on first call and pinned across |
| 293 | /// reads so each tool's `description()` and `input_schema()` are sampled |
| 294 | /// exactly once per registration. MCP adapters whose upstream description |
| 295 | /// drifts on reconnect would otherwise rewrite the catalog mid-session |
| 296 | /// and bust the prefix cache. The cache is invalidated on `register`, |
| 297 | /// `remove`, and `clear`. |
| 298 | #[must_use] |
| 299 | pub fn to_api_tools(&self) -> Vec<Tool> { |
| 300 | self.api_cache |
| 301 | .get_or_init(|| self.build_api_tools()) |
| 302 | .clone() |
| 303 | } |
| 304 | |
| 305 | fn build_api_tools(&self) -> Vec<Tool> { |
| 306 | let read_only_authority = self.context.tool_authority.as_deref().filter(|authority| { |
| 307 | authority.authority == super::spec::ToolMutationAuthority::ReadOnly |
| 308 | }); |
| 309 | let evidence_only = read_only_authority.is_some(); |
| 310 | let evidence_network = self |
| 311 | .context |
| 312 | .tool_authority |
| 313 | .as_ref() |
| 314 | .is_none_or(|authority| authority.network_access == Some(true)); |
| 315 | let mut tools: Vec<&Arc<dyn ToolSpec>> = self.tools.values().collect(); |
| 316 | tools.sort_by(|a, b| a.name().cmp(b.name())); |
| 317 | tools |
| 318 | .into_iter() |
| 319 | .filter(|tool| tool.model_visible()) |
| 320 | .filter(|tool| { |
| 321 | read_only_authority.is_none_or(|authority| { |
| 322 | readonly_evidence_tool(tool.as_ref()) |
| 323 | || (tool.name() == "Run" |
| 324 | && authority.verification |
| 325 | == super::spec::ToolVerificationAuthority::Bounded) |
| 326 | }) |
| 327 | }) |
| 328 | .filter(|tool| evidence_network || !matches!(tool.name(), "Web" | "web.run")) |
| 329 | .map(|tool| { |
| 330 | let mut schema = tool.input_schema(); |
| 331 | if evidence_only { |
| 332 | project_readonly_evidence_schema(tool.name(), &mut schema); |
| 333 | } else if tool.name() == "bash" |
| 334 | && (self.read_only_shell |
| 335 | || self.context.shell_policy |
| 336 | == codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly) |
| 337 | { |
| 338 | super::shell::strip_readonly_bash_schema_properties(&mut schema); |
| 339 | } |
| 340 | schema_sanitize::sanitize(&mut schema); |
| 341 | schema_canonicalize::canonicalize_schema(&mut schema); |
| 342 | Tool { |
| 343 | tool_type: None, |
| 344 | name: tool.name().to_string(), |
| 345 | description: if evidence_only |
| 346 | && matches!(tool.name(), "bash" | "Bash" | "exec_shell") |
| 347 | { |
| 348 | format!( |
| 349 | "{} {}", |
| 350 | tool.description(), |
| 351 | codewhale_execpolicy::command_safety::readonly_command_help() |
| 352 | ) |
| 353 | } else { |
| 354 | tool.description().to_string() |
| 355 | }, |
| 356 | input_schema: schema, |
| 357 | allowed_callers: Some(vec!["direct".to_string()]), |
| 358 | defer_loading: Some(tool.defer_loading()), |
| 359 | input_examples: None, |
| 360 | strict: None, |
| 361 | cache_control: None, |
| 362 | } |
| 363 | }) |
| 364 | .collect() |
| 365 | } |
| 366 | |
| 367 | fn invalidate_api_cache(&mut self) { |
| 368 | self.api_cache = OnceLock::new(); |
| 369 | } |
| 370 | |
| 371 | /// Convert tools to API Tool format with optional cache control on the last tool. |
| 372 | #[must_use] |
| 373 | pub fn to_api_tools_with_cache(&self, enable_cache: bool) -> Vec<Tool> { |
| 374 | let mut tools = self.to_api_tools(); |
| 375 | if enable_cache { |
| 376 | apply_tool_cache_breakpoint(&mut tools); |
| 377 | } |
| 378 | tools |
| 379 | } |
| 380 | |
| 381 | /// Flatten every registered tool into the exact facts the read-only |
| 382 | /// request projection is allowed to report: name, description, model |
| 383 | /// visibility, declared capabilities, declared approval requirement, and |
| 384 | /// whether the tool came from the plugin surface. |
| 385 | /// |
| 386 | /// This hands out *data*, never tool objects, so the projection layer |
| 387 | /// cannot execute anything. Output is sorted by name and does not touch the |
| 388 | /// registry's own ordering or the memoised API catalog. |
| 389 | #[must_use] |
| 390 | pub fn registry_facts( |
| 391 | &self, |
| 392 | plugin_names: &std::collections::HashSet<String>, |
| 393 | ) -> Vec<crate::tool_inspection::RegistryFacts> { |
| 394 | let mut facts: Vec<crate::tool_inspection::RegistryFacts> = self |
| 395 | .tools |
| 396 | .values() |
| 397 | .map(|tool| crate::tool_inspection::RegistryFacts { |
| 398 | name: tool.name().to_string(), |
| 399 | description: tool.description().to_string(), |
| 400 | model_visible: tool.model_visible(), |
| 401 | capabilities: tool |
| 402 | .capabilities() |
| 403 | .iter() |
| 404 | .map(|capability| format!("{capability:?}")) |
| 405 | .collect(), |
| 406 | approval: format!("{:?}", tool.approval_requirement()), |
| 407 | plugin: plugin_names.contains(tool.name()), |
| 408 | }) |
| 409 | .collect(); |
| 410 | facts.sort_by(|a, b| a.name.cmp(&b.name)); |
| 411 | facts |
| 412 | } |
| 413 | |
| 414 | /// Resolve a non-canonical tool name to a registered canonical name. |
| 415 | /// |
| 416 | /// Runs a deterministic ladder against the registered tool names: |
| 417 | /// 1. Lowercase exact match. |
| 418 | /// 2. Hyphens/spaces → underscores (read-file → read_file). |
| 419 | /// 3. CamelCase → snake_case (ReadFile → read_file). |
| 420 | /// 4. Strip trailing `_tool` / `-tool` suffix (twice). |
| 421 | /// |
| 422 | /// Returns `None` when no normalization matches (the caller surfaces |
| 423 | /// "Unknown tool … did you mean: …"). There is deliberately **no fuzzy |
| 424 | /// step**: a prefix guess over the registry would execute an arbitrary |
| 425 | /// sibling tool the model never asked for (#5123-class) — a hallucinated |
| 426 | /// name must fail, never dispatch. |
| 427 | #[must_use] |
| 428 | pub fn resolve(&self, requested: &str) -> Option<&str> { |
| 429 | let names: Vec<&str> = self.tools.keys().map(String::as_str).collect(); |
| 430 | let lower = requested.to_lowercase(); |
| 431 | |
| 432 | // 1. ASCII case-insensitive exact |
| 433 | if let Some(n) = names.iter().find(|n| n.eq_ignore_ascii_case(requested)) { |
| 434 | return Some(n); |
| 435 | } |
| 436 | // 2. hyphen/space → underscore |
| 437 | let snaked = lower.replace(['-', ' '], "_"); |
| 438 | if let Some(n) = names.iter().find(|n| **n == snaked) { |
| 439 | return Some(n); |
| 440 | } |
| 441 | // 3. CamelCase → snake_case |
| 442 | let cc = to_snake_case(requested); |
| 443 | if let Some(n) = names.iter().find(|n| **n == cc) { |
| 444 | return Some(n); |
| 445 | } |
| 446 | // 4. strip _tool/-tool/tool suffix, twice |
| 447 | let mut stripped = cc.clone(); |
| 448 | for _ in 0..2 { |
| 449 | for suf in ["_tool", "-tool", "tool"] { |
| 450 | if let Some(s) = stripped.strip_suffix(suf) { |
| 451 | stripped = s.to_string(); |
| 452 | break; |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | if !stripped.is_empty() |
| 457 | && let Some(n) = names.iter().find(|n| **n == stripped) |
| 458 | { |
| 459 | return Some(n); |
| 460 | } |
| 461 | None |
| 462 | } |
| 463 | |
| 464 | /// Remove a tool from the registry by name. Returns `true` if the tool |
| 465 | /// was present and removed, `false` if no tool with that name existed. |
| 466 | pub fn remove_tool(&mut self, name: &str) -> bool { |
| 467 | let existed = self.tools.remove(name).is_some(); |
| 468 | if existed { |
| 469 | self.invalidate_api_cache(); |
| 470 | } |
| 471 | existed |
| 472 | } |
| 473 | |
| 474 | /// Apply config.toml tool overrides to this registry. |
| 475 | /// |
| 476 | /// For each entry in `overrides`: |
| 477 | /// - `Disabled` removes the tool, built-ins included. |
| 478 | /// - `Script` / `Command` registers the user's implementation under a name |
| 479 | /// no built-in owns: a new tool, or a replacement for a drop-in plugin |
| 480 | /// script of that name. |
| 481 | /// - `Script` / `Command` keyed by a name in `builtin_names` is refused and |
| 482 | /// the built-in stays active: script tools cannot shadow built-ins (D4, |
| 483 | /// CURRENT_DECISIONS §26). |
| 484 | /// |
| 485 | /// Returns the refused override names so the engine can name each one to |
| 486 | /// the user ([`override_refusal_notice`]); the runtime log records every |
| 487 | /// refusal. `/plugin` does not list `[tools.overrides]` entries, so it |
| 488 | /// cannot show them there. |
| 489 | /// |
| 490 | /// `plugin_dir` is used as the base for relative script paths. |
| 491 | #[cfg(any(test, feature = "test-support"))] |
| 492 | pub fn apply_overrides( |
| 493 | &mut self, |
| 494 | overrides: &std::collections::HashMap<String, codewhale_runtime::config::ToolOverride>, |
| 495 | plugin_dir: &Path, |
| 496 | builtin_names: &std::collections::HashSet<String>, |
| 497 | ) -> Vec<String> { |
| 498 | self.apply_overrides_with_executor( |
| 499 | overrides, |
| 500 | plugin_dir, |
| 501 | builtin_names, |
| 502 | crate::tools::plugin::PluginExecutor::for_engine(), |
| 503 | ) |
| 504 | } |
| 505 | pub fn apply_overrides_with_executor( |
| 506 | &mut self, |
| 507 | overrides: &std::collections::HashMap<String, codewhale_runtime::config::ToolOverride>, |
| 508 | plugin_dir: &Path, |
| 509 | builtin_names: &std::collections::HashSet<String>, |
| 510 | executor: crate::tools::plugin::PluginExecutor, |
| 511 | ) -> Vec<String> { |
| 512 | let mut refused = Vec::new(); |
| 513 | for (tool_name, override_cfg) in overrides { |
| 514 | match override_cfg { |
| 515 | codewhale_runtime::config::ToolOverride::Disabled => { |
| 516 | let canonical = crate::conversation_modes::CREATOR_TOOL_NAMES |
| 517 | .iter() |
| 518 | .copied() |
| 519 | .find(|reserved| reserved.eq_ignore_ascii_case(tool_name)); |
| 520 | let removed = self.remove_tool(tool_name) |
| 521 | || canonical.is_some_and(|reserved| self.remove_tool(reserved)); |
| 522 | if removed { |
| 523 | tracing::info!("Tool '{}' disabled via config override", tool_name); |
| 524 | } else { |
| 525 | tracing::warn!("Cannot disable tool '{}': not registered", tool_name); |
| 526 | } |
| 527 | } |
| 528 | _ if builtin_names.contains(tool_name) |
| 529 | || crate::conversation_modes::CREATOR_TOOL_NAMES |
| 530 | .iter() |
| 531 | .any(|reserved| reserved.eq_ignore_ascii_case(tool_name)) => |
| 532 | { |
| 533 | tracing::error!("{}", override_refusal_notice(tool_name)); |
| 534 | refused.push(tool_name.clone()); |
| 535 | } |
| 536 | _ => { |
| 537 | // Script and Command overrides create replacement tools. |
| 538 | use crate::tools::plugin::tool_from_override_with_executor; |
| 539 | match tool_from_override_with_executor( |
| 540 | tool_name, |
| 541 | override_cfg, |
| 542 | plugin_dir, |
| 543 | executor.clone(), |
| 544 | ) { |
| 545 | Some(replacement) => { |
| 546 | self.register(replacement); |
| 547 | tracing::info!("Tool '{}' replaced via config override", tool_name); |
| 548 | } |
| 549 | None => { |
| 550 | if self.remove_tool(tool_name) { |
| 551 | tracing::warn!( |
| 552 | "Tool '{}' override did not create a replacement; removed the original tool to avoid override fallthrough", |
| 553 | tool_name |
| 554 | ); |
| 555 | } else { |
| 556 | tracing::warn!( |
| 557 | "Tool '{}' override did not create a replacement and no registered tool existed", |
| 558 | tool_name |
| 559 | ); |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | } |
| 566 | refused |
| 567 | } |
| 568 | |
| 569 | /// Load and register plugin tools from a directory. |
| 570 | /// |
| 571 | /// Each script with valid frontmatter (`# name:`, `# description:`, etc.) |
| 572 | /// becomes a registered `ScriptPluginTool`. Name collisions are refused: |
| 573 | /// a script tool never replaces a registered tool. |
| 574 | #[cfg(any(test, feature = "test-support"))] |
| 575 | pub fn load_plugins(&mut self, plugin_dir: &Path) { |
| 576 | self.load_plugins_with_executor( |
| 577 | plugin_dir, |
| 578 | crate::tools::plugin::PluginExecutor::for_engine(), |
| 579 | ); |
| 580 | } |
| 581 | pub fn load_plugins_with_executor( |
| 582 | &mut self, |
| 583 | plugin_dir: &Path, |
| 584 | executor: crate::tools::plugin::PluginExecutor, |
| 585 | ) { |
| 586 | if !plugin_dir.exists() { |
| 587 | tracing::debug!( |
| 588 | "Plugin directory {} does not exist, skipping", |
| 589 | plugin_dir.display() |
| 590 | ); |
| 591 | return; |
| 592 | } |
| 593 | let plugins = crate::tools::plugin::load_plugin_tools_with_executor(plugin_dir, executor); |
| 594 | let mut count = 0; |
| 595 | for tool in plugins { |
| 596 | if let Some(previous) = self.get(tool.name()) { |
| 597 | tracing::error!( |
| 598 | previous_origin = ?previous.registration_origin(), |
| 599 | plugin_origin = ?tool.registration_origin(), |
| 600 | "Cannot load plugin tool '{}': name is already registered; script tools cannot replace a registered tool, so give the script its own name", |
| 601 | codewhale_runtime::safe_label::SafeLabel::identifier(tool.name()) |
| 602 | ); |
| 603 | continue; |
| 604 | } |
| 605 | if crate::conversation_modes::CREATOR_TOOL_NAMES |
| 606 | .iter() |
| 607 | .any(|reserved| reserved.eq_ignore_ascii_case(tool.name())) |
| 608 | { |
| 609 | tracing::error!( |
| 610 | previous_origin = "reserved built-in tool", |
| 611 | plugin_origin = ?tool.registration_origin(), |
| 612 | "Cannot load plugin tool '{}': name is already registered; script tools cannot replace a registered tool, so give the script its own name", |
| 613 | codewhale_runtime::safe_label::SafeLabel::identifier(tool.name()) |
| 614 | ); |
| 615 | continue; |
| 616 | } |
| 617 | self.register(tool); |
| 618 | count += 1; |
| 619 | } |
| 620 | if count > 0 { |
| 621 | tracing::info!( |
| 622 | "Loaded {count} plugin tool(s) from {}", |
| 623 | plugin_dir.display() |
| 624 | ); |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | pub fn apply_tool_cache_breakpoint(tools: &mut [Tool]) { |
| 630 | for tool in tools.iter_mut() { |
| 631 | tool.cache_control = None; |
| 632 | } |
| 633 | let idx = tools |
| 634 | .iter() |
| 635 | .rposition(|tool| !tool.defer_loading.unwrap_or(false)) |
| 636 | .or_else(|| (!tools.is_empty()).then(|| tools.len() - 1)); |
| 637 | if let Some(idx) = idx { |
| 638 | tools[idx].cache_control = Some(codewhale_models::CacheControl { |
| 639 | cache_type: "ephemeral".to_string(), |
| 640 | }); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /// The complete model-visible and dispatchable surface for a machine or role |
| 645 | /// whose contract is evidence collection without project/process mutation. |
| 646 | pub fn readonly_evidence_tool_name(name: &str) -> bool { |
| 647 | matches!( |
| 648 | name, |
| 649 | "read" |
| 650 | | "bash" |
| 651 | | "Web" |
| 652 | | "web.run" |
| 653 | | "load_skill" |
| 654 | | "handle_read" |
| 655 | | "retrieve_tool_result" |
| 656 | | "todo_write" |
| 657 | ) |
| 658 | } |
| 659 | |
| 660 | /// True when a concrete registered tool is safe on the read-only evidence |
| 661 | /// surface. Static read-only capability is sufficient except for tools that |
| 662 | /// declare `StartsWorkspaceProgram` (Git/review): those may invoke |
| 663 | /// repository-configured helpers, so their safety cannot be proven from the |
| 664 | /// tool declaration alone. Scouts can still inspect Git through |
| 665 | /// classifier-bounded lowercase `bash` commands. |
| 666 | pub fn readonly_evidence_tool(tool: &dyn ToolSpec) -> bool { |
| 667 | readonly_evidence_tool_name(tool.name()) |
| 668 | || tool.is_read_only() |
| 669 | && !tool |
| 670 | .capabilities() |
| 671 | .contains(&ToolCapability::StartsWorkspaceProgram) |
| 672 | } |
| 673 | |
| 674 | fn project_readonly_evidence_schema(name: &str, schema: &mut Value) { |
| 675 | if name == "bash" { |
| 676 | super::shell::strip_readonly_bash_schema_properties(schema); |
| 677 | return; |
| 678 | } |
| 679 | // Probe with `pointer_mut`, never `schema["properties"]["action"]["enum"]`: |
| 680 | // serde_json's IndexMut auto-vivifies missing keys by inserting Null, so |
| 681 | // the old probe left `properties.action = {"enum": null}` inside schemas |
| 682 | // that have no action property (e.g. lowercase `bash`). Strict |
| 683 | // OpenAI-compatible validators then reject the whole request with |
| 684 | // `Invalid schema for function 'bash': null is not of type "array"` |
| 685 | // (observed on Fleet read-only workers; see registry tests). |
| 686 | // The same probe idiom lives in `tools/subagent` (grep `pointer_mut( |
| 687 | // "/properties/action/enum")`); keep the two sites greppable as one. |
| 688 | let Some(actions) = schema |
| 689 | .pointer_mut("/properties/action/enum") |
| 690 | .and_then(Value::as_array_mut) |
| 691 | else { |
| 692 | return; |
| 693 | }; |
| 694 | if name == "Web" { |
| 695 | actions.retain(|action| { |
| 696 | action |
| 697 | .as_str() |
| 698 | .is_some_and(|action| matches!(action, "search" | "fetch")) |
| 699 | }); |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | pub fn enforce_tool_authority( |
| 704 | name: &str, |
| 705 | input: &Value, |
| 706 | tool: &dyn ToolSpec, |
| 707 | context: &ToolContext, |
| 708 | ) -> Result<(), ToolError> { |
| 709 | crate::tools::execution_envelope::enforce_tool_denial(context, name, input)?; |
| 710 | if let Some(mode) = context.acp_host { |
| 711 | let canonical = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input); |
| 712 | if matches!(name, "bash" | "Bash" | "exec_shell") || canonical.starts_with("exec_shell") { |
| 713 | let prepared = tool.prepare(input.clone(), context)?; |
| 714 | if context.shell_policy == codewhale_agent_contract::worker_profile::ShellPolicy::None |
| 715 | || prepared |
| 716 | .input |
| 717 | .get("action") |
| 718 | .and_then(Value::as_str) |
| 719 | .unwrap_or("run") |
| 720 | != "run" |
| 721 | || prepared.starts_detached |
| 722 | || prepared.input.get("interactive").and_then(Value::as_bool) == Some(true) |
| 723 | || prepared.input.get("persist").and_then(Value::as_bool) == Some(true) |
| 724 | || prepared |
| 725 | .input |
| 726 | .get("command") |
| 727 | .and_then(Value::as_str) |
| 728 | .is_some_and(super::shell::foreground_command_requests_detach) |
| 729 | { |
| 730 | return Err(ToolError::permission_denied( |
| 731 | "ACP supports only admitted foreground shell commands; stateful and detached execution is unavailable", |
| 732 | )); |
| 733 | } |
| 734 | } |
| 735 | // The transport has no controls for these lifecycles. A fabricated |
| 736 | // tool name or alias cannot turn catalog omission into authority. |
| 737 | if !matches!( |
| 738 | tool.name(), |
| 739 | "read" |
| 740 | | "write" |
| 741 | | "edit" |
| 742 | | "read_file" |
| 743 | | "write_file" |
| 744 | | "edit_file" |
| 745 | | "list_dir" |
| 746 | | "file_search" |
| 747 | | "grep_files" |
| 748 | | "Git" |
| 749 | | "apply_patch" |
| 750 | | "bash" |
| 751 | | "context_archive_search" |
| 752 | | "present" |
| 753 | ) && tool.extension_caller().is_none() |
| 754 | { |
| 755 | return Err(ToolError::not_available(format!( |
| 756 | "{name} is outside the ACP foreground tool profile" |
| 757 | ))); |
| 758 | } |
| 759 | if mode == codewhale_config::AppMode::Plan |
| 760 | && !tool.prepare(input.clone(), context)?.read_only |
| 761 | { |
| 762 | return Err(ToolError::permission_denied( |
| 763 | "ACP Plan mode permits only read-only calls", |
| 764 | )); |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | let Some(authority) = context.tool_authority.as_ref() else { |
| 769 | return Ok(()); |
| 770 | }; |
| 771 | let evidence_only = authority.authority == super::spec::ToolMutationAuthority::ReadOnly; |
| 772 | let bounded_verifier = evidence_only |
| 773 | && name == "Run" |
| 774 | && authority.verification == super::spec::ToolVerificationAuthority::Bounded; |
| 775 | if evidence_only && !readonly_evidence_tool(tool) && !bounded_verifier { |
| 776 | return Err(ToolError::permission_denied(format!( |
| 777 | "worker '{}' cannot run {name}: it is outside the read-only evidence tool profile", |
| 778 | authority.owner |
| 779 | ))); |
| 780 | } |
| 781 | if evidence_only && matches!(name, "Web" | "web.run") && authority.network_access != Some(true) |
| 782 | { |
| 783 | return Err(ToolError::permission_denied(format!( |
| 784 | "worker '{}' cannot run {name}: its authority envelope does not grant network access", |
| 785 | authority.owner |
| 786 | ))); |
| 787 | } |
| 788 | let capabilities = tool.capabilities(); |
| 789 | if matches!(name, "bash" | "Bash" | "exec_shell") { |
| 790 | // One authority (#6015): a durable worker's shell is judged by the |
| 791 | // same agent read-only grammar and input normalization as in-session |
| 792 | // agents (`agent_readonly_bash_verdict`), and `BashTool::execute` |
| 793 | // applies it again under the clamped `ShellPolicy::ReadOnly`. The |
| 794 | // parent's parallel/approval classification (`is_read_only_for`) is |
| 795 | // not an authority here. |
| 796 | let verdict = super::shell::agent_readonly_bash_verdict(input); |
| 797 | if authority.shell != crate::tools::spec::ToolShellAuthority::ReadOnly { |
| 798 | return Err(ToolError::permission_denied(if verdict.is_ok() { |
| 799 | format!( |
| 800 | "worker '{}' cannot run {name}: its machine-readable authority envelope does not grant read-only shell access", |
| 801 | authority.owner |
| 802 | ) |
| 803 | } else { |
| 804 | format!( |
| 805 | "worker '{}' cannot run {name}: arbitrary command execution is outside its machine-readable authority envelope. {}", |
| 806 | authority.owner, |
| 807 | codewhale_execpolicy::command_safety::readonly_command_help() |
| 808 | ) |
| 809 | })); |
| 810 | } |
| 811 | if let Err(rejection) = verdict { |
| 812 | return Err(ToolError::permission_denied(format!( |
| 813 | "worker '{}' cannot run {name}: {}", |
| 814 | authority.owner, |
| 815 | super::shell::readonly_refusal( |
| 816 | &rejection, |
| 817 | super::shell::readonly_enforced_lane_available(context) |
| 818 | ) |
| 819 | ))); |
| 820 | } |
| 821 | let hosts = input |
| 822 | .get("command") |
| 823 | .and_then(Value::as_str) |
| 824 | .map(codewhale_execpolicy::command_safety::readonly_network_reads) |
| 825 | .unwrap_or_default() |
| 826 | .into_iter() |
| 827 | .map(codewhale_execpolicy::command_safety::NetworkRead::host) |
| 828 | .collect::<Vec<_>>(); |
| 829 | if !hosts.is_empty() && authority.network_access != Some(true) { |
| 830 | return Err(ToolError::permission_denied(format!( |
| 831 | "worker '{}' cannot use read-only network access to {}: its machine-readable authority envelope does not grant network access", |
| 832 | authority.owner, |
| 833 | hosts.join(", ") |
| 834 | ))); |
| 835 | } |
| 836 | return Ok(()); |
| 837 | } |
| 838 | if name == "Run" { |
| 839 | if bounded_verifier { |
| 840 | use crate::tools::execution_envelope::{VerificationBound, classify_verification}; |
| 841 | |
| 842 | let canonical = |
| 843 | codewhale_execpolicy::canonical_action::canonical_action_alias(name, input); |
| 844 | if matches!( |
| 845 | classify_verification(canonical, input), |
| 846 | Some(VerificationBound::Default | VerificationBound::Filter) |
| 847 | ) { |
| 848 | return Ok(()); |
| 849 | } |
| 850 | return Err(ToolError::permission_denied(format!( |
| 851 | "worker '{}' cannot run unbounded verification arguments. Re-run the default gate instead: drop any flag that can redirect what runs (run_tests `args` may only select tests), and report the blocked probe to the parent rather than working around it.", |
| 852 | authority.owner |
| 853 | ))); |
| 854 | } |
| 855 | return Err(ToolError::permission_denied(format!( |
| 856 | "worker '{}' cannot run {name}: arbitrary command execution is outside its machine-readable authority envelope. {}", |
| 857 | authority.owner, |
| 858 | codewhale_execpolicy::command_safety::readonly_command_help() |
| 859 | ))); |
| 860 | } |
| 861 | if name == "Git" || name.starts_with("git_") || name == "review" { |
| 862 | return Err(ToolError::permission_denied(format!( |
| 863 | "worker '{}' cannot run {name}: repository-configured Git helpers cannot prove read-only execution under its machine-readable authority envelope", |
| 864 | authority.owner |
| 865 | ))); |
| 866 | } |
| 867 | if tool.is_read_only_for(input) { |
| 868 | return Ok(()); |
| 869 | } |
| 870 | if capabilities.contains(&ToolCapability::ExecutesCode) { |
| 871 | return Err(ToolError::permission_denied(format!( |
| 872 | "worker '{}' cannot run {name}: code or child execution is outside its machine-readable authority envelope", |
| 873 | authority.owner |
| 874 | ))); |
| 875 | } |
| 876 | if let Some(paths) = authority_mutation_paths(name, input)? { |
| 877 | if paths.is_empty() { |
| 878 | return Err(ToolError::permission_denied(format!( |
| 879 | "worker '{}' mutation through {name} did not expose a bounded file target", |
| 880 | authority.owner |
| 881 | ))); |
| 882 | } |
| 883 | for path in paths { |
| 884 | if !authority.permits_mutation_path(context, &path)? { |
| 885 | return Err(ToolError::permission_denied(format!( |
| 886 | "worker '{}' cannot mutate '{path}' outside its machine-readable authority envelope", |
| 887 | authority.owner |
| 888 | ))); |
| 889 | } |
| 890 | } |
| 891 | return Ok(()); |
| 892 | } |
| 893 | Err(ToolError::permission_denied(format!( |
| 894 | "worker '{}' cannot run mutating tool {name}: the call has no authorized file target", |
| 895 | authority.owner |
| 896 | ))) |
| 897 | } |
| 898 | |
| 899 | fn authority_mutation_paths(name: &str, input: &Value) -> Result<Option<Vec<String>>, ToolError> { |
| 900 | let canonical = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input); |
| 901 | if canonical == "apply_patch" { |
| 902 | let mut patch_input = |
| 903 | codewhale_tools::param_alias::with_canonical_path_argument(input).into_owned(); |
| 904 | if let Some(object) = patch_input.as_object_mut() { |
| 905 | object.remove("action"); |
| 906 | } |
| 907 | let paths = codewhale_tools::patch_preflight::preflight_apply_patch(&patch_input) |
| 908 | .map_err(|error| ToolError::invalid_input(error.to_string()))? |
| 909 | .touched_files; |
| 910 | return Ok(Some(paths)); |
| 911 | } |
| 912 | let path_bound = matches!(canonical, "write_file" | "edit_file" | "fim_edit") |
| 913 | || (name == "pandoc_convert" && input.get("output_path").is_some()); |
| 914 | if !path_bound { |
| 915 | return Ok(None); |
| 916 | } |
| 917 | Ok(Some(mutation_target_paths(name, input))) |
| 918 | } |
| 919 | |
| 920 | pub(crate) fn mutation_target_paths(name: &str, input: &Value) -> Vec<String> { |
| 921 | if name == "pandoc_convert" { |
| 922 | return input |
| 923 | .get("output_path") |
| 924 | .and_then(Value::as_str) |
| 925 | .into_iter() |
| 926 | .map(str::to_string) |
| 927 | .collect(); |
| 928 | } |
| 929 | let mut paths = Vec::new(); |
| 930 | for key in codewhale_tools::param_alias::path_argument_keys() { |
| 931 | if let Some(path) = input.get(key).and_then(Value::as_str) |
| 932 | && !paths.iter().any(|seen| seen == path) |
| 933 | { |
| 934 | paths.push(path.to_string()); |
| 935 | } |
| 936 | } |
| 937 | paths |
| 938 | } |
| 939 | |
| 940 | pub const RESERVED_TOOL_NAMES: &[&str] = &[ |
| 941 | "read", |
| 942 | "write", |
| 943 | "edit", |
| 944 | "File", |
| 945 | "read_file", |
| 946 | "write_file", |
| 947 | "edit_file", |
| 948 | "list_dir", |
| 949 | "retrieve_tool_result", |
| 950 | "present", |
| 951 | "show_data", |
| 952 | "bash", |
| 953 | "Bash", |
| 954 | "terminal_run", |
| 955 | "terminal_send", |
| 956 | "terminal_wait", |
| 957 | "terminal_cancel", |
| 958 | "terminal_reset", |
| 959 | "terminal/run", |
| 960 | "terminal/send", |
| 961 | "terminal/wait", |
| 962 | "terminal/cancel", |
| 963 | "terminal/reset", |
| 964 | "file_search", |
| 965 | "grep_files", |
| 966 | "Git", |
| 967 | "diagnostics", |
| 968 | "tui_help", |
| 969 | "pandoc_convert", |
| 970 | "image_ocr", |
| 971 | "read_media", |
| 972 | "load_skill", |
| 973 | "project_map", |
| 974 | "Run", |
| 975 | "validate_data", |
| 976 | "context_archive_get", |
| 977 | "context_archive_search", |
| 978 | "tasks", |
| 979 | "github", |
| 980 | "automation", |
| 981 | "send_later", |
| 982 | "task_shell_wait", |
| 983 | "Web", |
| 984 | "web.run", |
| 985 | "finance", |
| 986 | "image_analyze", |
| 987 | "request_user_input", |
| 988 | "apply_patch", |
| 989 | "revert_turn", |
| 990 | "speech", |
| 991 | "tts", |
| 992 | "rlm", |
| 993 | "harness", |
| 994 | "handle_read", |
| 995 | "review", |
| 996 | "verify", |
| 997 | "note", |
| 998 | "fim_edit", |
| 999 | "remember", |
| 1000 | "memory_search", |
| 1001 | "memory_get", |
| 1002 | "session_search", |
| 1003 | "session_get", |
| 1004 | "lsp", |
| 1005 | "notify", |
| 1006 | "request_plugin_install", |
| 1007 | "start_mcp_server", |
| 1008 | "registry_sync", |
| 1009 | "start_registry_mcp_server", |
| 1010 | "todo_write", |
| 1011 | "work_update", |
| 1012 | "TodoWrite", |
| 1013 | "todo", |
| 1014 | "checklist_write", |
| 1015 | "checklist_update", |
| 1016 | "update_plan", |
| 1017 | "create_goal", |
| 1018 | "get_goal", |
| 1019 | "update_goal", |
| 1020 | "workflow", |
| 1021 | "agent", |
| 1022 | "agents/list", |
| 1023 | "agents/message", |
| 1024 | "agents/followup", |
| 1025 | "agents/interrupt", |
| 1026 | "agents/coordinate", |
| 1027 | "agents/wait", |
| 1028 | "tool_search", |
| 1029 | "tool_search_tool_regex", |
| 1030 | "tool_search_tool_bm25", |
| 1031 | "multi_tool_use.parallel", |
| 1032 | "code_execution", |
| 1033 | "execute_tools", |
| 1034 | "js_execution", |
| 1035 | "authenticate", |
| 1036 | "list_mcp_resources", |
| 1037 | "list_mcp_resource_templates", |
| 1038 | "mcp_read_resource", |
| 1039 | "read_mcp_resource", |
| 1040 | "mcp_get_prompt", |
| 1041 | ]; |
| 1042 | |
| 1043 | #[must_use] |
| 1044 | pub fn is_reserved_tool_name(name: &str) -> bool { |
| 1045 | RESERVED_TOOL_NAMES |
| 1046 | .iter() |
| 1047 | .chain(crate::conversation_modes::CREATOR_TOOL_NAMES.iter()) |
| 1048 | .any(|reserved| reserved.eq_ignore_ascii_case(name)) |
| 1049 | } |
| 1050 | |
| 1051 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1052 | pub enum DynamicToolNameRefusal { |
| 1053 | Reserved, |
| 1054 | Duplicate, |
| 1055 | } |
| 1056 | |
| 1057 | impl DynamicToolNameRefusal { |
| 1058 | #[must_use] |
| 1059 | pub fn reason(self) -> &'static str { |
| 1060 | match self { |
| 1061 | Self::Reserved => "a name reserved for a built-in tool", |
| 1062 | Self::Duplicate => "the same name as an earlier dynamic tool in the request", |
| 1063 | } |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | #[must_use] |
| 1068 | pub fn dynamic_tool_name_refusal( |
| 1069 | name: &str, |
| 1070 | earlier: &[DynamicToolSpec], |
| 1071 | ) -> Option<DynamicToolNameRefusal> { |
| 1072 | if is_reserved_tool_name(name) { |
| 1073 | Some(DynamicToolNameRefusal::Reserved) |
| 1074 | } else if earlier.iter().any(|spec| spec.name == name) { |
| 1075 | Some(DynamicToolNameRefusal::Duplicate) |
| 1076 | } else { |
| 1077 | None |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | pub fn validate_dynamic_tool_names(dynamic_tools: &[DynamicToolSpec]) -> Result<(), String> { |
| 1082 | for (index, spec) in dynamic_tools.iter().enumerate() { |
| 1083 | if let Some(refusal) = dynamic_tool_name_refusal(&spec.name, &dynamic_tools[..index]) { |
| 1084 | return Err(format!( |
| 1085 | "invalid request: dynamic tool `{}` uses {}", |
| 1086 | codewhale_runtime::safe_label::SafeLabel::identifier(&spec.name), |
| 1087 | refusal.reason() |
| 1088 | )); |
| 1089 | } |
| 1090 | } |
| 1091 | Ok(()) |
| 1092 | } |
| 1093 | |
| 1094 | /// Builder for constructing a `ToolRegistry` with common tools. |
| 1095 | pub struct ToolRegistryBuilder { |
| 1096 | tools: Vec<Arc<dyn ToolSpec>>, |
| 1097 | read_only_shell: bool, |
| 1098 | } |
| 1099 | |
| 1100 | /// Feature/config-dependent native Agent-mode tool surface. |
| 1101 | /// |
| 1102 | /// Parent Agent/Yolo turns and default child sub-agents both build through this |
| 1103 | /// options object so the catalog does not drift as new first-party tools are |
| 1104 | /// gated behind feature flags or config state. |
| 1105 | #[derive(Clone)] |
| 1106 | pub struct AgentToolSurfaceOptions { |
| 1107 | pub shell_policy: codewhale_agent_contract::worker_profile::ShellPolicy, |
| 1108 | pub apply_patch_enabled: bool, |
| 1109 | pub web_search_enabled: bool, |
| 1110 | pub memory_tool_enabled: bool, |
| 1111 | pub vision_config: Option<codewhale_runtime::config::VisionModelConfig>, |
| 1112 | pub speech_output_dir: Option<PathBuf>, |
| 1113 | pub goal_state: Option<SharedGoalState>, |
| 1114 | pub goal_complete_judge: bool, |
| 1115 | pub goal_blocked_judge: bool, |
| 1116 | /// `request_user_input` payload ceilings from `[tools]` (#5949). Carried on |
| 1117 | /// the surface options so model-spawned children inherit the parent's |
| 1118 | /// configured limits instead of silently falling back to the defaults. |
| 1119 | pub user_input_limits: super::user_input::UserInputLimits, |
| 1120 | /// Register `request_plugin_install`. The engine turns this off outside |
| 1121 | /// the interactive TUI and when contextual tips are off (0.10.1 plugin |
| 1122 | /// offering policy, rules 3 and 11); children inherit the parent's value. |
| 1123 | pub request_plugin_install_enabled: bool, |
| 1124 | } |
| 1125 | |
| 1126 | impl AgentToolSurfaceOptions { |
| 1127 | #[must_use] |
| 1128 | pub fn new(shell_policy: codewhale_agent_contract::worker_profile::ShellPolicy) -> Self { |
| 1129 | Self { |
| 1130 | shell_policy, |
| 1131 | apply_patch_enabled: false, |
| 1132 | web_search_enabled: false, |
| 1133 | memory_tool_enabled: false, |
| 1134 | vision_config: None, |
| 1135 | speech_output_dir: None, |
| 1136 | goal_state: None, |
| 1137 | goal_complete_judge: false, |
| 1138 | goal_blocked_judge: false, |
| 1139 | user_input_limits: super::user_input::UserInputLimits::default(), |
| 1140 | request_plugin_install_enabled: true, |
| 1141 | } |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | impl ToolRegistryBuilder { |
| 1146 | /// Create a new builder. |
| 1147 | #[must_use] |
| 1148 | pub fn new() -> Self { |
| 1149 | Self { |
| 1150 | tools: Vec::new(), |
| 1151 | read_only_shell: false, |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | /// Add a custom tool. |
| 1156 | #[must_use] |
| 1157 | pub fn with_tool(mut self, tool: Arc<dyn ToolSpec>) -> Self { |
| 1158 | let name = tool.name().to_string(); |
| 1159 | if let Some(slot) = self |
| 1160 | .tools |
| 1161 | .iter_mut() |
| 1162 | .find(|existing| existing.name() == name) |
| 1163 | { |
| 1164 | *slot = tool; |
| 1165 | } else { |
| 1166 | self.tools.push(tool); |
| 1167 | } |
| 1168 | self |
| 1169 | } |
| 1170 | |
| 1171 | /// Add client-executed runtime tools. A dynamic tool never replaces a |
| 1172 | /// tool already in the builder (#6559 D04-10): `with_tool` treats a |
| 1173 | /// repeated name as a planned upgrade, which let a client's `exec_shell` |
| 1174 | /// or `read` silently take over the builtin handler and its approval |
| 1175 | /// policy. The model-facing name is the bare `name`, so a second dynamic |
| 1176 | /// tool with the same name in another namespace is refused the same way. |
| 1177 | /// A name in [`RESERVED_TOOL_NAMES`] is refused whether or not that tool |
| 1178 | /// is registered for this turn, so a later `with_subagent_tools` or a |
| 1179 | /// builtin gated off by mode cannot be shadowed. Every refusal is logged. |
| 1180 | /// |
| 1181 | /// Turn and thread admission reject the same specs with |
| 1182 | /// [`validate_dynamic_tool_names`] before a registry is built, so the |
| 1183 | /// runtime client is told; this refusal is defence in depth. Exposing a |
| 1184 | /// namespaced model-facing name is a protocol change. |
| 1185 | #[must_use] |
| 1186 | pub fn with_dynamic_tools(mut self, dynamic_tools: &[DynamicToolSpec]) -> Self { |
| 1187 | for (index, spec) in dynamic_tools.iter().enumerate() { |
| 1188 | let tool: Arc<dyn ToolSpec> = |
| 1189 | Arc::new(super::dynamic::RuntimeDynamicTool::new(spec.clone())); |
| 1190 | if let Some(refusal) = dynamic_tool_name_refusal(&spec.name, &dynamic_tools[..index]) { |
| 1191 | tracing::warn!( |
| 1192 | refused_origin = ?tool.registration_origin(), |
| 1193 | "Refusing runtime dynamic tool with {}: {}", |
| 1194 | refusal.reason(), |
| 1195 | codewhale_runtime::safe_label::SafeLabel::identifier(tool.name()) |
| 1196 | ); |
| 1197 | continue; |
| 1198 | } |
| 1199 | if let Some(existing) = self |
| 1200 | .tools |
| 1201 | .iter() |
| 1202 | .find(|existing| existing.name() == tool.name()) |
| 1203 | { |
| 1204 | tracing::warn!( |
| 1205 | existing_origin = ?existing.registration_origin(), |
| 1206 | refused_origin = ?tool.registration_origin(), |
| 1207 | "Refusing runtime dynamic tool that collides with a registered tool: {}", |
| 1208 | codewhale_runtime::safe_label::SafeLabel::identifier(tool.name()) |
| 1209 | ); |
| 1210 | continue; |
| 1211 | } |
| 1212 | self.tools.push(tool); |
| 1213 | } |
| 1214 | self |
| 1215 | } |
| 1216 | |
| 1217 | /// Include file tools (read, write, edit, list). |
| 1218 | #[must_use] |
| 1219 | pub fn with_file_tools(self) -> Self { |
| 1220 | use super::file::{EditFileTool, ListDirTool, ReadFileTool, WriteFileTool}; |
| 1221 | use super::file_tool::{EditTool, ReadTool, WriteTool}; |
| 1222 | self.with_tool(Arc::new(ReadTool)) |
| 1223 | .with_tool(Arc::new(WriteTool)) |
| 1224 | .with_tool(Arc::new(EditTool)) |
| 1225 | // Execution names protocol clients call directly. |
| 1226 | // `model_visible=false` keeps them out of new catalogs. |
| 1227 | .with_tool(Arc::new(ReadFileTool)) |
| 1228 | .with_tool(Arc::new(WriteFileTool)) |
| 1229 | .with_tool(Arc::new(EditFileTool)) |
| 1230 | .with_tool(Arc::new(ListDirTool)) |
| 1231 | } |
| 1232 | |
| 1233 | /// Include only read-only file tools (read, list). |
| 1234 | #[must_use] |
| 1235 | #[cfg(any(test, feature = "test-support"))] |
| 1236 | pub fn with_read_only_file_tools(self) -> Self { |
| 1237 | use super::file::{ListDirTool, ReadFileTool}; |
| 1238 | use super::file_tool::ReadTool; |
| 1239 | self.with_tool(Arc::new(ReadTool)) |
| 1240 | .with_tool(Arc::new(ReadFileTool)) |
| 1241 | .with_tool(Arc::new(ListDirTool)) |
| 1242 | .with_tool(Arc::new( |
| 1243 | super::tool_result_retrieval::RetrieveToolResultTool, |
| 1244 | )) |
| 1245 | } |
| 1246 | |
| 1247 | #[must_use] |
| 1248 | pub fn with_present_tool(self) -> Self { |
| 1249 | use super::present::PresentTool; |
| 1250 | self.with_tool(Arc::new(PresentTool)) |
| 1251 | } |
| 1252 | |
| 1253 | #[must_use] |
| 1254 | pub fn with_show_data_tool(self) -> Self { |
| 1255 | self.with_tool(Arc::new(super::show_data::ShowDataTool)) |
| 1256 | } |
| 1257 | |
| 1258 | /// Include shell execution tools. |
| 1259 | #[must_use] |
| 1260 | pub fn with_shell_tools(self) -> Self { |
| 1261 | self.with_foreground_shell_tools().with_terminal_tools() |
| 1262 | } |
| 1263 | |
| 1264 | /// Include only the cancellable foreground shell tool. |
| 1265 | /// |
| 1266 | /// Protocol hosts that cannot safely own a persistent PTY session use |
| 1267 | /// this surface instead of [`Self::with_shell_tools`]. |
| 1268 | #[must_use] |
| 1269 | pub fn with_foreground_shell_tools(self) -> Self { |
| 1270 | use super::shell::LowercaseBashTool; |
| 1271 | self.with_tool(Arc::new(LowercaseBashTool)) |
| 1272 | } |
| 1273 | |
| 1274 | /// Include only the foreground, direct-argv read-only shell surface. |
| 1275 | #[must_use] |
| 1276 | pub fn with_read_only_shell_tool(mut self) -> Self { |
| 1277 | use super::shell::LowercaseBashTool; |
| 1278 | self.read_only_shell = true; |
| 1279 | self.with_tool(Arc::new(LowercaseBashTool)) |
| 1280 | } |
| 1281 | |
| 1282 | /// Include the stateful PTY terminal tools. Like `exec_shell`, these are |
| 1283 | /// only exposed when the active shell policy allows shell access. |
| 1284 | #[cfg(not(target_env = "ohos"))] |
| 1285 | #[must_use] |
| 1286 | pub fn with_terminal_tools(self) -> Self { |
| 1287 | use super::terminal_session::{ |
| 1288 | TerminalCancelTool, TerminalResetTool, TerminalRunTool, TerminalSendTool, |
| 1289 | TerminalWaitTool, |
| 1290 | }; |
| 1291 | self.with_tool(Arc::new(TerminalRunTool)) |
| 1292 | .with_tool(Arc::new(TerminalSendTool)) |
| 1293 | .with_tool(Arc::new(TerminalWaitTool)) |
| 1294 | .with_tool(Arc::new(TerminalCancelTool)) |
| 1295 | .with_tool(Arc::new(TerminalResetTool)) |
| 1296 | } |
| 1297 | |
| 1298 | /// OpenHarmony does not include the `portable-pty` dependency, so keep the |
| 1299 | /// ordinary shell tools without advertising unavailable persistent PTYs. |
| 1300 | #[cfg(target_env = "ohos")] |
| 1301 | #[must_use] |
| 1302 | pub fn with_terminal_tools(self) -> Self { |
| 1303 | self |
| 1304 | } |
| 1305 | |
| 1306 | /// Search is part of the canonical `File` action surface. |
| 1307 | #[must_use] |
| 1308 | pub fn with_search_tools(self) -> Self { |
| 1309 | self.with_tool(Arc::new(super::file_search::FileSearchTool)) |
| 1310 | .with_tool(Arc::new(super::search::GrepFilesTool)) |
| 1311 | } |
| 1312 | |
| 1313 | /// Include the canonical `Git` inspection/history surface. |
| 1314 | #[must_use] |
| 1315 | pub fn with_git_tools(self) -> Self { |
| 1316 | use super::git_tool::GitTool; |
| 1317 | self.with_tool(Arc::new(GitTool::new("Git"))) |
| 1318 | } |
| 1319 | |
| 1320 | /// Git history is part of the canonical `Git` action surface. |
| 1321 | #[must_use] |
| 1322 | pub fn with_git_history_tools(self) -> Self { |
| 1323 | self |
| 1324 | } |
| 1325 | |
| 1326 | /// Include the `tui_help` command/keybinding reference (#1708). The |
| 1327 | /// catalog it reads is compiled in, so there is nothing to probe. |
| 1328 | #[must_use] |
| 1329 | pub fn with_tui_help_tool(self) -> Self { |
| 1330 | use super::tui_help::TuiHelpTool; |
| 1331 | self.with_tool(Arc::new(TuiHelpTool)) |
| 1332 | } |
| 1333 | |
| 1334 | /// Include the `pandoc_convert` tool only when the `pandoc` |
| 1335 | /// binary is present on this host. Same probe-then-decide |
| 1336 | /// pattern v0.8.31 introduced for Python — when pandoc is |
| 1337 | /// missing the tool is not registered, so the model never |
| 1338 | /// sees a binary it can't actually use. |
| 1339 | #[must_use] |
| 1340 | pub fn with_pandoc_tools(self) -> Self { |
| 1341 | if codewhale_dependencies::host_tool_available("pandoc_convert", || { |
| 1342 | codewhale_dependencies::resolve_pandoc().is_some() |
| 1343 | }) { |
| 1344 | use super::pandoc::PandocConvertTool; |
| 1345 | self.with_tool(Arc::new(PandocConvertTool)) |
| 1346 | } else { |
| 1347 | self |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | /// Include the `image_ocr` tool only when a local OCR backend is present. |
| 1352 | /// macOS uses the built-in Vision framework, while other platforms use |
| 1353 | /// Tesseract when installed. |
| 1354 | #[must_use] |
| 1355 | pub fn with_image_ocr_tools(self) -> Self { |
| 1356 | if codewhale_dependencies::host_tool_available("image_ocr", super::image_ocr::ocr_available) |
| 1357 | { |
| 1358 | use super::image_ocr::ImageOcrTool; |
| 1359 | self.with_tool(Arc::new(ImageOcrTool)) |
| 1360 | } else { |
| 1361 | self |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | /// Include the `read_media` tool for safe multimodal media inspection. |
| 1366 | #[must_use] |
| 1367 | pub fn with_read_media_tool(self) -> Self { |
| 1368 | use super::read_media::ReadMediaTool; |
| 1369 | self.with_tool(Arc::new(ReadMediaTool)) |
| 1370 | } |
| 1371 | |
| 1372 | /// Include the `load_skill` tool (#434) so the model can pull a |
| 1373 | /// SKILL.md body + companion file list into context with one |
| 1374 | /// call instead of `read_file` + `list_dir` against the path |
| 1375 | /// shown in the system prompt's `## Skills` section. |
| 1376 | #[must_use] |
| 1377 | pub fn with_skill_tools(self) -> Self { |
| 1378 | use super::skill::LoadSkillTool; |
| 1379 | self.with_tool(Arc::new(LoadSkillTool)) |
| 1380 | } |
| 1381 | |
| 1382 | /// Include cargo test runner tool. |
| 1383 | #[must_use] |
| 1384 | pub fn with_test_runner_tool(self) -> Self { |
| 1385 | use super::run_tool::RunTool; |
| 1386 | self.with_tool(Arc::new(RunTool::new("Run"))) |
| 1387 | } |
| 1388 | |
| 1389 | /// Include structured data validation tool (`validate_data`). |
| 1390 | #[must_use] |
| 1391 | pub fn with_validation_tools(self) -> Self { |
| 1392 | use super::validate_data::ValidateDataTool; |
| 1393 | self.with_tool(Arc::new(ValidateDataTool)) |
| 1394 | } |
| 1395 | |
| 1396 | /// Include retrieval for spilled historical tool results. |
| 1397 | #[must_use] |
| 1398 | pub fn with_tool_result_retrieval_tool(self) -> Self { |
| 1399 | use super::tool_result_retrieval::RetrieveToolResultTool; |
| 1400 | self.with_tool(Arc::new(RetrieveToolResultTool)) |
| 1401 | } |
| 1402 | |
| 1403 | /// Include reads of the pre-compaction transcript archive. |
| 1404 | #[must_use] |
| 1405 | pub fn with_compaction_archive_tools(self) -> Self { |
| 1406 | use super::context_archive::ContextArchiveSearchTool; |
| 1407 | self.with_tool(Arc::new(ContextArchiveSearchTool)) |
| 1408 | } |
| 1409 | |
| 1410 | /// Include durable task, gate, PR-attempt, GitHub, and automation tools. |
| 1411 | /// |
| 1412 | /// Each family is one tool with an `action` parameter (`tasks`, `github`, |
| 1413 | /// `automation`). Per-action execution aliases were removed in v0.9.3. |
| 1414 | /// |
| 1415 | /// The shell-related task tool (`task_shell_wait`) is *not* included here — |
| 1416 | /// use `with_runtime_task_shell_tools` to register it when `allow_shell` |
| 1417 | /// is true. |
| 1418 | #[must_use] |
| 1419 | pub fn with_runtime_task_tools(self) -> Self { |
| 1420 | use super::automation::AutomationTool; |
| 1421 | use super::github::GithubTool; |
| 1422 | use super::send_later::SendLaterTool; |
| 1423 | use super::tasks::TasksTool; |
| 1424 | |
| 1425 | self.with_tool(Arc::new(TasksTool::new("tasks"))) |
| 1426 | .with_tool(Arc::new(GithubTool::new("github"))) |
| 1427 | .with_tool(Arc::new(AutomationTool::new("automation"))) |
| 1428 | .with_tool(Arc::new(SendLaterTool::new("send_later"))) |
| 1429 | } |
| 1430 | |
| 1431 | /// Include the shell-related task tool (`task_shell_wait`). |
| 1432 | /// |
| 1433 | /// Gated behind `allow_shell` because it polls and cancels the background |
| 1434 | /// jobs that `Bash` starts; background work has one entry point, the shell |
| 1435 | /// tool's `background=true`. |
| 1436 | #[must_use] |
| 1437 | pub fn with_runtime_task_shell_tools(self) -> Self { |
| 1438 | use super::tasks::TaskShellWaitTool; |
| 1439 | self.with_tool(Arc::new(TaskShellWaitTool)) |
| 1440 | } |
| 1441 | |
| 1442 | /// Include only read-only durable task, PR-attempt, GitHub, and automation |
| 1443 | /// inspection tools. Plan mode uses this surface so it can observe state |
| 1444 | /// without starting work, changing remotes, or mutating automation config. |
| 1445 | /// |
| 1446 | /// The model sees the same canonical `tasks` / `github` / `automation` / |
| 1447 | /// `send_later` tools as the full surface, restricted to their read-only |
| 1448 | /// actions. |
| 1449 | #[must_use] |
| 1450 | pub fn with_runtime_read_only_task_tools(self) -> Self { |
| 1451 | use super::automation::AutomationTool; |
| 1452 | use super::github::GithubTool; |
| 1453 | use super::send_later::SendLaterTool; |
| 1454 | use super::tasks::TasksTool; |
| 1455 | |
| 1456 | self.with_tool(Arc::new(TasksTool::read_only("tasks"))) |
| 1457 | .with_tool(Arc::new(GithubTool::read_only("github"))) |
| 1458 | .with_tool(Arc::new(AutomationTool::read_only("automation"))) |
| 1459 | .with_tool(Arc::new(SendLaterTool::read_only("send_later"))) |
| 1460 | } |
| 1461 | |
| 1462 | /// Include web search and fetch tools. |
| 1463 | /// |
| 1464 | /// These are feature-gated behind `Feature::WebSearch` in `tool_setup.rs`. |
| 1465 | #[must_use] |
| 1466 | pub fn with_web_tools(self) -> Self { |
| 1467 | use super::web_run::WebRunTool; |
| 1468 | use super::web_tool::WebTool; |
| 1469 | self.with_tool(Arc::new(WebTool::new("Web"))) |
| 1470 | .with_tool(Arc::new(WebRunTool)) |
| 1471 | } |
| 1472 | |
| 1473 | /// Register the `image_analyze` vision tool. |
| 1474 | /// Only registered when `[vision_model]` is configured in config.toml. |
| 1475 | #[must_use] |
| 1476 | pub fn with_vision_tools( |
| 1477 | self, |
| 1478 | config: codewhale_runtime::config::VisionModelConfig, |
| 1479 | route_client: Option<CodewhaleClient>, |
| 1480 | ) -> Self { |
| 1481 | use crate::vision::tools::ImageAnalyzeTool; |
| 1482 | self.with_tool(Arc::new(ImageAnalyzeTool::new_with_route_client( |
| 1483 | config, |
| 1484 | route_client, |
| 1485 | ))) |
| 1486 | } |
| 1487 | |
| 1488 | /// Include request_user_input tool under the session's configured payload |
| 1489 | /// ceilings (`[tools] user_input_max_questions` / `user_input_max_options`, |
| 1490 | /// #5949). The limits ride the tool instance so the validator, the JSON |
| 1491 | /// schema, and the model-visible description cannot drift apart. |
| 1492 | #[must_use] |
| 1493 | pub fn with_user_input_tool(self, limits: super::user_input::UserInputLimits) -> Self { |
| 1494 | use super::user_input::RequestUserInputTool; |
| 1495 | self.with_tool(Arc::new(RequestUserInputTool::new(limits))) |
| 1496 | } |
| 1497 | |
| 1498 | /// Include patch tools (`apply_patch`). |
| 1499 | #[must_use] |
| 1500 | pub fn with_patch_tools(self) -> Self { |
| 1501 | self.with_tool(Arc::new(super::apply_patch::ApplyPatchTool)) |
| 1502 | } |
| 1503 | |
| 1504 | /// Include the `revert_turn` tool. Approval-gated since it mutates |
| 1505 | /// the workspace; the model uses it when the user asks to "undo my |
| 1506 | /// last edit". Backed by the per-workspace snapshot side-repo |
| 1507 | /// (`codewhale_snapshot`). |
| 1508 | #[must_use] |
| 1509 | pub fn with_revert_turn_tool(self) -> Self { |
| 1510 | use super::revert_turn::RevertTurnTool; |
| 1511 | self.with_tool(Arc::new(RevertTurnTool)) |
| 1512 | } |
| 1513 | |
| 1514 | /// Include the `speech` (TTS) tool. |
| 1515 | #[must_use] |
| 1516 | pub fn with_speech_tools( |
| 1517 | self, |
| 1518 | client: Option<CodewhaleClient>, |
| 1519 | output_dir: Option<PathBuf>, |
| 1520 | ) -> Self { |
| 1521 | use super::speech::SpeechTool; |
| 1522 | self.with_tool(Arc::new(SpeechTool::new(client, output_dir))) |
| 1523 | } |
| 1524 | |
| 1525 | /// Include the canonical persistent RLM session tool. |
| 1526 | #[must_use] |
| 1527 | pub fn with_rlm_tool(self) -> Self { |
| 1528 | use super::rlm::RlmTool; |
| 1529 | self.with_tool(Arc::new(RlmTool::new(super::rlm::RLM_TOOL_NAME))) |
| 1530 | } |
| 1531 | |
| 1532 | /// Include `handle_read`, the bounded projection reader for symbolic |
| 1533 | /// `var_handle` payloads. |
| 1534 | #[must_use] |
| 1535 | pub fn with_handle_tools(self) -> Self { |
| 1536 | use super::handle::HandleReadTool; |
| 1537 | self.with_tool(Arc::new(HandleReadTool)) |
| 1538 | } |
| 1539 | |
| 1540 | /// Include the review tool. |
| 1541 | #[must_use] |
| 1542 | pub fn with_review_tool(self, client: Option<CodewhaleClient>, model: String) -> Self { |
| 1543 | use super::review::ReviewTool; |
| 1544 | self.with_tool(Arc::new(ReviewTool::new(client, model))) |
| 1545 | } |
| 1546 | |
| 1547 | /// Include the FIM (Fill-in-the-Middle) edit tool. |
| 1548 | #[must_use] |
| 1549 | pub fn with_fim_tool(self, client: Option<CodewhaleClient>, model: String) -> Self { |
| 1550 | use super::fim::FimEditTool; |
| 1551 | let Some(client) = client.filter(CodewhaleClient::can_request_fim_completion) else { |
| 1552 | return self; |
| 1553 | }; |
| 1554 | self.with_tool(Arc::new(FimEditTool::new(Some(client), model))) |
| 1555 | } |
| 1556 | |
| 1557 | /// Include the `remember` tool — model-callable bullet-add into the |
| 1558 | /// user memory file (#489). Only register when the user has opted |
| 1559 | /// in to the memory feature; without that, the tool would surface |
| 1560 | /// in the model's catalog but always fail with "memory disabled". |
| 1561 | #[must_use] |
| 1562 | pub fn with_remember_tool(self) -> Self { |
| 1563 | use super::remember::RememberTool; |
| 1564 | self.with_tool(Arc::new(RememberTool)) |
| 1565 | } |
| 1566 | |
| 1567 | /// Include the native-memory retrieval tool alongside reviewed capture. |
| 1568 | #[must_use] |
| 1569 | pub fn with_native_memory_tools(self) -> Self { |
| 1570 | use super::native_memory::MemorySearchTool; |
| 1571 | self.with_tool(Arc::new(MemorySearchTool)) |
| 1572 | } |
| 1573 | |
| 1574 | /// Include the prior-session recall tool (#5715). Always-on: it is |
| 1575 | /// read-only and workspace-scoped, so there is no opt-in to honor. |
| 1576 | #[must_use] |
| 1577 | pub fn with_session_recall_tools(self) -> Self { |
| 1578 | use super::session::SessionSearchTool; |
| 1579 | self.with_tool(Arc::new(SessionSearchTool)) |
| 1580 | } |
| 1581 | |
| 1582 | /// Include the model-facing LSP intelligence tools. They reuse the |
| 1583 | /// session [`codewhale_lsp::LspManager`] attached to `ToolContext` and never |
| 1584 | /// spawn a second server lifecycle. |
| 1585 | #[must_use] |
| 1586 | pub fn with_lsp_tool(self) -> Self { |
| 1587 | use super::lsp::LspTool; |
| 1588 | self.with_tool(Arc::new(LspTool)) |
| 1589 | } |
| 1590 | |
| 1591 | /// Include the `notify` tool — model-callable desktop notification |
| 1592 | /// (#1322). Routes through the existing `tui::notifications` OSC 9 / |
| 1593 | /// BEL pipeline so the user's `[notifications].method` config is |
| 1594 | /// honoured automatically (including `off`). Always safe to register |
| 1595 | /// because the tool has no side effects beyond a single terminal |
| 1596 | /// escape write. |
| 1597 | #[must_use] |
| 1598 | pub fn with_notify_tool(self) -> Self { |
| 1599 | use super::notify::NotifyTool; |
| 1600 | self.with_tool(Arc::new(NotifyTool)) |
| 1601 | } |
| 1602 | |
| 1603 | /// Include `request_plugin_install` — model-callable review request. |
| 1604 | /// Never installs; the TUI surfaces `/plugin trust` or catalog install |
| 1605 | /// for the human. |
| 1606 | #[must_use] |
| 1607 | pub fn with_request_plugin_install_tool(self) -> Self { |
| 1608 | use super::request_plugin_install::RequestPluginInstallTool; |
| 1609 | self.with_tool(Arc::new(RequestPluginInstallTool)) |
| 1610 | } |
| 1611 | |
| 1612 | /// Include MCP tools from a connected pool as first-class registry |
| 1613 | /// citizens. Each MCP tool is wrapped in a lightweight adapter that |
| 1614 | /// implements `ToolSpec`, so the unified `ToolRegistryBuilder` flow |
| 1615 | /// handles them alongside native tools. |
| 1616 | /// |
| 1617 | /// MCP tools are marked `defer_loading` by default (except discovery |
| 1618 | /// helpers) to keep the model-visible catalog compact. |
| 1619 | #[must_use] |
| 1620 | pub async fn with_mcp_tools( |
| 1621 | mut self, |
| 1622 | mcp_pool: std::sync::Arc<tokio::sync::Mutex<crate::mcp::McpPool>>, |
| 1623 | ) -> Self { |
| 1624 | let pool = mcp_pool.lock().await; |
| 1625 | let tool_servers = pool.resolved_tool_servers(); |
| 1626 | for (name, tool) in pool.all_tools() { |
| 1627 | let adapter = Arc::new(McpToolAdapter { |
| 1628 | delegated_read: tool_servers |
| 1629 | .get(&name) |
| 1630 | .and_then(|server| pool.delegated_read_for(&name, server, &tool.name)), |
| 1631 | server_name: tool_servers.get(&name).cloned(), |
| 1632 | name: name.clone(), |
| 1633 | tool: tool.clone(), |
| 1634 | pool: mcp_pool.clone(), |
| 1635 | }); |
| 1636 | self.tools.push(adapter); |
| 1637 | } |
| 1638 | drop(pool); |
| 1639 | self |
| 1640 | } |
| 1641 | |
| 1642 | /// Register the `start_mcp_server` tool for dynamically adding MCP servers |
| 1643 | /// from conversation context. Does not register MCP tool adapters — those |
| 1644 | /// are returned by `pool.to_api_tools()` in `engine.mcp_tools()`. |
| 1645 | #[must_use] |
| 1646 | pub fn with_runtime_mcp_tool( |
| 1647 | mut self, |
| 1648 | mcp_pool: std::sync::Arc<tokio::sync::Mutex<crate::mcp::McpPool>>, |
| 1649 | ) -> Self { |
| 1650 | self.tools |
| 1651 | .push(Arc::new(super::runtime_mcp::StartRuntimeMcpServer::new( |
| 1652 | mcp_pool, |
| 1653 | ))); |
| 1654 | self |
| 1655 | } |
| 1656 | |
| 1657 | /// Register the `registry_sync` tool for fetching and caching |
| 1658 | /// MCP Registry server metadata. |
| 1659 | #[must_use] |
| 1660 | pub fn with_registry_mcp_sync_tool(mut self) -> Self { |
| 1661 | self.tools |
| 1662 | .push(Arc::new(super::mcp_registry::McpSyncRegistry::new())); |
| 1663 | self |
| 1664 | } |
| 1665 | |
| 1666 | /// Register the structured Registry launcher. Unlike `start_mcp_server`, |
| 1667 | /// this accepts no free-form command and can only launch cached, |
| 1668 | /// zero-environment stdio candidates. |
| 1669 | #[must_use] |
| 1670 | pub fn with_registry_mcp_start_tool( |
| 1671 | mut self, |
| 1672 | mcp_pool: std::sync::Arc<tokio::sync::Mutex<crate::mcp::McpPool>>, |
| 1673 | ) -> Self { |
| 1674 | self.tools |
| 1675 | .push(Arc::new(super::mcp_registry::StartRegistryMcpServer::new( |
| 1676 | mcp_pool, |
| 1677 | ))); |
| 1678 | self |
| 1679 | } |
| 1680 | |
| 1681 | /// Include all agent tools under a typed shell policy. |
| 1682 | #[must_use] |
| 1683 | pub fn with_agent_tools_policy( |
| 1684 | self, |
| 1685 | shell_policy: codewhale_agent_contract::worker_profile::ShellPolicy, |
| 1686 | user_input_limits: super::user_input::UserInputLimits, |
| 1687 | ) -> Self { |
| 1688 | let builder = self |
| 1689 | .with_file_tools() |
| 1690 | .with_present_tool() |
| 1691 | .with_show_data_tool() |
| 1692 | .with_search_tools() |
| 1693 | .with_user_input_tool(user_input_limits) |
| 1694 | .with_git_tools() |
| 1695 | .with_git_history_tools() |
| 1696 | .with_tui_help_tool() |
| 1697 | .with_lsp_tool() |
| 1698 | .with_skill_tools() |
| 1699 | .with_test_runner_tool() |
| 1700 | .with_validation_tools() |
| 1701 | .with_tool_result_retrieval_tool() |
| 1702 | .with_compaction_archive_tools() |
| 1703 | .with_handle_tools() |
| 1704 | .with_runtime_task_tools() |
| 1705 | .with_revert_turn_tool() |
| 1706 | .with_pandoc_tools() |
| 1707 | .with_image_ocr_tools() |
| 1708 | .with_read_media_tool(); |
| 1709 | |
| 1710 | match shell_policy { |
| 1711 | codewhale_agent_contract::worker_profile::ShellPolicy::Full => { |
| 1712 | builder.with_shell_tools().with_runtime_task_shell_tools() |
| 1713 | } |
| 1714 | codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly => { |
| 1715 | builder.with_read_only_shell_tool() |
| 1716 | } |
| 1717 | codewhale_agent_contract::worker_profile::ShellPolicy::None => builder, |
| 1718 | } |
| 1719 | } |
| 1720 | |
| 1721 | /// Include the native Agent-mode surface shared by the parent runtime and |
| 1722 | /// default child sub-agents, excluding the `agent` launcher itself. |
| 1723 | #[must_use] |
| 1724 | pub fn with_agent_runtime_surface( |
| 1725 | self, |
| 1726 | client: Option<CodewhaleClient>, |
| 1727 | model: String, |
| 1728 | options: AgentToolSurfaceOptions, |
| 1729 | todo_list: super::todo::SharedTodoList, |
| 1730 | ) -> Self { |
| 1731 | let speech_client = client.clone(); |
| 1732 | let vision_client = client.clone(); |
| 1733 | let mut builder = self |
| 1734 | .with_agent_tools_policy(options.shell_policy, options.user_input_limits) |
| 1735 | .with_todo_tool(todo_list) |
| 1736 | .with_review_tool(client.clone(), model.clone()) |
| 1737 | .with_rlm_tool() |
| 1738 | .with_fim_tool(client, model); |
| 1739 | |
| 1740 | // No client means no speech provider to call: do not advertise a |
| 1741 | // capability the session cannot deliver (#5941). |
| 1742 | if speech_client.is_some() { |
| 1743 | builder = builder.with_speech_tools(speech_client, options.speech_output_dir.clone()); |
| 1744 | } |
| 1745 | |
| 1746 | if let Some(goal_state) = options.goal_state { |
| 1747 | let gate = super::goal::GoalGate::from_flags( |
| 1748 | options.goal_complete_judge, |
| 1749 | options.goal_blocked_judge, |
| 1750 | None, |
| 1751 | ); |
| 1752 | builder = builder.with_goal_tools(goal_state, gate); |
| 1753 | } |
| 1754 | if options.apply_patch_enabled { |
| 1755 | builder = builder.with_patch_tools(); |
| 1756 | } |
| 1757 | if options.web_search_enabled { |
| 1758 | builder = builder.with_web_tools(); |
| 1759 | } |
| 1760 | if options.memory_tool_enabled { |
| 1761 | builder = builder.with_remember_tool().with_native_memory_tools(); |
| 1762 | } |
| 1763 | if let Some(vision_config) = options.vision_config { |
| 1764 | builder = builder.with_vision_tools(vision_config, vision_client); |
| 1765 | } |
| 1766 | |
| 1767 | builder = builder.with_notify_tool(); |
| 1768 | if options.request_plugin_install_enabled { |
| 1769 | builder = builder.with_request_plugin_install_tool(); |
| 1770 | } |
| 1771 | builder.with_session_recall_tools() |
| 1772 | } |
| 1773 | |
| 1774 | /// Include the full child-inherited Agent surface under resolved |
| 1775 | /// feature/config options. |
| 1776 | #[must_use] |
| 1777 | #[allow(clippy::too_many_arguments)] |
| 1778 | pub fn with_full_agent_surface_options( |
| 1779 | self, |
| 1780 | client: Option<CodewhaleClient>, |
| 1781 | model: String, |
| 1782 | manager: super::subagent::SharedSubAgentManager, |
| 1783 | runtime: super::subagent::SubAgentRuntime, |
| 1784 | options: AgentToolSurfaceOptions, |
| 1785 | todo_list: super::todo::SharedTodoList, |
| 1786 | ) -> Self { |
| 1787 | self.with_agent_runtime_surface(client, model, options, todo_list) |
| 1788 | .with_subagent_tools(manager, runtime) |
| 1789 | } |
| 1790 | |
| 1791 | /// Include the `todo_write` work-progress tool with a shared `TodoList`. |
| 1792 | #[must_use] |
| 1793 | pub fn with_todo_tool(self, todo_list: super::todo::SharedTodoList) -> Self { |
| 1794 | use super::todo::TodoWriteTool; |
| 1795 | self.with_tool(Arc::new(TodoWriteTool::new(todo_list))) |
| 1796 | } |
| 1797 | |
| 1798 | /// Include runtime goal tools (`create_goal`, `get_goal`, `update_goal`). |
| 1799 | #[must_use] |
| 1800 | pub fn with_goal_tools( |
| 1801 | self, |
| 1802 | goal_state: super::goal::SharedGoalState, |
| 1803 | gate: Option<Arc<super::goal::GoalGate>>, |
| 1804 | ) -> Self { |
| 1805 | use super::goal::{CreateGoalTool, GetGoalTool, UpdateGoalTool}; |
| 1806 | self.with_tool(Arc::new(CreateGoalTool::new(goal_state.clone()))) |
| 1807 | .with_tool(Arc::new(GetGoalTool::new(goal_state.clone()))) |
| 1808 | .with_tool(Arc::new(UpdateGoalTool::new(goal_state).with_gate(gate))) |
| 1809 | } |
| 1810 | |
| 1811 | /// Include sub-agent management tools. |
| 1812 | #[must_use] |
| 1813 | pub fn with_subagent_tools( |
| 1814 | self, |
| 1815 | manager: super::subagent::SharedSubAgentManager, |
| 1816 | runtime: super::subagent::SubAgentRuntime, |
| 1817 | ) -> Self { |
| 1818 | use super::subagent::AgentTool; |
| 1819 | use super::workflow::WorkflowTool; |
| 1820 | |
| 1821 | let goal_gate_opts = ( |
| 1822 | runtime.agent_tool_surface_options.goal_state.clone(), |
| 1823 | runtime.agent_tool_surface_options.goal_complete_judge, |
| 1824 | runtime.agent_tool_surface_options.goal_blocked_judge, |
| 1825 | ); |
| 1826 | let mut builder = self |
| 1827 | .with_tool(Arc::new(WorkflowTool::new( |
| 1828 | Arc::clone(&manager), |
| 1829 | runtime.clone(), |
| 1830 | ))) |
| 1831 | .with_tool(Arc::new(AgentTool::new( |
| 1832 | Arc::clone(&manager), |
| 1833 | runtime.clone(), |
| 1834 | ))); |
| 1835 | if let (Some(goal_state), complete, blocked) = goal_gate_opts |
| 1836 | && (complete || blocked) |
| 1837 | { |
| 1838 | let gate = super::goal::GoalGate::from_flags( |
| 1839 | complete, |
| 1840 | blocked, |
| 1841 | Some((Arc::clone(&manager), runtime.clone())), |
| 1842 | ); |
| 1843 | builder.tools.retain(|tool| tool.name() != "update_goal"); |
| 1844 | builder = builder.with_tool(Arc::new( |
| 1845 | super::goal::UpdateGoalTool::new(goal_state).with_gate(gate), |
| 1846 | )); |
| 1847 | } |
| 1848 | builder |
| 1849 | } |
| 1850 | |
| 1851 | /// Build the registry with the given context. |
| 1852 | #[must_use] |
| 1853 | pub fn build(self, context: ToolContext) -> ToolRegistry { |
| 1854 | // A route known to be text-only cannot see what `read_media` returns, |
| 1855 | // so it is not offered there (`image_ocr` remains for text in images). |
| 1856 | let blind = context.route_capabilities.image_input |
| 1857 | == codewhale_config::route::CapabilityState::Unsupported; |
| 1858 | let mut registry = ToolRegistry::new(context); |
| 1859 | registry.read_only_shell = self.read_only_shell; |
| 1860 | registry.register_all( |
| 1861 | self.tools |
| 1862 | .into_iter() |
| 1863 | .filter(|tool| !(blind && tool.name() == "read_media")) |
| 1864 | .collect(), |
| 1865 | ); |
| 1866 | registry |
| 1867 | } |
| 1868 | } |
| 1869 | |
| 1870 | impl Default for ToolRegistryBuilder { |
| 1871 | fn default() -> Self { |
| 1872 | Self::new() |
| 1873 | } |
| 1874 | } |
| 1875 | |
| 1876 | /// Convert CamelCase to snake_case. |
| 1877 | fn to_snake_case(s: &str) -> String { |
| 1878 | let mut out = String::with_capacity(s.len() + 4); |
| 1879 | for (i, ch) in s.chars().enumerate() { |
| 1880 | if ch.is_uppercase() { |
| 1881 | if i > 0 { |
| 1882 | out.push('_'); |
| 1883 | } |
| 1884 | out.push(ch.to_ascii_lowercase()); |
| 1885 | } else { |
| 1886 | out.push(ch); |
| 1887 | } |
| 1888 | } |
| 1889 | out |
| 1890 | } |
| 1891 | |
| 1892 | /// Adapter that wraps an MCP tool definition so it can live in the |
| 1893 | /// unified `ToolRegistry` alongside native tools (§5.B). |
| 1894 | struct McpToolAdapter { |
| 1895 | delegated_read: Option<Arc<crate::mcp::DelegatedMcpRead>>, |
| 1896 | name: String, |
| 1897 | /// Diagnostic snapshot from the pool's exact route projection. |
| 1898 | server_name: Option<String>, |
| 1899 | tool: crate::mcp::McpTool, |
| 1900 | pool: std::sync::Arc<tokio::sync::Mutex<crate::mcp::McpPool>>, |
| 1901 | } |
| 1902 | |
| 1903 | fn is_mcp_read_helper(name: &str) -> bool { |
| 1904 | matches!( |
| 1905 | name, |
| 1906 | "list_mcp_resources" |
| 1907 | | "list_mcp_resource_templates" |
| 1908 | | "mcp_read_resource" |
| 1909 | | "read_mcp_resource" |
| 1910 | | "mcp_get_prompt" |
| 1911 | ) |
| 1912 | } |
| 1913 | |
| 1914 | #[async_trait::async_trait] |
| 1915 | impl ToolSpec for McpToolAdapter { |
| 1916 | fn delegated_mcp_read(&self) -> Option<Arc<crate::mcp::DelegatedMcpRead>> { |
| 1917 | self.delegated_read.clone() |
| 1918 | } |
| 1919 | |
| 1920 | fn name(&self) -> &str { |
| 1921 | &self.name |
| 1922 | } |
| 1923 | |
| 1924 | fn registration_origin(&self) -> std::borrow::Cow<'_, str> { |
| 1925 | use codewhale_runtime::safe_label::SafeLabel; |
| 1926 | match &self.server_name { |
| 1927 | Some(server) => format!( |
| 1928 | "MCP server {}, tool {}", |
| 1929 | SafeLabel::identifier(server), |
| 1930 | SafeLabel::identifier(&self.tool.name) |
| 1931 | ) |
| 1932 | .into(), |
| 1933 | None => format!( |
| 1934 | "MCP tool {} (server unknown)", |
| 1935 | SafeLabel::identifier(&self.name) |
| 1936 | ) |
| 1937 | .into(), |
| 1938 | } |
| 1939 | } |
| 1940 | |
| 1941 | fn description(&self) -> &str { |
| 1942 | // McpTool.description is Option<String>; fall back to the |
| 1943 | // prefixed name when absent. |
| 1944 | self.tool.description.as_deref().unwrap_or(&self.name) |
| 1945 | } |
| 1946 | |
| 1947 | fn input_schema(&self) -> Value { |
| 1948 | self.tool.input_schema.clone() |
| 1949 | } |
| 1950 | |
| 1951 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 1952 | // Conservatively treat MCP tools as requiring approval and |
| 1953 | // network access unless they're known discovery helpers. |
| 1954 | if is_mcp_read_helper(&self.name) { |
| 1955 | vec![ToolCapability::ReadOnly] |
| 1956 | } else if self.delegated_read.is_some() { |
| 1957 | vec![ |
| 1958 | ToolCapability::ReadOnly, |
| 1959 | ToolCapability::Network, |
| 1960 | ToolCapability::RequiresApproval, |
| 1961 | ] |
| 1962 | } else { |
| 1963 | vec![ToolCapability::Network, ToolCapability::RequiresApproval] |
| 1964 | } |
| 1965 | } |
| 1966 | |
| 1967 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 1968 | if is_mcp_read_helper(&self.name) { |
| 1969 | ApprovalRequirement::Auto |
| 1970 | } else { |
| 1971 | ApprovalRequirement::Required |
| 1972 | } |
| 1973 | } |
| 1974 | |
| 1975 | fn defer_loading(&self) -> bool { |
| 1976 | // Discovery helpers stay loaded; everything else is deferred. |
| 1977 | !is_mcp_read_helper(&self.name) |
| 1978 | } |
| 1979 | |
| 1980 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 1981 | self.execute_rich(input, context) |
| 1982 | .await |
| 1983 | .map(RichToolResult::into_result) |
| 1984 | } |
| 1985 | |
| 1986 | async fn execute_rich( |
| 1987 | &self, |
| 1988 | input: Value, |
| 1989 | context: &ToolContext, |
| 1990 | ) -> Result<RichToolResult, ToolError> { |
| 1991 | crate::profile_constitution::admit_desktop_browser_call( |
| 1992 | &self.name, |
| 1993 | context.account_fence.as_deref(), |
| 1994 | ) |
| 1995 | .await?; |
| 1996 | let mut refused = false; |
| 1997 | let admit = |pool: &mut crate::mcp::McpPool| { |
| 1998 | let admitted = match context.plugin_registry.as_ref() { |
| 1999 | Some(plugins) => pool.bind_caller_plugins(Arc::clone(plugins)), |
| 2000 | None => Ok(()), |
| 2001 | } |
| 2002 | .and_then(|()| pool.validate_native_caller(context.plugin_registry.as_deref())); |
| 2003 | refused = admitted.is_err(); |
| 2004 | admitted |
| 2005 | }; |
| 2006 | if context.child_host.is_some() |
| 2007 | && let Some(grant) = &self.delegated_read |
| 2008 | { |
| 2009 | let result = crate::mcp::call_delegated_read_unlocked( |
| 2010 | &self.pool, |
| 2011 | grant, |
| 2012 | &self.name, |
| 2013 | input, |
| 2014 | &context.disallowed_tools, |
| 2015 | admit, |
| 2016 | ) |
| 2017 | .await; |
| 2018 | return match result { |
| 2019 | Ok(result) => Ok(mcp_result_to_bounded_rich_tool_result(result)), |
| 2020 | Err(error) if refused => Err(ToolError::not_available(error.to_string())), |
| 2021 | Err(error) => Err(ToolError::permission_denied(error.to_string())), |
| 2022 | }; |
| 2023 | } |
| 2024 | let result = crate::mcp::call_tool_unlocked( |
| 2025 | &self.pool, |
| 2026 | &self.name, |
| 2027 | input, |
| 2028 | &context.disallowed_tools, |
| 2029 | context.human_decision.as_ref(), |
| 2030 | admit, |
| 2031 | ) |
| 2032 | .await; |
| 2033 | match result { |
| 2034 | Ok(result) => Ok(mcp_result_to_bounded_rich_tool_result(result)), |
| 2035 | Err(error) if refused => Err(ToolError::not_available(error.to_string())), |
| 2036 | Err(error) => Err(ToolError::execution_failed(format!( |
| 2037 | "MCP tool failed: {error}" |
| 2038 | ))), |
| 2039 | } |
| 2040 | } |
| 2041 | } |
| 2042 | |
| 2043 | const MCP_IMAGE_TEXT_PLACEHOLDER: &str = "[MCP image payload removed from text output]"; |
| 2044 | |
| 2045 | /// Map an MCP `tools/call` result to the provider-neutral rich result used by |
| 2046 | /// native tools. Image payloads travel as typed blocks instead of being |
| 2047 | /// duplicated into the JSON text as multi-megabyte base64 strings. |
| 2048 | /// |
| 2049 | /// MCP servers signal tool failure with `isError: true` on an otherwise |
| 2050 | /// successful JSON-RPC response. Error results keep their text payload |
| 2051 | /// verbatim so the model still sees the server's message (#5123-class). |
| 2052 | fn mcp_result_to_rich_tool_result(mut result: Value) -> RichToolResult { |
| 2053 | let mut content_blocks = Vec::new(); |
| 2054 | if let Some(object) = result.as_object_mut() { |
| 2055 | object.remove("_meta"); |
| 2056 | object.remove("resultType"); |
| 2057 | } |
| 2058 | if let Some(items) = result.get_mut("content").and_then(Value::as_array_mut) { |
| 2059 | for item in items { |
| 2060 | let Some(object) = item.as_object_mut() else { |
| 2061 | continue; |
| 2062 | }; |
| 2063 | object.remove("_meta"); |
| 2064 | if object.get("type").and_then(Value::as_str) != Some("image") { |
| 2065 | continue; |
| 2066 | } |
| 2067 | |
| 2068 | let mime_type = object |
| 2069 | .get("mimeType") |
| 2070 | .and_then(Value::as_str) |
| 2071 | .map(str::to_owned); |
| 2072 | let data = object.remove("data"); |
| 2073 | if data.is_some() { |
| 2074 | object.insert( |
| 2075 | "data".to_string(), |
| 2076 | Value::String(MCP_IMAGE_TEXT_PLACEHOLDER.to_string()), |
| 2077 | ); |
| 2078 | } |
| 2079 | // Keep malformed image entries in the typed stream with empty |
| 2080 | // fields so the shared rich-result boundary rejects them and |
| 2081 | // emits the same visible omission receipt as invalid base64, |
| 2082 | // unsupported MIME types, oversized images, and extra images. |
| 2083 | // Dropping them here would silently remove the payload before the |
| 2084 | // boundary had anything to count. |
| 2085 | let (mime_type, data) = match (mime_type, data) { |
| 2086 | (Some(mime_type), Some(Value::String(data))) => (mime_type, data), |
| 2087 | _ => (String::new(), String::new()), |
| 2088 | }; |
| 2089 | content_blocks.push(ToolResultContentBlock::Image { mime_type, data }); |
| 2090 | } |
| 2091 | } |
| 2092 | |
| 2093 | let content = serde_json::to_string(&result).unwrap_or_else(|_| result.to_string()); |
| 2094 | let is_error = result |
| 2095 | .get("isError") |
| 2096 | .and_then(Value::as_bool) |
| 2097 | .unwrap_or(false); |
| 2098 | let result = if is_error { |
| 2099 | let text = result |
| 2100 | .get("content") |
| 2101 | .and_then(Value::as_array) |
| 2102 | .map(|items| { |
| 2103 | items |
| 2104 | .iter() |
| 2105 | .filter_map(|item| item.get("text").and_then(Value::as_str)) |
| 2106 | .collect::<Vec<_>>() |
| 2107 | .join("\n") |
| 2108 | }) |
| 2109 | .filter(|text| !text.is_empty()) |
| 2110 | .unwrap_or(content); |
| 2111 | ToolResult::error(text) |
| 2112 | } else { |
| 2113 | ToolResult::success(content) |
| 2114 | }; |
| 2115 | RichToolResult::with_content_blocks(result, content_blocks) |
| 2116 | } |
| 2117 | |
| 2118 | /// Convert and bound an MCP result at the shared direct/parallel execution |
| 2119 | /// seam. The registry applies the same boundary to every rich tool; keeping it |
| 2120 | /// here too protects the engine's MCP fast path and text-only adapter callers. |
| 2121 | pub fn mcp_result_to_bounded_rich_tool_result(result: Value) -> RichToolResult { |
| 2122 | crate::image_attach::bound_rich_tool_result(mcp_result_to_rich_tool_result(result)) |
| 2123 | } |
| 2124 | |
| 2125 | #[cfg(test)] |
| 2126 | pub(super) fn mcp_tool_adapter_for_test(name: &str) -> Arc<dyn ToolSpec> { |
| 2127 | Arc::new(McpToolAdapter { |
| 2128 | delegated_read: None, |
| 2129 | name: name.to_string(), |
| 2130 | server_name: None, |
| 2131 | tool: crate::mcp::McpTool { |
| 2132 | name: name.to_string(), |
| 2133 | description: None, |
| 2134 | input_schema: serde_json::json!({"type": "object"}), |
| 2135 | annotations: None, |
| 2136 | }, |
| 2137 | pool: Arc::new(tokio::sync::Mutex::new(crate::mcp::McpPool::new( |
| 2138 | codewhale_mcp::config::McpConfig::default(), |
| 2139 | ))), |
| 2140 | }) |
| 2141 | } |
| 2142 | |
| 2143 | // === Unit Tests === |
| 2144 | |
| 2145 | #[cfg(test)] |
| 2146 | mod tests; |
| 2147 | |
| 2148 | #[cfg(test)] |
| 2149 | mod reserved_name_tests { |
| 2150 | use super::*; |
| 2151 | |
| 2152 | fn dynamic(namespace: &str, name: &str) -> DynamicToolSpec { |
| 2153 | DynamicToolSpec { |
| 2154 | namespace: Some(namespace.to_string()), |
| 2155 | name: name.to_string(), |
| 2156 | description: "client tool".to_string(), |
| 2157 | input_schema: serde_json::json!({"type": "object"}), |
| 2158 | defer_loading: false, |
| 2159 | } |
| 2160 | } |
| 2161 | |
| 2162 | #[test] |
| 2163 | fn reserved_tool_names_cover_a_fully_enabled_builder() { |
| 2164 | use codewhale_agent_contract::worker_profile::ShellPolicy; |
| 2165 | |
| 2166 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 2167 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2168 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 2169 | let config = codewhale_runtime::config::Config::default() |
| 2170 | .with_legacy_root(Some("test-key".to_string()), None); |
| 2171 | let client = CodewhaleClient::new(&config).expect("stub client should construct"); |
| 2172 | let model = "deepseek-v4-flash".to_string(); |
| 2173 | let manager = |
| 2174 | crate::tools::subagent::new_shared_subagent_manager(tmp.path().to_path_buf(), 2); |
| 2175 | let runtime = crate::tools::subagent::SubAgentRuntime::new( |
| 2176 | client.clone(), |
| 2177 | model.clone(), |
| 2178 | ctx, |
| 2179 | true, |
| 2180 | None, |
| 2181 | manager.clone(), |
| 2182 | ); |
| 2183 | let mut options = AgentToolSurfaceOptions::new(ShellPolicy::Full); |
| 2184 | options.apply_patch_enabled = true; |
| 2185 | options.web_search_enabled = true; |
| 2186 | options.memory_tool_enabled = true; |
| 2187 | options.goal_state = Some(crate::tools::goal::new_shared_goal_state()); |
| 2188 | options.vision_config = Some(codewhale_runtime::config::VisionModelConfig { |
| 2189 | model_http_policy: None, |
| 2190 | model: "vision-model".to_string(), |
| 2191 | api_key: None, |
| 2192 | base_url: None, |
| 2193 | }); |
| 2194 | let pool = Arc::new(tokio::sync::Mutex::new(crate::mcp::McpPool::new( |
| 2195 | codewhale_mcp::config::McpConfig::default(), |
| 2196 | ))); |
| 2197 | let builder = ToolRegistryBuilder::new() |
| 2198 | .with_full_agent_surface_options( |
| 2199 | Some(client), |
| 2200 | model.clone(), |
| 2201 | manager, |
| 2202 | runtime, |
| 2203 | options, |
| 2204 | crate::tools::todo::new_shared_todo_list(), |
| 2205 | ) |
| 2206 | .with_tool(Arc::new(super::super::fim::FimEditTool::new(None, model))) |
| 2207 | .with_speech_tools(None, None) |
| 2208 | .with_foreground_shell_tools() |
| 2209 | .with_runtime_read_only_task_tools() |
| 2210 | .with_read_only_file_tools() |
| 2211 | .with_registry_mcp_sync_tool() |
| 2212 | .with_runtime_mcp_tool(Arc::clone(&pool)) |
| 2213 | .with_registry_mcp_start_tool(pool); |
| 2214 | |
| 2215 | let missing: Vec<&str> = builder |
| 2216 | .tools |
| 2217 | .iter() |
| 2218 | .map(|tool| tool.name()) |
| 2219 | .filter(|name| !RESERVED_TOOL_NAMES.contains(name)) |
| 2220 | .collect(); |
| 2221 | assert!( |
| 2222 | missing.is_empty(), |
| 2223 | "add these builder tool names to RESERVED_TOOL_NAMES: {missing:?}" |
| 2224 | ); |
| 2225 | for name in ["read", "agent", "workflow", "agents/wait", "apply_patch"] { |
| 2226 | assert!(RESERVED_TOOL_NAMES.contains(&name), "{name}"); |
| 2227 | } |
| 2228 | } |
| 2229 | |
| 2230 | #[test] |
| 2231 | fn dynamic_tool_names_are_refused_when_reserved_or_repeated() { |
| 2232 | assert_eq!( |
| 2233 | dynamic_tool_name_refusal("agent", &[]), |
| 2234 | Some(DynamicToolNameRefusal::Reserved) |
| 2235 | ); |
| 2236 | assert_eq!( |
| 2237 | dynamic_tool_name_refusal("READ", &[]), |
| 2238 | Some(DynamicToolNameRefusal::Reserved) |
| 2239 | ); |
| 2240 | assert_eq!( |
| 2241 | dynamic_tool_name_refusal("plugin_manager", &[]), |
| 2242 | Some(DynamicToolNameRefusal::Reserved) |
| 2243 | ); |
| 2244 | assert_eq!( |
| 2245 | dynamic_tool_name_refusal("lookup", &[dynamic("first", "lookup")]), |
| 2246 | Some(DynamicToolNameRefusal::Duplicate) |
| 2247 | ); |
| 2248 | assert_eq!(dynamic_tool_name_refusal("lookup", &[]), None); |
| 2249 | |
| 2250 | let err = validate_dynamic_tool_names(&[dynamic("a", "lookup"), dynamic("b", "agent")]) |
| 2251 | .expect_err("reserved name"); |
| 2252 | assert!(err.contains("`agent`"), "{err}"); |
| 2253 | let err = validate_dynamic_tool_names(&[dynamic("a", "lookup"), dynamic("b", "lookup")]) |
| 2254 | .expect_err("duplicate name"); |
| 2255 | assert!(err.contains("`lookup`"), "{err}"); |
| 2256 | assert!(validate_dynamic_tool_names(&[dynamic("a", "lookup")]).is_ok()); |
| 2257 | } |
| 2258 | |
| 2259 | #[test] |
| 2260 | fn a_dynamic_tool_cannot_take_a_name_registered_after_it() { |
| 2261 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2262 | let registry = ToolRegistryBuilder::new() |
| 2263 | .with_dynamic_tools(&[dynamic("client", "agent"), dynamic("client", "lookup")]) |
| 2264 | .build(ToolContext::new(tmp.path().to_path_buf())); |
| 2265 | assert!(!registry.contains("agent")); |
| 2266 | assert!(registry.contains("lookup")); |
| 2267 | } |
| 2268 | } |
| 2269 |