use codive_prompts::PromptStore;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileChangeMetadata {
pub file_path: String,
pub old_content: Option<String>,
pub new_content: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolOutput {
pub content: String,
pub is_error: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file_change: Option<FileChangeMetadata>,
}
impl ToolOutput {
pub fn success(content: impl Into<String>) -> Self {
Self {
content: content.into(),
is_error: false,
file_change: None,
}
}
pub fn error(content: impl Into<String>) -> Self {
Self {
content: content.into(),
is_error: true,
file_change: None,
}
}
pub fn is_success(&self) -> bool {
!self.is_error
}
pub fn with_file_change(
mut self,
file_path: impl Into<String>,
old_content: Option<String>,
new_content: impl Into<String>,
) -> Self {
self.file_change = Some(FileChangeMetadata {
file_path: file_path.into(),
old_content,
new_content: new_content.into(),
});
self
}
}
#[async_trait]
pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn parameters_schema(&self) -> serde_json::Value;
async fn execute(&self, params: serde_json::Value) -> ToolOutput;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInfo {
pub name: String,
pub description: String,
pub parameters: serde_json::Value,
}
impl ToolInfo {
pub fn from_tool(tool: &dyn Tool) -> Self {
Self {
name: tool.name().to_string(),
description: tool.description().to_string(),
parameters: tool.parameters_schema(),
}
}
}
#[derive(Default)]
pub struct ToolRegistry {
tools: HashMap<String, Arc<dyn Tool>>,
}
impl ToolRegistry {
pub fn new() -> Self {
Self {
tools: HashMap::new(),
}
}
pub fn register(&mut self, tool: Arc<dyn Tool>) {
let name = tool.name().to_string();
self.tools.insert(name, tool);
}
pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
self.tools.get(name).cloned()
}
pub fn contains(&self, name: &str) -> bool {
self.tools.contains_key(name)
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn tool_infos(&self) -> Vec<ToolInfo> {
self.tools
.values()
.map(|tool| ToolInfo::from_tool(tool.as_ref()))
.collect()
}
pub fn tool_infos_with_store(&self, store: &PromptStore) -> Vec<ToolInfo> {
self.tools
.values()
.map(|tool| {
let description = store
.tool(tool.name())
.unwrap_or_else(|| tool.description())
.to_string();
ToolInfo {
name: tool.name().to_string(),
description,
parameters: tool.parameters_schema(),
}
})
.collect()
}
pub fn names(&self) -> Vec<&str> {
self.tools.keys().map(|s| s.as_str()).collect()
}
pub fn unregister(&mut self, name: &str) -> Option<Arc<dyn Tool>> {
self.tools.remove(name)
}
}
impl std::fmt::Debug for ToolRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolRegistry")
.field("tools", &self.names())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
struct TestTool {
name: String,
}
impl TestTool {
fn new(name: impl Into<String>) -> Self {
Self { name: name.into() }
}
}
#[async_trait]
impl Tool for TestTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
"A test tool for unit tests"
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"input": { "type": "string" }
}
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let input = params
.get("input")
.and_then(|v| v.as_str())
.unwrap_or("default");
ToolOutput::success(format!("Processed: {}", input))
}
}
#[test]
fn test_tool_output_success() {
let output = ToolOutput::success("done");
assert!(output.is_success());
assert!(!output.is_error);
assert_eq!(output.content, "done");
}
#[test]
fn test_tool_output_error() {
let output = ToolOutput::error("failed");
assert!(!output.is_success());
assert!(output.is_error);
assert_eq!(output.content, "failed");
}
#[test]
fn test_registry_register_and_get() {
let mut registry = ToolRegistry::new();
assert!(registry.is_empty());
registry.register(Arc::new(TestTool::new("test")));
assert!(!registry.is_empty());
assert_eq!(registry.len(), 1);
assert!(registry.contains("test"));
let tool = registry.get("test").unwrap();
assert_eq!(tool.name(), "test");
}
#[test]
fn test_registry_get_nonexistent() {
let registry = ToolRegistry::new();
assert!(registry.get("nonexistent").is_none());
}
#[test]
fn test_registry_multiple_tools() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("tool1")));
registry.register(Arc::new(TestTool::new("tool2")));
registry.register(Arc::new(TestTool::new("tool3")));
assert_eq!(registry.len(), 3);
assert!(registry.contains("tool1"));
assert!(registry.contains("tool2"));
assert!(registry.contains("tool3"));
}
#[test]
fn test_registry_replace_tool() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("test")));
registry.register(Arc::new(TestTool::new("test")));
assert_eq!(registry.len(), 1);
}
#[test]
fn test_registry_unregister() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("test")));
assert!(registry.contains("test"));
let removed = registry.unregister("test");
assert!(removed.is_some());
assert!(!registry.contains("test"));
assert!(registry.is_empty());
}
#[test]
fn test_registry_names() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("alpha")));
registry.register(Arc::new(TestTool::new("beta")));
let mut names = registry.names();
names.sort();
assert_eq!(names, vec!["alpha", "beta"]);
}
#[test]
fn test_tool_info_from_tool() {
let tool = TestTool::new("my_tool");
let info = ToolInfo::from_tool(&tool);
assert_eq!(info.name, "my_tool");
assert_eq!(info.description, "A test tool for unit tests");
assert!(info.parameters.is_object());
}
#[test]
fn test_registry_tool_infos() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("tool1")));
registry.register(Arc::new(TestTool::new("tool2")));
let infos = registry.tool_infos();
assert_eq!(infos.len(), 2);
}
#[tokio::test]
async fn test_tool_execute() {
let tool = TestTool::new("test");
let output = tool.execute(serde_json::json!({"input": "hello"})).await;
assert!(output.is_success());
assert_eq!(output.content, "Processed: hello");
}
#[tokio::test]
async fn test_tool_execute_via_registry() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("test")));
let tool = registry.get("test").unwrap();
let output = tool.execute(serde_json::json!({"input": "world"})).await;
assert!(output.is_success());
assert_eq!(output.content, "Processed: world");
}
#[test]
fn test_registry_debug() {
let mut registry = ToolRegistry::new();
registry.register(Arc::new(TestTool::new("test")));
let debug = format!("{:?}", registry);
assert!(debug.contains("ToolRegistry"));
assert!(debug.contains("test"));
}
}