use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use async_trait::async_trait;
use codewhale_protocol::{ToolKind, ToolOutput, ToolPayload};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
tokio::task_local! {
static TOOL_EXECUTION_LOCK_HELD: ();
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ToolCapability {
ReadOnly,
WritesFiles,
ExecutesCode,
Network,
Sandboxable,
RequiresApproval,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApprovalRequirement {
#[default]
Auto,
Suggest,
Required,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ToolError {
#[error("Failed to validate input: {message}")]
InvalidInput { message: String },
#[error("Failed to validate input: missing required field '{field}'")]
MissingField { field: String },
#[error("Failed to resolve path '{}': path escapes workspace", path.display())]
PathEscape { path: PathBuf },
#[error("Failed to execute tool: {message}")]
ExecutionFailed { message: String },
#[error("Failed to execute tool: operation timed out after {seconds}s")]
Timeout { seconds: u64 },
#[error("Failed to locate tool: {message}")]
NotAvailable { message: String },
#[error("Failed to authorize tool execution: {message}")]
PermissionDenied { message: String },
}
impl ToolError {
#[must_use]
pub fn invalid_input(msg: impl Into<String>) -> Self {
Self::InvalidInput {
message: msg.into(),
}
}
#[must_use]
pub fn missing_field(field: impl Into<String>) -> Self {
Self::MissingField {
field: field.into(),
}
}
#[must_use]
pub fn execution_failed(msg: impl Into<String>) -> Self {
Self::ExecutionFailed {
message: msg.into(),
}
}
#[must_use]
pub fn path_escape(path: impl Into<PathBuf>) -> Self {
Self::PathEscape { path: path.into() }
}
#[must_use]
pub fn not_available(msg: impl Into<String>) -> Self {
Self::NotAvailable {
message: msg.into(),
}
}
#[must_use]
pub fn permission_denied(msg: impl Into<String>) -> Self {
Self::PermissionDenied {
message: msg.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
pub content: String,
pub success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
impl ToolResult {
#[must_use]
pub fn success(content: impl Into<String>) -> Self {
Self {
content: content.into(),
success: true,
metadata: None,
}
}
#[must_use]
pub fn error(message: impl Into<String>) -> Self {
Self {
content: message.into(),
success: false,
metadata: None,
}
}
pub fn json<T: Serialize>(value: &T) -> std::result::Result<Self, serde_json::Error> {
Ok(Self {
content: serde_json::to_string_pretty(value)?,
success: true,
metadata: None,
})
}
#[must_use]
pub fn with_metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
}
pub fn required_str<'a>(input: &'a Value, field: &str) -> std::result::Result<&'a str, ToolError> {
input.get(field).and_then(Value::as_str).ok_or_else(|| {
let provided: Vec<&str> = input
.as_object()
.map(|obj| obj.keys().map(|k| k.as_str()).collect())
.unwrap_or_default();
if provided.is_empty() {
ToolError::missing_field(field)
} else {
let hint = format!(
"missing required field '{field}'. Input provided: {}",
provided.join(", ")
);
ToolError::invalid_input(hint)
}
})
}
#[must_use]
pub fn optional_str<'a>(input: &'a Value, field: &str) -> Option<&'a str> {
input.get(field).and_then(Value::as_str)
}
pub fn required_u64(input: &Value, field: &str) -> std::result::Result<u64, ToolError> {
input
.get(field)
.and_then(Value::as_u64)
.ok_or_else(|| ToolError::missing_field(field))
}
#[must_use]
pub fn optional_u64(input: &Value, field: &str, default: u64) -> u64 {
input.get(field).and_then(Value::as_u64).unwrap_or(default)
}
#[must_use]
pub fn optional_bool(input: &Value, field: &str, default: bool) -> bool {
input.get(field).and_then(Value::as_bool).unwrap_or(default)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSpec {
pub name: String,
pub input_schema: Value,
pub output_schema: Value,
pub supports_parallel_tool_calls: bool,
pub timeout_ms: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfiguredToolSpec {
pub spec: ToolSpec,
pub supports_parallel_tool_calls: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolCallSource {
Direct,
JsRepl,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
pub name: String,
pub payload: ToolPayload,
pub source: ToolCallSource,
pub raw_tool_call_id: Option<String>,
}
impl ToolCall {
pub fn execution_subject(&self, fallback_cwd: &str) -> (String, String, &'static str) {
match &self.payload {
ToolPayload::LocalShell { params } => (
params.command.clone(),
params
.cwd
.clone()
.unwrap_or_else(|| fallback_cwd.to_string()),
"shell",
),
_ => (self.name.clone(), fallback_cwd.to_string(), "tool"),
}
}
}
#[derive(Debug, Clone)]
pub struct ToolInvocation {
pub call_id: String,
pub tool_name: String,
pub payload: ToolPayload,
pub source: ToolCallSource,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FunctionCallError {
ToolNotFound { name: String },
KindMismatch { expected: ToolKind, got: ToolKind },
MutatingToolRejected { name: String },
TimedOut { name: String, timeout_ms: u64 },
Cancelled { name: String },
ExecutionFailed { name: String, error: String },
}
#[async_trait]
pub trait ToolHandler: Send + Sync {
fn kind(&self) -> ToolKind;
fn matches_kind(&self, kind: ToolKind) -> bool {
self.kind() == kind
}
fn is_mutating(&self) -> bool {
false
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> std::result::Result<ToolOutput, FunctionCallError>;
}
#[derive(Debug)]
pub struct ToolCallRuntime {
execution_lock: Arc<RwLock<()>>,
}
impl Default for ToolCallRuntime {
fn default() -> Self {
Self {
execution_lock: Arc::new(RwLock::new(())),
}
}
}
#[derive(Debug)]
enum ToolExecutionGuard {
Parallel(#[allow(dead_code)] OwnedRwLockReadGuard<()>),
Serial(#[allow(dead_code)] OwnedRwLockWriteGuard<()>),
Reentrant,
}
impl ToolCallRuntime {
async fn acquire(&self, supports_parallel: bool) -> ToolExecutionGuard {
if TOOL_EXECUTION_LOCK_HELD.try_with(|_| ()).is_ok() {
return ToolExecutionGuard::Reentrant;
}
if supports_parallel {
ToolExecutionGuard::Parallel(self.execution_lock.clone().read_owned().await)
} else {
ToolExecutionGuard::Serial(self.execution_lock.clone().write_owned().await)
}
}
}
#[derive(Default)]
pub struct ToolRegistry {
handlers: HashMap<String, Arc<dyn ToolHandler>>,
specs: HashMap<String, ConfiguredToolSpec>,
runtime: ToolCallRuntime,
}
impl ToolRegistry {
pub fn register(&mut self, spec: ToolSpec, handler: Arc<dyn ToolHandler>) -> Result<()> {
let name = spec.name.clone();
self.specs.insert(
name.clone(),
ConfiguredToolSpec {
supports_parallel_tool_calls: spec.supports_parallel_tool_calls,
spec,
},
);
self.handlers.insert(name, handler);
Ok(())
}
pub fn list_specs(&self) -> Vec<ConfiguredToolSpec> {
self.specs.values().cloned().collect()
}
pub async fn dispatch(
&self,
call: ToolCall,
allow_mutating: bool,
) -> std::result::Result<ToolOutput, FunctionCallError> {
let handler = self.handlers.get(&call.name).cloned().ok_or_else(|| {
FunctionCallError::ToolNotFound {
name: call.name.clone(),
}
})?;
let configured =
self.specs
.get(&call.name)
.cloned()
.ok_or_else(|| FunctionCallError::ToolNotFound {
name: call.name.clone(),
})?;
let payload_kind = tool_payload_kind(&call.payload);
let expected = handler.kind();
if !handler.matches_kind(payload_kind) {
return Err(FunctionCallError::KindMismatch {
expected,
got: payload_kind,
});
}
if handler.is_mutating() && !allow_mutating {
return Err(FunctionCallError::MutatingToolRejected { name: call.name });
}
let invocation = ToolInvocation {
call_id: call
.raw_tool_call_id
.clone()
.unwrap_or_else(|| format!("tool-call-{}", uuid::Uuid::new_v4())),
tool_name: call.name.clone(),
payload: call.payload,
source: call.source,
};
let _guard = self
.runtime
.acquire(configured.supports_parallel_tool_calls)
.await;
TOOL_EXECUTION_LOCK_HELD
.scope(
(),
self.execute_with_timeout(handler, configured.spec.timeout_ms, invocation),
)
.await
}
async fn execute_with_timeout(
&self,
handler: Arc<dyn ToolHandler>,
timeout_ms: Option<u64>,
invocation: ToolInvocation,
) -> std::result::Result<ToolOutput, FunctionCallError> {
if let Some(timeout_ms) = timeout_ms {
let name = invocation.tool_name.clone();
match tokio::time::timeout(
Duration::from_millis(timeout_ms),
handler.handle(invocation),
)
.await
{
Ok(result) => result,
Err(_) => Err(FunctionCallError::TimedOut { name, timeout_ms }),
}
} else {
handler.handle(invocation).await
}
}
}
fn tool_payload_kind(payload: &ToolPayload) -> ToolKind {
match payload {
ToolPayload::Mcp { .. } => ToolKind::Mcp,
ToolPayload::Function { .. }
| ToolPayload::Custom { .. }
| ToolPayload::LocalShell { .. } => ToolKind::Function,
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn tool_result_success_sets_plain_content() {
let content = "operation completed successfully";
let result = ToolResult::success(content);
assert!(result.success);
assert_eq!(result.content, content);
assert!(result.metadata.is_none());
}
#[test]
fn tool_result_json_round_trips_content() {
let result = ToolResult::json(&json!({"ok": true})).expect("json");
assert!(result.success);
assert!(result.content.contains("\"ok\": true"));
}
#[test]
fn helper_extractors_validate_shape() {
let input = json!({"name": "demo", "count": 7, "enabled": true});
assert_eq!(required_str(&input, "name").expect("name"), "demo");
assert_eq!(optional_str(&input, "name"), Some("demo"));
assert_eq!(optional_str(&input, "missing"), None);
assert_eq!(optional_str(&input, "count"), None);
assert_eq!(optional_str(&json!({"name": null}), "name"), None);
assert_eq!(optional_u64(&input, "count", 0), 7);
assert!(optional_bool(&input, "enabled", false));
assert!(matches!(
required_u64(&input, "name"),
Err(ToolError::MissingField { .. })
));
}
#[test]
fn required_u64_rejects_missing_or_non_integer_values() {
assert!(matches!(
required_u64(&json!({}), "count"),
Err(ToolError::MissingField { .. })
));
assert_eq!(required_u64(&json!({"count": 42}), "count").unwrap(), 42);
assert_eq!(
required_u64(&json!({"count": u64::MAX}), "count").unwrap(),
u64::MAX
);
for value in [json!(-1), json!(2.5), json!("42")] {
assert!(matches!(
required_u64(&json!({"count": value}), "count"),
Err(ToolError::MissingField { .. })
));
}
}
#[test]
fn required_str_reports_provided_fields_on_missing_required_field() {
let input = json!({"path": "src/lib.rs", "content": "new body"});
let err = required_str(&input, "replace").expect_err("replace is missing");
let message = err.to_string();
assert!(message.contains("missing required field 'replace'"));
assert!(message.contains("Input provided:"));
assert!(message.contains("path"));
assert!(message.contains("content"));
}
#[test]
fn tool_error_display_matches_legacy_text() {
let err = ToolError::missing_field("path");
assert_eq!(
err.to_string(),
"Failed to validate input: missing required field 'path'"
);
}
#[test]
fn tool_error_missing_field_constructor() {
let err = ToolError::missing_field("my_field");
assert!(matches!(err, ToolError::MissingField { field } if field == "my_field"));
}
#[test]
fn tool_error_not_available_displays_reason() {
let err = ToolError::not_available("custom tool not found");
assert!(matches!(err, ToolError::NotAvailable { .. }));
assert_eq!(
err.to_string(),
"Failed to locate tool: custom tool not found"
);
}
#[test]
fn tool_error_permission_denied_displays_reason() {
let err = ToolError::permission_denied("unauthorized user");
assert!(matches!(err, ToolError::PermissionDenied { .. }));
assert_eq!(
err.to_string(),
"Failed to authorize tool execution: unauthorized user"
);
}
#[test]
fn tool_error_execution_failed_displays_reason() {
let err = ToolError::execution_failed("process crashed");
assert!(
matches!(err, ToolError::ExecutionFailed { ref message } if message == "process crashed")
);
assert_eq!(err.to_string(), "Failed to execute tool: process crashed");
}
#[test]
fn tool_error_invalid_input_creates_correct_variant() {
let err = ToolError::invalid_input("test invalid message");
match err {
ToolError::InvalidInput { message } => {
assert_eq!(message, "test invalid message");
}
_ => panic!("Expected ToolError::InvalidInput, got {err:?}"),
}
}
#[test]
fn tool_error_path_escape_display() {
let path = std::path::PathBuf::from("../outside");
let err = ToolError::path_escape(path);
assert_eq!(
err.to_string(),
"Failed to resolve path '../outside': path escapes workspace"
);
}
#[test]
fn tool_call_execution_subject_uses_local_shell_command_and_cwd() {
let call = ToolCall {
name: "shell".to_string(),
payload: ToolPayload::LocalShell {
params: codewhale_protocol::LocalShellParams {
command: "ls -l".to_string(),
cwd: Some("/custom/dir".to_string()),
timeout_ms: None,
},
},
source: ToolCallSource::Direct,
raw_tool_call_id: None,
};
assert_eq!(
call.execution_subject("/fallback/dir"),
("ls -l".to_string(), "/custom/dir".to_string(), "shell")
);
}
#[test]
fn tool_call_execution_subject_falls_back_for_shell_without_cwd() {
let call = ToolCall {
name: "shell".to_string(),
payload: ToolPayload::LocalShell {
params: codewhale_protocol::LocalShellParams {
command: "echo hello".to_string(),
cwd: None,
timeout_ms: None,
},
},
source: ToolCallSource::Direct,
raw_tool_call_id: None,
};
assert_eq!(
call.execution_subject("/fallback/dir"),
(
"echo hello".to_string(),
"/fallback/dir".to_string(),
"shell"
)
);
}
#[test]
fn tool_call_execution_subject_uses_tool_name_for_non_shell_payloads() {
let call = ToolCall {
name: "my_tool".to_string(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
source: ToolCallSource::Direct,
raw_tool_call_id: None,
};
assert_eq!(
call.execution_subject("/fallback/dir"),
("my_tool".to_string(), "/fallback/dir".to_string(), "tool")
);
}
}