feat: add mode and token metrics info to storage messages [CLIENTS-26] (#7795)

* feat(storage): add mode and token metrics to storage messages

Add mode (plan/act) tracking to ApiProviderInfo and ClineMessageModelInfo interfaces, ensuring each storage message contains the operational mode used during API requests.

Refactor token metrics tracking by consolidating cache write/read tokens, input/output tokens, and total cost into a centralized taskMetrics object. This enables better tracking and storage of token usage and costs throughout the task lifecycle, including for partial/cancelled streams.

Updated api_req_started and api_req_finished messages to include comprehensive token metrics, allowing for accurate cost reporting even when streams are cancelled or fail mid-execution.

* update unit tests with mode

* store task metrics per assistant turn
This commit is contained in:
Bee authored and GitHub committed 2025-12-02 13:52:44 -08:00
1 parent c81fa0a9d6
commit 09692d7d3a
8 files changed
+152 -90

No files matched your search

+1
View File
@@ -61,6 +61,7 @@ export interface ApiHandlerModel {
export interface ApiProviderInfo {
providerId: string
model: ApiHandlerModel
mode: Mode
customPrompt?: string // "compact"
autoCondenseThreshold?: number // 0-1 range
}
@@ -116,6 +116,7 @@ export const mockProviderInfo = {
supportsPromptCache: false,
},
},
mode: "act" as const,
}
const makeMockProviderInfo = (modelId: string, providerId: string = "test") => ({
@@ -15,6 +15,7 @@ const mockProviderInfos: { name: string; providerInfo: ApiProviderInfo; expected
providerInfo: {
providerId: "openai",
model: { id: "gpt-5", info: {} as any },
mode: "act" as const,
},
expectedFamily: ModelFamily.GPT_5,
},
@@ -23,6 +24,7 @@ const mockProviderInfos: { name: string; providerInfo: ApiProviderInfo; expected
providerInfo: {
providerId: "anthropic",
model: { id: "claude-3.5-sonnet-20241022", info: {} as any },
mode: "act" as const,
},
expectedFamily: ModelFamily.NEXT_GEN,
},
@@ -31,6 +33,7 @@ const mockProviderInfos: { name: string; providerInfo: ApiProviderInfo; expected
providerInfo: {
providerId: "ollama",
model: { id: "llama-3.2-1b", info: {} as any },
mode: "act" as const,
customPrompt: "compact",
},
expectedFamily: ModelFamily.XS,
@@ -40,6 +43,7 @@ const mockProviderInfos: { name: string; providerInfo: ApiProviderInfo; expected
providerInfo: {
providerId: "openai",
model: { id: "gpt-3.5-turbo", info: {} as any },
mode: "act" as const,
},
expectedFamily: ModelFamily.GENERIC,
},
+99 -82
View File
@@ -67,7 +67,6 @@ import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@sha
import { CLINE_MCP_TOOL_IDENTIFIER } from "@shared/mcp"
import { USER_CONTENT_TAGS } from "@shared/messages/constants"
import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message"
import type { Mode } from "@shared/storage/types"
import { ClineDefaultTool } from "@shared/tools"
import { ClineAskResponse } from "@shared/WebviewMessage"
import { isClaude4PlusModelFamily, isGPT5ModelFamily, isLocalModel, isNextGenModelFamily } from "@utils/model-utils"
@@ -94,7 +93,7 @@ import {
ClineTextContentBlock,
ClineToolResponseContent,
ClineUserContent,
} from "@/shared/messages/content"
} from "@/shared/messages"
import { ShowMessageType } from "@/shared/proto/index.host"
import { isClineCliInstalled, isCliSubagentContext } from "@/utils/cli-detector"
import { isInTestMode } from "../../services/test/TestMode"
@@ -715,6 +714,7 @@ export class Task {
const modelInfo: ClineMessageModelInfo = {
providerId: providerInfo.providerId,
modelId: providerInfo.model.id,
mode: providerInfo.mode,
}
if (partial !== undefined) {
@@ -1992,7 +1992,7 @@ export class Task {
const mode = this.stateManager.getGlobalSettingsKey("mode")
const providerId = (mode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider) as string
const customPrompt = this.stateManager.getGlobalSettingsKey("customPrompt")
return { model, providerId, customPrompt }
return { model, providerId, customPrompt, mode }
}
private getApiRequestIdSafe(): string | undefined {
@@ -2446,20 +2446,17 @@ export class Task {
this.taskState.apiRequestsSinceLastTodoUpdate++
// Used to know what models were used in the task if user wants to export metadata for error reporting purposes
const { model, providerId, customPrompt } = this.getCurrentProviderInfo()
const { model, providerId, customPrompt, mode } = this.getCurrentProviderInfo()
if (providerId && model.id) {
try {
await this.modelContextTracker.recordModelUsage(
providerId,
model.id,
this.stateManager.getGlobalSettingsKey("mode"),
)
await this.modelContextTracker.recordModelUsage(providerId, model.id, mode)
} catch {}
}
const modelInfo = {
const modelInfo: ClineMessageModelInfo = {
modelId: model.id,
providerId: providerId,
mode: mode,
}
if (this.taskState.consecutiveMistakeCount >= this.stateManager.getGlobalSettingsKey("maxConsecutiveMistakes")) {
@@ -2696,10 +2693,7 @@ export class Task {
content: userContent,
})
const modeSetting = this.stateManager.getGlobalSettingsKey("mode")
const currentMode: Mode = modeSetting === "act" ? "act" : "plan"
telemetryService.captureConversationTurnEvent(this.ulid, providerId, model.id, "user", currentMode)
telemetryService.captureConversationTurnEvent(this.ulid, providerId, model.id, "user", modelInfo.mode)
// Capture task initialization timing telemetry for the first API request
if (isFirstRequest) {
@@ -2722,11 +2716,7 @@ export class Task {
await this.postStateToWebview()
try {
let cacheWriteTokens = 0
let cacheReadTokens = 0
let inputTokens = 0
let outputTokens = 0
let totalCost: number | undefined
const taskMetrics = { cacheWriteTokens: 0, cacheReadTokens: 0, inputTokens: 0, outputTokens: 0, totalCost: 0 }
const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
if (this.diffViewProvider.isEditing) {
@@ -2742,6 +2732,20 @@ export class Task {
console.log("updating partial message", lastMessage)
// await this.saveClineMessagesAndUpdateHistory()
}
// update api_req_started to have cancelled and cost, so that we can display the cost of the partial stream
await updateApiReqMsg({
messageStateHandler: this.messageStateHandler,
lastApiReqIndex,
inputTokens: taskMetrics.inputTokens,
outputTokens: taskMetrics.outputTokens,
cacheWriteTokens: taskMetrics.cacheWriteTokens,
cacheReadTokens: taskMetrics.cacheReadTokens,
totalCost: taskMetrics.totalCost,
api: this.api,
cancelReason,
streamingFailedMessage,
})
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
// Let assistant know their response was interrupted for when task is resumed
await this.messageStateHandler.addToApiConversationHistory({
@@ -2758,35 +2762,29 @@ export class Task {
}]`,
},
],
modelInfo,
metrics: {
tokens: {
prompt: taskMetrics.inputTokens,
completion: taskMetrics.outputTokens,
cached: (taskMetrics.cacheWriteTokens ?? 0) + (taskMetrics.cacheReadTokens ?? 0),
},
cost: taskMetrics.totalCost,
},
})
// update api_req_started to have cancelled and cost, so that we can display the cost of the partial stream
await updateApiReqMsg({
messageStateHandler: this.messageStateHandler,
lastApiReqIndex,
inputTokens,
outputTokens,
cacheWriteTokens,
cacheReadTokens,
totalCost,
api: this.api,
cancelReason,
streamingFailedMessage,
})
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
telemetryService.captureConversationTurnEvent(
this.ulid,
providerId,
modelInfo.modelId,
"assistant",
currentMode,
modelInfo.mode,
{
tokensIn: inputTokens,
tokensOut: outputTokens,
cacheWriteTokens,
cacheReadTokens,
totalCost,
tokensIn: taskMetrics.inputTokens,
tokensOut: taskMetrics.outputTokens,
cacheWriteTokens: taskMetrics.cacheWriteTokens,
cacheReadTokens: taskMetrics.cacheReadTokens,
totalCost: taskMetrics.totalCost,
},
this.useNativeToolCalls, // For assistant turn only.
)
@@ -2826,11 +2824,11 @@ export class Task {
case "usage":
this.streamHandler.setRequestId(chunk.id)
didReceiveUsageChunk = true
inputTokens += chunk.inputTokens
outputTokens += chunk.outputTokens
cacheWriteTokens += chunk.cacheWriteTokens ?? 0
cacheReadTokens += chunk.cacheReadTokens ?? 0
totalCost = chunk.totalCost
taskMetrics.inputTokens += chunk.inputTokens
taskMetrics.outputTokens += chunk.outputTokens
taskMetrics.cacheWriteTokens += chunk.cacheWriteTokens ?? 0
taskMetrics.cacheReadTokens += chunk.cacheReadTokens ?? 0
taskMetrics.totalCost = chunk.totalCost ?? taskMetrics.totalCost
break
case "reasoning": {
// Process the reasoning delta through the handler
@@ -2996,11 +2994,11 @@ export class Task {
if (!didReceiveUsageChunk) {
this.api.getApiStreamUsage?.().then(async (apiStreamUsage) => {
if (apiStreamUsage) {
inputTokens += apiStreamUsage.inputTokens
outputTokens += apiStreamUsage.outputTokens
cacheWriteTokens += apiStreamUsage.cacheWriteTokens ?? 0
cacheReadTokens += apiStreamUsage.cacheReadTokens ?? 0
totalCost = apiStreamUsage.totalCost
taskMetrics.inputTokens += apiStreamUsage.inputTokens
taskMetrics.outputTokens += apiStreamUsage.outputTokens
taskMetrics.cacheWriteTokens += apiStreamUsage.cacheWriteTokens ?? 0
taskMetrics.cacheReadTokens += apiStreamUsage.cacheReadTokens ?? 0
taskMetrics.totalCost = apiStreamUsage.totalCost ?? taskMetrics.totalCost
}
})
}
@@ -3009,12 +3007,12 @@ export class Task {
await updateApiReqMsg({
messageStateHandler: this.messageStateHandler,
lastApiReqIndex,
inputTokens,
outputTokens,
cacheWriteTokens,
cacheReadTokens,
inputTokens: taskMetrics.inputTokens,
outputTokens: taskMetrics.outputTokens,
cacheWriteTokens: taskMetrics.cacheWriteTokens,
cacheReadTokens: taskMetrics.cacheReadTokens,
api: this.api,
totalCost,
totalCost: taskMetrics.totalCost,
})
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.postStateToWebview()
@@ -3024,39 +3022,21 @@ export class Task {
throw new Error("Cline instance aborted")
}
this.taskState.didCompleteReadingStream = true
// set any blocks to be complete to allow presentAssistantMessage to finish and set userMessageContentReady to true
// (could be a text block that had no subsequent tool uses, or a text block at the very end, or an invalid tool use, etc. whatever the case, presentAssistantMessage relies on these blocks either to be completed or the user to reject a block in order to proceed and eventually set userMessageContentReady to true)
const partialBlocks = this.taskState.assistantMessageContent.filter((block) => block.partial)
partialBlocks.forEach((block) => {
block.partial = false
})
// in case there are native tool calls pending
const partialToolBlocks = toolUseHandler.getPartialToolUsesAsContent()?.map((block) => ({ ...block, partial: false }))
this.processNativeToolCalls(assistantTextOnly, partialToolBlocks)
if (partialBlocks.length > 0) {
await this.presentAssistantMessage() // if there is content to update then it will complete and update this.userMessageContentReady to true, which we pwaitfor before making the next request. all this is really doing is presenting the last partial message that we just set to complete
}
// now add to apiconversationhistory
// need to save assistant responses to file before proceeding to tool use since user can exit at any moment and we wouldn't be able to save the assistant's response
let didEndLoop = false
if (assistantMessage.length > 0 || this.useNativeToolCalls) {
const currentMode = this.stateManager.getGlobalSettingsKey("mode")
// Stored the assistant API response immediately after the stream finishes in the same turn
const assistantHasContent = assistantMessage.length > 0 || this.useNativeToolCalls
if (assistantHasContent) {
telemetryService.captureConversationTurnEvent(
this.ulid,
providerId,
model.id,
"assistant",
currentMode,
modelInfo.mode,
{
tokensIn: inputTokens,
tokensOut: outputTokens,
cacheWriteTokens,
cacheReadTokens,
totalCost,
tokensIn: taskMetrics.inputTokens,
tokensOut: taskMetrics.outputTokens,
cacheWriteTokens: taskMetrics.cacheWriteTokens,
cacheReadTokens: taskMetrics.cacheReadTokens,
totalCost: taskMetrics.totalCost,
},
this.useNativeToolCalls,
)
@@ -3109,9 +3089,38 @@ export class Task {
content: assistantContent,
modelInfo,
id: requestId,
metrics: {
tokens: {
prompt: taskMetrics.inputTokens,
completion: taskMetrics.outputTokens,
cached: (taskMetrics.cacheWriteTokens ?? 0) + (taskMetrics.cacheReadTokens ?? 0),
},
cost: taskMetrics.totalCost,
},
})
}
}
this.taskState.didCompleteReadingStream = true
// set any blocks to be complete to allow presentAssistantMessage to finish and set userMessageContentReady to true
// (could be a text block that had no subsequent tool uses, or a text block at the very end, or an invalid tool use, etc. whatever the case, presentAssistantMessage relies on these blocks either to be completed or the user to reject a block in order to proceed and eventually set userMessageContentReady to true)
const partialBlocks = this.taskState.assistantMessageContent.filter((block) => block.partial)
partialBlocks.forEach((block) => {
block.partial = false
})
// in case there are native tool calls pending
const partialToolBlocks = toolUseHandler.getPartialToolUsesAsContent()?.map((block) => ({ ...block, partial: false }))
this.processNativeToolCalls(assistantTextOnly, partialToolBlocks)
if (partialBlocks.length > 0) {
await this.presentAssistantMessage() // if there is content to update then it will complete and update this.userMessageContentReady to true, which we pwaitfor before making the next request. all this is really doing is presenting the last partial message that we just set to complete
}
// now add to apiconversationhistory
// need to save assistant responses to file before proceeding to tool use since user can exit at any moment and we wouldn't be able to save the assistant's response
let didEndLoop = false
if (assistantHasContent) {
// NOTE: this comment is here for future reference - this was a workaround for userMessageContent not getting set to true. It was due to it not recursively calling for partial blocks when didRejectTool, so it would get stuck waiting for a partial block to complete before it could continue.
// in case the content blocks finished
// it may be the api stream finished after the last parsed content block was executed, so we are able to detect out of bounds and set userMessageContentReady to true (note you should not call presentAssistantMessage since if the last block is completed it will be presented again)
@@ -3169,6 +3178,14 @@ export class Task {
],
modelInfo,
id: this.streamHandler.requestId,
metrics: {
tokens: {
prompt: taskMetrics.inputTokens,
completion: taskMetrics.outputTokens,
cached: (taskMetrics.cacheWriteTokens ?? 0) + (taskMetrics.cacheReadTokens ?? 0),
},
cost: taskMetrics.totalCost,
},
})
let response: ClineAskResponse
+1 -1
View File
@@ -12,7 +12,7 @@ import { DictationSettings } from "./DictationSettings"
import { FocusChainSettings } from "./FocusChainSettings"
import { HistoryItem } from "./HistoryItem"
import { McpDisplayMode } from "./McpDisplayMode"
import { ClineMessageModelInfo } from "./messages/content"
import { ClineMessageModelInfo } from "./messages"
import { OnboardingModelGroup } from "./proto/cline/state"
import { Mode, OpenaiReasoningEffort } from "./storage/types"
import { TelemetrySetting } from "./TelemetrySetting"
+8 -7
View File
@@ -1,13 +1,9 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ClineMessageMetricsInfo, ClineMessageModelInfo } from "./metrics"
type ClinePromptInputContent = string
export type ClinePromptInputContent = string
type ClineMessageRole = "user" | "assistant"
export interface ClineMessageModelInfo {
modelId: string
providerId: string
}
export type ClineMessageRole = "user" | "assistant"
export interface ClineReasoningDetailParam {
type: "reasoning.text" | string
@@ -97,6 +93,11 @@ export interface ClineStorageMessage extends Anthropic.MessageParam {
* MUST be removed before sending message to any LLM provider.
*/
modelInfo?: ClineMessageModelInfo
/**
* LLM operational and performance metrics for this message
* Includes token counts, costs.
*/
metrics?: ClineMessageMetricsInfo
}
/**
+20
View File
@@ -0,0 +1,20 @@
// Core content types
export type {
ClineAssistantContent,
ClineAssistantRedactedThinkingBlock,
ClineAssistantThinkingBlock,
ClineAssistantToolUseBlock,
ClineContent,
ClineDocumentContentBlock,
ClineImageContentBlock,
ClineMessageRole,
ClinePromptInputContent,
ClineReasoningDetailParam,
ClineStorageMessage,
ClineTextContentBlock,
ClineToolResponseContent,
ClineUserContent,
ClineUserToolResultContentBlock,
} from "./content"
export { cleanContentBlock, convertClineStorageToAnthropicMessage, REASONING_DETAILS_PROVIDERS } from "./content"
export type { ClineMessageMetricsInfo, ClineMessageModelInfo } from "./metrics"
+18
View File
@@ -0,0 +1,18 @@
import { Mode } from "../storage/types"
export interface ClineMessageModelInfo {
modelId: string
providerId: string
mode: Mode
}
interface ClineTokensInfo {
prompt: number // Total input tokens (includes cached + non-cached)
completion: number // Total output tokens
cached: number // Subset of prompt_tokens that were cache hits
}
export interface ClineMessageMetricsInfo {
tokens?: ClineTokensInfo
cost?: number // Monetary cost for this turn
}