diff --git a/proto/cline/task.proto b/proto/cline/task.proto index 1e28084e..fc867e94 100644 --- a/proto/cline/task.proto +++ b/proto/cline/task.proto @@ -70,6 +70,7 @@ message TaskResponse { int32 tokens_out = 8; int32 cache_writes = 9; int32 cache_reads = 10; + string model_id = 11; } // Request for getting task history with filtering @@ -99,6 +100,7 @@ message TaskItem { int32 tokens_out = 8; int32 cache_writes = 9; int32 cache_reads = 10; + string model_id = 11; } // Request for ask response operation diff --git a/proto/cline/ui.proto b/proto/cline/ui.proto index c4528f57..85772a15 100644 --- a/proto/cline/ui.proto +++ b/proto/cline/ui.proto @@ -184,6 +184,11 @@ message ClineApiReqInfo { ApiReqRetryStatus retry_status = 9; } +message ClineModelInfo { + string provider_id = 1; + string model_id = 2; +} + // Main ClineMessage type message ClineMessage { int64 ts = 1; @@ -210,6 +215,7 @@ message ClineMessage { ClineAskQuestion ask_question = 20; ClineAskNewTask ask_new_task = 21; ClineApiReqInfo api_req_info = 22; + ClineModelInfo model_info = 23; } // UiService provides methods for managing UI interactions diff --git a/src/core/api/providers/anthropic.ts b/src/core/api/providers/anthropic.ts index a157542c..ad76870f 100644 --- a/src/core/api/providers/anthropic.ts +++ b/src/core/api/providers/anthropic.ts @@ -150,14 +150,16 @@ export class AnthropicHandler implements ApiHandler { for await (const chunk of stream) { switch (chunk?.type) { case "message_start": - // tells us cache reads/writes/input/output - const usage = chunk.message.usage - yield { - type: "usage", - inputTokens: usage.input_tokens || 0, - outputTokens: usage.output_tokens || 0, - cacheWriteTokens: usage.cache_creation_input_tokens || undefined, - cacheReadTokens: usage.cache_read_input_tokens || undefined, + { + // tells us cache reads/writes/input/output + const usage = chunk.message.usage + yield { + type: "usage", + inputTokens: usage.input_tokens || 0, + outputTokens: usage.output_tokens || 0, + cacheWriteTokens: usage.cache_creation_input_tokens || undefined, + cacheReadTokens: usage.cache_read_input_tokens || undefined, + } } break case "message_delta": @@ -178,15 +180,7 @@ export class AnthropicHandler implements ApiHandler { yield { type: "reasoning", reasoning: chunk.content_block.thinking || "", - } - const thinking = chunk.content_block.thinking - const signature = chunk.content_block.signature - if (thinking && signature) { - yield { - type: "ant_thinking", - thinking, - signature, - } + signature: chunk.content_block.signature, } break case "redacted_thinking": @@ -194,10 +188,7 @@ export class AnthropicHandler implements ApiHandler { yield { type: "reasoning", reasoning: "[Redacted thinking block]", - } - yield { - type: "ant_redacted_thinking", - data: chunk.content_block.data, + redacted_data: chunk.content_block.data, } break case "tool_use": @@ -236,10 +227,10 @@ export class AnthropicHandler implements ApiHandler { case "signature_delta": // It's used when sending the thinking block back to the API // API expects this in completed form, not as array of deltas - if (thinkingDeltaAccumulator && chunk.delta.signature) { + if (chunk.delta.signature) { yield { - type: "ant_thinking", - thinking: thinkingDeltaAccumulator, + type: "reasoning", + reasoning: "", // reasoning text is already sent via thinking_delta signature: chunk.delta.signature, } } diff --git a/src/core/api/providers/cline.ts b/src/core/api/providers/cline.ts index 8905c6df..571ae006 100644 --- a/src/core/api/providers/cline.ts +++ b/src/core/api/providers/cline.ts @@ -165,8 +165,7 @@ export class ClineHandler implements ApiHandler { if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) { yield { type: "reasoning", - // @ts-ignore-next-line - reasoning: delta.reasoning, + reasoning: typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning), } } @@ -185,8 +184,9 @@ export class ClineHandler implements ApiHandler { !shouldSkipReasoningForModel(this.options.openRouterModelId) ) { yield { - type: "reasoning_details", - reasoning_details: delta.reasoning_details, + type: "reasoning", + reasoning: "", + details: delta.reasoning_details, } } diff --git a/src/core/api/providers/minimax.ts b/src/core/api/providers/minimax.ts index a8dc1717..e25f2448 100644 --- a/src/core/api/providers/minimax.ts +++ b/src/core/api/providers/minimax.ts @@ -66,12 +66,11 @@ export class MinimaxHandler implements ApiHandler { tool_choice: nativeToolsOn ? { type: "any" } : undefined, }) - let thinkingDeltaAccumulator = "" const lastStartedToolCall = { id: "", name: "", arguments: "" } for await (const chunk of stream) { switch (chunk?.type) { - case "message_start": + case "message_start": { // tells us cache reads/writes/input/output const usage = chunk.message.usage yield { @@ -82,6 +81,7 @@ export class MinimaxHandler implements ApiHandler { cacheReadTokens: usage.cache_read_input_tokens || undefined, } break + } case "message_delta": // tells us stop_reason, stop_sequence, and output tokens along the way and at the end of the message yield { @@ -100,13 +100,11 @@ export class MinimaxHandler implements ApiHandler { type: "reasoning", reasoning: chunk.content_block.thinking || "", } - const thinking = chunk.content_block.thinking - const signature = chunk.content_block.signature - if (thinking && signature) { + if (chunk.content_block.thinking && chunk.content_block.signature) { yield { - type: "ant_thinking", - thinking, - signature, + type: "reasoning", + reasoning: chunk.content_block.thinking, + signature: chunk.content_block.signature, } } break @@ -115,10 +113,7 @@ export class MinimaxHandler implements ApiHandler { yield { type: "reasoning", reasoning: "[Redacted thinking block]", - } - yield { - type: "ant_redacted_thinking", - data: chunk.content_block.data, + redacted_data: chunk.content_block.data, } break case "tool_use": @@ -152,15 +147,14 @@ export class MinimaxHandler implements ApiHandler { type: "reasoning", reasoning: chunk.delta.thinking, } - thinkingDeltaAccumulator += chunk.delta.thinking break case "signature_delta": // It's used when sending the thinking block back to the API // API expects this in completed form, not as array of deltas - if (thinkingDeltaAccumulator && chunk.delta.signature) { + if (chunk.delta.signature) { yield { - type: "ant_thinking", - thinking: thinkingDeltaAccumulator, + type: "reasoning", + reasoning: "", signature: chunk.delta.signature, } } diff --git a/src/core/api/providers/openai-native.ts b/src/core/api/providers/openai-native.ts index c4e2ed64..be7ba9f2 100644 --- a/src/core/api/providers/openai-native.ts +++ b/src/core/api/providers/openai-native.ts @@ -114,7 +114,7 @@ export class OpenAiNativeHandler implements ApiHandler { } case "gpt-5-2025-08-07": case "gpt-5-mini-2025-08-07": - case "gpt-5-nano-2025-08-07": + case "gpt-5-nano-2025-08-07": { const stream = await client.chat.completions.create({ model: model.id, temperature: 1, @@ -148,6 +148,7 @@ export class OpenAiNativeHandler implements ApiHandler { } } break + } default: { const stream = await client.chat.completions.create({ model: model.id, diff --git a/src/core/api/providers/openrouter.ts b/src/core/api/providers/openrouter.ts index bf285a60..ffe15cb7 100644 --- a/src/core/api/providers/openrouter.ts +++ b/src/core/api/providers/openrouter.ts @@ -127,8 +127,7 @@ export class OpenRouterHandler implements ApiHandler { if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) { yield { type: "reasoning", - // @ts-ignore-next-line - reasoning: delta.reasoning, + reasoning: typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning), } } @@ -142,8 +141,9 @@ export class OpenRouterHandler implements ApiHandler { !shouldSkipReasoningForModel(this.options.openRouterModelId) ) { yield { - type: "reasoning_details", - reasoning_details: delta.reasoning_details, + type: "reasoning", + reasoning: "", + details: delta.reasoning_details, } } diff --git a/src/core/api/providers/vercel-ai-gateway.ts b/src/core/api/providers/vercel-ai-gateway.ts index f190554e..446a4b07 100644 --- a/src/core/api/providers/vercel-ai-gateway.ts +++ b/src/core/api/providers/vercel-ai-gateway.ts @@ -95,8 +95,9 @@ export class VercelAIGatewayHandler implements ApiHandler { delta.reasoning_details.length // exists and non-0 ) { yield { - type: "reasoning_details", - reasoning_details: delta.reasoning_details, + type: "reasoning", + reasoning: "", + details: delta.reasoning_details, } } diff --git a/src/core/api/providers/vertex.ts b/src/core/api/providers/vertex.ts index d392091e..3edd1965 100644 --- a/src/core/api/providers/vertex.ts +++ b/src/core/api/providers/vertex.ts @@ -166,7 +166,7 @@ export class VertexHandler implements ApiHandler { for await (const chunk of stream) { switch (chunk?.type) { - case "message_start": + case "message_start": { const usage = chunk.message.usage yield { type: "usage", @@ -176,6 +176,7 @@ export class VertexHandler implements ApiHandler { cacheReadTokens: usage.cache_read_input_tokens || undefined, } break + } case "message_delta": yield { type: "usage", diff --git a/src/core/api/transform/anthropic-format.ts b/src/core/api/transform/anthropic-format.ts index 116c0a2e..b73ec932 100644 --- a/src/core/api/transform/anthropic-format.ts +++ b/src/core/api/transform/anthropic-format.ts @@ -1,14 +1,14 @@ -import { MessageParam } from "@anthropic-ai/sdk/resources/index" +import { ClineStorageMessage } from "@/shared/messages/content" /** * Sanitize Anthropic messages by removing reasoning details and adding ephemeral cache control * to the last two user messages to prevent them from being stored in Anthropic's cache. */ export function sanitizeAnthropicMessages( - messages: Array, + messages: Array, lastUserMsgIndex?: number, secondLastMsgUserIndex?: number, -): Array { +): Array { return messages.map((_message, index) => { const message = removeReasoningDetails(_message) const addCacheControl = lastUserMsgIndex !== undefined && secondLastMsgUserIndex !== undefined @@ -58,7 +58,7 @@ export function sanitizeAnthropicMessages( /** * Remove reasoning details from a single Anthropic message parameter */ -function removeReasoningDetails(param: MessageParam): MessageParam { +function removeReasoningDetails(param: ClineStorageMessage): ClineStorageMessage { if (Array.isArray(param.content)) { return { ...param, diff --git a/src/core/api/transform/ollama-format.ts b/src/core/api/transform/ollama-format.ts index 85e723cd..b2c703fa 100644 --- a/src/core/api/transform/ollama-format.ts +++ b/src/core/api/transform/ollama-format.ts @@ -1,7 +1,13 @@ -import { Anthropic } from "@anthropic-ai/sdk" import { Message } from "ollama" +import { + ClineAssistantToolUseBlock, + ClineImageContentBlock, + ClineStorageMessage, + ClineTextContentBlock, + ClineUserToolResultContentBlock, +} from "@/shared/messages/content" -export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): Message[] { +export function convertToOllamaMessages(anthropicMessages: Omit[]): Message[] { const ollamaMessages: Message[] = [] for (const anthropicMessage of anthropicMessages) { @@ -13,8 +19,8 @@ export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.Me } else { if (anthropicMessage.role === "user") { const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ - nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] - toolMessages: Anthropic.ToolResultBlockParam[] + nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[] + toolMessages: ClineUserToolResultContentBlock[] }>( (acc, part) => { if (part.type === "tool_result") { @@ -70,8 +76,8 @@ export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.Me } } else if (anthropicMessage.role === "assistant") { const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ - nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] - toolMessages: Anthropic.ToolUseBlockParam[] + nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[] + toolMessages: ClineAssistantToolUseBlock[] }>( (acc, part) => { if (part.type === "tool_use") { diff --git a/src/core/api/transform/openai-format.ts b/src/core/api/transform/openai-format.ts index f32d7443..be169b98 100644 --- a/src/core/api/transform/openai-format.ts +++ b/src/core/api/transform/openai-format.ts @@ -1,8 +1,17 @@ import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" +import { + ClineAssistantRedactedThinkingBlock, + ClineAssistantThinkingBlock, + ClineAssistantToolUseBlock, + ClineImageContentBlock, + ClineStorageMessage, + ClineTextContentBlock, + ClineUserToolResultContentBlock, +} from "@/shared/messages/content" export function convertToOpenAiMessages( - anthropicMessages: Anthropic.Messages.MessageParam[], + anthropicMessages: Omit[], ): OpenAI.Chat.ChatCompletionMessageParam[] { const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [] @@ -23,8 +32,8 @@ export function convertToOpenAiMessages( */ if (anthropicMessage.role === "user") { const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ - nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] - toolMessages: Anthropic.ToolResultBlockParam[] + nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[] + toolMessages: ClineUserToolResultContentBlock[] }>( (acc, part) => { if (part.type === "tool_result") { @@ -38,7 +47,7 @@ export function convertToOpenAiMessages( ) // Process tool result messages FIRST since they must follow the tool use messages - const toolResultImages: Anthropic.Messages.ImageBlockParam[] = [] + const toolResultImages: ClineImageContentBlock[] = [] toolMessages.forEach((toolMessage) => { // The Anthropic SDK allows tool results to be a string or an array of text and image blocks, enabling rich and structured content. In contrast, the OpenAI SDK only supports tool results as a single string, so we map the Anthropic tool result parts into one concatenated string to maintain compatibility. let content: string @@ -102,8 +111,13 @@ export function convertToOpenAiMessages( } } else if (anthropicMessage.role === "assistant") { const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{ - nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] - toolMessages: Anthropic.ToolUseBlockParam[] + nonToolMessages: ( + | ClineTextContentBlock + | ClineImageContentBlock + | ClineAssistantThinkingBlock + | ClineAssistantRedactedThinkingBlock + )[] + toolMessages: ClineAssistantToolUseBlock[] }>( (acc, part) => { if (part.type === "tool_use") { @@ -119,6 +133,7 @@ export function convertToOpenAiMessages( // Process non-tool messages let content: string | undefined const reasoningDetails: any[] = [] + const thinkingBlock = [] if (nonToolMessages.length > 0) { nonToolMessages.forEach((part) => { // @ts-ignore-next-line @@ -134,13 +149,16 @@ export function convertToOpenAiMessages( // @ts-ignore-next-line // delete part.reasoning_details } + if (part.type === "thinking" && part.thinking) { + thinkingBlock.push(part) + } }) content = nonToolMessages .map((part) => { - if (part.type === "image") { - return "" // impossible as the assistant cannot send images + if (part.type === "text" && part.text) { + return part.text } - return part.text + return "" }) .join("\n") } diff --git a/src/core/api/transform/stream.ts b/src/core/api/transform/stream.ts index ab546075..98d0bbc9 100644 --- a/src/core/api/transform/stream.ts +++ b/src/core/api/transform/stream.ts @@ -1,39 +1,11 @@ export type ApiStream = AsyncGenerator -export type ApiStreamChunk = - | ApiStreamTextChunk - | ApiStreamReasoningChunk - | ApiStreamReasoningDetailsChunk - | ApiStreamAnthropicThinkingChunk - | ApiStreamAnthropicRedactedThinkingChunk - | ApiStreamUsageChunk - | ApiStreamToolCallsChunk +export type ApiStreamChunk = ApiStreamTextChunk | ApiStreamThinkingChunk | ApiStreamUsageChunk | ApiStreamToolCallsChunk export interface ApiStreamTextChunk { type: "text" text: string } -export interface ApiStreamReasoningChunk { - type: "reasoning" - reasoning: string -} - -export interface ApiStreamReasoningDetailsChunk { - type: "reasoning_details" - reasoning_details: any // openrouter has various properties that we can pass back unmodified in api requests to preserve reasoning traces -} - -export interface ApiStreamAnthropicThinkingChunk { - type: "ant_thinking" - thinking: string - signature: string -} - -export interface ApiStreamAnthropicRedactedThinkingChunk { - type: "ant_redacted_thinking" - data: string -} - export interface ApiStreamUsageChunk { type: "usage" inputTokens: number @@ -58,3 +30,11 @@ export interface ApiStreamToolCall { arguments?: any } } + +export interface ApiStreamThinkingChunk { + type: "reasoning" + reasoning: string + details?: unknown // openrouter has various properties that we can pass back unmodified in api requests to preserve reasoning traces + signature?: string + redacted_data?: string +} diff --git a/src/core/api/transform/tool-use-handler.ts b/src/core/api/transform/tool-use-handler.ts index fc08a55e..52b82f9a 100644 --- a/src/core/api/transform/tool-use-handler.ts +++ b/src/core/api/transform/tool-use-handler.ts @@ -1,8 +1,8 @@ -import { Anthropic } from "@anthropic-ai/sdk" import type { ToolUse } from "@core/assistant-message" import { JSONParser } from "@streamparser/json" import { McpHub } from "@/services/mcp/McpHub" import { CLINE_MCP_TOOL_IDENTIFIER } from "@/shared/mcp" +import { ClineAssistantToolUseBlock } from "@/shared/messages/content" import { ClineDefaultTool } from "@/shared/tools" export interface PendingToolUse { @@ -32,7 +32,7 @@ const ESCAPE_MAP: Record = { const ESCAPE_PATTERN = /\\[ntr"\\]/g /** - * Handles streaming native tool use blocks and converts them to Anthropic.ToolUseBlockParam format + * Handles streaming native tool use blocks and converts them to ClineAssistantToolUseBlock format */ export class ToolUseHandler { private pendingToolUses = new Map() @@ -60,7 +60,7 @@ export class ToolUseHandler { } } - getFinalizedToolUse(id: string): Anthropic.ToolUseBlockParam | undefined { + getFinalizedToolUse(id: string): ClineAssistantToolUseBlock | undefined { const pending = this.pendingToolUses.get(id) if (!pending?.name) { return undefined @@ -85,8 +85,8 @@ export class ToolUseHandler { } } - getAllFinalizedToolUses(): Anthropic.ToolUseBlockParam[] { - const results: Anthropic.ToolUseBlockParam[] = [] + getAllFinalizedToolUses(): ClineAssistantToolUseBlock[] { + const results: ClineAssistantToolUseBlock[] = [] for (const id of this.pendingToolUses.keys()) { const toolUse = this.getFinalizedToolUse(id) if (toolUse) { diff --git a/src/core/assistant-message/index.ts b/src/core/assistant-message/index.ts index c1f74ef0..d12d1153 100644 --- a/src/core/assistant-message/index.ts +++ b/src/core/assistant-message/index.ts @@ -1,9 +1,10 @@ import { ClineDefaultTool } from "@shared/tools" -export type AssistantMessageContent = TextContent | ToolUse + +export type AssistantMessageContent = TextStreamContent | ToolUse | ReasoningStreamContent export { parseAssistantMessageV2 } from "./parse-assistant-message" -export interface TextContent { +export interface TextStreamContent { type: "text" content: string partial: boolean @@ -54,3 +55,13 @@ export interface ToolUse { // Whether this tool use was initiated by a native tool call isNativeToolCall?: boolean } + +export interface ReasoningStreamContent { + type: "reasoning" + reasoning: string + details?: any // openrouter has various properties that we can pass back unmodified in api requests to preserve reasoning traces + signature?: string + redacted?: boolean // whether this reasoning block has been redacted + data?: string // redacted data + partial: boolean +} diff --git a/src/core/assistant-message/parse-assistant-message.ts b/src/core/assistant-message/parse-assistant-message.ts index 836c548d..9d7f39ef 100644 --- a/src/core/assistant-message/parse-assistant-message.ts +++ b/src/core/assistant-message/parse-assistant-message.ts @@ -1,5 +1,5 @@ import { ClineDefaultTool, toolUseNames } from "@shared/tools" -import { AssistantMessageContent, TextContent, ToolParamName, ToolUse, toolParamNames } from "." // Assuming types are defined in index.ts or a similar file +import { AssistantMessageContent, TextStreamContent, ToolParamName, ToolUse, toolParamNames } from "." // Assuming types are defined in index.ts or a similar file // parseAssistantmessageV1 removed in https://github.com/cline/cline/pull/5425 @@ -27,7 +27,7 @@ import { AssistantMessageContent, TextContent, ToolParamName, ToolUse, toolParam export function parseAssistantMessageV2(assistantMessage: string): AssistantMessageContent[] { const contentBlocks: AssistantMessageContent[] = [] let currentTextContentStart = 0 // Index where the current text block started - let currentTextContent: TextContent | undefined + let currentTextContent: TextStreamContent | undefined let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use let currentToolUse: ToolUse | undefined let currentParamValueStart = 0 // Index *after* the opening tag of the current param diff --git a/src/core/controller/task/getTaskHistory.ts b/src/core/controller/task/getTaskHistory.ts index 560f55fe..751e5ee9 100644 --- a/src/core/controller/task/getTaskHistory.ts +++ b/src/core/controller/task/getTaskHistory.ts @@ -103,6 +103,7 @@ export async function getTaskHistory(controller: Controller, request: GetTaskHis tokensOut: item.tokensOut || 0, cacheWrites: item.cacheWrites || 0, cacheReads: item.cacheReads || 0, + modelId: item.modelId || "", })) return TaskHistoryArray.create({ diff --git a/src/core/task/index.ts b/src/core/task/index.ts index ac4d1313..e70ffb9c 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -1,5 +1,4 @@ import { setTimeout as setTimeoutPromise } from "node:timers/promises" -import { Anthropic } from "@anthropic-ai/sdk" import { ApiHandler, ApiProviderInfo, buildApiHandler } from "@core/api" import { ApiStream } from "@core/api/transform/stream" import { AssistantMessageContent, parseAssistantMessageV2 } from "@core/assistant-message" @@ -83,6 +82,16 @@ import { HostProvider } from "@/hosts/host-provider" import { isSubagentCommand, transformClineCommand } from "@/integrations/cli-subagents/subagent_command" import { ClineError, ClineErrorType, ErrorService } from "@/services/error" import { TerminalHangStage, TerminalUserInterventionAction, telemetryService } from "@/services/telemetry" +import { + ClineAssistantContent, + ClineAssistantRedactedThinkingBlock, + ClineContent, + ClineImageContentBlock, + ClineMessageModelInfo, + ClineStorageMessage, + ClineToolResponseContent, + ClineUserContent, +} from "@/shared/messages/content" import { ShowMessageType } from "@/shared/proto/index.host" import { isClineCliInstalled, isCliSubagentContext } from "@/utils/cli-detector" import { isInTestMode } from "../../services/test/TestMode" @@ -95,9 +104,7 @@ import { MessageStateHandler } from "./message-state" import { TaskState } from "./TaskState" import { ToolExecutor } from "./ToolExecutor" import { detectAvailableCliTools, extractProviderDomainFromUrl, updateApiReqMsg } from "./utils" - -export type ToolResponse = string | Array -type UserContent = Array +export type ToolResponse = ClineToolResponseContent type TaskParams = { controller: Controller @@ -693,6 +700,12 @@ export class Task { throw new Error("Cline instance aborted") } + const providerInfo = this.getCurrentProviderInfo() + const modelInfo: ClineMessageModelInfo = { + providerId: providerInfo.providerId, + modelId: providerInfo.model.id, + } + if (partial !== undefined) { const lastMessage = this.messageStateHandler.getClineMessages().at(-1) const isUpdatingPreviousPartial = @@ -719,6 +732,7 @@ export class Task { images, files, partial, + modelInfo, }) await this.postStateToWebview() return sayTs @@ -751,6 +765,7 @@ export class Task { text, images, files, + modelInfo, }) await this.postStateToWebview() return sayTs @@ -767,6 +782,7 @@ export class Task { text, images, files, + modelInfo, }) await this.postStateToWebview() return sayTs @@ -801,7 +817,7 @@ export class Task { } private async runUserPromptSubmitHook( - userContent: UserContent, + userContent: ClineContent[], _context: "initial_task" | "resume" | "feedback", ): Promise<{ cancel?: boolean; contextModification?: string; errorMessage?: string }> { const hooksEnabled = this.stateManager.getGlobalSettingsKey("hooksEnabled") @@ -879,9 +895,9 @@ export class Task { this.taskState.isInitialized = true - const imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images) + const imageBlocks: ClineImageContentBlock[] = formatResponse.imageBlocks(images) - const userContent: UserContent = [ + const userContent: ClineUserContent[] = [ { type: "text", text: `\n${task}\n`, @@ -1042,7 +1058,7 @@ export class Task { const { response, text, images, files } = await this.ask(askType) // calls poststatetowebview // Initialize newUserContent array for hook context - const newUserContent: UserContent = [] + const newUserContent: ClineContent[] = [] // Run TaskResume hook AFTER user clicks resume button const hooksEnabled = this.stateManager.getGlobalSettingsKey("hooksEnabled") @@ -1118,15 +1134,15 @@ export class Task { const existingApiConversationHistory = this.messageStateHandler.getApiConversationHistory() // Remove the last user message so we can update it with the resume message - let modifiedOldUserContent: UserContent // either the last message if its user message, or the user message before the last (assistant) message - let modifiedApiConversationHistory: Anthropic.Messages.MessageParam[] // need to remove the last user message to replace with new modified user message + let modifiedOldUserContent: ClineContent[] // either the last message if its user message, or the user message before the last (assistant) message + let modifiedApiConversationHistory: ClineStorageMessage[] // need to remove the last user message to replace with new modified user message if (existingApiConversationHistory.length > 0) { const lastMessage = existingApiConversationHistory[existingApiConversationHistory.length - 1] if (lastMessage.role === "assistant") { modifiedApiConversationHistory = [...existingApiConversationHistory] modifiedOldUserContent = [] } else if (lastMessage.role === "user") { - const existingUserContent: UserContent = Array.isArray(lastMessage.content) + const existingUserContent: ClineContent[] = Array.isArray(lastMessage.content) ? lastMessage.content : [{ type: "text", text: lastMessage.content }] modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1) @@ -1244,7 +1260,7 @@ export class Task { await this.initiateTaskLoop(newUserContent) } - private async initiateTaskLoop(userContent: UserContent): Promise { + private async initiateTaskLoop(userContent: ClineContent[]): Promise { let nextUserContent = userContent let includeFileDetails = true while (!this.taskState.abort) { @@ -1472,7 +1488,7 @@ export class Task { } // Tools - async executeCommandTool(command: string, timeoutSeconds: number | undefined): Promise<[boolean, ToolResponse]> { + async executeCommandTool(command: string, timeoutSeconds: number | undefined): Promise<[boolean, ClineToolResponseContent]> { // For Cline CLI subagents, we want to parse and process the command to ensure flags are correct const isSubagent = isSubagentCommand(command) @@ -2333,7 +2349,7 @@ export class Task { } } - async recursivelyMakeClineRequests(userContent: UserContent, includeFileDetails: boolean = false): Promise { + async recursivelyMakeClineRequests(userContent: ClineContent[], includeFileDetails: boolean = false): Promise { // Check abort flag at the very start to prevent any execution after cancellation if (this.taskState.abort) { throw new Error("Task instance aborted") @@ -2355,6 +2371,11 @@ export class Task { } catch {} } + const modelInfo = { + modelId: model.id, + providerId: providerId, + } + if (this.taskState.consecutiveMistakeCount >= this.stateManager.getGlobalSettingsKey("maxConsecutiveMistakes")) { const autoApprovalSettings = this.stateManager.getGlobalSettingsKey("autoApprovalSettings") if (autoApprovalSettings.enableNotifications) { @@ -2374,7 +2395,7 @@ export class Task { await this.say("user_feedback", text, images, files) // This userContent is for the *next* API call. - const feedbackUserContent: UserContent = [] + const feedbackUserContent: ClineUserContent[] = [] feedbackUserContent.push({ type: "text", text: formatResponse.tooManyMistakes(text), @@ -2518,7 +2539,7 @@ export class Task { } } - let parsedUserContent: UserContent + let parsedUserContent: ClineContent[] let environmentDetails: string let clinerulesError: boolean @@ -2675,7 +2696,7 @@ export class Task { telemetryService.captureConversationTurnEvent( this.ulid, providerId, - this.api.getModel().id, + modelInfo.modelId, "assistant", currentMode, { @@ -2712,9 +2733,11 @@ export class Task { let assistantTextOnly = "" // For API history (text only, no tool XML) let reasoningMessage = "" const reasoningDetails = [] - const antThinkingContent: (Anthropic.Messages.RedactedThinkingBlock | Anthropic.Messages.ThinkingBlock)[] = [] + const redactedThinkingContent: ClineAssistantRedactedThinkingBlock[] = [] this.taskState.isStreaming = true let didReceiveUsageChunk = false + let reasoningSignature = "" + try { for await (const chunk of stream) { if (!chunk) { @@ -2730,35 +2753,34 @@ export class Task { totalCost = chunk.totalCost break case "reasoning": - // reasoning will always come before assistant message - reasoningMessage += chunk.reasoning + // reasoning will always come before assistant message chunks + if (chunk.reasoning) { + reasoningMessage += chunk.reasoning + } // fixes bug where cancelling task > aborts task > for loop may be in middle of streaming reasoning > say function throws error before we get a chance to properly clean up and cancel the task. if (!this.taskState.abort) { await this.say("reasoning", reasoningMessage, undefined, undefined, true) } - break - // for cline/openrouter providers - case "reasoning_details": - // reasoning_details may be an array of 0 or 1 items depending on how openrouter returns it - if (Array.isArray(chunk.reasoning_details)) { - reasoningDetails.push(...chunk.reasoning_details) - } else { - reasoningDetails.push(chunk.reasoning_details) + if (chunk.signature) { + reasoningSignature = chunk.signature + break } - break - // for anthropic providers - case "ant_thinking": - antThinkingContent.push({ - type: "thinking", - thinking: chunk.thinking, - signature: chunk.signature, - }) - break - case "ant_redacted_thinking": - antThinkingContent.push({ - type: "redacted_thinking", - data: chunk.data, - }) + if (chunk.details) { + // reasoning_details may be an array of 0 or 1 items depending on how openrouter returns it + if (Array.isArray(chunk.details)) { + reasoningDetails.push(...chunk.details) + } else { + reasoningDetails.push(chunk.details) + } + } + + if (chunk.redacted_data) { + redactedThinkingContent.push({ + type: "redacted_thinking", + data: chunk.redacted_data, + }) + } + break case "tool_calls": { if (!chunk.tool_call) { @@ -3006,25 +3028,25 @@ export class Task { const toolUseBlocks = this.toolUseHandler.getAllFinalizedToolUses() // Build content array with thinking blocks, text (if any), and tool use blocks - const assistantContent: Array< - | Anthropic.Messages.RedactedThinkingBlock - | Anthropic.Messages.ThinkingBlock - | Anthropic.Messages.TextBlockParam - | Anthropic.ToolUseBlockParam - > = [ + const assistantContent: Array = [ // This is critical for maintaining the model's reasoning flow and conversation integrity. // "When providing thinking blocks, the entire sequence of consecutive thinking blocks must match the outputs generated by the model during the original request; you cannot rearrange or modify the sequence of these blocks." The signature_delta is used to verify that the thinking was generated by Claude, and the thinking blocks will be ignored if it's incorrect or missing. // https://docs.claude.com/en/docs/build-with-claude/extended-thinking#preserving-thinking-blocks - ...antThinkingContent, + ...redactedThinkingContent, ] - + if (reasoningMessage.trim().length > 0) { + assistantContent.push({ + type: "thinking", + thinking: reasoningMessage, + signature: reasoningSignature, + }) + } // Only add text block if there's actual text (not just tool XML) if (assistantTextOnly.trim().length > 0) { assistantContent.push({ type: "text", text: assistantTextOnly, // reasoning_details only exists for cline/openrouter providers - // @ts-ignore-next-line reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined, }) } @@ -3039,6 +3061,7 @@ export class Task { await this.messageStateHandler.addToApiConversationHistory({ role: "assistant", content: assistantContent, + modelInfo, }) } @@ -3103,6 +3126,7 @@ export class Task { text: "Failure: I did not provide a response.", }, ], + modelInfo, }) let response: ClineAskResponse @@ -3162,10 +3186,10 @@ export class Task { } async loadContext( - userContent: UserContent, + userContent: ClineContent[], includeFileDetails: boolean = false, useCompactPrompt = false, - ): Promise<[UserContent, string, boolean]> { + ): Promise<[ClineContent[], string, boolean]> { // Track if we need to check clinerulesFile let needsClinerulesFileCheck = false diff --git a/src/core/task/message-state.ts b/src/core/task/message-state.ts index a038ec60..cbece20f 100644 --- a/src/core/task/message-state.ts +++ b/src/core/task/message-state.ts @@ -1,4 +1,3 @@ -import Anthropic from "@anthropic-ai/sdk" import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker" import getFolderSize from "get-folder-size" import Mutex from "p-mutex" @@ -8,6 +7,7 @@ import { combineCommandSequences } from "@/shared/combineCommandSequences" import { ClineMessage } from "@/shared/ExtensionMessage" import { getApiMetrics } from "@/shared/getApiMetrics" import { HistoryItem } from "@/shared/HistoryItem" +import { ClineStorageMessage } from "@/shared/messages/content" import { getCwd, getDesktopDir } from "@/utils/path" import { ensureTaskDirectoryExists, saveApiConversationHistory, saveClineMessages } from "../storage/disk" import { TaskState } from "./TaskState" @@ -22,7 +22,7 @@ interface MessageStateHandlerParams { } export class MessageStateHandler { - private apiConversationHistory: Anthropic.MessageParam[] = [] + private apiConversationHistory: ClineStorageMessage[] = [] private clineMessages: ClineMessage[] = [] private taskIsFavorited: boolean private checkpointTracker: CheckpointTracker | undefined @@ -58,11 +58,11 @@ export class MessageStateHandler { return await this.stateMutex.withLock(fn) } - getApiConversationHistory(): Anthropic.MessageParam[] { + getApiConversationHistory(): ClineStorageMessage[] { return this.apiConversationHistory } - setApiConversationHistory(newHistory: Anthropic.MessageParam[]): void { + setApiConversationHistory(newHistory: ClineStorageMessage[]): void { this.apiConversationHistory = newHistory } @@ -93,6 +93,7 @@ export class MessageStateHandler { (message) => !(message.ask === "resume_task" || message.ask === "resume_completed_task"), ) ] + const lastModelInfo = [...this.apiConversationHistory].reverse().find((msg) => msg.modelInfo !== undefined) const taskDir = await ensureTaskDirectoryExists(this.taskId) let taskDirSize = 0 try { @@ -119,6 +120,7 @@ export class MessageStateHandler { conversationHistoryDeletedRange: this.taskState.conversationHistoryDeletedRange, isFavorited: this.taskIsFavorited, checkpointManagerErrorMessage: this.taskState.checkpointManagerErrorMessage, + modelId: lastModelInfo?.modelInfo?.modelId, }) } catch (error) { console.error("Failed to save cline messages:", error) @@ -135,7 +137,7 @@ export class MessageStateHandler { }) } - async addToApiConversationHistory(message: Anthropic.MessageParam) { + async addToApiConversationHistory(message: ClineStorageMessage) { // Protect with mutex to prevent concurrent modifications from corrupting data (RC-4) return await this.withStateLock(async () => { this.apiConversationHistory.push(message) @@ -143,7 +145,7 @@ export class MessageStateHandler { }) } - async overwriteApiConversationHistory(newHistory: Anthropic.MessageParam[]): Promise { + async overwriteApiConversationHistory(newHistory: ClineStorageMessage[]): Promise { // Protect with mutex to prevent concurrent modifications from corrupting data (RC-4) return await this.withStateLock(async () => { this.apiConversationHistory = newHistory diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 57f5915f..6a3866ad 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -12,6 +12,7 @@ import { DictationSettings } from "./DictationSettings" import { FocusChainSettings } from "./FocusChainSettings" import { HistoryItem } from "./HistoryItem" import { McpDisplayMode } from "./McpDisplayMode" +import { ClineMessageModelInfo } from "./messages/content" import { Mode, OpenaiReasoningEffort } from "./storage/types" import { TelemetrySetting } from "./TelemetrySetting" import { UserInfo } from "./UserInfo" @@ -119,6 +120,7 @@ export interface ClineMessage { isOperationOutsideWorkspace?: boolean conversationHistoryIndex?: number conversationHistoryDeletedRange?: [number, number] // for when conversation history is truncated for API requests + modelInfo?: ClineMessageModelInfo } export type ClineAsk = diff --git a/src/shared/HistoryItem.ts b/src/shared/HistoryItem.ts index b44d2339..bef07dad 100644 --- a/src/shared/HistoryItem.ts +++ b/src/shared/HistoryItem.ts @@ -15,4 +15,6 @@ export type HistoryItem = { conversationHistoryDeletedRange?: [number, number] isFavorited?: boolean checkpointManagerErrorMessage?: string + + modelId?: string } diff --git a/src/shared/messages/content.ts b/src/shared/messages/content.ts new file mode 100644 index 00000000..62885144 --- /dev/null +++ b/src/shared/messages/content.ts @@ -0,0 +1,71 @@ +import { Anthropic } from "@anthropic-ai/sdk" + +type ClinePromptInputContent = string + +type ClineMessageRole = "user" | "assistant" + +export interface ClineMessageModelInfo { + modelId: string + providerId: string +} + +export interface ClineReasoningDetailParam { + type: "reasoning.text" | string + text: string + signature: string + format: "anthropic-claude-v1" | string + index: number +} + +/** + * An extension of Anthropic.MessageParam that includes Cline-specific fields: reasoning_details. + * This ensures backward compatibility where the messages were stored in Anthropic format with addtional + * fields unknown to Anthropic SDK. + */ +export interface ClineTextContentBlock extends Anthropic.Messages.TextBlockParam { + // reasoning_details only exists for cline/openrouter providers + reasoning_details?: ClineReasoningDetailParam[] +} + +export interface ClineImageContentBlock extends Anthropic.ImageBlockParam {} + +export interface ClineDocumentContentBlock extends Anthropic.DocumentBlockParam {} + +export interface ClineUserToolResultContentBlock extends Anthropic.ToolResultBlockParam {} + +// Assistant only content types +export interface ClineAssistantToolUseBlock extends Anthropic.ToolUseBlockParam {} + +export interface ClineAssistantThinkingBlock extends Anthropic.Messages.ThinkingBlock {} + +export interface ClineAssistantRedactedThinkingBlock extends Anthropic.Messages.RedactedThinkingBlockParam {} + +export type ClineToolResponseContent = ClinePromptInputContent | Array + +export type ClineUserContent = + | ClineTextContentBlock + | ClineImageContentBlock + | ClineDocumentContentBlock + | ClineUserToolResultContentBlock + +export type ClineAssistantContent = + | ClineTextContentBlock + | ClineImageContentBlock + | ClineDocumentContentBlock + | ClineAssistantToolUseBlock + | ClineAssistantThinkingBlock + | ClineAssistantRedactedThinkingBlock + +export type ClineContent = ClineUserContent | ClineAssistantContent + +/** + * An extension of Anthropic.MessageParam that includes Cline-specific fields. + * This ensures backward compatibility where the messages were stored in Anthropic format, + * while allowing for additional metadata specific to Cline to avoid unknown fields in Anthropic SDK + * added by ignoring the type checking for those fields. + */ +export interface ClineStorageMessage extends Anthropic.MessageParam { + role: ClineMessageRole + content: ClinePromptInputContent | ClineContent[] + modelInfo?: ClineMessageModelInfo +} diff --git a/src/shared/proto-conversions/cline-message.ts b/src/shared/proto-conversions/cline-message.ts index 64b7b33d..1e4c77f3 100644 --- a/src/shared/proto-conversions/cline-message.ts +++ b/src/shared/proto-conversions/cline-message.ts @@ -200,6 +200,7 @@ export function convertClineMessageToProto(message: AppClineMessage): ProtoCline askQuestion: undefined, askNewTask: undefined, apiReqInfo: undefined, + modelInfo: message.modelInfo ?? undefined, } return protoMessage diff --git a/webview-ui/src/components/history/HistoryView.tsx b/webview-ui/src/components/history/HistoryView.tsx index 23150c2f..56c6dbf2 100644 --- a/webview-ui/src/components/history/HistoryView.tsx +++ b/webview-ui/src/components/history/HistoryView.tsx @@ -629,6 +629,7 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { )} )} + {item.modelId &&
Model: {item.modelId}
} {!!item.totalCost && (