GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(provider): skip empty-text filtering for assistant messages in normalizeMessages (#16748) by altendky · Pull Request #16750 · anomalyco/opencode

Conversation

@altendky

@altendky altendky commented Mar 9, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Issue for this PR

Closes #16748
Related: #13286, #16246, #15074, #10970, #14716, #6176, #9364, #8010

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Fixes Anthropic API rejections (thinking blocks in the latest assistant message cannot be modified) caused by empty text parts being stripped from assistant messages, shifting thinking block positions and invalidating cryptographic signatures.

Root cause

Two independent filters remove empty text parts from assistant messages:

  1. opencode's normalizeMessages() in transform.ts — unconditionally filters text === "" from all message roles, including assistant
  2. AI SDK's convertToLanguageModelPrompt — strips empty text parts from assistant messages unless providerOptions != null (identical behavior in both v5 and v6)

When Anthropic models use adaptive thinking (Opus 4.6, Sonnet 4.6), the model commonly emits a whitespace-only text part between reasoning blocks. After processor.ts:321 calls trimEnd(), this becomes "". Removing it changes the block arrangement (e.g., [thinking, text, thinking, text, tool_use] → [thinking, thinking, text, tool_use]), invalidating the positionally-sensitive thinking block signatures.

Changes

  • transform.ts: Skip empty-text filtering for assistant messages that contain reasoning blocks (signatures are positionally sensitive). Still strips trailing empty text to prevent cache_control on empty text blocks from applyCaching.
  • message-v2.ts (providerMetadata): Set providerMetadata: {} on empty text parts lacking metadata, so the AI SDK's internal filter preserves them. This uses the SDK's own escape hatch (providerOptions != null → keep the part).
  • message-v2.ts (aborted message check): Empty text parts no longer count as "real content" when deciding whether to keep an aborted assistant message. Previously, an aborted message with [step-start, reasoning, text("")] was kept, preserved by normalizeMessages (reasoning present), then rejected by Anthropic when applyCaching set cache_control on the empty text.

Relationship to other open PRs

AI SDK v5→v6 migration (#13527, #15997, #12342, #13228): The AI SDK's empty-text filter in convertToLanguageModelPrompt is identical in v5 and v6 — this bug exists on both versions and the v6 migration does not address it. Those PRs only change transform.ts/message-v2.ts for type compatibility (async toModelMessages, as typeof msg.content casts, toModelOutput wrapper change) and Opus 4.6 variant definitions.

Thinking block / signature PRs:

  • fix: preserve thinking block signatures and fix compaction headroom asymmetry #14393 (preserve thinking block signatures) — Closest overlap. Removes the differentModel guard so providerMetadata always passes through. If that PR lands first, the providerMetadata: {} workaround in message-v2.ts here becomes unnecessary, but the transform.ts fix is still needed since normalizeMessages() independently strips the empty text part.
  • fix(provider): preserve redacted_thinking blocks and fix signature validation #12131 (preserve redacted_thinking blocks) — Removes trimEnd() on thinking text in processor.ts and reorders reasoning blocks. Addresses related signature issues but does not fix normalizeMessages() stripping empty text parts between reasoning blocks.
  • fix: expand Anthropic detection and strip whitespace-only text blocks #12634 (expand Anthropic detection and strip whitespace-only text) — Would make this bug worse: changes the filter from text !== "" to text.trim() !== "", stripping even more content from assistant messages without distinguishing by role.
  • fix: filter empty content blocks for Bedrock provider #14586 (filter empty content blocks for Bedrock) — Extends the same empty-content filter to Bedrock. Orthogonal provider — doesn't address the assistant-message signature issue.
  • fix: strip reasoning parts when switching to non-interleaved models #11572 (strip reasoning parts for non-interleaved models) — Cross-model switching fix. Unrelated to empty-text filtering.
  • fix: strip incompatible thinking blocks when switching to Claude #8958 (strip incompatible thinking blocks when switching to Claude) — Cross-model switching fix. Unrelated to empty-text filtering.

None of these PRs is a superset of this one. The transform.ts fix here is not covered by any other open PR.

How did you verify your code works?

  • All 106 transform tests pass, 0 failures
  • All message-v2 tests pass
  • New tests reproduce the exact scenarios:
    • Reasoning with signatures around an empty text part — verifies all 5 parts preserved
    • Trailing empty text stripped to prevent cache_control errors
    • Interstitial empty text preserved but trailing stripped in same message
    • Aborted messages with only reasoning + empty text excluded from history

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

jwcrystal reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
@altendky
test: reproduce empty text filtering breaking thinking block signatur…
6695085
…es (anomalyco#16748)

Add failing test demonstrating that normalizeMessages() removes empty text
parts between reasoning blocks in assistant messages, invalidating Anthropic
thinking block signatures. The test constructs [reasoning(sig1), text(''),
reasoning(sig2), text('...'), tool-call] and asserts all 5 parts are preserved.
Currently fails with Expected length: 5, Received length: 4.
@github-actions github-actions Bot added needs:compliance This means the issue will auto-close after 2 hours. needs:issue labels Mar 9, 2026
@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Based on my search results, I found related PRs addressing thinking block and empty content filtering issues, but these appear to be related fixes rather than duplicates of the current test reproduction PR (#16750):

Related PRs:

  • fix(provider): preserve redacted_thinking blocks and fix signature validation #12131 - fix(provider): preserve redacted_thinking blocks and fix signature validation - Addresses thinking block signature validation
  • fix: expand Anthropic detection and strip whitespace-only text blocks #12634 - fix: expand Anthropic detection and strip whitespace-only text blocks - Related to whitespace/empty content handling
  • fix: filter empty content blocks for Bedrock provider #14586 - fix: filter empty content blocks for Bedrock provider - Empty content filtering for another provider
  • fix: strip reasoning parts when switching to non-interleaved models #11572 - fix: strip reasoning parts when switching to non-interleaved models - Related to reasoning/thinking block handling
  • fix: strip incompatible thinking blocks when switching to Claude #8958 - fix: strip incompatible thinking blocks when switching to Claude - Thinking block compatibility

The current PR #16750 is a test reproduction case that demonstrates the issue described in #16748, whereas the related PRs are attempted fixes or related provider handling. No exact duplicate reproduction test was found.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
altendky marked this pull request as draft March 9, 2026 13:02
@altendky
fix(provider): skip empty-text filtering for assistant messages in no…
bae2f84
…rmalizeMessages

Assistant messages must be replayed verbatim because Anthropic thinking block
signatures encode positional context. Removing an empty text part between two
reasoning blocks changes the block arrangement and invalidates the cryptographic
signatures, causing the API to reject with 'thinking blocks cannot be modified'.

The empty-text filter is still applied to user and tool messages where Anthropic
rejects empty content.

Update existing tests to reflect that assistant content is now preserved, and
add tests for non-assistant filtering.
@altendky altendky changed the title test: reproduce empty text filtering breaking thinking block signatures (#16748) fix(provider): skip empty-text filtering for assistant messages in normalizeMessages (#16748) Mar 9, 2026
@github-actions github-actions Bot removed needs:issue needs:compliance This means the issue will auto-close after 2 hours. labels Mar 9, 2026
@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for updating your PR! It now meets our contributing guidelines. 👍

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
altendky marked this pull request as ready for review March 9, 2026 13:12
altendky added 3 commits March 9, 2026 09:16
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
2ea031a
@altendky
fix: filter empty text from assistant messages without reasoning blocks
4b4f2ce
The previous fix preserved all assistant messages verbatim in normalizeMessages
to protect thinking block signatures. This was too broad — assistant messages
without reasoning blocks (e.g. compaction summaries) also had empty text parts
preserved, causing Anthropic to reject with 'text content blocks must be non-empty'.

Now only assistant messages with reasoning blocks are preserved verbatim.
Assistant messages without reasoning have empty text blocks filtered normally.

Also clean up empty text parts at the source: in the processor text-end handler,
remove parts that end up empty (no text, no metadata) instead of persisting them.
Parts with metadata (thinking signatures) are still preserved.
@altendky
revert: drop removePart for empty text in processor to avoid create-d…
e750dad
…elete race

The text-start handler persists an empty part to the DB, then text-end
would conditionally delete it. If the process crashes between the two,
a dangling empty part remains. The transform.ts and message-v2.ts
replay-time defenses already handle empty text parts correctly, making
the processor-level cleanup redundant.
@altendky

altendky commented Mar 9, 2026

Copy link
Copy Markdown
Contributor Author

History of the Modified Code

Timeline

Date Commit What happened
2025-11-28 13f89fdb8 (PR #4811) First empty-message filter added in message-v2.ts. A community contributor (DS / @Tarquinen) added .filter((msg) => msg.parts.length > 0) before convertToModelMessages() to prevent crashing when empty messages hit the AI SDK. Only filtered at the UIMessage level — no part-level filtering.
2026-01-05 c285304a (no PR, direct commit) Anthropic empty-content filter added in transform.ts by Aiden Cline. Anthropic's API rejects messages with empty content, so this filters out empty text and reasoning parts from array content, and removes messages that become empty. Applied to all roles (user, assistant, tool) indiscriminately. Tests all used role: "assistant" messages.
2026-01-20 021e42c0b (no PR, direct commit) differentModel guard added in message-v2.ts by Aiden Cline. When switching between providers, stale providerMetadata (e.g. Anthropic signatures sent to OpenAI) caused 400 errors. Fix: only include providerMetadata when the model matches. This introduced the conditional ...(differentModel ? {} : { providerMetadata: part.metadata }).
2026-02-13 0d90a22f9 (PR #13439) Opus 4.6 adaptive thinking enabled on vertex/bedrock/anthropic. This is when Opus 4.6 started producing interleaved reasoning blocks with cryptographic signatures, creating the conditions for the bug.

How the bug emerged

The empty-content filter from Jan 5 (c285304a) was written before Opus 4.6 adaptive thinking existed (Feb 13). At the time, reasoning parts with empty text were genuinely useless — there were no cryptographic signatures to preserve. The filter treated all roles identically.

Once Opus 4.6 arrived, it began producing patterns like:

reasoning(sig1) → text("") → reasoning(sig2) → text("answer")

The empty text("") is structurally significant — the signatures encode positional context. There are two independent stripping points:

  1. transform.ts: The normalizeMessages filter removes text("") from assistant messages, shifting the reasoning block positions and invalidating signatures.

  2. message-v2.ts: Even if transform.ts is fixed, the AI SDK's internal convertToLanguageModelPrompt strips text parts where text === "" && providerOptions == null. The differentModel guard from Jan 20 was correct for its purpose (don't send foreign metadata), but when part.metadata is undefined for an empty text part from the same model, the resulting providerMetadata: undefined causes the AI SDK to strip the part.

PRs in flight

  • PR fix(provider): skip empty-text filtering for assistant messages in normalizeMessages (#16748) #16750 (this branch's upstream PR, opened 2026-03-09): The fix under review. Skips empty-text filtering for assistant messages with reasoning blocks in transform.ts, and adds the providerMetadata: {} fallback in message-v2.ts.

  • PR fix: preserve thinking block signatures and fix compaction headroom asymmetry #14393 (opened 2026-02-20, still open): An earlier, broader attempt at fixing the signature stripping problem that proposed removing the differentModel guard entirely (always pass metadata through). That PR also bundled a compaction headroom fix. It was never merged — presumably because always passing foreign provider metadata was considered too risky. The current branch's approach is more surgical: keep the guard but patch the specific empty-text-with-no-metadata case.

Summary

The code being modified was never designed for the Opus 4.6 world. The empty-content filter (c285304a, Jan 5) predates adaptive thinking by 5+ weeks and assumed empty parts are always safe to strip. The differentModel metadata guard (021e42c0b, Jan 20) was solving a real cross-provider problem but created a gap where same-model empty text parts lose their metadata lifeline. Both pieces of code were correct when written — the bug is an emergent interaction with Opus 4.6's signature-sensitive thinking blocks.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
altendky marked this pull request as draft March 10, 2026 20:11
@altendky
fix: prevent cache_control on empty text blocks from aborted messages
83362bd
Aborted assistant messages with [step-start, reasoning, text('')] were
included in the conversation replay because the empty text part passed
the 'has real content' check. The empty text survived normalizeMessages
(reasoning blocks present) and received cache_control via applyCaching,
causing Anthropic to reject with 'cache_control cannot be set for empty
text blocks'.

Two fixes:
- Exclude empty text from the aborted-message content check so messages
  with only reasoning + empty text are skipped entirely
- Strip trailing empty text from assistant messages with reasoning in
  normalizeMessages (interstitial empty text between reasoning blocks is
  preserved for signature integrity)

Reproduces: ses_3272b8b1dffe8ACUMp7xjxhFEw
@altendky
altendky marked this pull request as ready for review March 10, 2026 23:52
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
c7bc348
@github-actions github-actions Bot mentioned this pull request Mar 11, 2026
fix(provider): resolve bedrock compaction failures for Claude models #17043
Closed
altendky added 2 commits March 11, 2026 12:46
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
2631e6c
@altendky
fix: skip empty text parts in applyCaching to prevent cache_control r…
a95c4ea
…ejection

Defense-in-depth: when applyCaching selects the last content part to
decorate with cache_control, it now walks backwards past empty text
parts (text === ""). This prevents Anthropic from rejecting requests
with 'cache_control cannot be set for empty text blocks', regardless
of how the empty text ended up in the message array.

If every content part is empty text, cache_control falls through to
message-level options instead.
@shadow-hg

shadow-hg commented Mar 12, 2026

Copy link
Copy Markdown

谢谢你的修复,这个问题困扰了我很久。

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
2a020c1
This was referenced Mar 13, 2026
fix: filter empty content blocks for Bedrock provider #17381
Closed
fix(provider): handle empty content for bedrock/openai-compatible APIs #17394
Closed
fix(provider): handle empty content for bedrock/openai-compatible APIs #17396
Closed
fix(provider): drop empty content messages after interleaved reasoning filter #17712
Closed
fix(opencode): filter empty text content blocks for all providers #17742
Closed
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
a0c42ce
This was referenced Apr 20, 2026
fix: preserve thinking/redacted_thinking blocks in Anthropic message transforms #23574
Closed
fix: preserve thinking/redacted_thinking blocks in Anthropic message transforms #23755
Closed
rekram1-node and others added 12 commits April 22, 2026 00:35
@rekram1-node
feat: update codex plugin to support 5.5 (anomalyco#23789)
97f3c74
@Hona
chore: bump Bun to 1.3.13 (anomalyco#23791)
69e2f3b
@Brendonovich
fix(app): improve icon override handling in project edit dialog (anom…
a45d9a9
…alyco#23768)
@opencode-agent
chore: update nix node_modules hashes
ed3d364
@Hona
fix: preserve BOM in text tool round-trips (anomalyco#23797)
bb69648
@opencode-agent
chore: generate
bfb954e
@Hona
test: fix cross-spawn stderr race on Windows CI (anomalyco#23808)
0595c28
@opencode-agent
chore: generate
6aa475f
@Brendonovich
fix: consolidate project avatar source logic (anomalyco#23819)
88c5f6b
@nexxeln
fix(tui): fail fast on invalid session startup (anomalyco#23837)
2a480a9
@opencode-agent
chore: generate
266e965
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
b60f27b
@rekram1-node
rekram1-node force-pushed the dev branch from 1026791 to ac26394 Compare April 23, 2026 04:27
@PershingSquare PershingSquare mentioned this pull request Apr 23, 2026
Bedrock Claude Opus 4.7 replays thinking blocks through interleaved OpenAI-compatible transform #23926
Closed
@bainos bainos mentioned this pull request Apr 23, 2026
fix(opencode): preserve reasoning providerMetadata across model switches #23104
Closed
3 tasks done
altendky added 6 commits April 23, 2026 12:58
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
d943e72
# Conflicts:
#	packages/app/src/context/layout.tsx
#	packages/app/src/pages/layout/sidebar-items.tsx
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
b718398
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
01ddb73
# Conflicts:
#	packages/opencode/src/provider/transform.ts
#	packages/opencode/test/session/message-v2.test.ts
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
0f9547a
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
731e856
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
ef77a24
@github-actions github-actions Bot mentioned this pull request May 1, 2026
provider: Bedrock non-Anthropic message cleanup and xhigh→max #25189
Closed
altendky added 2 commits May 1, 2026 11:20
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
9aecdd4
# Conflicts:
#	packages/opencode/src/plugin/codex.ts
@altendky
Merge branch 'dev' into test/thinking-signature-empty-text
3255f80
@wzli wzli mentioned this pull request May 12, 2026
Whitespace content causes API validation errors in provider transformations #8903
Closed
@rekram1-node

rekram1-node commented May 15, 2026

Copy link
Copy Markdown
Member

Automated PR Cleanup

Thank you for contributing to opencode.

Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions.

This PR was closed because it matched the following cleanup criteria:

  • The PR was created more than 1 month ago
  • The PR had fewer than 2 positive reactions
  • Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR

PRs created within the last month are not affected by this cleanup.

If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate.

Thanks again for taking the time to contribute.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@rekram1-node rekram1-node closed this May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

normalizeMessages() removes empty text parts between reasoning blocks, invalidating Anthropic thinking block signatures

Uh oh!

There was an error while loading. Please reload this page.

7 participants

@altendky @shadow-hg @chan1103 @rekram1-node @Hona @Brendonovich @nexxeln
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.