import { query } from "@anthropic-ai/claude-agent-sdk";try { for await (const message of query({ prompt: "Optimize my React app performance and track progress with todos", // Re-enable TodoWrite, which this example monitors. Without it, the SDK uses // Task tools instead and these tool_use blocks never appear. options: { maxTurns: 15, env: { ...process.env, CLAUDE_CODE_ENABLE_TASKS: "0" } } })) { // Todo updates are reflected in the message stream if (message.type === "assistant") { for (const block of message.message.content) { if (block.type === "tool_use" && block.name === "TodoWrite") { const todos = block.input.todos; console.log("Todo Status Update:"); todos.forEach((todo, index) => { const status = todo.status === "completed" ? "✅" : todo.status === "in_progress" ? "🔧" : "❌"; console.log(`${index + 1}. ${status} ${todo.content}`); }); } } } }} catch (error) { // A single-shot query() throws after yielding an error result, // such as when the maxTurns limit is hit. console.log(`Session ended with an error: ${error}`);}
实时进度显示
Copy
import { query } from "@anthropic-ai/claude-agent-sdk";class TodoTracker { private todos: any[] = []; displayProgress() { if (this.todos.length === 0) return; const completed = this.todos.filter((t) => t.status === "completed").length; const inProgress = this.todos.filter((t) => t.status === "in_progress").length; const total = this.todos.length; console.log(`\nProgress: ${completed}/${total} completed`); console.log(`Currently working on: ${inProgress} task(s)\n`); this.todos.forEach((todo, index) => { const icon = todo.status === "completed" ? "✅" : todo.status === "in_progress" ? "🔧" : "❌"; const text = todo.status === "in_progress" ? todo.activeForm : todo.content; console.log(`${index + 1}. ${icon} ${text}`); }); } async trackQuery(prompt: string) { try { for await (const message of query({ prompt, // Re-enable TodoWrite, which this tracker watches for. options: { maxTurns: 20, env: { ...process.env, CLAUDE_CODE_ENABLE_TASKS: "0" } } })) { if (message.type === "assistant") { for (const block of message.message.content) { if (block.type === "tool_use" && block.name === "TodoWrite") { this.todos = block.input.todos; this.displayProgress(); } } } } } catch (error) { // A single-shot query() throws after yielding an error result, // such as when the maxTurns limit is hit. console.log(`Session ended with an error: ${error}`); } }}// Usageconst tracker = new TodoTracker();await tracker.trackQuery("Build a complete authentication system with todos");