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