use std::sync::Arc;
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use thiserror::Error;
use crate::events::{TodoItem, TodoStatus};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const TODO_WRITE_TOOL_NAME: &str = "todo_write";
pub const MAX_TODOS: usize = 20;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum TodoError {
#[error(
"todo {index} has empty content — every step needs a short description of the work, \
e.g. \"add the --json flag\""
)]
EmptyContent { index: usize },
#[error(
"todo {index} has unknown status {status:?} — use \"pending\", \"in_progress\" or \
\"completed\""
)]
UnknownStatus { index: usize, status: String },
#[error(
"{count} todos are marked in_progress — at most one step may be in_progress at a time; \
mark the others pending or completed and send the whole list again"
)]
MultipleInProgress { count: usize },
#[error(
"{count} todos exceeds the limit of {max} — keep the checklist to the steps of the \
task in hand, not every eventual follow-up",
max = MAX_TODOS
)]
TooManyItems { count: usize },
#[error("the checklist was not stored ({0}) — the list is unchanged")]
Unavailable(String),
}
pub trait TodoStore: Send + Sync {
fn replace(&self, todos: Vec<TodoItem>) -> Result<(), TodoError>;
}
#[derive(Debug, Deserialize)]
struct RawTodo {
content: String,
status: String,
}
#[derive(Debug, Deserialize)]
struct TodoWriteArgs {
todos: Vec<RawTodo>,
}
fn parse_todos(raw: Vec<RawTodo>) -> Result<Vec<TodoItem>, TodoError> {
if raw.len() > MAX_TODOS {
return Err(TodoError::TooManyItems { count: raw.len() });
}
let mut items = Vec::with_capacity(raw.len());
for (i, item) in raw.into_iter().enumerate() {
let content = item.content.trim();
if content.is_empty() {
return Err(TodoError::EmptyContent { index: i });
}
let status = parse_status(&item.status).ok_or_else(|| TodoError::UnknownStatus {
index: i,
status: item.status.clone(),
})?;
items.push(TodoItem {
content: content.to_string(),
status,
});
}
let in_progress = items
.iter()
.filter(|t| t.status == TodoStatus::InProgress)
.count();
if in_progress > 1 {
return Err(TodoError::MultipleInProgress { count: in_progress });
}
Ok(items)
}
fn parse_status(raw: &str) -> Option<TodoStatus> {
match raw {
"pending" => Some(TodoStatus::Pending),
"in_progress" => Some(TodoStatus::InProgress),
"completed" => Some(TodoStatus::Completed),
_ => None,
}
}
fn summarise(todos: &[TodoItem]) -> String {
if todos.is_empty() {
return "Checklist cleared.".to_string();
}
let count = |s: TodoStatus| todos.iter().filter(|t| t.status == s).count();
let mut out = format!(
"Checklist updated: {} of {} completed, {} pending.",
count(TodoStatus::Completed),
todos.len(),
count(TodoStatus::Pending)
);
if let Some(active) = todos
.iter()
.find(|t| t.status == TodoStatus::InProgress)
.map(|t| t.content.as_str())
{
out.push_str(&format!(" In progress: {active}"));
}
out
}
pub struct TodoWriteTool {
store: Arc<dyn TodoStore>,
}
impl TodoWriteTool {
pub fn new(store: Arc<dyn TodoStore>) -> Self {
Self { store }
}
}
#[async_trait]
impl ToolExecutor for TodoWriteTool {
fn name(&self) -> &str {
TODO_WRITE_TOOL_NAME
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": TODO_WRITE_TOOL_NAME,
"description": "Track the steps of a multi-step task as a checklist. Call it once when you plan the work, then again the moment a step starts or finishes, so the list always shows what is done and what remains. Send the WHOLE list every time — it replaces the stored one — and keep at most one step in_progress.",
"parameters": {
"type": "object",
"properties": {
"todos": {
"type": "array",
"description": "The complete checklist, in the order the steps should happen. An empty array clears it.",
"items": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "The step, as a short imperative phrase."
},
"status": {
"type": "string",
"enum": ["pending", "in_progress", "completed"],
"description": "pending = not started; in_progress = being worked on now (at most one); completed = done."
}
},
"required": ["content", "status"],
"additionalProperties": false
}
}
},
"required": ["todos"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let parsed: TodoWriteArgs = match serde_json::from_value(args) {
Ok(p) => p,
Err(e) => {
return ToolResult::err(format!(
"todo_write arguments did not match the expected shape ({e}). Pass \
'todos' as an array of objects, each with a 'content' string and a \
'status' of \"pending\", \"in_progress\" or \"completed\"."
));
}
};
let todos = match parse_todos(parsed.todos) {
Ok(t) => t,
Err(e) => return ToolResult::err(e.to_string()),
};
let summary = summarise(&todos);
match self.store.replace(todos) {
Ok(()) => ToolResult::ok(summary),
Err(e) => ToolResult::err(e.to_string()),
}
}
}
#[cfg(test)]
#[path = "checklist_tests.rs"]
mod tests;