strands/vended_plugins/todos/
mod.rs1use std::num::NonZeroUsize;
28
29use async_trait::async_trait;
30use serde::{Deserialize, Serialize};
31use serde_json::json;
32
33use crate::agent::LocalAgent;
34use crate::injection::{InjectionContext, InjectionTrigger};
35use crate::plugins::Plugin;
36use crate::tools::{FunctionTool, ToolError, ToolSource};
37use crate::types::{ContentBlock, JsonSchema, JsonValue, Role};
38use crate::vended_plugins::context_injector::{ContextInjector, ContextInjectorConfig};
39
40const STATE_KEY: &str = "todos";
41const DEFAULT_NAME: &str = "strands:todos";
42const DEFAULT_REMINDER_INTERVAL: usize = 10;
43const TOOL_NAME: &str = "todo_write";
44
45const TODO_WRITE_DESCRIPTION: &str = concat!(
47 "Create and maintain a structured task list for the current session. Use proactively for ",
48 "multi-step work (roughly 3+ distinct steps). Keep exactly one item in_progress at a time, ",
49 "and update status as you go rather than batching. The current list is re-surfaced to you ",
50 "periodically, so you do not need to restate it. Pass an empty list to clear it when the ",
51 "work is done."
52);
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57#[non_exhaustive]
58pub enum TodoStatus {
59 Pending,
61 InProgress,
63 Completed,
65}
66
67impl TodoStatus {
68 fn as_str(self) -> &'static str {
69 match self {
70 Self::Pending => "pending",
71 Self::InProgress => "in_progress",
72 Self::Completed => "completed",
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(rename_all = "camelCase")]
81#[non_exhaustive]
82pub struct TodoItem {
83 pub content: String,
85 pub active_form: String,
87 pub status: TodoStatus,
89}
90
91impl TodoItem {
92 pub fn new(content: impl Into<String>, active_form: impl Into<String>, status: TodoStatus) -> Self {
94 Self {
95 content: content.into(),
96 active_form: active_form.into(),
97 status,
98 }
99 }
100}
101
102#[derive(Deserialize)]
103struct TodoWriteInput {
104 todos: Vec<TodoItem>,
105}
106
107fn todo_line(todo: &TodoItem) -> String {
108 let label = if todo.status == TodoStatus::InProgress && !todo.active_form.is_empty() {
109 &todo.active_form
110 } else {
111 &todo.content
112 };
113 format!(" [{}] {label}", todo.status.as_str())
114}
115
116fn render_list(todos: &[TodoItem]) -> String {
117 todos.iter().map(todo_line).collect::<Vec<_>>().join("\n")
118}
119
120fn input_schema() -> JsonSchema {
121 json!({
122 "type": "object",
123 "properties": {
124 "todos": {
125 "type": "array",
126 "items": {
127 "type": "object",
128 "properties": {
129 "content": {"type": "string", "description": "The task, imperative: \"Run tests\"."},
130 "activeForm": {
131 "type": "string",
132 "description": "Present continuous, shown while in progress: \"Running tests\"."
133 },
134 "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]}
135 },
136 "required": ["content", "activeForm", "status"],
137 "additionalProperties": false
138 },
139 "description": "The full updated list."
140 }
141 },
142 "required": ["todos"],
143 "additionalProperties": false
144 })
145}
146
147#[derive(Debug, Clone, Default, bon::Builder)]
149#[builder(on(String, into))]
150pub struct TodosConfig {
151 pub name: Option<String>,
155 pub state_key: Option<String>,
157 pub reminder_interval: Option<NonZeroUsize>,
161}
162
163#[derive(Debug, Clone)]
177pub struct Todos {
178 name: String,
179 state_key: String,
180 reminder_interval: usize,
181 injector_name: String,
182}
183
184impl Default for Todos {
185 fn default() -> Self {
186 Self::new(TodosConfig::default())
187 }
188}
189
190impl Todos {
191 #[must_use]
193 pub fn new(config: TodosConfig) -> Self {
194 let name = config.name.unwrap_or_else(|| DEFAULT_NAME.to_owned());
195 Self {
196 injector_name: format!("{name}:injector"),
197 name,
198 state_key: config.state_key.unwrap_or_else(|| STATE_KEY.to_owned()),
199 reminder_interval: config
200 .reminder_interval
201 .map_or(DEFAULT_REMINDER_INTERVAL, NonZeroUsize::get),
202 }
203 }
204
205 #[must_use]
207 pub fn todo_write_tool(&self) -> FunctionTool {
208 let state_key = self.state_key.clone();
209 FunctionTool::builder(TOOL_NAME, TODO_WRITE_DESCRIPTION)
210 .input_schema(input_schema())
211 .callback(move |input, context| {
212 let state_key = state_key.clone();
213 async move {
214 let input: TodoWriteInput = serde_json::from_value(input)?;
215 let state = context.agent().app_state();
216 if input.todos.is_empty() {
217 state.delete(&state_key);
218 return Ok::<JsonValue, ToolError>("Todo list cleared".into());
219 }
220 state.set(&state_key, &input.todos)?;
221 let remaining = input
222 .todos
223 .iter()
224 .filter(|todo| todo.status != TodoStatus::Completed)
225 .count();
226 Ok(format!("{remaining} todos remaining\n{}", render_list(&input.todos)).into())
227 }
228 })
229 }
230
231 fn reminder_due(&self, context: &InjectionContext) -> bool {
235 let todos: Option<Vec<TodoItem>> = context.app_state.get(&self.state_key).ok().flatten();
236 if todos.is_none_or(|todos| todos.is_empty()) {
237 return false;
238 }
239 let mut calls_since_shown = 0;
240 for message in context.messages.iter().rev() {
241 if message.content.iter().any(|block| self.shows_list(block)) {
242 return calls_since_shown >= self.reminder_interval;
243 }
244 if message.role == Role::Assistant {
245 calls_since_shown += 1;
246 }
247 }
248 true
249 }
250
251 fn shows_list(&self, block: &ContentBlock) -> bool {
252 match block {
253 ContentBlock::Injected(injected) => injected.source == self.injector_name,
254 ContentBlock::ToolUse(tool_use) => tool_use.name == TOOL_NAME,
255 _ => false,
256 }
257 }
258
259 fn render_reminder(state_key: &str, context: &InjectionContext) -> Option<String> {
260 let todos: Vec<TodoItem> = context.app_state.get(state_key).ok().flatten()?;
261 if todos.is_empty() {
262 return None;
263 }
264 Some(format!(
265 "<system-reminder>\nYour current todo list:\n{}\nKeep it up to date with todo_write as you work.\n</system-reminder>",
266 render_list(&todos)
267 ))
268 }
269}
270
271#[async_trait]
272impl Plugin for Todos {
273 fn name(&self) -> &str {
274 &self.name
275 }
276
277 async fn init_agent(&self, agent: &mut LocalAgent) -> crate::Result<()> {
278 let state_key = self.state_key.clone();
279 let pacing = self.clone();
280 let config = ContextInjectorConfig::new(move |context| {
281 let reminder = Self::render_reminder(&state_key, &context);
282 async move { Ok(reminder) }
283 })
284 .with_name(self.injector_name.clone())
285 .with_trigger(InjectionTrigger::predicate(move |context| {
286 Ok(pacing.reminder_due(context))
287 }));
288 ContextInjector::new(config).init_agent(agent).await
289 }
290
291 fn get_tools(&self) -> Vec<ToolSource> {
292 vec![self.todo_write_tool().into()]
293 }
294}
295
296#[cfg(test)]
297mod tests;