Skip to main content

strands/vended_plugins/todos/
mod.rs

1//! `Todos`: a structured task list the agent maintains for multi-step work.
2//!
3//! A single `todo_write` tool writes the current list to the agent's app state; an internal
4//! [`ContextInjector`] re-renders that list at intervals, so the agent keeps its plan in view
5//! without restating it. Each rendered list is an injected block, and only the latest user
6//! message's injected blocks are sent, so the model sees one current copy.
7//!
8//! The reminder is paced in model calls, not user turns, so a long single invocation gets it
9//! mid-loop. The model last saw the list on the call after a `todo_write` or in a reminder; the
10//! next reminder waits `reminder_interval` model calls after that, since repeating a list the
11//! model has just read only costs tokens.
12//!
13//! ```
14//! use strands::Agent;
15//! use strands::testing::MockModel;
16//! use strands::vended_plugins::todos::Todos;
17//!
18//! let agent = Agent::builder()
19//!     .model(MockModel::new())
20//!     .plugins([Todos::default()])
21//!     .printer(false)
22//!     .build()?;
23//! # let _ = agent;
24//! # Ok::<(), strands::Error>(())
25//! ```
26
27use 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
45// The `todo_write` tool description.
46const 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/// Where a todo stands.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57#[non_exhaustive]
58pub enum TodoStatus {
59    /// Not started (`pending`).
60    Pending,
61    /// Being worked on (`in_progress`).
62    InProgress,
63    /// Done (`completed`).
64    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/// One entry of the todo list, stored in app state in this JSON shape. Unknown keys are dropped on
78/// input.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(rename_all = "camelCase")]
81#[non_exhaustive]
82pub struct TodoItem {
83    /// The task, imperative: "Run tests".
84    pub content: String,
85    /// Present continuous, shown while in progress: "Running tests".
86    pub active_form: String,
87    /// Where the task stands.
88    pub status: TodoStatus,
89}
90
91impl TodoItem {
92    /// A todo.
93    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/// Configuration for the [`Todos`] plugin (`TodosConfig`).
148#[derive(Debug, Clone, Default, bon::Builder)]
149#[builder(on(String, into))]
150pub struct TodosConfig {
151    /// Plugin name. It also tags the reminder blocks the plugin injects, and that tag keeps a retry
152    /// or a restored session from injecting a second copy, so keep it stable. Defaults to
153    /// `strands:todos`.
154    pub name: Option<String>,
155    /// App-state key the list is stored under. Defaults to `todos`.
156    pub state_key: Option<String>,
157    /// Re-render the list every this many model calls, counted from the call that last showed it:
158    /// the one after a `todo_write` call, or a reminder. `1` re-renders it on every call that does
159    /// not already carry a `todo_write` result. Defaults to `10`.
160    pub reminder_interval: Option<NonZeroUsize>,
161}
162
163/// Gives the agent a `todo_write` tool and keeps the current list in view (`Todos`).
164///
165/// The tool persists the list to the agent's app state under the state key; every
166/// `reminder_interval` model calls, counted from the call that last showed the list, the plugin
167/// re-renders it as a `<system-reminder>`. Sharing one instance across agents is safe: the list
168/// lives in per-agent state, not on the plugin.
169///
170/// One agent takes one `Todos`. The tool is always named `todo_write`, so registering a second
171/// instance fails no matter how `name` and `state_key` are set.
172///
173/// A reminder changes the tail of the request it is sent with. On a provider without explicit
174/// cache points that moves the cached prefix boundary, so a lower `reminder_interval` trades cache
175/// hits and tokens for a fresher list.
176#[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    /// The plugin with `config`.
192    #[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    /// The `todo_write` tool, writing to `state_key`.
206    #[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    /// Whether there is a list and `reminder_interval` model calls have passed since one showed it.
232    /// Read from the messages rather than a counter, so there is no state to restore, and a list
233    /// the conversation does not show is re-rendered at once.
234    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;