fix(sdk): use max instead of sum for OpenRouter cost fields - #1198
Conversation
usage.cost already includes upstream_inference_cost on non-BYOK routes, so summing them double-counts the upstream component. Use Math.max to pick the correct value for both BYOK (cost=0, upstream>0) and normal (cost>upstream) routes. Fixes CodebuffAI#1164
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Good catch and a clean, minimal fix. The reasoning matches how OpenRouter's A few things a maintainer will want to check before porting:
The PR is marked "unstable" mergeability — worth checking whether that's just CI flake or a real conflict before it lands. |
All three cost-calculation paths in the SDK (promptAiSdkStream, promptAiSdk, promptAiSdkStructured) sum usage.cost and cost_details.upstream_inference_cost to derive the dollar amount charged as credits. Per OpenRouter's accounting, usage.cost is the total charge and upstream_inference_cost is the upstream component already included in that total -- so summing them roughly doubles the true spend on non-BYOK routes.
Changed the aggregation from cost + upstream to Math.max(cost, upstream), which returns the correct value in both shapes:
Normal route: cost is the authoritative total (includes upstream + margin); upstream < cost; max picks cost.
BYOK route: cost is 0; upstream carries the real spend; max picks upstream.
This matches the server-side extractUsageAndCost semantics documented in common/src/constants/freebuff-models.ts.
Existing usage-receipts.test.ts passes (strengthened the assertion from > 0 to exact expected credits). TypeScript compiles clean.
Fixes #1164