(options?: TaskToolsOptions)
| 66 | }; |
| 67 | |
| 68 | export function createTaskTools(options?: TaskToolsOptions): { |
| 69 | tools: Array<{ definition: ToolDefinition; executor: ToolExecutor }>; |
| 70 | tasks: Map<string, Task>; |
| 71 | } { |
| 72 | const tasks = new Map<string, Task>(); |
| 73 | let nextId = 1; |
| 74 | |
| 75 | // 从持久化数据恢复 |
| 76 | if (options?.initialTasks) { |
| 77 | for (const task of options.initialTasks) { |
| 78 | tasks.set(task.id, task); |
| 79 | const numId = parseInt(task.id, 10); |
| 80 | if (!isNaN(numId) && numId >= nextId) { |
| 81 | nextId = numId + 1; |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // 持久化并推送事件 |
| 87 | const emitUpdate = async () => { |
| 88 | const taskList = Array.from(tasks.values()); |
| 89 | if (options?.onSave) { |
| 90 | await options.onSave(taskList); |
| 91 | } |
| 92 | if (options?.sendEvent) { |
| 93 | options.sendEvent({ |
| 94 | type: "task_update", |
| 95 | tasks: taskList.map((t) => ({ |
| 96 | id: t.id, |
| 97 | subject: t.subject, |
| 98 | status: t.status, |
| 99 | description: t.description, |
| 100 | })), |
| 101 | }); |
| 102 | } |
| 103 | }; |
| 104 | |
| 105 | const createExecutor: ToolExecutor = { |
| 106 | execute: async (args: Record<string, unknown>) => { |
| 107 | const task: Task = { |
| 108 | id: String(nextId++), |
| 109 | subject: requireString(args, "subject"), |
| 110 | description: optionalString(args, "description"), |
| 111 | status: "pending", |
| 112 | }; |
| 113 | tasks.set(task.id, task); |
| 114 | await emitUpdate(); |
| 115 | return JSON.stringify(task); |
| 116 | }, |
| 117 | }; |
| 118 | |
| 119 | const updateExecutor: ToolExecutor = { |
| 120 | execute: async (args: Record<string, unknown>) => { |
| 121 | const taskId = requireString(args, "task_id"); |
| 122 | const task = tasks.get(taskId); |
| 123 | if (!task) { |
| 124 | throw new Error(`Task "${taskId}" not found`); |
| 125 | } |
no test coverage detected