#18445 · @LucasSantana-Dev · opened Mar 20, 2026 at 9:41 PM UTC · last updated Mar 21, 2026 at 8:38 PM UTC
fix(cost): account for OpenRouter cache write tokens
Score breakdown
Impact
Clarity
Urgency
Ease Of Review
Guidelines
Readiness
Size
Trust
Traction
Summary
This PR fixes a critical cost underestimation bug for OpenRouter users by correctly accounting for cache write tokens. It ensures the in-app cost tracker accurately reflects actual billing.
Description
Issue for this PR
Closes #18440
Type of change
- [x] Bug fix
- [ ] New feature
- [ ] Refactor / code improvement
- [ ] Documentation
What does this PR do?
This fixes OpenRouter cost underestimation when cache write tokens are present. OpenAI-compatible responses can report prompt_tokens_details.cache_write_tokens, but we were not carrying that through for usage accounting.
Changes in this PR:
- parse
cache_write_tokensin OpenAI-compatible provider paths (stream + non-stream) - persist that value into provider metadata (
openrouter.usage.cacheWriteInputTokens) - include that metadata fallback in
Session.getUsageso cache write tokens are counted in token/cost totals - add regression coverage for the OpenRouter metadata path in
Session.getUsagetests
How did you verify your code works?
cd packages/opencode && bun test test/session/compaction.test.tscd packages/opencode && bun run typecheck
Screenshots / recordings
Not a UI change.
Checklist
- [x] I have tested my changes locally
- [x] I have not included unrelated changes in this PR
Linked Issues
#18440 Cache write tokens not accounted for when using OpenRouter, causing cost underestimation
View issueComments
PR comments
rekram1-node
I'm having a hard time trusting these PRs because if u look at the file paths u edited, it specifically says it is specifically and ONLY for copilot, so what does that have to do with openrouter?
That codepath should basically never be hit unless u have a custom provider configured to use the github copilot sdk which I kinda doubt?
rekram1-node
It even has a readme saying as much: https://github.com/anomalyco/opencode/tree/dev/packages/opencode/src/provider/sdk/copilot#readme
LucasSantana-Dev
It even has a readme saying as much:
https://github.com/anomalyco/opencode/tree/dev/packages/opencode/src/provider/sdk/copilot#readme
I'll have a second look on that and figure out a more structured and fitting solution for the idea i had!
Changed Files
packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts
+16−0packages/opencode/src/session/index.ts
+2−0packages/opencode/test/session/compaction.test.ts
+24−0