(model, prompt, options)
| 61 | |
| 62 | const claudeCodeAgent: Agent.Definition = { |
| 63 | async run(model, prompt, options) { |
| 64 | options.logger.log(`claude-agent-sdk --model ${model} ${prompt}`); |
| 65 | |
| 66 | const cacheKey = sessionKey(model, options.cwd); |
| 67 | const existingSessionID = sessionCache.get(cacheKey); |
| 68 | |
| 69 | const actions: string[] = []; |
| 70 | const usage = { |
| 71 | input: 0, |
| 72 | output: 0, |
| 73 | cost: 0, |
| 74 | }; |
| 75 | |
| 76 | try { |
| 77 | const result = query({ |
| 78 | prompt, |
| 79 | options: { |
| 80 | model, |
| 81 | cwd: options.cwd, |
| 82 | // Resume existing session if available |
| 83 | ...(existingSessionID ? { resume: existingSessionID } : {}), |
| 84 | allowedTools: ["Read", "Write", "Edit", "Grep", "Glob", "Bash"], |
| 85 | }, |
| 86 | }); |
| 87 | |
| 88 | // Stream and log messages |
| 89 | for await (const message of result) { |
| 90 | // Extract and cache session ID from messages |
| 91 | sessionCache.set(cacheKey, message.session_id); |
| 92 | |
| 93 | // Accumulate token usage if available (only SDKResultMessage has usage) |
| 94 | if (message.type === "result" && "usage" in message) { |
| 95 | usage.input += message.usage.input_tokens || 0; |
| 96 | usage.output += message.usage.output_tokens || 0; |
| 97 | usage.cost += message.total_cost_usd || 0; |
| 98 | } |
| 99 | |
| 100 | actions.push(JSON.stringify(message)); |
| 101 | logJson(message, options); |
| 102 | } |
| 103 | } catch (error) { |
| 104 | // Clear session cache on error, like other agents do |
| 105 | sessionCache.delete(cacheKey); |
| 106 | logError( |
| 107 | { |
| 108 | error: "claude_agent_sdk_failed", |
| 109 | details: serializeError(error), |
| 110 | }, |
| 111 | options, |
| 112 | ); |
| 113 | throw error; |
| 114 | } |
| 115 | |
| 116 | return { actions, usage }; |
| 117 | }, |
| 118 | }; |
| 119 | |
| 120 | export default claudeCodeAgent; |
nothing calls this directly
no test coverage detected