Skip to main content

mojentic/llm/tools/ephemeral_task_manager/
list_tasks.rs

1use super::task_list::TaskList;
2use crate::error::Result;
3use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
4use async_trait::async_trait;
5use serde_json::{json, Value};
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9/// Tool for listing all tasks in the ephemeral task manager
10#[derive(Clone)]
11pub struct ListTasksTool {
12    task_list: Arc<Mutex<TaskList>>,
13}
14
15impl ListTasksTool {
16    /// Creates a new ListTasksTool with a shared task list
17    pub fn new(task_list: Arc<Mutex<TaskList>>) -> Self {
18        Self { task_list }
19    }
20
21    /// Formats a list of tasks as a string
22    fn format_tasks(&self, tasks: &[super::task::Task]) -> String {
23        if tasks.is_empty() {
24            return "No tasks found.".to_string();
25        }
26
27        tasks
28            .iter()
29            .map(|task| format!("{}. {} ({})", task.id, task.description, task.status.as_str()))
30            .collect::<Vec<_>>()
31            .join("\n")
32    }
33}
34
35#[async_trait]
36impl LlmTool for ListTasksTool {
37    async fn run(
38        &self,
39        _args: &HashMap<String, Value>,
40        _ctx: &crate::llm::tools::ToolRunCtx,
41    ) -> Result<Value> {
42        let task_list = self.task_list.lock().unwrap();
43        let tasks = task_list.list_tasks();
44        let task_list_str = self.format_tasks(&tasks);
45
46        Ok(json!({
47            "count": tasks.len(),
48            "tasks": task_list_str,
49            "summary": format!("Found {} tasks\n\n{}", tasks.len(), task_list_str)
50        }))
51    }
52
53    fn descriptor(&self) -> ToolDescriptor {
54        ToolDescriptor {
55            r#type: "function".to_string(),
56            function: FunctionDescriptor {
57                name: "list_tasks".to_string(),
58                description: "List all tasks in the task list.".to_string(),
59                parameters: json!({
60                    "type": "object",
61                    "properties": {}
62                }),
63            },
64        }
65    }
66    fn clone_box(&self) -> Box<dyn LlmTool> {
67        Box::new(self.clone())
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use crate::llm::tools::ToolRunCtx;
75
76    #[tokio::test]
77    async fn test_list_tasks_empty() {
78        let task_list = Arc::new(Mutex::new(TaskList::new()));
79        let tool = ListTasksTool::new(Arc::clone(&task_list));
80        let result = tool.run(&HashMap::new(), &ToolRunCtx::default()).await.unwrap();
81        assert_eq!(result["count"], 0);
82    }
83
84    #[tokio::test]
85    async fn test_list_tasks_with_items() {
86        let task_list = Arc::new(Mutex::new(TaskList::new()));
87        {
88            let mut list = task_list.lock().unwrap();
89            list.append_task("task one".to_string());
90        }
91        let tool = ListTasksTool::new(Arc::clone(&task_list));
92        let result = tool.run(&HashMap::new(), &ToolRunCtx::default()).await.unwrap();
93        assert_eq!(result["count"], 1);
94    }
95
96    #[test]
97    fn test_descriptor() {
98        let task_list = Arc::new(Mutex::new(TaskList::new()));
99        let tool = ListTasksTool::new(task_list);
100        assert_eq!(tool.descriptor().function.name, "list_tasks");
101    }
102}