MCPcopy Index your code
hub / github.com/CodebuffAI/codebuff / overwriteCostWithBilledCredits

Function overwriteCostWithBilledCredits

web/src/llm-api/openrouter.ts:1085–1108  ·  view source on GitHub ↗

* Overwrite the cost field in the final SSE chunk to reflect actual billed credits. * This ensures the SDK calculates the exact credits value we stored in the database, * making the server the single source of truth for credit tracking.

(line: string, billedCredits: number)

Source from the content-addressed store, hash-verified

1083 * making the server the single source of truth for credit tracking.
1084 */
1085function overwriteCostWithBilledCredits(line: string, billedCredits: number): string {
1086 if (!line.startsWith('data: ')) {
1087 return line
1088 }
1089
1090 const raw = line.slice('data: '.length)
1091 if (raw === '[DONE]\n' || raw === '[DONE]') {
1092 return line
1093 }
1094
1095 try {
1096 const obj = JSON.parse(raw)
1097 // Only modify if there's usage data (final chunk)
1098 if (obj.usage) {
1099 obj.usage.cost = creditsToFakeCost(billedCredits)
1100 obj.usage.cost_details = { upstream_inference_cost: 0 }
1101 return `data: ${JSON.stringify(obj)}\n`
1102 }
1103 } catch {
1104 // If parsing fails, return original line
1105 }
1106
1107 return line
1108}

Callers 1

startFunction · 0.85

Calls 2

parseMethod · 0.80
creditsToFakeCostFunction · 0.70

Tested by

no test coverage detected