Skip to main content

aither_agent/
todo.rs

1//! Built-in todo list system for tracking long tasks.
2//!
3//! Provides a tool for agents to manage tasks during complex operations.
4//! Designed to work like Claude Code's `TodoWrite` for tracking multi-step work.
5
6use std::borrow::Cow;
7use std::fmt::Write as _;
8use std::sync::Arc;
9
10#[cfg(test)]
11mod tests {
12    use super::*;
13    use aither_core::llm::tool::ToolDefinition;
14
15    #[test]
16    fn todo_schema_has_status_enum() {
17        let tool = TodoTool::new();
18        let def = ToolDefinition::new(&tool);
19        let schema = def.arguments_openai_schema();
20
21        // Navigate to status field
22        let schema_obj = schema.as_object().expect("schema should be object");
23        let properties = schema_obj
24            .get("properties")
25            .expect("should have properties")
26            .as_object()
27            .unwrap();
28        let todos = properties
29            .get("todos")
30            .expect("should have todos")
31            .as_object()
32            .unwrap();
33        let items = todos
34            .get("items")
35            .expect("todos should have items")
36            .as_object()
37            .unwrap();
38        let item_props = items
39            .get("properties")
40            .expect("item should have properties")
41            .as_object()
42            .unwrap();
43        let status = item_props
44            .get("status")
45            .expect("should have status")
46            .as_object()
47            .unwrap();
48
49        // Status should have enum
50        assert!(
51            status.contains_key("enum") || status.contains_key("type"),
52            "Status should have enum or type field. Full schema: {}",
53            serde_json::to_string_pretty(&schema).unwrap()
54        );
55    }
56}
57
58use aither_core::llm::{Tool, ToolResult};
59use arc_swap::ArcSwap;
60use schemars::JsonSchema;
61use serde::{Deserialize, Serialize};
62
63/// Status of a todo item.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
65#[serde(rename_all = "snake_case")]
66pub enum TodoStatus {
67    /// Task not yet started.
68    Pending,
69    /// Task currently being worked on.
70    InProgress,
71    /// Task finished.
72    Completed,
73}
74
75/// A single todo item.
76#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
77pub struct TodoItem {
78    /// Description of what needs to be done (imperative form).
79    /// Example: "Run tests", "Fix authentication bug"
80    pub content: String,
81    /// Current status of the task.
82    pub status: TodoStatus,
83    /// Present continuous form shown during execution.
84    /// Example: "Running tests", "Fixing authentication bug"
85    #[serde(rename = "activeForm")]
86    pub active_form: String,
87}
88
89/// Shared todo list state.
90#[derive(Debug, Clone, Default)]
91pub struct TodoList {
92    items: Arc<ArcSwap<Vec<TodoItem>>>,
93}
94
95impl TodoList {
96    /// Creates a new empty todo list.
97    #[must_use]
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Returns all items in the list.
103    ///
104    /// # Panics
105    ///
106    /// Panics if the list lock was poisoned by a panic in another thread.
107    #[must_use]
108    pub fn items(&self) -> Vec<TodoItem> {
109        self.items.load_full().as_ref().clone()
110    }
111
112    /// Replaces the entire todo list with new items.
113    ///
114    /// # Panics
115    ///
116    /// Panics if the list lock was poisoned by a panic in another thread.
117    pub fn write(&self, items: Vec<TodoItem>) {
118        self.items.store(Arc::new(items));
119    }
120
121    /// Clears all tasks.
122    ///
123    /// # Panics
124    ///
125    /// Panics if the list lock was poisoned by a panic in another thread.
126    pub fn clear(&self) {
127        self.items.store(Arc::new(Vec::new()));
128    }
129
130    /// Returns the currently in-progress task, if any.
131    ///
132    /// # Panics
133    ///
134    /// Panics if the list lock was poisoned by a panic in another thread.
135    #[must_use]
136    pub fn current_task(&self) -> Option<TodoItem> {
137        self.items
138            .load()
139            .iter()
140            .find(|i| i.status == TodoStatus::InProgress)
141            .cloned()
142    }
143
144    /// Returns a formatted summary of progress.
145    ///
146    /// # Panics
147    ///
148    /// Panics if the list lock was poisoned by a panic in another thread.
149    #[must_use]
150    pub fn progress_summary(&self) -> String {
151        let items = self.items.load();
152        if items.is_empty() {
153            return String::new();
154        }
155
156        let completed = items
157            .iter()
158            .filter(|i| i.status == TodoStatus::Completed)
159            .count();
160        let in_progress = items
161            .iter()
162            .filter(|i| i.status == TodoStatus::InProgress)
163            .count();
164        let pending = items
165            .iter()
166            .filter(|i| i.status == TodoStatus::Pending)
167            .count();
168        let total = items.len();
169
170        let mut summary = format!("Progress: {completed}/{total} completed");
171        if in_progress > 0
172            && let Some(current) = items.iter().find(|i| i.status == TodoStatus::InProgress)
173        {
174            let _ = write!(summary, " | Current: {}", current.active_form);
175        }
176        if pending > 0 {
177            let _ = write!(summary, " | {pending} pending");
178        }
179        summary
180    }
181}
182
183/// Manage an in-memory structured task list for tracking progress on complex work.
184///
185/// This tool only updates runtime task state shown in UI/context.
186/// It does NOT create or edit tasks.md on disk.
187///
188/// Use proactively when tasks require 3+ steps, involve multiple files,
189/// or need careful organization. Updates replace the entire list.
190///
191/// Task states: pending, `in_progress`, completed.
192/// Keep exactly one task `in_progress` at a time.
193/// Mark tasks complete immediately when done.
194#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
195pub struct TodoWriteArgs {
196    /// The complete updated todo list. This replaces any existing todos.
197    pub todos: Vec<TodoItem>,
198}
199
200/// Tool for managing a todo list.
201///
202/// This tool helps track progress on complex, multi-step tasks.
203/// Use it proactively when working on tasks that require multiple steps.
204#[derive(Debug, Clone)]
205pub struct TodoTool {
206    list: TodoList,
207}
208
209impl TodoTool {
210    /// Creates a new todo tool with its own list.
211    #[must_use]
212    pub fn new() -> Self {
213        Self {
214            list: TodoList::new(),
215        }
216    }
217
218    /// Creates a todo tool sharing the given list.
219    #[must_use]
220    pub const fn with_list(list: TodoList) -> Self {
221        Self { list }
222    }
223
224    /// Returns a reference to the underlying todo list.
225    #[must_use]
226    pub const fn list(&self) -> &TodoList {
227        &self.list
228    }
229}
230
231impl Default for TodoTool {
232    fn default() -> Self {
233        Self::new()
234    }
235}
236
237impl Tool for TodoTool {
238    fn name(&self) -> Cow<'static, str> {
239        Cow::Borrowed("todo")
240    }
241
242    type Arguments = TodoWriteArgs;
243    type Res = ToolResult;
244
245    fn call(
246        &self,
247        arguments: Self::Arguments,
248    ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
249        std::future::ready((|| {
250            // Validate: at most one task should be in_progress
251            let in_progress_count = arguments
252                .todos
253                .iter()
254                .filter(|t| t.status == TodoStatus::InProgress)
255                .count();
256
257            if in_progress_count > 1 {
258                return Err(anyhow::anyhow!(
259                    "Only one task should be in_progress at a time, found {in_progress_count}"
260                ));
261            }
262
263            self.list.write(arguments.todos);
264
265            // TodoWrite succeeds with no output - the UI shows the todo list separately
266            Ok(ToolResult::Done)
267        })())
268    }
269}