Back to TodoWrite
Tools → TodoWrite
s02 (237 LOC) → s03 (329 LOC)
LOC Delta
+92lines
New Tools
1
todo
New Classes
1
TodoManager
New Functions
0
Tools
One Handler Per Tool
237 LOC
4 tools: bash, read_file, write_file, edit_file
toolsTodoWrite
Plan Before You Act
329 LOC
5 tools: bash, read_file, write_file, edit_file, todo
planningSource Code Diff
s02 (s02_tool_use.ts) -> s03 (s03_todo_write.ts)
| 1 | 1 | #!/usr/bin/env node | |
| 2 | 2 | /** | |
| 3 | - | * s02_tool_use.ts - Tools | |
| 3 | + | * s03_todo_write.ts - TodoWrite | |
| 4 | 4 | * | |
| 5 | - | * The loop from s01 does not change. We add more tools and a dispatch map: | |
| 6 | - | * | |
| 7 | - | * { tool_name: handler } | |
| 8 | - | * | |
| 9 | - | * Key insight: adding a tool means adding one handler. | |
| 5 | + | * The model tracks its own progress through a TodoManager. | |
| 6 | + | * A nag reminder pushes it to keep the plan updated. | |
| 10 | 7 | */ | |
| 11 | 8 | ||
| 12 | 9 | import { spawnSync } from "node:child_process"; | |
| 13 | 10 | import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 11 | + | import { resolve } from "node:path"; | |
| 14 | 12 | import process from "node:process"; | |
| 15 | 13 | import { createInterface } from "node:readline/promises"; | |
| 16 | - | import { resolve } from "node:path"; | |
| 17 | 14 | import type Anthropic from "@anthropic-ai/sdk"; | |
| 18 | 15 | import "dotenv/config"; | |
| 19 | 16 | import { buildSystemPrompt, createAnthropicClient, resolveModel, shellToolDescription } from "./shared"; | |
| 20 | 17 | ||
| 21 | - | type ToolUseName = "bash" | "read_file" | "write_file" | "edit_file"; | |
| 18 | + | type ToolUseName = "bash" | "read_file" | "write_file" | "edit_file" | "todo"; | |
| 22 | 19 | ||
| 20 | + | type TodoStatus = "pending" | "in_progress" | "completed"; | |
| 21 | + | ||
| 23 | 22 | type ToolUseBlock = { | |
| 24 | 23 | id: string; | |
| 25 | 24 | type: "tool_use"; | |
| 26 | 25 | name: ToolUseName; | |
| 27 | 26 | input: Record<string, unknown>; | |
| 28 | 27 | }; | |
| 29 | 28 | ||
| 30 | 29 | type TextBlock = { | |
| 31 | 30 | type: "text"; | |
| 32 | 31 | text: string; | |
| 33 | 32 | }; | |
| 34 | 33 | ||
| 35 | 34 | type ToolResultBlock = { | |
| 36 | 35 | type: "tool_result"; | |
| 37 | 36 | tool_use_id: string; | |
| 38 | 37 | content: string; | |
| 39 | 38 | }; | |
| 40 | 39 | ||
| 41 | 40 | type MessageContent = string | Array<ToolUseBlock | TextBlock | ToolResultBlock>; | |
| 42 | 41 | ||
| 43 | 42 | type Message = { | |
| 44 | 43 | role: "user" | "assistant"; | |
| 45 | 44 | content: MessageContent; | |
| 46 | 45 | }; | |
| 47 | 46 | ||
| 47 | + | type TodoItem = { | |
| 48 | + | id: string; | |
| 49 | + | text: string; | |
| 50 | + | status: TodoStatus; | |
| 51 | + | }; | |
| 52 | + | ||
| 48 | 53 | const WORKDIR = process.cwd(); | |
| 49 | 54 | const MODEL = resolveModel(); | |
| 50 | 55 | const client = createAnthropicClient(); | |
| 51 | 56 | ||
| 52 | - | const SYSTEM = buildSystemPrompt(`You are a coding agent at ${WORKDIR}. Use tools to solve tasks. Act, don't explain.`); | |
| 57 | + | const SYSTEM = buildSystemPrompt(`You are a coding agent at ${WORKDIR}. | |
| 58 | + | Use the todo tool to plan multi-step tasks. Mark in_progress before starting, completed when done. | |
| 59 | + | Prefer tools over prose.`); | |
| 53 | 60 | ||
| 61 | + | class TodoManager { | |
| 62 | + | private items: TodoItem[] = []; | |
| 63 | + | ||
| 64 | + | update(items: unknown): string { | |
| 65 | + | if (!Array.isArray(items)) { | |
| 66 | + | throw new Error("items must be an array"); | |
| 67 | + | } | |
| 68 | + | if (items.length > 20) { | |
| 69 | + | throw new Error("Max 20 todos allowed"); | |
| 70 | + | } | |
| 71 | + | ||
| 72 | + | let inProgressCount = 0; | |
| 73 | + | const validated = items.map((item, index) => { | |
| 74 | + | const record = (item ?? {}) as Record<string, unknown>; | |
| 75 | + | const text = String(record.text ?? "").trim(); | |
| 76 | + | const status = String(record.status ?? "pending").toLowerCase() as TodoStatus; | |
| 77 | + | const id = String(record.id ?? index + 1); | |
| 78 | + | ||
| 79 | + | if (!text) throw new Error(`Item ${id}: text required`); | |
| 80 | + | if (!["pending", "in_progress", "completed"].includes(status)) { | |
| 81 | + | throw new Error(`Item ${id}: invalid status '${status}'`); | |
| 82 | + | } | |
| 83 | + | if (status === "in_progress") inProgressCount += 1; | |
| 84 | + | ||
| 85 | + | return { id, text, status }; | |
| 86 | + | }); | |
| 87 | + | ||
| 88 | + | if (inProgressCount > 1) { | |
| 89 | + | throw new Error("Only one task can be in_progress at a time"); | |
| 90 | + | } | |
| 91 | + | ||
| 92 | + | this.items = validated; | |
| 93 | + | return this.render(); | |
| 94 | + | } | |
| 95 | + | ||
| 96 | + | render(): string { | |
| 97 | + | if (this.items.length === 0) return "No todos."; | |
| 98 | + | ||
| 99 | + | const lines = this.items.map((item) => { | |
| 100 | + | const marker = { | |
| 101 | + | pending: "[ ]", | |
| 102 | + | in_progress: "[>]", | |
| 103 | + | completed: "[x]", | |
| 104 | + | }[item.status]; | |
| 105 | + | return `${marker} #${item.id}: ${item.text}`; | |
| 106 | + | }); | |
| 107 | + | ||
| 108 | + | const done = this.items.filter((item) => item.status === "completed").length; | |
| 109 | + | lines.push(`\n(${done}/${this.items.length} completed)`); | |
| 110 | + | return lines.join("\n"); | |
| 111 | + | } | |
| 112 | + | } | |
| 113 | + | ||
| 114 | + | const TODO = new TodoManager(); | |
| 115 | + | ||
| 54 | 116 | function safePath(relativePath: string): string { | |
| 55 | 117 | const filePath = resolve(WORKDIR, relativePath); | |
| 56 | 118 | const normalizedWorkdir = `${WORKDIR}${process.platform === "win32" ? "\\" : "/"}`; | |
| 57 | 119 | if (filePath !== WORKDIR && !filePath.startsWith(normalizedWorkdir)) { | |
| 58 | 120 | throw new Error(`Path escapes workspace: ${relativePath}`); | |
| 59 | 121 | } | |
| 60 | 122 | return filePath; | |
| 61 | 123 | } | |
| 62 | 124 | ||
| 63 | 125 | function runBash(command: string): string { | |
| 64 | 126 | const dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]; | |
| 65 | 127 | if (dangerous.some((item) => command.includes(item))) { | |
| 66 | 128 | return "Error: Dangerous command blocked"; | |
| 67 | 129 | } | |
| 68 | 130 | ||
| 69 | 131 | const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh"; | |
| 70 | 132 | const args = process.platform === "win32" | |
| 71 | 133 | ? ["/d", "/s", "/c", command] | |
| 72 | 134 | : ["-lc", command]; | |
| 73 | 135 | ||
| 74 | 136 | const result = spawnSync(shell, args, { | |
| 75 | 137 | cwd: WORKDIR, | |
| 76 | 138 | encoding: "utf8", | |
| 77 | 139 | timeout: 120_000, | |
| 78 | 140 | }); | |
| 79 | 141 | ||
| 80 | 142 | if (result.error?.name === "TimeoutError") { | |
| 81 | 143 | return "Error: Timeout (120s)"; | |
| 82 | 144 | } | |
| 83 | 145 | ||
| 84 | 146 | const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(); | |
| 85 | 147 | return output.slice(0, 50_000) || "(no output)"; | |
| 86 | 148 | } | |
| 87 | 149 | ||
| 88 | 150 | function runRead(path: string, limit?: number): string { | |
| 89 | 151 | try { | |
| 90 | 152 | let lines = readFileSync(safePath(path), "utf8").split(/\r?\n/); | |
| 91 | 153 | if (limit && limit < lines.length) { | |
| 92 | 154 | lines = lines.slice(0, limit).concat(`... (${lines.length - limit} more)`); | |
| 93 | 155 | } | |
| 94 | 156 | return lines.join("\n").slice(0, 50_000); | |
| 95 | 157 | } catch (error) { | |
| 96 | 158 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 97 | 159 | } | |
| 98 | 160 | } | |
| 99 | 161 | ||
| 100 | 162 | function runWrite(path: string, content: string): string { | |
| 101 | 163 | try { | |
| 102 | 164 | const filePath = safePath(path); | |
| 103 | 165 | mkdirSync(resolve(filePath, ".."), { recursive: true }); | |
| 104 | 166 | writeFileSync(filePath, content, "utf8"); | |
| 105 | 167 | return `Wrote ${content.length} bytes`; | |
| 106 | 168 | } catch (error) { | |
| 107 | 169 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 108 | 170 | } | |
| 109 | 171 | } | |
| 110 | 172 | ||
| 111 | 173 | function runEdit(path: string, oldText: string, newText: string): string { | |
| 112 | 174 | try { | |
| 113 | 175 | const filePath = safePath(path); | |
| 114 | 176 | const content = readFileSync(filePath, "utf8"); | |
| 115 | 177 | if (!content.includes(oldText)) { | |
| 116 | 178 | return `Error: Text not found in ${path}`; | |
| 117 | 179 | } | |
| 118 | 180 | writeFileSync(filePath, content.replace(oldText, newText), "utf8"); | |
| 119 | 181 | return `Edited ${path}`; | |
| 120 | 182 | } catch (error) { | |
| 121 | 183 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 122 | 184 | } | |
| 123 | 185 | } | |
| 124 | 186 | ||
| 125 | 187 | const TOOL_HANDLERS: Record<ToolUseName, (input: Record<string, unknown>) => string> = { | |
| 126 | 188 | bash: (input) => runBash(String(input.command ?? "")), | |
| 127 | 189 | read_file: (input) => runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined), | |
| 128 | 190 | write_file: (input) => runWrite(String(input.path ?? ""), String(input.content ?? "")), | |
| 129 | 191 | edit_file: (input) => | |
| 130 | 192 | runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")), | |
| 193 | + | todo: (input) => TODO.update(input.items), | |
| 131 | 194 | }; | |
| 132 | 195 | ||
| 133 | 196 | const TOOLS = [ | |
| 134 | 197 | { | |
| 135 | 198 | name: "bash", | |
| 136 | 199 | description: shellToolDescription(), | |
| 137 | 200 | input_schema: { | |
| 138 | 201 | type: "object", | |
| 139 | 202 | properties: { | |
| 140 | 203 | command: { type: "string" }, | |
| 141 | 204 | }, | |
| 142 | 205 | required: ["command"], | |
| 143 | 206 | }, | |
| 144 | 207 | }, | |
| 145 | 208 | { | |
| 146 | 209 | name: "read_file", | |
| 147 | 210 | description: "Read file contents.", | |
| 148 | 211 | input_schema: { | |
| 149 | 212 | type: "object", | |
| 150 | 213 | properties: { | |
| 151 | 214 | path: { type: "string" }, | |
| 152 | 215 | limit: { type: "integer" }, | |
| 153 | 216 | }, | |
| 154 | 217 | required: ["path"], | |
| 155 | 218 | }, | |
| 156 | 219 | }, | |
| 157 | 220 | { | |
| 158 | 221 | name: "write_file", | |
| 159 | 222 | description: "Write content to file.", | |
| 160 | 223 | input_schema: { | |
| 161 | 224 | type: "object", | |
| 162 | 225 | properties: { | |
| 163 | 226 | path: { type: "string" }, | |
| 164 | 227 | content: { type: "string" }, | |
| 165 | 228 | }, | |
| 166 | 229 | required: ["path", "content"], | |
| 167 | 230 | }, | |
| 168 | 231 | }, | |
| 169 | 232 | { | |
| 170 | 233 | name: "edit_file", | |
| 171 | 234 | description: "Replace exact text in file.", | |
| 172 | 235 | input_schema: { | |
| 173 | 236 | type: "object", | |
| 174 | 237 | properties: { | |
| 175 | 238 | path: { type: "string" }, | |
| 176 | 239 | old_text: { type: "string" }, | |
| 177 | 240 | new_text: { type: "string" }, | |
| 178 | 241 | }, | |
| 179 | 242 | required: ["path", "old_text", "new_text"], | |
| 180 | 243 | }, | |
| 181 | 244 | }, | |
| 245 | + | { | |
| 246 | + | name: "todo", | |
| 247 | + | description: "Update task list. Track progress on multi-step tasks.", | |
| 248 | + | input_schema: { | |
| 249 | + | type: "object", | |
| 250 | + | properties: { | |
| 251 | + | items: { | |
| 252 | + | type: "array", | |
| 253 | + | items: { | |
| 254 | + | type: "object", | |
| 255 | + | properties: { | |
| 256 | + | id: { type: "string" }, | |
| 257 | + | text: { type: "string" }, | |
| 258 | + | status: { | |
| 259 | + | type: "string", | |
| 260 | + | enum: ["pending", "in_progress", "completed"], | |
| 261 | + | }, | |
| 262 | + | }, | |
| 263 | + | required: ["id", "text", "status"], | |
| 264 | + | }, | |
| 265 | + | }, | |
| 266 | + | }, | |
| 267 | + | required: ["items"], | |
| 268 | + | }, | |
| 269 | + | }, | |
| 182 | 270 | ]; | |
| 183 | 271 | ||
| 184 | 272 | function assistantText(content: Array<ToolUseBlock | TextBlock | ToolResultBlock>) { | |
| 185 | 273 | return content | |
| 186 | 274 | .filter((block): block is TextBlock => block.type === "text") | |
| 187 | 275 | .map((block) => block.text) | |
| 188 | 276 | .join("\n"); | |
| 189 | 277 | } | |
| 190 | 278 | ||
| 191 | 279 | export async function agentLoop(messages: Message[]) { | |
| 280 | + | let roundsSinceTodo = 0; | |
| 281 | + | ||
| 192 | 282 | while (true) { | |
| 193 | 283 | const response = await client.messages.create({ | |
| 194 | 284 | model: MODEL, | |
| 195 | 285 | system: SYSTEM, | |
| 196 | 286 | messages: messages as Anthropic.Messages.MessageParam[], | |
| 197 | 287 | tools: TOOLS as Anthropic.Messages.Tool[], | |
| 198 | 288 | max_tokens: 8000, | |
| 199 | 289 | }); | |
| 200 | 290 | ||
| 201 | 291 | messages.push({ | |
| 202 | 292 | role: "assistant", | |
| 203 | 293 | content: response.content as Array<ToolUseBlock | TextBlock>, | |
| 204 | 294 | }); | |
| 205 | 295 | ||
| 206 | 296 | if (response.stop_reason !== "tool_use") { | |
| 207 | 297 | return; | |
| 208 | 298 | } | |
| 209 | 299 | ||
| 210 | - | const results: ToolResultBlock[] = []; | |
| 300 | + | const results: Array<TextBlock | ToolResultBlock> = []; | |
| 301 | + | let usedTodo = false; | |
| 211 | 302 | ||
| 212 | 303 | for (const block of response.content) { | |
| 213 | 304 | if (block.type !== "tool_use") continue; | |
| 214 | 305 | ||
| 215 | 306 | const handler = TOOL_HANDLERS[block.name as ToolUseName]; | |
| 216 | - | const output = handler | |
| 217 | - | ? handler(block.input as Record<string, unknown>) | |
| 218 | - | : `Unknown tool: ${block.name}`; | |
| 307 | + | let output: string; | |
| 219 | 308 | ||
| 309 | + | try { | |
| 310 | + | output = handler | |
| 311 | + | ? handler(block.input as Record<string, unknown>) | |
| 312 | + | : `Unknown tool: ${block.name}`; | |
| 313 | + | } catch (error) { | |
| 314 | + | output = `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 315 | + | } | |
| 316 | + | ||
| 220 | 317 | console.log(`> ${block.name}: ${output.slice(0, 200)}`); | |
| 221 | 318 | results.push({ | |
| 222 | 319 | type: "tool_result", | |
| 223 | 320 | tool_use_id: block.id, | |
| 224 | 321 | content: output, | |
| 225 | 322 | }); | |
| 323 | + | ||
| 324 | + | if (block.name === "todo") { | |
| 325 | + | usedTodo = true; | |
| 326 | + | } | |
| 226 | 327 | } | |
| 227 | 328 | ||
| 329 | + | roundsSinceTodo = usedTodo ? 0 : roundsSinceTodo + 1; | |
| 330 | + | if (roundsSinceTodo >= 3) { | |
| 331 | + | results.unshift({ | |
| 332 | + | type: "text", | |
| 333 | + | text: "<reminder>Update your todos.</reminder>", | |
| 334 | + | }); | |
| 335 | + | } | |
| 336 | + | ||
| 228 | 337 | messages.push({ | |
| 229 | 338 | role: "user", | |
| 230 | 339 | content: results, | |
| 231 | 340 | }); | |
| 232 | 341 | } | |
| 233 | 342 | } | |
| 234 | 343 | ||
| 235 | 344 | async function main() { | |
| 236 | 345 | const rl = createInterface({ | |
| 237 | 346 | input: process.stdin, | |
| 238 | 347 | output: process.stdout, | |
| 239 | 348 | }); | |
| 240 | 349 | ||
| 241 | 350 | const history: Message[] = []; | |
| 242 | 351 | ||
| 243 | 352 | while (true) { | |
| 244 | 353 | let query = ""; | |
| 245 | 354 | try { | |
| 246 | - | query = await rl.question("\x1b[36ms02 >> \x1b[0m"); | |
| 355 | + | query = await rl.question("\x1b[36ms03 >> \x1b[0m"); | |
| 247 | 356 | } catch (error) { | |
| 248 | 357 | if ( | |
| 249 | 358 | error instanceof Error && | |
| 250 | 359 | (("code" in error && error.code === "ERR_USE_AFTER_CLOSE") || error.name === "AbortError") | |
| 251 | 360 | ) { | |
| 252 | 361 | break; | |
| 253 | 362 | } | |
| 254 | 363 | throw error; | |
| 255 | 364 | } | |
| 256 | 365 | if (!query.trim() || ["q", "exit"].includes(query.trim().toLowerCase())) { | |
| 257 | 366 | break; | |
| 258 | 367 | } | |
| 259 | 368 | ||
| 260 | 369 | history.push({ role: "user", content: query }); | |
| 261 | 370 | await agentLoop(history); | |
| 262 | 371 | ||
| 263 | 372 | const last = history[history.length - 1]?.content; | |
| 264 | 373 | if (Array.isArray(last)) { | |
| 265 | 374 | const text = assistantText(last); | |
| 266 | 375 | if (text) console.log(text); | |
| 267 | 376 | } | |
| 268 | 377 | console.log(); | |
| 269 | 378 | } | |
| 270 | 379 | ||
| 271 | 380 | rl.close(); | |
| 272 | 381 | } | |
| 273 | 382 | ||
| 274 | 383 | void main(); |