fix(opencode): repair thinking blocks rejected by Anthropic API
Problem
Anthropic signs each thinking block against its original position. Two things break signatures and trigger thinking blocks cannot be modified 400s:
-
Interleaved thinking flattened by the AI SDK — opencode's Vercel AI SDK regroups all thinking blocks to the front of the assistant turn instead of leaving them interleaved with the tool_use blocks they authorized. The displaced blocks no longer match their signed positions.
-
Stale signatures on historical assistant turns replayed in a new request context (after context compaction or provider failover).
-
Final block constraint — Anthropic also rejects an assistant message whose final block is a
thinkingblock.
Strategy
- Keep a single signed thinking block only when it is the lone block in the latest assistant turn (the normal, still-valid current-turn case).
- Downgrade all others to
<thinking>text — preserves reasoning content without invalid signatures. - Drop
redacted_thinkingblocks (no readable text to preserve). - Guard against a trailing
thinkingblock being the final block in the message. - Sanitize lone UTF-16 surrogates in downgraded text to avoid invalid-UTF8 400s.
Cache impact
None on the static prefix. The transform runs before cache_control anchors are applied, so anchors land on the already-normalized structure. Historical turns render deterministically once they become non-last. The only cost is the unavoidable one-time tail transition when the current turn becomes historical.
Tests
6 new test cases covering: flattened interleaving, single-block preservation, historical downgrades, redacted_thinking drops, lone-surrogate sanitization, and trailing-thinking-block downgrade.
Need help on this PR? Tag @codesmith with what you need. Autofix is disabled.
Summary by cubic
Repairs Anthropic 400s by normalizing thinking blocks in opencode requests. Prevents errors from flattened interleaving, stale signatures on historical turns, and final thinking blocks.
- Bug Fixes
- Keep a single signed
thinkingblock only in the latest assistant turn; downgrade all others to<thinking>text. - Drop
redacted_thinkingblocks unless it’s the single block in the latest assistant turn; never allow it as the final block. - Prevent
thinkingas the final block in an assistant message. - Sanitize lone UTF-16 surrogates in downgraded text.
- Keep a single signed