|
| 1 | +import type { Anthropic } from "@anthropic-ai/sdk" |
| 2 | +import { |
| 3 | + type ApiHandlerOptions, |
| 4 | + claudeCodeDefaultModelId, |
| 5 | + type ClaudeCodeModelId, |
| 6 | + claudeCodeModels, |
| 7 | +} from "@roo-code/types" |
| 8 | +import { type ApiHandler } from ".." |
| 9 | +import { ApiStreamUsageChunk, type ApiStream } from "../transform/stream" |
| 10 | +import { runClaudeCode } from "../../integrations/claude-code/run" |
| 11 | +import { ClaudeCodeMessage } from "../../integrations/claude-code/types" |
| 12 | +import { BaseProvider } from "./base-provider" |
| 13 | + |
| 14 | +export class ClaudeCodeHandler extends BaseProvider implements ApiHandler { |
| 15 | + private options: ApiHandlerOptions |
| 16 | + |
| 17 | + constructor(options: ApiHandlerOptions) { |
| 18 | + super() |
| 19 | + this.options = options |
| 20 | + } |
| 21 | + |
| 22 | + override async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { |
| 23 | + const claudeProcess = runClaudeCode({ |
| 24 | + systemPrompt, |
| 25 | + messages, |
| 26 | + path: this.options.claudeCodePath, |
| 27 | + modelId: this.getModel().id, |
| 28 | + }) |
| 29 | + |
| 30 | + const dataQueue: string[] = [] |
| 31 | + let processError = null |
| 32 | + let errorOutput = "" |
| 33 | + let exitCode: number | null = null |
| 34 | + |
| 35 | + claudeProcess.stdout.on("data", (data) => { |
| 36 | + const output = data.toString() |
| 37 | + const lines = output.split("\n").filter((line: string) => line.trim() !== "") |
| 38 | + |
| 39 | + for (const line of lines) { |
| 40 | + dataQueue.push(line) |
| 41 | + } |
| 42 | + }) |
| 43 | + |
| 44 | + claudeProcess.stderr.on("data", (data) => { |
| 45 | + errorOutput += data.toString() |
| 46 | + }) |
| 47 | + |
| 48 | + claudeProcess.on("close", (code) => { |
| 49 | + exitCode = code |
| 50 | + }) |
| 51 | + |
| 52 | + claudeProcess.on("error", (error) => { |
| 53 | + processError = error |
| 54 | + }) |
| 55 | + |
| 56 | + // Usage is included with assistant messages, |
| 57 | + // but cost is included in the result chunk |
| 58 | + let usage: ApiStreamUsageChunk = { |
| 59 | + type: "usage", |
| 60 | + inputTokens: 0, |
| 61 | + outputTokens: 0, |
| 62 | + cacheReadTokens: 0, |
| 63 | + cacheWriteTokens: 0, |
| 64 | + } |
| 65 | + |
| 66 | + while (exitCode !== 0 || dataQueue.length > 0) { |
| 67 | + if (dataQueue.length === 0) { |
| 68 | + await new Promise((resolve) => setImmediate(resolve)) |
| 69 | + } |
| 70 | + |
| 71 | + if (exitCode !== null && exitCode !== 0) { |
| 72 | + throw new Error( |
| 73 | + `Claude Code process exited with code ${exitCode}.${errorOutput ? ` Error output: ${errorOutput.trim()}` : ""}`, |
| 74 | + ) |
| 75 | + } |
| 76 | + |
| 77 | + const data = dataQueue.shift() |
| 78 | + if (!data) { |
| 79 | + continue |
| 80 | + } |
| 81 | + |
| 82 | + const chunk = this.attemptParseChunk(data) |
| 83 | + |
| 84 | + if (!chunk) { |
| 85 | + yield { |
| 86 | + type: "text", |
| 87 | + text: data || "", |
| 88 | + } |
| 89 | + |
| 90 | + continue |
| 91 | + } |
| 92 | + |
| 93 | + if (chunk.type === "system" && chunk.subtype === "init") { |
| 94 | + continue |
| 95 | + } |
| 96 | + |
| 97 | + if (chunk.type === "assistant" && "message" in chunk) { |
| 98 | + const message = chunk.message |
| 99 | + |
| 100 | + if (message.stop_reason !== null && message.stop_reason !== "tool_use") { |
| 101 | + const errorMessage = |
| 102 | + message.content[0]?.text || `Claude Code stopped with reason: ${message.stop_reason}` |
| 103 | + |
| 104 | + if (errorMessage.includes("Invalid model name")) { |
| 105 | + throw new Error( |
| 106 | + errorMessage + |
| 107 | + `\n\nAPI keys and subscription plans allow different models. Make sure the selected model is included in your plan.`, |
| 108 | + ) |
| 109 | + } |
| 110 | + |
| 111 | + throw new Error(errorMessage) |
| 112 | + } |
| 113 | + |
| 114 | + for (const content of message.content) { |
| 115 | + if (content.type === "text") { |
| 116 | + yield { |
| 117 | + type: "text", |
| 118 | + text: content.text, |
| 119 | + } |
| 120 | + } else { |
| 121 | + console.warn("Unsupported content type:", content.type) |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + usage.inputTokens += message.usage.input_tokens |
| 126 | + usage.outputTokens += message.usage.output_tokens |
| 127 | + usage.cacheReadTokens = (usage.cacheReadTokens || 0) + (message.usage.cache_read_input_tokens || 0) |
| 128 | + usage.cacheWriteTokens = |
| 129 | + (usage.cacheWriteTokens || 0) + (message.usage.cache_creation_input_tokens || 0) |
| 130 | + |
| 131 | + continue |
| 132 | + } |
| 133 | + |
| 134 | + if (chunk.type === "result" && "result" in chunk) { |
| 135 | + usage.totalCost = chunk.cost_usd || 0 |
| 136 | + |
| 137 | + yield usage |
| 138 | + } |
| 139 | + |
| 140 | + if (processError) { |
| 141 | + throw processError |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + getModel() { |
| 147 | + const modelId = this.options.apiModelId |
| 148 | + if (modelId && modelId in claudeCodeModels) { |
| 149 | + const id = modelId as ClaudeCodeModelId |
| 150 | + return { id, info: claudeCodeModels[id] } |
| 151 | + } |
| 152 | + |
| 153 | + return { |
| 154 | + id: claudeCodeDefaultModelId, |
| 155 | + info: claudeCodeModels[claudeCodeDefaultModelId], |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + // TOOD: Validate instead of parsing |
| 160 | + private attemptParseChunk(data: string): ClaudeCodeMessage | null { |
| 161 | + try { |
| 162 | + return JSON.parse(data) |
| 163 | + } catch (error) { |
| 164 | + console.error("Error parsing chunk:", error) |
| 165 | + return null |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments