| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Arc; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use anyhow::Result; |
| 7 | use async_trait::async_trait; |
| 8 | use codewhale_protocol::{ToolKind, ToolOutput, ToolPayload}; |
| 9 | use serde::{Deserialize, Serialize}; |
| 10 | use serde_json::Value; |
| 11 | use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock}; |
| 12 | |
| 13 | pub mod names; |
| 14 | mod outcome; |
| 15 | pub mod param_alias; |
| 16 | pub mod patch_preflight; |
| 17 | mod prepared; |
| 18 | mod resources; |
| 19 | |
| 20 | pub use outcome::{ToolExecutionOutcome, ToolTerminalStatus}; |
| 21 | pub use prepared::PreparedToolCall; |
| 22 | pub use resources::{ResourceClaim, schedule_non_conflicting}; |
| 23 | |
| 24 | tokio::task_local! { |
| 25 | static TOOL_EXECUTION_LOCK_HELD: (); |
| 26 | } |
| 27 | |
| 28 | /// Capabilities that a tool may have or require. |
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 30 | pub enum ToolCapability { |
| 31 | /// Tool only reads data, never modifies state. |
| 32 | ReadOnly, |
| 33 | /// Tool writes to the filesystem. |
| 34 | WritesFiles, |
| 35 | /// Tool executes arbitrary shell commands. |
| 36 | ExecutesCode, |
| 37 | /// Tool makes network requests. |
| 38 | Network, |
| 39 | /// Tool can be run in a sandbox. |
| 40 | Sandboxable, |
| 41 | /// Tool requires user approval before execution. |
| 42 | RequiresApproval, |
| 43 | StartsWorkspaceProgram, |
| 44 | } |
| 45 | |
| 46 | /// Approval requirement for a tool. |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 48 | pub enum ApprovalRequirement { |
| 49 | /// Never needs approval: safe read-only operations. |
| 50 | #[default] |
| 51 | Auto, |
| 52 | /// Suggest approval but allow user to skip. |
| 53 | Suggest, |
| 54 | /// Always require explicit user approval. |
| 55 | Required, |
| 56 | } |
| 57 | |
| 58 | /// Errors that can occur during tool execution. |
| 59 | #[derive(Debug, Clone, thiserror::Error)] |
| 60 | pub enum ToolError { |
| 61 | #[error("Failed to validate input: {message}")] |
| 62 | InvalidInput { message: String }, |
| 63 | #[error("Failed to validate input: missing required field '{field}'")] |
| 64 | MissingField { field: String }, |
| 65 | #[error("Failed to resolve path '{}': path escapes workspace", path.display())] |
| 66 | PathEscape { path: PathBuf }, |
| 67 | #[error("Failed to execute tool: {message}")] |
| 68 | ExecutionFailed { |
| 69 | message: String, |
| 70 | /// Structured facts about the failure, in the same shape a |
| 71 | /// `ToolResult` would carry them. A process-backed tool that reports a |
| 72 | /// nonzero exit or a timeout as an error puts its `exit_code` and |
| 73 | /// `status` here, so observers (hooks, receipts) still see them. |
| 74 | metadata: Option<Value>, |
| 75 | }, |
| 76 | #[error("Failed to execute tool: operation timed out after {seconds}s")] |
| 77 | Timeout { seconds: u64 }, |
| 78 | #[error("Tool execution cancelled: {message}")] |
| 79 | Cancelled { message: String }, |
| 80 | #[error("Failed to locate tool: {message}")] |
| 81 | NotAvailable { message: String }, |
| 82 | #[error("Failed to authorize tool execution: {message}")] |
| 83 | PermissionDenied { message: String }, |
| 84 | } |
| 85 | |
| 86 | impl ToolError { |
| 87 | #[must_use] |
| 88 | pub fn invalid_input(msg: impl Into<String>) -> Self { |
| 89 | Self::InvalidInput { |
| 90 | message: msg.into(), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | #[must_use] |
| 95 | pub fn missing_field(field: impl Into<String>) -> Self { |
| 96 | Self::MissingField { |
| 97 | field: field.into(), |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | #[must_use] |
| 102 | pub fn execution_failed(msg: impl Into<String>) -> Self { |
| 103 | Self::ExecutionFailed { |
| 104 | message: msg.into(), |
| 105 | metadata: None, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// An execution failure that still carries structured result metadata, |
| 110 | /// such as a shell command's `exit_code` and `status`. |
| 111 | #[must_use] |
| 112 | pub fn execution_failed_with_metadata(msg: impl Into<String>, metadata: Value) -> Self { |
| 113 | Self::ExecutionFailed { |
| 114 | message: msg.into(), |
| 115 | metadata: Some(metadata), |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// Structured metadata the failing tool attached, if any. |
| 120 | #[must_use] |
| 121 | pub fn metadata(&self) -> Option<&Value> { |
| 122 | match self { |
| 123 | Self::ExecutionFailed { metadata, .. } => metadata.as_ref(), |
| 124 | _ => None, |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | #[must_use] |
| 129 | pub fn cancelled(msg: impl Into<String>) -> Self { |
| 130 | Self::Cancelled { |
| 131 | message: msg.into(), |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | #[must_use] |
| 136 | pub fn path_escape(path: impl Into<PathBuf>) -> Self { |
| 137 | Self::PathEscape { path: path.into() } |
| 138 | } |
| 139 | |
| 140 | #[must_use] |
| 141 | pub fn not_available(msg: impl Into<String>) -> Self { |
| 142 | Self::NotAvailable { |
| 143 | message: msg.into(), |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | #[must_use] |
| 148 | pub fn permission_denied(msg: impl Into<String>) -> Self { |
| 149 | Self::PermissionDenied { |
| 150 | message: msg.into(), |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Result of a tool execution. |
| 156 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 157 | pub struct ToolResult { |
| 158 | /// The output content, which may be JSON or plain text. |
| 159 | pub content: String, |
| 160 | /// Whether the execution was successful. |
| 161 | pub success: bool, |
| 162 | /// Optional structured metadata. |
| 163 | #[serde(skip_serializing_if = "Option::is_none")] |
| 164 | pub metadata: Option<Value>, |
| 165 | } |
| 166 | |
| 167 | /// Provider-neutral non-text content returned alongside a tool result. |
| 168 | /// Image-producing tools return owned base64 bytes here (MCP uses its standard |
| 169 | /// `content` image blocks). A path in `ToolResult.metadata` is descriptive |
| 170 | /// metadata, never permission for the engine to read another host file. |
| 171 | /// The runtime validates format, full decode and size, retains one image per |
| 172 | /// result, and keeps omitted-image receipts with the text result. |
| 173 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 174 | #[serde(tag = "type", rename_all = "snake_case")] |
| 175 | pub enum ToolResultContentBlock { |
| 176 | Image { mime_type: String, data: String }, |
| 177 | } |
| 178 | |
| 179 | impl ToolResult { |
| 180 | /// Create a successful result with content. |
| 181 | #[must_use] |
| 182 | pub fn success(content: impl Into<String>) -> Self { |
| 183 | Self { |
| 184 | content: content.into(), |
| 185 | success: true, |
| 186 | metadata: None, |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Create an error result with message. |
| 191 | #[must_use] |
| 192 | pub fn error(message: impl Into<String>) -> Self { |
| 193 | Self { |
| 194 | content: message.into(), |
| 195 | success: false, |
| 196 | metadata: None, |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// Create a successful result from JSON. |
| 201 | pub fn json<T: Serialize>(value: &T) -> std::result::Result<Self, serde_json::Error> { |
| 202 | Ok(Self { |
| 203 | content: serde_json::to_string(value)?, |
| 204 | success: true, |
| 205 | metadata: None, |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | /// Add metadata to the result. |
| 210 | #[must_use] |
| 211 | pub fn with_metadata(mut self, metadata: Value) -> Self { |
| 212 | self.metadata = Some(metadata); |
| 213 | self |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /// Name the JSON type of a value the way a tool schema would spell it. |
| 218 | #[must_use] |
| 219 | pub fn json_type_name(value: &Value) -> &'static str { |
| 220 | match value { |
| 221 | Value::Null => "null", |
| 222 | Value::Bool(_) => "boolean", |
| 223 | Value::Number(_) => "number", |
| 224 | Value::String(_) => "string", |
| 225 | Value::Array(_) => "array", |
| 226 | Value::Object(_) => "object", |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// Render a value for an error message, truncated so a huge payload cannot |
| 231 | /// swamp the transcript. |
| 232 | #[must_use] |
| 233 | pub fn value_preview(value: &Value) -> String { |
| 234 | let preview = value.to_string(); |
| 235 | if preview.chars().count() > 120 { |
| 236 | preview.chars().take(117).collect::<String>() + "..." |
| 237 | } else { |
| 238 | preview |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | /// The one error every type mismatch on a tool parameter produces. |
| 243 | /// |
| 244 | /// Names the parameter, the type that arrived, and the type the schema |
| 245 | /// declares, plus the offending value — everything the caller needs to fix |
| 246 | /// the call on the next turn without another round trip. |
| 247 | #[must_use] |
| 248 | pub fn type_mismatch(field: &str, value: &Value, expected: &str) -> ToolError { |
| 249 | ToolError::invalid_input(format!( |
| 250 | "field '{field}' must be {expected}; got {}. Received: {}", |
| 251 | json_type_name(value), |
| 252 | value_preview(value) |
| 253 | )) |
| 254 | } |
| 255 | |
| 256 | /// Whether a value counts as "the caller did not supply this field". |
| 257 | /// |
| 258 | /// JSON `null` is the wire spelling of absence, so an optional field set to |
| 259 | /// `null` takes its default rather than erroring. This is the *only* |
| 260 | /// tolerance in the optional extractors, and it is uniform across all of |
| 261 | /// them: `null` means no value, and no value is exactly what a default is |
| 262 | /// for. Every other type mismatch is an error. |
| 263 | fn is_absent(value: Option<&Value>) -> bool { |
| 264 | matches!(value, None | Some(Value::Null)) |
| 265 | } |
| 266 | |
| 267 | /// Helper to extract a required string field from JSON input. |
| 268 | pub fn required_str<'a>(input: &'a Value, field: &str) -> std::result::Result<&'a str, ToolError> { |
| 269 | if let Some(value) = input.get(field) { |
| 270 | if let Some(string_value) = value.as_str() { |
| 271 | return Ok(string_value); |
| 272 | } |
| 273 | |
| 274 | return Err(type_mismatch(field, value, "a string")); |
| 275 | } |
| 276 | |
| 277 | // When the field is missing, list the fields the caller *did* |
| 278 | // supply so the model can spot the mismatch without a retry. |
| 279 | let provided: Vec<&str> = input |
| 280 | .as_object() |
| 281 | .map(|obj| obj.keys().map(|k| k.as_str()).collect()) |
| 282 | .unwrap_or_default(); |
| 283 | if provided.is_empty() { |
| 284 | Err(ToolError::missing_field(field)) |
| 285 | } else { |
| 286 | let hint = format!( |
| 287 | "missing required field '{field}'. Input provided: {}", |
| 288 | provided.join(", ") |
| 289 | ); |
| 290 | Err(ToolError::invalid_input(hint)) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | /// Require the `action` discriminator on a canonical action-family call. |
| 295 | /// |
| 296 | /// Every family schema marks `action` required, but the wrappers used to |
| 297 | /// default a missing one (`File` → read, `Git` → status, `Web` → search, |
| 298 | /// `Run` → tests). A call that merely omitted or misspelled the discriminator |
| 299 | /// therefore ran a *different* operation and returned that operation's success |
| 300 | /// receipt: `File{path, content}` answered an intended write with the file's |
| 301 | /// current contents, so the write silently never happened. Same shape as |
| 302 | /// #5209 — refuse, and name the values that actually dispatch. |
| 303 | /// |
| 304 | /// `actions` must be the set this tool instance can really run, so a mode that |
| 305 | /// hides `write` never suggests it. |
| 306 | pub fn required_action( |
| 307 | input: &Value, |
| 308 | tool: &str, |
| 309 | actions: &[&str], |
| 310 | ) -> std::result::Result<String, ToolError> { |
| 311 | match input.get("action") { |
| 312 | Some(Value::String(action)) => Ok(action.clone()), |
| 313 | Some(other) => Err(ToolError::invalid_input(format!( |
| 314 | "{tool} requires `action` to be a string, got {other}; nothing was run. Pass one of: {}.", |
| 315 | actions.join(", ") |
| 316 | ))), |
| 317 | None => Err(ToolError::invalid_input(format!( |
| 318 | "{tool} requires an `action` parameter; nothing was run. Pass one of: {}.", |
| 319 | actions.join(", ") |
| 320 | ))), |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | /// Helper to extract an optional string field from JSON input. |
| 325 | /// |
| 326 | /// A wrong type is an error, never a silent `None`. See [`type_mismatch`] |
| 327 | /// for why nothing is coerced. |
| 328 | pub fn optional_str<'a>( |
| 329 | input: &'a Value, |
| 330 | field: &str, |
| 331 | ) -> std::result::Result<Option<&'a str>, ToolError> { |
| 332 | let value = input.get(field); |
| 333 | if is_absent(value) { |
| 334 | return Ok(None); |
| 335 | } |
| 336 | let value = value.expect("is_absent covers the None case"); |
| 337 | value |
| 338 | .as_str() |
| 339 | .map(Some) |
| 340 | .ok_or_else(|| type_mismatch(field, value, "a string")) |
| 341 | } |
| 342 | |
| 343 | /// Read a JSON number as a non-negative integer, accepting whole-number |
| 344 | /// floats such as `200.0`. |
| 345 | /// |
| 346 | /// Several providers serialize every JSON number as a float, so a ranged |
| 347 | /// `read` arrives as `{"offset": 200.0}`. Exact integers keep the `as_u64` |
| 348 | /// fast path (so `u64::MAX` stays exact); a float is accepted only when it |
| 349 | /// is finite, non-negative, has no fractional part and fits in `u64`. |
| 350 | /// Negative, fractional, string and array values are still refused. |
| 351 | #[must_use] |
| 352 | pub fn json_nonnegative_integer(value: &Value) -> Option<u64> { |
| 353 | if let Some(number) = value.as_u64() { |
| 354 | return Some(number); |
| 355 | } |
| 356 | let float = value.as_f64()?; |
| 357 | // 2^64 is exactly representable as f64; anything at or above it overflows. |
| 358 | const U64_LIMIT: f64 = 18_446_744_073_709_551_616.0; |
| 359 | if float.is_finite() && float >= 0.0 && float.fract() == 0.0 && float < U64_LIMIT { |
| 360 | // The guards above make this cast exact. |
| 361 | return Some(float as u64); |
| 362 | } |
| 363 | None |
| 364 | } |
| 365 | |
| 366 | /// Helper to extract a required u64 field from JSON input. |
| 367 | /// |
| 368 | /// Absence (field missing or `null`) is a `missing_field` error; a value |
| 369 | /// that is present but not a u64 is a [`type_mismatch`] naming the field and |
| 370 | /// the expected type, so the caller fixes the field's type instead of |
| 371 | /// re-sending it as missing. |
| 372 | pub fn required_u64(input: &Value, field: &str) -> std::result::Result<u64, ToolError> { |
| 373 | let value = input.get(field); |
| 374 | if is_absent(value) { |
| 375 | return Err(ToolError::missing_field(field)); |
| 376 | } |
| 377 | let value = value.expect("is_absent covers the None case"); |
| 378 | json_nonnegative_integer(value) |
| 379 | .ok_or_else(|| type_mismatch(field, value, "a non-negative integer")) |
| 380 | } |
| 381 | |
| 382 | /// Helper to extract an optional u64 field with default. |
| 383 | /// |
| 384 | /// A wrong type is an error, never a silent fall back to `default`. |
| 385 | pub fn optional_u64( |
| 386 | input: &Value, |
| 387 | field: &str, |
| 388 | default: u64, |
| 389 | ) -> std::result::Result<u64, ToolError> { |
| 390 | let value = input.get(field); |
| 391 | if is_absent(value) { |
| 392 | return Ok(default); |
| 393 | } |
| 394 | let value = value.expect("is_absent covers the None case"); |
| 395 | json_nonnegative_integer(value) |
| 396 | .ok_or_else(|| type_mismatch(field, value, "a non-negative integer")) |
| 397 | } |
| 398 | |
| 399 | /// Helper to extract an optional bool field with default. |
| 400 | /// |
| 401 | /// A wrong type is an error, never a silent fall back to `default`. In |
| 402 | /// particular the string `"true"` is refused rather than coerced: the |
| 403 | /// default this used to fall back to is frequently the *opposite* of what |
| 404 | /// the caller asked for, and some of those defaults gate irreversible |
| 405 | /// actions. |
| 406 | pub fn optional_bool( |
| 407 | input: &Value, |
| 408 | field: &str, |
| 409 | default: bool, |
| 410 | ) -> std::result::Result<bool, ToolError> { |
| 411 | Ok(optional_bool_opt(input, field)?.unwrap_or(default)) |
| 412 | } |
| 413 | |
| 414 | /// Helper to extract an optional bool that has no default. |
| 415 | /// |
| 416 | /// `None` means the caller did not supply the field; a wrong type is an |
| 417 | /// error. Use this where "unset" is itself meaningful — an authority |
| 418 | /// declaration that is dropped instead of read is a restriction that |
| 419 | /// silently evaporates. |
| 420 | pub fn optional_bool_opt( |
| 421 | input: &Value, |
| 422 | field: &str, |
| 423 | ) -> std::result::Result<Option<bool>, ToolError> { |
| 424 | let value = input.get(field); |
| 425 | if is_absent(value) { |
| 426 | return Ok(None); |
| 427 | } |
| 428 | let value = value.expect("is_absent covers the None case"); |
| 429 | value |
| 430 | .as_bool() |
| 431 | .map(Some) |
| 432 | .ok_or_else(|| type_mismatch(field, value, "a boolean")) |
| 433 | } |
| 434 | |
| 435 | /// Descriptor that describes a tool available in the registry. |
| 436 | /// |
| 437 | /// Contains the tool's name, its JSON input/output schemas, and |
| 438 | /// execution constraints such as timeout and parallelism. |
| 439 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 440 | pub struct ToolDescriptor { |
| 441 | /// Unique name used to look up the tool. |
| 442 | pub name: String, |
| 443 | /// JSON Schema describing the tool's expected input parameters. |
| 444 | pub input_schema: Value, |
| 445 | /// JSON Schema describing the tool's output format. |
| 446 | pub output_schema: Value, |
| 447 | /// Whether multiple invocations of this tool may run concurrently. |
| 448 | pub supports_parallel_tool_calls: bool, |
| 449 | /// Optional per-call timeout in milliseconds; `None` means no timeout. |
| 450 | pub timeout_ms: Option<u64>, |
| 451 | } |
| 452 | |
| 453 | /// A [`ToolDescriptor`] together with its runtime configuration. |
| 454 | /// |
| 455 | /// Wraps a `ToolDescriptor` and exposes the parallelism flag directly so the |
| 456 | /// dispatcher can check it without digging into the inner spec. |
| 457 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 458 | pub struct ConfiguredToolDescriptor { |
| 459 | /// The underlying tool descriptor. |
| 460 | pub spec: ToolDescriptor, |
| 461 | /// Whether this tool supports concurrent invocations. |
| 462 | pub supports_parallel_tool_calls: bool, |
| 463 | } |
| 464 | |
| 465 | /// Identifies where a tool call originated from. |
| 466 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 467 | #[serde(rename_all = "snake_case")] |
| 468 | pub enum ToolCallSource { |
| 469 | /// Direct invocation from the model or user. |
| 470 | Direct, |
| 471 | /// Invocation through the JavaScript REPL environment. |
| 472 | JsRepl, |
| 473 | } |
| 474 | |
| 475 | /// A tool invocation request before it has been validated and dispatched. |
| 476 | /// |
| 477 | /// Contains the tool name, its input payload, and metadata about where the |
| 478 | /// call originated. |
| 479 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 480 | pub struct ToolCall { |
| 481 | /// Name of the tool to invoke. |
| 482 | pub name: String, |
| 483 | /// The input payload for the tool. |
| 484 | pub payload: ToolPayload, |
| 485 | /// Where this call originated (direct or REPL). |
| 486 | pub source: ToolCallSource, |
| 487 | /// Optional raw tool-call identifier from the upstream provider. |
| 488 | pub raw_tool_call_id: Option<String>, |
| 489 | } |
| 490 | |
| 491 | impl ToolCall { |
| 492 | /// Derive the execution subject for this call. |
| 493 | /// |
| 494 | /// For local shell payloads this returns the shell command and its |
| 495 | /// working directory; for all other payloads the tool name and the |
| 496 | /// provided `fallback_cwd` are returned instead. The third element |
| 497 | /// of the tuple is a human-readable kind label (`"shell"` or `"tool"`). |
| 498 | pub fn execution_subject(&self, fallback_cwd: &str) -> (String, String, &'static str) { |
| 499 | match &self.payload { |
| 500 | ToolPayload::LocalShell { params } => ( |
| 501 | params.command.clone(), |
| 502 | params |
| 503 | .cwd |
| 504 | .clone() |
| 505 | .unwrap_or_else(|| fallback_cwd.to_string()), |
| 506 | "shell", |
| 507 | ), |
| 508 | _ => (self.name.clone(), fallback_cwd.to_string(), "tool"), |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | /// A validated tool invocation ready to be handled. |
| 514 | /// |
| 515 | /// Created by the registry after a [`ToolCall`] passes validation, this |
| 516 | /// carries all the context a [`ToolHandler`] needs to execute the tool. |
| 517 | #[derive(Debug, Clone)] |
| 518 | pub struct ToolInvocation { |
| 519 | /// Unique identifier for this invocation (generated or from the provider). |
| 520 | pub call_id: String, |
| 521 | /// Name of the tool being invoked. |
| 522 | pub tool_name: String, |
| 523 | /// The input payload for the tool. |
| 524 | pub payload: ToolPayload, |
| 525 | /// Where this invocation originated. |
| 526 | pub source: ToolCallSource, |
| 527 | } |
| 528 | |
| 529 | /// Errors that can occur during tool dispatch and execution. |
| 530 | /// |
| 531 | /// Unlike [`ToolError`], which represents input validation failures within |
| 532 | /// a tool, `FunctionCallError` covers problems at the dispatch layer: the |
| 533 | /// tool was not found, its kind did not match, it was rejected because it |
| 534 | /// is mutating, it timed out, was cancelled, or its handler returned an |
| 535 | /// error. |
| 536 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 537 | pub enum FunctionCallError { |
| 538 | /// No tool with the given name is registered. |
| 539 | ToolNotFound { name: String }, |
| 540 | /// The payload kind does not match the handler's expected kind. |
| 541 | KindMismatch { expected: ToolKind, got: ToolKind }, |
| 542 | /// The tool is mutating but `allow_mutating` was `false`. |
| 543 | MutatingToolRejected { name: String }, |
| 544 | /// The tool execution exceeded its configured timeout. |
| 545 | TimedOut { name: String, timeout_ms: u64 }, |
| 546 | /// The tool execution was cancelled. |
| 547 | Cancelled { name: String }, |
| 548 | /// The tool handler returned an error. |
| 549 | ExecutionFailed { name: String, error: String }, |
| 550 | } |
| 551 | |
| 552 | /// Trait implemented by concrete tool handlers. |
| 553 | /// |
| 554 | /// Each registered tool is backed by a handler that reports its kind, |
| 555 | /// whether it is mutating, and performs the actual execution. |
| 556 | #[async_trait] |
| 557 | pub trait ToolHandler: Send + Sync { |
| 558 | /// The [`ToolKind`] this handler expects (e.g. `Function` or `Mcp`). |
| 559 | fn kind(&self) -> ToolKind; |
| 560 | |
| 561 | /// Returns `true` if `kind` matches this handler's expected kind. |
| 562 | /// |
| 563 | /// The default implementation compares against [`kind()`](ToolHandler::kind). |
| 564 | fn matches_kind(&self, kind: ToolKind) -> bool { |
| 565 | self.kind() == kind |
| 566 | } |
| 567 | |
| 568 | /// Whether this tool performs side-effects that require user approval. |
| 569 | /// |
| 570 | /// Defaults to `false` (read-only / safe). |
| 571 | fn is_mutating(&self) -> bool { |
| 572 | false |
| 573 | } |
| 574 | |
| 575 | /// Execute the tool with the given invocation context. |
| 576 | async fn handle( |
| 577 | &self, |
| 578 | invocation: ToolInvocation, |
| 579 | ) -> std::result::Result<ToolOutput, FunctionCallError>; |
| 580 | } |
| 581 | |
| 582 | /// Manages concurrent tool execution via a read/write lock. |
| 583 | /// |
| 584 | /// Parallel-safe tools acquire a read lock (allowing overlap), while |
| 585 | /// serial tools acquire a write lock (exclusive access). Reentrant calls |
| 586 | /// (e.g. a tool invoking another tool) skip locking to avoid deadlock. |
| 587 | #[derive(Debug)] |
| 588 | pub struct ToolCallRuntime { |
| 589 | execution_lock: Arc<RwLock<()>>, |
| 590 | } |
| 591 | |
| 592 | impl Default for ToolCallRuntime { |
| 593 | fn default() -> Self { |
| 594 | Self { |
| 595 | execution_lock: Arc::new(RwLock::new(())), |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | #[derive(Debug)] |
| 601 | enum ToolExecutionGuard { |
| 602 | Parallel { _guard: OwnedRwLockReadGuard<()> }, |
| 603 | Serial { _guard: OwnedRwLockWriteGuard<()> }, |
| 604 | Reentrant, |
| 605 | } |
| 606 | |
| 607 | impl ToolCallRuntime { |
| 608 | async fn acquire(&self, supports_parallel: bool) -> ToolExecutionGuard { |
| 609 | if TOOL_EXECUTION_LOCK_HELD.try_with(|_| ()).is_ok() { |
| 610 | return ToolExecutionGuard::Reentrant; |
| 611 | } |
| 612 | |
| 613 | if supports_parallel { |
| 614 | ToolExecutionGuard::Parallel { |
| 615 | _guard: self.execution_lock.clone().read_owned().await, |
| 616 | } |
| 617 | } else { |
| 618 | ToolExecutionGuard::Serial { |
| 619 | _guard: self.execution_lock.clone().write_owned().await, |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | /// Central registry that maps tool names to their specs and handlers. |
| 626 | /// |
| 627 | /// Use [`register()`](ToolRegistry::register) to add tools, then |
| 628 | /// [`dispatch()`](ToolRegistry::dispatch) to invoke them. The registry |
| 629 | /// owns a [`ToolCallRuntime`] that manages concurrent execution. |
| 630 | #[derive(Default)] |
| 631 | pub struct ToolRegistry { |
| 632 | handlers: HashMap<String, Arc<dyn ToolHandler>>, |
| 633 | specs: HashMap<String, ConfiguredToolDescriptor>, |
| 634 | runtime: ToolCallRuntime, |
| 635 | } |
| 636 | |
| 637 | impl ToolRegistry { |
| 638 | /// Register a tool with its specification and handler. |
| 639 | /// |
| 640 | /// The tool's name is taken from `spec.name`. Returns an error if |
| 641 | /// registration fails (currently infallible, but the `Result` is |
| 642 | /// reserved for future validation). |
| 643 | pub fn register(&mut self, spec: ToolDescriptor, handler: Arc<dyn ToolHandler>) -> Result<()> { |
| 644 | let name = spec.name.clone(); |
| 645 | self.specs.insert( |
| 646 | name.clone(), |
| 647 | ConfiguredToolDescriptor { |
| 648 | supports_parallel_tool_calls: spec.supports_parallel_tool_calls, |
| 649 | spec, |
| 650 | }, |
| 651 | ); |
| 652 | self.handlers.insert(name, handler); |
| 653 | Ok(()) |
| 654 | } |
| 655 | |
| 656 | /// Validate and execute a tool call. |
| 657 | /// |
| 658 | /// Looks up the tool by name, verifies the payload kind matches the |
| 659 | /// handler, enforces the `allow_mutating` guard, acquires the |
| 660 | /// appropriate execution lock, and forwards the call to the handler. |
| 661 | /// Returns a [`FunctionCallError`] if any validation step fails or |
| 662 | /// the handler returns an error. |
| 663 | pub async fn dispatch( |
| 664 | &self, |
| 665 | call: ToolCall, |
| 666 | allow_mutating: bool, |
| 667 | ) -> std::result::Result<ToolOutput, FunctionCallError> { |
| 668 | let handler = self.handlers.get(&call.name).cloned().ok_or_else(|| { |
| 669 | FunctionCallError::ToolNotFound { |
| 670 | name: call.name.clone(), |
| 671 | } |
| 672 | })?; |
| 673 | let configured = |
| 674 | self.specs |
| 675 | .get(&call.name) |
| 676 | .cloned() |
| 677 | .ok_or_else(|| FunctionCallError::ToolNotFound { |
| 678 | name: call.name.clone(), |
| 679 | })?; |
| 680 | |
| 681 | let payload_kind = tool_payload_kind(&call.payload); |
| 682 | let expected = handler.kind(); |
| 683 | if !handler.matches_kind(payload_kind) { |
| 684 | return Err(FunctionCallError::KindMismatch { |
| 685 | expected, |
| 686 | got: payload_kind, |
| 687 | }); |
| 688 | } |
| 689 | if handler.is_mutating() && !allow_mutating { |
| 690 | return Err(FunctionCallError::MutatingToolRejected { name: call.name }); |
| 691 | } |
| 692 | |
| 693 | let invocation = ToolInvocation { |
| 694 | call_id: call |
| 695 | .raw_tool_call_id |
| 696 | .clone() |
| 697 | .unwrap_or_else(|| format!("tool-call-{}", uuid::Uuid::new_v4())), |
| 698 | tool_name: call.name.clone(), |
| 699 | payload: call.payload, |
| 700 | source: call.source, |
| 701 | }; |
| 702 | |
| 703 | let _guard = self |
| 704 | .runtime |
| 705 | .acquire(configured.supports_parallel_tool_calls) |
| 706 | .await; |
| 707 | |
| 708 | TOOL_EXECUTION_LOCK_HELD |
| 709 | .scope( |
| 710 | (), |
| 711 | self.execute_with_timeout(handler, configured.spec.timeout_ms, invocation), |
| 712 | ) |
| 713 | .await |
| 714 | } |
| 715 | |
| 716 | async fn execute_with_timeout( |
| 717 | &self, |
| 718 | handler: Arc<dyn ToolHandler>, |
| 719 | timeout_ms: Option<u64>, |
| 720 | invocation: ToolInvocation, |
| 721 | ) -> std::result::Result<ToolOutput, FunctionCallError> { |
| 722 | if let Some(timeout_ms) = timeout_ms { |
| 723 | let name = invocation.tool_name.clone(); |
| 724 | match tokio::time::timeout( |
| 725 | Duration::from_millis(timeout_ms), |
| 726 | handler.handle(invocation), |
| 727 | ) |
| 728 | .await |
| 729 | { |
| 730 | Ok(result) => result, |
| 731 | Err(_) => Err(FunctionCallError::TimedOut { name, timeout_ms }), |
| 732 | } |
| 733 | } else { |
| 734 | handler.handle(invocation).await |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | fn tool_payload_kind(payload: &ToolPayload) -> ToolKind { |
| 740 | match payload { |
| 741 | ToolPayload::Mcp { .. } => ToolKind::Mcp, |
| 742 | ToolPayload::Function { .. } |
| 743 | | ToolPayload::Custom { .. } |
| 744 | | ToolPayload::LocalShell { .. } => ToolKind::Function, |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | #[cfg(test)] |
| 749 | mod tests { |
| 750 | use serde_json::json; |
| 751 | |
| 752 | use super::*; |
| 753 | |
| 754 | #[test] |
| 755 | fn tool_result_success_sets_plain_content() { |
| 756 | let content = "operation completed successfully"; |
| 757 | let result = ToolResult::success(content); |
| 758 | |
| 759 | assert!(result.success); |
| 760 | assert_eq!(result.content, content); |
| 761 | assert!(result.metadata.is_none()); |
| 762 | } |
| 763 | |
| 764 | #[test] |
| 765 | fn tool_result_json_round_trips_content() { |
| 766 | let result = ToolResult::json(&json!({"ok": true})).expect("json"); |
| 767 | assert!(result.success); |
| 768 | let content: serde_json::Value = |
| 769 | serde_json::from_str(&result.content).expect("content is valid json"); |
| 770 | assert_eq!(content, json!({"ok": true})); |
| 771 | } |
| 772 | |
| 773 | #[test] |
| 774 | fn helper_extractors_validate_shape() { |
| 775 | let input = json!({"name": "demo", "count": 7, "enabled": true}); |
| 776 | assert_eq!(required_str(&input, "name").expect("name"), "demo"); |
| 777 | assert_eq!(optional_str(&input, "name").unwrap(), Some("demo")); |
| 778 | assert_eq!(optional_str(&input, "missing").unwrap(), None); |
| 779 | assert_eq!(optional_str(&json!({"name": null}), "name").unwrap(), None); |
| 780 | assert_eq!(optional_u64(&input, "count", 0).unwrap(), 7); |
| 781 | assert!(optional_bool(&input, "enabled", false).unwrap()); |
| 782 | // "name" is present but a string: a type mismatch, not a missing |
| 783 | // field, so the caller fixes the type instead of re-sending the name. |
| 784 | let err = required_u64(&input, "name") |
| 785 | .expect_err("a present string is not a missing u64") |
| 786 | .to_string(); |
| 787 | assert!( |
| 788 | err.contains("field 'name' must be a non-negative integer"), |
| 789 | "{err}" |
| 790 | ); |
| 791 | } |
| 792 | |
| 793 | /// The rule, stated once: an optional parameter of the wrong JSON type is |
| 794 | /// an error that names the parameter, what arrived, and what was wanted. |
| 795 | /// `null` alone means "absent" and takes the default. |
| 796 | #[test] |
| 797 | fn optional_extractors_refuse_type_mismatches_instead_of_defaulting() { |
| 798 | // The shipping bug: a stringy "true" became the default `false`, |
| 799 | // which for `dry_run` is the opposite of what the caller asked and |
| 800 | // gates an irreversible action. |
| 801 | let err = optional_bool(&json!({"dry_run": "true"}), "dry_run", false) |
| 802 | .expect_err("a stringy bool must not become the default") |
| 803 | .to_string(); |
| 804 | assert!(err.contains("dry_run"), "{err}"); |
| 805 | assert!(err.contains("must be a boolean"), "{err}"); |
| 806 | assert!(err.contains("got string"), "{err}"); |
| 807 | assert!(err.contains("\"true\""), "{err}"); |
| 808 | |
| 809 | for bad in [json!("true"), json!(1), json!(0), json!([]), json!({})] { |
| 810 | assert!( |
| 811 | optional_bool(&json!({"flag": bad}), "flag", false).is_err(), |
| 812 | "optional_bool accepted {bad}" |
| 813 | ); |
| 814 | } |
| 815 | for bad in [json!("7"), json!(-1), json!(1.5), json!(true), json!([7])] { |
| 816 | assert!( |
| 817 | optional_u64(&json!({"n": bad}), "n", 42).is_err(), |
| 818 | "optional_u64 accepted {bad}" |
| 819 | ); |
| 820 | } |
| 821 | for bad in [json!(7), json!(true), json!(["a"]), json!({"a": 1})] { |
| 822 | assert!( |
| 823 | optional_str(&json!({"s": bad}), "s").is_err(), |
| 824 | "optional_str accepted {bad}" |
| 825 | ); |
| 826 | } |
| 827 | |
| 828 | // `null` is the wire spelling of absence, uniformly across all three. |
| 829 | assert!(optional_bool(&json!({"flag": null}), "flag", true).unwrap()); |
| 830 | assert_eq!(optional_u64(&json!({"n": null}), "n", 42).unwrap(), 42); |
| 831 | assert_eq!(optional_str(&json!({"s": null}), "s").unwrap(), None); |
| 832 | } |
| 833 | |
| 834 | #[test] |
| 835 | fn type_mismatch_truncates_a_huge_offending_value() { |
| 836 | let big = Value::String("x".repeat(500)); |
| 837 | let err = type_mismatch("body", &big, "a boolean").to_string(); |
| 838 | assert!(err.contains("body"), "{err}"); |
| 839 | assert!(err.ends_with("..."), "{err}"); |
| 840 | assert!(err.chars().count() < 250, "{err}"); |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn required_u64_distinguishes_missing_from_type_mismatch() { |
| 845 | // Absent (or null) is a missing-field error. |
| 846 | assert!(matches!( |
| 847 | required_u64(&json!({}), "count"), |
| 848 | Err(ToolError::MissingField { .. }) |
| 849 | )); |
| 850 | assert!(matches!( |
| 851 | required_u64(&json!({"count": null}), "count"), |
| 852 | Err(ToolError::MissingField { .. }) |
| 853 | )); |
| 854 | |
| 855 | // Present and valid values pass through, including the extremes. |
| 856 | assert_eq!(required_u64(&json!({"count": 42}), "count").unwrap(), 42); |
| 857 | assert_eq!( |
| 858 | required_u64(&json!({"count": u64::MAX}), "count").unwrap(), |
| 859 | u64::MAX |
| 860 | ); |
| 861 | |
| 862 | // Whole-number floats are integers some providers send as `200.0`. |
| 863 | assert_eq!( |
| 864 | required_u64(&json!({"count": 200.0}), "count").unwrap(), |
| 865 | 200 |
| 866 | ); |
| 867 | assert_eq!(required_u64(&json!({"count": 0.0}), "count").unwrap(), 0); |
| 868 | assert_eq!( |
| 869 | optional_u64(&json!({"count": 200.0}), "count", 7).unwrap(), |
| 870 | 200 |
| 871 | ); |
| 872 | |
| 873 | // Present but wrongly typed is a type mismatch naming the field and |
| 874 | // the expected type — never a missing-field misdirection. Floats that |
| 875 | // are negative, fractional or beyond u64 stay refused. |
| 876 | for value in [ |
| 877 | json!(-1), |
| 878 | json!(-1.0), |
| 879 | json!(2.5), |
| 880 | json!(1.8446744073709552e19), |
| 881 | json!("42"), |
| 882 | ] { |
| 883 | let err = required_u64(&json!({"count": value}), "count") |
| 884 | .expect_err("wrong type must not look missing") |
| 885 | .to_string(); |
| 886 | assert!( |
| 887 | err.contains("field 'count' must be a non-negative integer"), |
| 888 | "{err}" |
| 889 | ); |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | #[test] |
| 894 | fn required_str_reports_provided_fields_on_missing_required_field() { |
| 895 | let input = json!({"path": "src/lib.rs", "content": "new body"}); |
| 896 | let err = required_str(&input, "replace").expect_err("replace is missing"); |
| 897 | let message = err.to_string(); |
| 898 | assert!(message.contains("missing required field 'replace'")); |
| 899 | assert!(message.contains("Input provided:")); |
| 900 | assert!(message.contains("path")); |
| 901 | assert!(message.contains("content")); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn required_str_reports_wrong_type_when_field_exists() { |
| 906 | let input = json!({"replace": [{"path": "src/lib.rs", "content": "new body"}]}); |
| 907 | let err = required_str(&input, "replace").expect_err("replace has wrong type"); |
| 908 | let message = err.to_string(); |
| 909 | assert!(message.contains("field 'replace' must be a string")); |
| 910 | assert!(message.contains("got array")); |
| 911 | assert!(message.contains(r#""content":"new body""#)); |
| 912 | assert!(message.contains(r#""path":"src/lib.rs""#)); |
| 913 | } |
| 914 | |
| 915 | #[test] |
| 916 | fn tool_error_display_matches_legacy_text() { |
| 917 | let err = ToolError::missing_field("path"); |
| 918 | assert_eq!( |
| 919 | err.to_string(), |
| 920 | "Failed to validate input: missing required field 'path'" |
| 921 | ); |
| 922 | } |
| 923 | |
| 924 | #[test] |
| 925 | fn tool_error_missing_field_constructor() { |
| 926 | let err = ToolError::missing_field("my_field"); |
| 927 | assert!(matches!(err, ToolError::MissingField { field } if field == "my_field")); |
| 928 | } |
| 929 | |
| 930 | #[test] |
| 931 | fn tool_error_not_available_displays_reason() { |
| 932 | let err = ToolError::not_available("custom tool not found"); |
| 933 | |
| 934 | assert!(matches!(err, ToolError::NotAvailable { .. })); |
| 935 | assert_eq!( |
| 936 | err.to_string(), |
| 937 | "Failed to locate tool: custom tool not found" |
| 938 | ); |
| 939 | } |
| 940 | |
| 941 | #[test] |
| 942 | fn tool_error_permission_denied_displays_reason() { |
| 943 | let err = ToolError::permission_denied("unauthorized user"); |
| 944 | |
| 945 | assert!(matches!(err, ToolError::PermissionDenied { .. })); |
| 946 | assert_eq!( |
| 947 | err.to_string(), |
| 948 | "Failed to authorize tool execution: unauthorized user" |
| 949 | ); |
| 950 | } |
| 951 | |
| 952 | #[test] |
| 953 | fn tool_error_execution_failed_displays_reason() { |
| 954 | let err = ToolError::execution_failed("process crashed"); |
| 955 | |
| 956 | assert!( |
| 957 | matches!(err, ToolError::ExecutionFailed { ref message, .. } if message == "process crashed") |
| 958 | ); |
| 959 | assert_eq!(err.to_string(), "Failed to execute tool: process crashed"); |
| 960 | } |
| 961 | |
| 962 | #[test] |
| 963 | fn tool_error_invalid_input_creates_correct_variant() { |
| 964 | let err = ToolError::invalid_input("test invalid message"); |
| 965 | match err { |
| 966 | ToolError::InvalidInput { message } => { |
| 967 | assert_eq!(message, "test invalid message"); |
| 968 | } |
| 969 | _ => panic!("Expected ToolError::InvalidInput, got {err:?}"), |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | #[test] |
| 974 | fn tool_error_path_escape_display() { |
| 975 | let path = std::path::PathBuf::from("../outside"); |
| 976 | let err = ToolError::path_escape(path); |
| 977 | assert_eq!( |
| 978 | err.to_string(), |
| 979 | "Failed to resolve path '../outside': path escapes workspace" |
| 980 | ); |
| 981 | } |
| 982 | |
| 983 | #[test] |
| 984 | fn tool_call_execution_subject_uses_local_shell_command_and_cwd() { |
| 985 | let call = ToolCall { |
| 986 | name: "shell".to_string(), |
| 987 | payload: ToolPayload::LocalShell { |
| 988 | params: codewhale_protocol::LocalShellParams { |
| 989 | command: "ls -l".to_string(), |
| 990 | cwd: Some("/custom/dir".to_string()), |
| 991 | timeout_ms: None, |
| 992 | }, |
| 993 | }, |
| 994 | source: ToolCallSource::Direct, |
| 995 | raw_tool_call_id: None, |
| 996 | }; |
| 997 | |
| 998 | assert_eq!( |
| 999 | call.execution_subject("/fallback/dir"), |
| 1000 | ("ls -l".to_string(), "/custom/dir".to_string(), "shell") |
| 1001 | ); |
| 1002 | } |
| 1003 | |
| 1004 | #[test] |
| 1005 | fn tool_call_execution_subject_falls_back_for_shell_without_cwd() { |
| 1006 | let call = ToolCall { |
| 1007 | name: "shell".to_string(), |
| 1008 | payload: ToolPayload::LocalShell { |
| 1009 | params: codewhale_protocol::LocalShellParams { |
| 1010 | command: "echo hello".to_string(), |
| 1011 | cwd: None, |
| 1012 | timeout_ms: None, |
| 1013 | }, |
| 1014 | }, |
| 1015 | source: ToolCallSource::Direct, |
| 1016 | raw_tool_call_id: None, |
| 1017 | }; |
| 1018 | |
| 1019 | assert_eq!( |
| 1020 | call.execution_subject("/fallback/dir"), |
| 1021 | ( |
| 1022 | "echo hello".to_string(), |
| 1023 | "/fallback/dir".to_string(), |
| 1024 | "shell" |
| 1025 | ) |
| 1026 | ); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn tool_call_execution_subject_uses_tool_name_for_non_shell_payloads() { |
| 1031 | let call = ToolCall { |
| 1032 | name: "my_tool".to_string(), |
| 1033 | payload: ToolPayload::Function { |
| 1034 | arguments: "{}".to_string(), |
| 1035 | }, |
| 1036 | source: ToolCallSource::Direct, |
| 1037 | raw_tool_call_id: None, |
| 1038 | }; |
| 1039 | |
| 1040 | assert_eq!( |
| 1041 | call.execution_subject("/fallback/dir"), |
| 1042 | ("my_tool".to_string(), "/fallback/dir".to_string(), "tool") |
| 1043 | ); |
| 1044 | } |
| 1045 | } |
| 1046 |