-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathUpdateTodoListTool.ts
More file actions
224 lines (196 loc) · 6.75 KB
/
UpdateTodoListTool.ts
File metadata and controls
224 lines (196 loc) · 6.75 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import { Task } from "../task/Task"
import { formatResponse } from "../prompts/responses"
import { BaseTool, ToolCallbacks } from "./BaseTool"
import type { ToolUse } from "../../shared/tools"
import cloneDeep from "clone-deep"
import crypto from "crypto"
import { TodoItem, TodoStatus, todoStatusSchema } from "@roo-code/types"
import { getLatestTodo } from "../../shared/todo"
interface UpdateTodoListParams {
todos: string
}
let approvedTodoList: TodoItem[] | undefined = undefined
export class UpdateTodoListTool extends BaseTool<"update_todo_list"> {
readonly name = "update_todo_list" as const
async execute(params: UpdateTodoListParams, task: Task, callbacks: ToolCallbacks): Promise<void> {
const { pushToolResult, handleError, askApproval } = callbacks
try {
const todosRaw = params.todos
let todos: TodoItem[]
try {
todos = parseMarkdownChecklist(todosRaw || "")
} catch {
task.consecutiveMistakeCount++
task.recordToolError("update_todo_list")
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.toolError("The todos parameter is not valid markdown checklist or JSON"))
return
}
const { valid, error } = validateTodos(todos)
if (!valid) {
task.consecutiveMistakeCount++
task.recordToolError("update_todo_list")
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.toolError(error || "todos parameter validation failed"))
return
}
let normalizedTodos: TodoItem[] = todos.map((t) => ({
id: t.id,
content: t.content,
status: normalizeStatus(t.status),
}))
const approvalMsg = JSON.stringify({
tool: "updateTodoList",
todos: normalizedTodos,
})
approvedTodoList = cloneDeep(normalizedTodos)
const didApprove = await askApproval("tool", approvalMsg)
if (!didApprove) {
pushToolResult("User declined to update the todoList.")
return
}
const isTodoListChanged =
approvedTodoList !== undefined && JSON.stringify(normalizedTodos) !== JSON.stringify(approvedTodoList)
if (isTodoListChanged) {
normalizedTodos = approvedTodoList ?? []
task.say(
"user_edit_todos",
JSON.stringify({
tool: "updateTodoList",
todos: normalizedTodos,
}),
)
}
await setTodoListForTask(task, normalizedTodos)
if (isTodoListChanged) {
const md = todoListToMarkdown(normalizedTodos)
pushToolResult(formatResponse.toolResult("User edits todo:\n\n" + md))
} else {
pushToolResult(formatResponse.toolResult("Todo list updated successfully."))
}
} catch (error) {
await handleError("update todo list", error as Error)
}
}
override async handlePartial(task: Task, block: ToolUse<"update_todo_list">): Promise<void> {
const todosRaw = block.params.todos
// Parse the markdown checklist to maintain consistent format with execute()
let todos: TodoItem[]
try {
todos = parseMarkdownChecklist(todosRaw || "")
} catch {
// If parsing fails during partial, send empty array
todos = []
}
const approvalMsg = JSON.stringify({
tool: "updateTodoList",
todos: todos,
})
await task.ask("tool", approvalMsg, block.partial).catch(() => {})
}
}
export function addTodoToTask(cline: Task, content: string, status: TodoStatus = "pending", id?: string): TodoItem {
const todo: TodoItem = {
id: id ?? crypto.randomUUID(),
content,
status,
}
if (!cline.todoList) cline.todoList = []
cline.todoList.push(todo)
return todo
}
export function updateTodoStatusForTask(cline: Task, id: string, nextStatus: TodoStatus): boolean {
if (!cline.todoList) return false
const idx = cline.todoList.findIndex((t) => t.id === id)
if (idx === -1) return false
const current = cline.todoList[idx]
if (
(current.status === "pending" && nextStatus === "in_progress") ||
(current.status === "in_progress" && nextStatus === "completed") ||
current.status === nextStatus
) {
cline.todoList[idx] = { ...current, status: nextStatus }
return true
}
return false
}
export function removeTodoFromTask(cline: Task, id: string): boolean {
if (!cline.todoList) return false
const idx = cline.todoList.findIndex((t) => t.id === id)
if (idx === -1) return false
cline.todoList.splice(idx, 1)
return true
}
export function getTodoListForTask(cline: Task): TodoItem[] | undefined {
return cline.todoList?.slice()
}
export async function setTodoListForTask(cline?: Task, todos?: TodoItem[]) {
if (cline === undefined) return
cline.todoList = Array.isArray(todos) ? todos : []
}
export function restoreTodoListForTask(cline: Task, todoList?: TodoItem[]) {
if (todoList) {
cline.todoList = Array.isArray(todoList) ? todoList : []
return
}
cline.todoList = getLatestTodo(cline.clineMessages)
}
function todoListToMarkdown(todos: TodoItem[]): string {
return todos
.map((t) => {
let box = "[ ]"
if (t.status === "completed") box = "[x]"
else if (t.status === "in_progress") box = "[-]"
return `${box} ${t.content}`
})
.join("\n")
}
function normalizeStatus(status: string | undefined): TodoStatus {
if (status === "completed") return "completed"
if (status === "in_progress") return "in_progress"
return "pending"
}
export function parseMarkdownChecklist(md: string): TodoItem[] {
if (typeof md !== "string") return []
// Normalize literal escape sequences (e.g. "\\n", "\\r\\n") that some
// models/providers send instead of actual newline characters.
const normalized = md.replace(/\\r\\n|\\n/g, "\n")
const lines = normalized
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean)
const todos: TodoItem[] = []
for (const line of lines) {
const match = line.match(/^(?:-\s*)?\[\s*([ xX\-~])\s*\]\s+(.+)$/)
if (!match) continue
let status: TodoStatus = "pending"
if (match[1] === "x" || match[1] === "X") status = "completed"
else if (match[1] === "-" || match[1] === "~") status = "in_progress"
const id = crypto
.createHash("md5")
.update(match[2] + status)
.digest("hex")
todos.push({
id,
content: match[2],
status,
})
}
return todos
}
export function setPendingTodoList(todos: TodoItem[]) {
approvedTodoList = todos
}
function validateTodos(todos: any[]): { valid: boolean; error?: string } {
if (!Array.isArray(todos)) return { valid: false, error: "todos must be an array" }
for (const [i, t] of todos.entries()) {
if (!t || typeof t !== "object") return { valid: false, error: `Item ${i + 1} is not an object` }
if (!t.id || typeof t.id !== "string") return { valid: false, error: `Item ${i + 1} is missing id` }
if (!t.content || typeof t.content !== "string")
return { valid: false, error: `Item ${i + 1} is missing content` }
if (t.status && !todoStatusSchema.options.includes(t.status as TodoStatus))
return { valid: false, error: `Item ${i + 1} has invalid status` }
}
return { valid: true }
}
export const updateTodoListTool = new UpdateTodoListTool()