use super::task_list::TaskList;
use crate::error::Result;
use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct ListTasksTool {
task_list: Arc<Mutex<TaskList>>,
}
impl ListTasksTool {
pub fn new(task_list: Arc<Mutex<TaskList>>) -> Self {
Self { task_list }
}
fn format_tasks(&self, tasks: &[super::task::Task]) -> String {
if tasks.is_empty() {
return "No tasks found.".to_string();
}
tasks
.iter()
.map(|task| format!("{}. {} ({})", task.id, task.description, task.status.as_str()))
.collect::<Vec<_>>()
.join("\n")
}
}
#[async_trait]
impl LlmTool for ListTasksTool {
async fn run(
&self,
_args: &HashMap<String, Value>,
_ctx: &crate::llm::tools::ToolRunCtx,
) -> Result<Value> {
let task_list = self.task_list.lock().unwrap();
let tasks = task_list.list_tasks();
let task_list_str = self.format_tasks(&tasks);
Ok(json!({
"count": tasks.len(),
"tasks": task_list_str,
"summary": format!("Found {} tasks\n\n{}", tasks.len(), task_list_str)
}))
}
fn descriptor(&self) -> ToolDescriptor {
ToolDescriptor {
r#type: "function".to_string(),
function: FunctionDescriptor {
name: "list_tasks".to_string(),
description: "List all tasks in the task list.".to_string(),
parameters: json!({
"type": "object",
"properties": {}
}),
},
}
}
fn clone_box(&self) -> Box<dyn LlmTool> {
Box::new(self.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::tools::ToolRunCtx;
#[tokio::test]
async fn test_list_tasks_empty() {
let task_list = Arc::new(Mutex::new(TaskList::new()));
let tool = ListTasksTool::new(Arc::clone(&task_list));
let result = tool.run(&HashMap::new(), &ToolRunCtx::default()).await.unwrap();
assert_eq!(result["count"], 0);
}
#[tokio::test]
async fn test_list_tasks_with_items() {
let task_list = Arc::new(Mutex::new(TaskList::new()));
{
let mut list = task_list.lock().unwrap();
list.append_task("task one".to_string());
}
let tool = ListTasksTool::new(Arc::clone(&task_list));
let result = tool.run(&HashMap::new(), &ToolRunCtx::default()).await.unwrap();
assert_eq!(result["count"], 1);
}
#[test]
fn test_descriptor() {
let task_list = Arc::new(Mutex::new(TaskList::new()));
let tool = ListTasksTool::new(task_list);
assert_eq!(tool.descriptor().function.name, "list_tasks");
}
}