1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
"""Task tracking for multi-step work.
An agent given a five-part task will quietly do three of them and report
success. Writing the plan down first, and updating it as it goes, is the
cheapest thing that keeps the whole task in view.
The list lives in memory and is rendered back to the model on every update, so
the current state is always in the conversation rather than something the model
has to remember.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from ..errors import ToolError
from .base import BaseTool
#: The states a task moves through. Kept small on purpose.
STATUSES = ("pending", "in_progress", "completed", "cancelled")
#: The columns a rendered board uses, in order.
ORDER = ("in_progress", "pending", "completed", "cancelled")
MAX_TASKS = 50
class TodoTool(BaseTool):
"""Maintain a checklist of what the current task requires."""
def __init__(self) -> None:
self._items: List[Dict[str, str]] = []
self._next_id = 1
@property
def name(self) -> str:
return "todo"
@property
def description(self) -> str:
return (
"Track a checklist of steps for the current task. Create the full "
"list before starting a multi-step job, keep exactly one item "
"'in_progress' at a time, and mark items completed as you finish "
"them. The rendered list comes back on every update, so you do not "
"need to track it yourself. Use it for anything with more than "
"about three steps; skip it for single actions."
)
@property
def parameters(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["add", "update", "list", "clear"],
"description": (
"add: append tasks. update: change one task's status. "
"list: render the current checklist. clear: remove all."
),
},
"tasks": {
"type": "array",
"items": {"type": "string"},
"description": "Task descriptions. Required for 'add'.",
},
"id": {
"type": "integer",
"description": "Task id to update. Required for 'update'.",
},
"status": {
"type": "string",
"enum": list(STATUSES),
"description": "New status for a task. Required for 'update'.",
},
},
"required": ["action"],
}
# ------------------------------------------------------------------
def _find(self, task_id: Any) -> Dict[str, str]:
try:
wanted = int(task_id)
except (TypeError, ValueError):
raise ToolError(f"Task id must be an integer, got {task_id!r}.") from None
for item in self._items:
if int(item["id"]) == wanted:
return item
valid = ", ".join(str(i["id"]) for i in self._items) or "(none)"
raise ToolError(f"No task with id {wanted}. Existing ids: {valid}")
def _render(self) -> str:
if not self._items:
return "The checklist is empty."
done = sum(1 for i in self._items if i["status"] == "completed")
cancelled = sum(1 for i in self._items if i["status"] == "cancelled")
total = len(self._items)
summary = f"{done}/{total} complete"
if cancelled:
summary += f", {cancelled} cancelled"
lines = [f"Checklist ({summary}):"]
for status in ORDER:
group = [i for i in self._items if i["status"] == status]
if not group:
continue
label = {"in_progress": "IN PROGRESS", "pending": "TODO",
"completed": "DONE", "cancelled": "SKIPPED"}[status]
lines.append(f"\n{label}")
for item in group:
text = item["task"]
if len(text) > 120:
text = text[:120] + "..."
lines.append(f" [{str(item['id']):>2}] {text}")
remaining = total - done - cancelled
if remaining:
lines.append(f"\n{remaining} item(s) still open.")
else:
lines.append("\nEverything on the list is finished.")
return "\n".join(lines)
def _add(self, tasks: Optional[List[str]]) -> str:
if not tasks:
raise ToolError("'add' needs a 'tasks' list of descriptions.")
room = MAX_TASKS - len(self._items)
if room <= 0:
raise ToolError(
f"The checklist is full ({MAX_TASKS} items). Update or clear "
"existing tasks before adding more."
)
for text in tasks[:room]:
self._items.append({
"id": str(self._next_id),
"task": str(text),
"status": "pending",
})
self._next_id += 1
if len(tasks) > room:
return self._render() + f"\n\n... {len(tasks) - room} task(s) dropped: the list is full."
return self._render()
def _update(self, task_id: Any, status: Optional[str]) -> str:
if task_id is None:
raise ToolError("'update' needs a task 'id'.")
if status not in STATUSES:
raise ToolError(
f"Invalid status {status!r}. Use one of: {', '.join(STATUSES)}."
)
item = self._find(task_id)
previous = item["status"]
item["status"] = status
# Keep at most one task in progress so "what am I doing now" stays
# unambiguous as the list gets long.
cleared = ""
if status == "in_progress":
for other in self._items:
if other is not item and other["status"] == "in_progress":
other["status"] = "pending"
cleared = f"\nMoved task [{other['id']}] back to pending."
return (
f"Task [{item['id']}]: {previous} -> {status}.{cleared}\n\n" + self._render()
)
async def execute(
self,
action: str,
tasks: Optional[List[str]] = None,
id: Optional[int] = None, # noqa: A002 - matches the JSON Schema name
status: Optional[str] = None,
**kwargs: Any,
) -> str:
if action == "list":
return self._render()
if action == "add":
return self._add(tasks)
if action == "update":
return self._update(id, status)
if action == "clear":
count = len(self._items)
self._items.clear()
return f"Cleared {count} task(s)."
raise ToolError(
f"Unsupported action {action!r}. Use 'add', 'update', 'list', or 'clear'."
)
__all__ = ["TodoTool"]
|