1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::PathBuf;
5use strum::Display;
6
7#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq, JsonSchema, Hash, Display)]
9#[serde(rename_all = "snake_case")]
10pub enum TodoStatus {
11 Pending,
12 #[strum(serialize = "In Progress")]
13 InProgress,
14 Completed,
15}
16
17#[derive(
19 Deserialize, Serialize, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, JsonSchema, Hash, Display,
20)]
21#[serde(rename_all = "snake_case")]
22pub enum TodoPriority {
23 High = 0,
24 Medium = 1,
25 Low = 2,
26}
27
28#[derive(Deserialize, Serialize, Debug, Clone, JsonSchema, Hash)]
30pub struct TodoItem {
31 pub content: String,
33 pub status: TodoStatus,
35 pub priority: TodoPriority,
37 pub id: String,
39}
40
41#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq, JsonSchema, Hash)]
42#[serde(rename_all = "snake_case")]
43pub enum TodoWriteFileOperation {
44 Created,
45 Modified,
46}
47
48pub type TodoList = Vec<TodoItem>;
50
51fn get_todos_dir() -> Result<PathBuf, std::io::Error> {
53 let home_dir = dirs::home_dir().ok_or_else(|| {
54 std::io::Error::new(std::io::ErrorKind::NotFound, "Home directory not found")
55 })?;
56 let todos_dir = home_dir.join(".steer").join("todos");
57
58 if !todos_dir.exists() {
59 fs::create_dir_all(&todos_dir)?;
60 }
61
62 Ok(todos_dir)
63}
64
65fn get_todo_file_path() -> Result<PathBuf, std::io::Error> {
67 let workspace_id = match std::env::var("STEER_WORKSPACE_ID") {
68 Ok(id) => id,
69 Err(_) => {
70 let current_dir = std::env::current_dir()?;
72 hex::encode(current_dir.to_string_lossy().as_bytes())
74 }
75 };
76 let dir = get_todos_dir()?;
77 Ok(dir.join(format!("{workspace_id}.json")))
78}
79
80fn read_todos() -> Result<TodoList, std::io::Error> {
82 let file_path = get_todo_file_path()?;
83
84 if !file_path.exists() {
85 return Ok(Vec::new());
86 }
87
88 let content = fs::read_to_string(&file_path)?;
89 serde_json::from_str(&content)
90 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
91}
92
93fn write_todos(todos: &TodoList) -> Result<TodoWriteFileOperation, std::io::Error> {
95 let file_path = get_todo_file_path()?;
96 let file_existed = file_path.exists();
97
98 let content = serde_json::to_string_pretty(todos)
99 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
100 fs::write(&file_path, content)?;
101
102 Ok(if file_existed {
103 TodoWriteFileOperation::Modified
104 } else {
105 TodoWriteFileOperation::Created
106 })
107}
108
109pub mod read {
110 use super::read_todos;
111 use crate::result::TodoListResult;
112 use crate::{ExecutionContext, ToolError};
113 use schemars::JsonSchema;
114 use serde::{Deserialize, Serialize};
115 use steer_macros::tool;
116
117 #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
118 pub struct TodoReadParams {
120 }
122
123 tool! {
124 TodoReadTool {
125 params: TodoReadParams,
126 output: TodoListResult,
127 variant: TodoRead,
128 description: r#"Use this tool to read the current to-do list for the session. This tool should be used proactively and frequently to ensure that you are aware of
129the status of the current task list. You should make use of this tool as often as possible, especially in the following situations:
130- At the beginning of conversations to see what's pending
131- Before starting new tasks to prioritize work
132- When the user asks about previous tasks or plans
133- Whenever you're uncertain about what to do next
134- After completing tasks to update your understanding of remaining work
135- After every few messages to ensure you're on track
136
137Usage:
138- This tool takes in no parameters. So leave the input blank or empty. DO NOT include a dummy object, placeholder string or a key like "input" or "empty". LEAVE IT BLANK.
139- Returns a list of todo items with their status, priority, and content
140- Use this information to track progress and plan next steps
141- If no todos exist yet, an empty list will be returned"#,
142 name: "TodoRead",
143 require_approval: false
144 }
145
146 async fn run(
147 _tool: &TodoReadTool,
148 _params: TodoReadParams,
149 context: &ExecutionContext,
150 ) -> Result<TodoListResult, ToolError> {
151 if context.cancellation_token.is_cancelled() {
153 return Err(ToolError::Cancelled(TODO_READ_TOOL_NAME.to_string()));
154 }
155
156 let todos = read_todos().map_err(|e| ToolError::io(TODO_READ_TOOL_NAME, e.to_string()))?;
157 Ok(TodoListResult {
158 todos,
159 })
160 }
161 }
162}
163
164pub mod write {
165 use super::{TodoList, write_todos};
166 use crate::result::TodoWriteResult;
167 use crate::tools::todo::TodoWriteFileOperation;
168 use crate::{ExecutionContext, ToolError};
169 use schemars::JsonSchema;
170 use serde::{Deserialize, Serialize};
171 use steer_macros::tool;
172
173 #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
174 pub struct TodoWriteParams {
175 pub todos: TodoList,
177 }
178
179 tool! {
180 TodoWriteTool {
181 params: TodoWriteParams,
182 output: TodoWriteResult,
183 variant: TodoWrite,
184 description: r#"Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
185It also helps the user understand the progress of the task and overall progress of their requests.
186
187## When to Use This Tool
188Use this tool proactively in these scenarios:
189
1901. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
1912. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
1923. User explicitly requests todo list - When the user directly asks you to use the todo list
1934. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
1945. After receiving new instructions - Immediately capture user requirements as todos
1956. After completing a task - Mark it complete and add any new follow-up tasks
1967. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones.
197
198## When NOT to Use This Tool
199
200Skip using this tool when:
2011. There is only a single, straightforward task
2022. The task is trivial and tracking it provides no organizational benefit
2033. The task can be completed in less than 3 trivial steps
2044. The task is purely conversational or informational
205
206NOTE that you should use should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
207
208## Examples of When to Use the Todo List
209
210<example>
211User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
212Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
213*Uses grep or search tools to locate all instances of getCwd in the codebase*
214Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
215*Creates todo list with specific items for each file that needs updating*
216
217<reasoning>
218The assistant used the todo list because:
2191. First, the assistant searched to understand the scope of the task
2202. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
2213. The todo list helps ensure every instance is tracked and updated systematically
2224. This approach prevents missing any occurrences and maintains code consistency
223</reasoning>
224</example>
225
226
227<example>
228User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
229Assistant: I'll help implement these features. First, let's add all the features to the todo list.
230*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
231Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
232
233<reasoning>
234The assistant used the todo list because:
2351. The user provided multiple complex features to implement in a comma separated list
2362. The todo list helps organize these large features into manageable tasks
2373. This approach allows for tracking progress across the entire implementation
238</reasoning>
239</example>
240
241<example>
242User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
243Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
244*Reviews component structure, render patterns, state management, and data fetching*
245Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
246*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
247Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
248
249<reasoning>
250The assistant used the todo list because:
2511. First, the assistant examined the codebase to identify specific performance issues
2522. Based on this analysis, it identified multiple optimization opportunities
2533. Performance optimization is a non-trivial task requiring multiple steps
2544. The todo list helps methodically track improvements across different components
2555. This systematic approach ensures all performance bottlenecks are addressed
256</reasoning>
257</example>
258
259## Examples of When NOT to Use the Todo List
260
261<example>
262User: How do I print 'Hello World' in Python?
263Assistant: In Python, you can print "Hello World" with this simple code:
264
265python
266print("Hello World")
267
268This will output the text "Hello World" to the console when executed.</assistant>
269
270<reasoning>
271The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
272</reasoning>
273</example>
274
275<example>
276User: What does the git status command do?
277Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
278
279<reasoning>
280The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
281</reasoning>
282</example>
283
284<example>
285User: Can you add a comment to the calculateTotal function to explain what it does?
286Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
287* Uses the edit_file tool to add a comment to the calculateTotal function *
288
289<reasoning>
290The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
291</reasoning>
292</example>
293
294<example>
295User: Run npm install for me and tell me what happens.
296Assistant: I'll run the npm install command for you.
297
298*Executes: npm install*
299
300The command completed successfully. Here's the output:
301[Output of npm install command]
302
303All dependencies have been installed according to your package.json file.
304
305<reasoning>
306The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
307</reasoning>
308</example>
309
310## Task States and Management
311
3121. **Task States**: Use these states to track progress:
313 - pending: Task not yet started
314 - in_progress: Currently working on (limit to ONE task at a time)
315 - completed: Task finished successfully
316 - cancelled: Task no longer needed
317
3182. **Task Management**:
319 - Update task status in real-time as you work
320 - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
321 - Only have ONE task in_progress at any time
322 - Complete current tasks before starting new ones
323 - Cancel tasks that become irrelevant
324
3253. **Task Breakdown**:
326 - Create specific, actionable items
327 - Break complex tasks into smaller, manageable steps
328 - Use clear, descriptive task names
329
330When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully."#,
331 name: "TodoWrite",
332 require_approval: false
333 }
334
335 async fn run(
336 _tool: &TodoWriteTool,
337 params: TodoWriteParams,
338 context: &ExecutionContext,
339 ) -> Result<TodoWriteResult, ToolError> {
340 if context.cancellation_token.is_cancelled() {
342 return Err(ToolError::Cancelled(TODO_WRITE_TOOL_NAME.to_string()));
343 }
344
345 write_todos(¶ms.todos).map_err(|e| ToolError::io(TODO_WRITE_TOOL_NAME, e.to_string()))?;
347
348 Ok(TodoWriteResult {
349 todos: params.todos,
350 operation: TodoWriteFileOperation::Created,
351 })
352 }
353 }
354}