4. 任务执行模式
4.1 任务管理 (Todo List)
typescript
interface TodoItem {
id: string;
content: string;
status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
}
class TodoManager {
private todos: TodoItem[] = [];
// 创建任务列表
createFromTask(task: string): TodoItem[] {
// 让 LLM 分解任务
const plan = await this.planTask(task);
this.todos = plan.steps.map((step, i) => ({
id: `${i + 1}`,
content: step,
status: i === 0 ? 'in_progress' : 'pending'
}));
return this.todos;
}
// 更新任务状态
update(id: string, status: TodoItem['status']) {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.status = status;
}
}
// 获取进度
getProgress(): string {
const completed = this.todos.filter(t => t.status === 'completed').length;
return `${completed}/${this.todos.length} tasks completed`;
}
}4.2 迭代执行循环
typescript
class ClaudeCodeAgent {
async executeTask(task: string) {
const messages: Message[] = [];
// 添加系统上下文
messages.push({
role: 'system',
content: await this.buildSystemPrompt()
});
// 添加用户任务
messages.push({
role: 'user',
content: task
});
let iteration = 0;
const maxIterations = 100;
while (iteration < maxIterations) {
// 调用 LLM
const response = await this.llm.chat({
messages,
tools: this.tools
});
// 处理文本输出
if (response.content) {
this.displayOutput(response.content);
}
// 检查是否完成
if (response.stop_reason === 'end_turn' && !response.tool_calls) {
break;
}
// 处理工具调用
if (response.tool_calls) {
messages.push({ role: 'assistant', content: response.content });
const results = await this.executeTools(response.tool_calls);
messages.push({ role: 'user', content: results });
}
iteration++;
}
}
async executeTools(toolCalls: ToolCall[]) {
const results = [];
for (const call of toolCalls) {
// 权限检查
if (this.requiresPermission(call)) {
const granted = await this.confirmManager.requestPermission(call);
if (!granted) {
results.push({
tool_use_id: call.id,
content: "Operation cancelled by user"
});
continue;
}
}
// 执行工具
try {
const result = await this.toolExecutor.execute(call);
results.push({
tool_use_id: call.id,
content: JSON.stringify(result)
});
} catch (error) {
results.push({
tool_use_id: call.id,
content: `Error: ${error.message}`
});
}
}
return results;
}
}