Skip to content

fix(anthropic): Fable 5.1 sessions lose reasoning after model switches and runtime events - #136782

Merged
steipete merged 2 commits into
mainfrom
steipete/openclaw-model-switching-5cce5f
Sep 3, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/openclaw-model-switching-5cce5f

Conversation

@steipete

@steipete steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where sessions on Claude Fable 5.1 would lose all prior reasoning after a mid-session model switch, and where organizations enforcing Anthropic's preserved-thinking prefix check (accounts created on or after 2026-08-31) would hit a hidden 400 Invalid signature in thinking block on the turn after any runtime event, followed by a duplicate request and a transcript-wide thinking wipe. Affected surfaces: every embedded-runtime chat on Anthropic-family routes (Control UI web chat, channels, cron/heartbeat turns), the /model and /think commands.

Why This Change Was Made

Fable 5.1 binds each thinking block to the model that produced it and to the exact request prefix that preceded it. Three harness behaviors conflicted with that contract, all verified live against api.anthropic.com with the thinking-binding-controls-2026-08-01 controls:

  1. Moving a session onto Fable 5.1 (from Opus 5, Sonnet 5, Opus 4.8, Fable 5) dropped the earlier reasoning client-side although Fable 5.1 reads those blocks. The replay contract in anthropic-model-contract.ts now preserves them; leaving Fable 5.1 still drops, matching the one-way binding.
  2. The per-turn runtime-context carrier (inbound channel metadata plus system events such as "Model switched to …") was injected as a transient user message after the active turn, stripped on the next request, and relocated to the tail inside tool loops. Under the prefix check that is a history edit and invalidates every later block. On Anthropic-family routes the carrier is now persisted right after its user turn and never stripped or relocated, including by the context-engine assembly that rebuilds each turn's window (Anthropic's documented no-beta pattern: leave earlier copies in place). Consecutive user turns (a /model or /think command turn followed by the prompt) are also no longer merged on replay for the Messages API, because the merged form lost the second turn's timestamp stamp and so differed from the bytes the active turn was signed over; Bedrock Converse keeps the merge for its strict alternation. Other providers keep the transient carrier.
  3. Direct API-key requests with adaptive thinking now send thinking.block_binding.prefix_mismatch_behavior: "drop_block" under the binding beta, so a residual prefix mismatch degrades to a server-side, unbilled drop with an operator-visible warning listing the dropped paths, instead of the 400 + retry + wipe path. OAuth, proxies, Bedrock, Vertex, and Foundry are unchanged; the existing strip-and-retry recovery remains the last resort there.

Non-goals: clear_at mid-conversation system messages (the carrier holds untrusted channel and tool content that must not gain system-role authority), the /model and /think system-prompt changes (still invalidate pre-switch blocks by design), and the cache-TTL pruning projection reverting on the next request (separate cache bug, filed as follow-up).

Production LOC: +351/-137 (net +214) | Tests: +1028/-150 | Docs: +51/-8. The production growth is the new replay contract (append-only carrier policy and its persistence lifecycle in the session prompt owner), the gated binding controls with telemetry in both Anthropic transports, and the Fable-target replay rule; the transient path, cache opt-out plumbing, and the load-time user-turn merge were removed or narrowed rather than duplicated.

User Impact

Switching a session onto Fable 5.1 keeps the reasoning it already has instead of re-planning cold. Fable 5.1 sessions on enforcing organizations no longer pay a duplicate request and lose all prior reasoning after model-switch notices, subagent/exec completions, or channel turns. Operators see a warning when Anthropic drops replayed thinking, with the reason and message paths.

Evidence

All live evidence is against api.anthropic.com with an API key, model claude-fable-5-1, through an isolated dev gateway (own state dir, port, and token) driving Control UI web-chat turns over chat.send.

Live matrix (direct API, thinking-binding-controls-2026-08-01, enforcement set explicitly)

Move Result
Fable 5.1 -> Opus 5 / Sonnet 5 / Fable 5, blocks passed through 200, every Fable block dropped as model_binding_mismatch, unbilled
Opus 5 / Sonnet 5 / Opus 4.8 -> Fable 5.1 200, input_transformations: [], reasoning kept
Opus 5 -> Sonnet 5 dropped (model_binding_mismatch)
Opus 4.8 <-> Sonnet 4.6 (regular blocks) replay fine across models
Edited system prompt / removed earlier carrier 400 Invalid signature in thinking block ... bound to a different conversation
Three consecutive user messages merged into one multi-block message next request not an edit ([])

Before (unpatched harness, enforcement error): /think low -> 400 -> existing recovery retried once without thinking and rewrote the transcript (repaired=4); a Fable block created with the runtime-context carrier present was rejected on the next turn once the carrier was stripped (Content that preceded this block when it was created is missing); with drop_block, the first request after every turn boundary reported prefix_binding_mismatch drops.

After (this branch, gateway through a recording proxy that injects the binding controls, /think max, Fable 5.1 -> Opus 5 -> Fable 5.1 with tool calls and carriers): nine requests, all 200, input_transformations: [] on every one, retained thinking blocks growing 1 -> 2 -> 3 -> 4 across turns, tool loops, both model switches, and the carriers persisted right after their user turns. The append-only prefix check (system, tools, message prefix byte-identical between consecutive requests) passes except where cache_control moves, which Anthropic ignores. Chat history (chat.history) shows no carrier text. Post-fix Opus 5 -> Fable 5.1 switch replayed the Opus thinking block and Fable answered from it (earlier I concluded ... Wednesday).

Direct-API phase: gateway against api.anthropic.com with no proxy, /think max, a Fable turn with a thinking block, then /think high (a system-prompt edit), then two more Fable turns. Every request returned 200, no [session-recovery] retry fired, and the gateway logged [anthropic] replayed thinking dropped: 1 block(s) (prefix_binding_mismatch at messages.2.content.0) on both following requests, which proves the controls were sent (Anthropic only reports input_transformations under the header) and that the invalidated block degraded to a server-side drop instead of the 400 + retry + wipe path.

Tests: regression tests fail on pre-change code for the model-bound replay rule, the context-engine assembly strip, the consecutive-user merge, and the runner persistence; lead reruns green: transport-message-transform 41, sanitize-session-history 81, validate-turns 34, context-engine-lifecycle 25, replay-sanitization 14, plus the worker's prompt-submit/session-boundary/transcript-policy/binding-parity/transport suites (431). node scripts/check-changed.mjs passed (exit 0) on the final diff: format, core and test typecheck shards, lint, dead-export scans, SDK surface, and repository guards. Codex autoreview: scoped-clean, no P0 findings (Codex, two passes: after the worker's implementation and on the final diff).

Follow-ups (not in this PR): cache-TTL pruning projection reverts on the next request (pruneExpiredCacheTtlToolResults), which busts the prompt cache and is a prefix edit; /model and /think still change the system prompt (documented); installModelPromptTransform (skill expansion) still rewrites the active prompt for the model only.

…nd runtime context

Claude Fable 5.1 binds each thinking block to the producing model and to the
exact request prefix that preceded it. Three harness behaviors conflicted with
that contract on Anthropic-family routes:

- Moving a session onto Fable 5.1 (from Opus 5, Sonnet 5, Opus 4.8, Fable 5)
  dropped readable reasoning client-side; the replay contract now preserves it
  while leaving Fable 5.1 still drops.
- The per-turn runtime-context carrier was injected transiently after the
  active user turn, stripped on the next request, relocated inside tool loops,
  and removed by the context-engine assembly. It is now persisted right after
  its user turn and replayed in place; inline inbound metadata stays in place
  too, and consecutive user turns are no longer merged at load for the
  Messages API because the merged form lost the second turn's timestamp stamp.
- Direct API-key requests with adaptive thinking send the
  thinking-binding-controls beta with prefix_mismatch_behavior=drop_block, so
  a residual mismatch degrades to a server-side unbilled drop with a warning
  listing the dropped paths instead of a 400, a duplicate request, and a
  transcript-wide thinking wipe. OAuth, proxies, Bedrock, Vertex, and Foundry
  keep the existing strip-and-retry recovery.

Live-verified against api.anthropic.com: nine-request Fable/Opus/Fable session
with tool loops and carriers reports input_transformations: [] on every
request with four retained thinking blocks; a /think change on the direct API
yields a logged server-side drop and no retry.
@clawsweeper

clawsweeper Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review September 3, 2026 00:59
@openclaw-barnacle openclaw-barnacle Bot added size: XL maintainer Maintainer-authored PR labels Sep 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 2, 2026, 9:23 PM ET / September 3, 2026, 01:23 UTC.

ClawSweeper review

What this changes

This PR retains hidden runtime context in Anthropic-family session history so thinking remains valid across model switches, tool loops, and session reopen.

Merge readiness

⛔ Blocked before merge - 7 items remain

Keep open. The patch repairs the session and provider boundaries that altered signed-thinking prefixes, but its durable hidden-context retention needs explicit maintainer acceptance before merge.

Priority: P1
Reviewed head: 8e731a0706d2059984a1f7ab0cf945eb5d261bf0
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner-boundary coverage and reported live-provider evidence support the fix, while the intentional retention contract remains for maintainer confirmation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.
Evidence reviewed 7 items Session-owner repair: Prompt submission queues a carrier only for append-only replay and cleans it up on preflight exit; the session reuses a recorded user/carrier pair during retries.
Replay boundary: The LLM boundary retains carriers only under append-only policy, and Anthropic turn validation preserves consecutive direct-Messages user turns under that policy.
Regression coverage: Added coverage verifies hidden carrier persistence, reopen ordering, provider-prefix stability, and reset cleanup; the merge-base implementation instead relocated the carrier to the request tail.
Findings None None.
Security None None.

How this fits together

The embedded agent runner turns persisted session history into model requests. This change preserves per-turn hidden context for Anthropic-family replay while provider adapters submit the resulting request.

flowchart LR
  A[User turn] --> B[Session history]
  B --> C[Hidden runtime context]
  C --> D[Transcript policy]
  D --> E[Anthropic request]
  E --> F[Thinking replay]
Loading

Decision needed

Question Recommendation
Should Anthropic-family sessions durably retain hidden runtime-context carriers to preserve prefix-bound thinking across replay and reopen? Accept durable carriers: Keep the documented retention model after confirming it matches session privacy and export expectations.

Why: This intentionally changes persisted session-transcript retention, affecting operator-visible retention and downgrade expectations rather than only request assembly.

Before merge

  • Resolve merge risk (P1) - Hidden runtime and inbound context now persists in Anthropic-family transcripts, so its retention, export, and downgrade behavior needs maintainer acceptance.
  • Resolve merge risk (P1) - The bug fix adds 214 net production lines; the growth is justified only if preserving retry/reopen ordering and provider-path parity cannot be safely absorbed by an existing owner.
  • Resolve merge risk (P1) - The API-specific beta and payload semantics could not be independently source-checked in this environment; the supplied redacted direct-provider trace is the available contract evidence.
  • Complete next step (P2) - Confirm that durable hidden runtime-context retention is acceptable for Anthropic-family transcript and export behavior before merge.
  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +214, Tests +878, Docs +43. Total +1135 across 52 files.

View PR surface stats
Area Files Added Removed Net
Source 25 351 137 +214
Tests 23 1028 150 +878
Docs 4 51 8 +43
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 52 1430 295 +1135

Review metrics

Metric Value Why it matters
Production vs test delta production +351/-137 (net +214); tests/test-support +1028/-150 (net +878); docs +51/-8 Production growth spans provider controls and session ordering, with substantial focused replay and reopen coverage.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts, unknown-data-model-change: src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm the retention contract (recommended)
    Confirm that existing transcript retention and export behavior may include durable hidden runtime-context entries before merging.
  2. Pause the persistence approach
    Hold the PR if durable hidden context is unacceptable, since signed-prefix stability then needs a different architecture.

Technical review

Best possible solution:

Keep the single policy-guided replay path once a maintainer accepts durable hidden-carrier retention; no smaller existing owner covers retry, reopen, and both provider transports together.

Do we have a high-confidence way to reproduce the issue?

Yes—source-reproducible: the merge-base boundary relocated or removed carrier context, while the added coverage exercises replay, reopen, reset, and ordering; this read-only review did not rerun the scenario.

Is this the best way to solve the issue?

Yes, subject to the retention decision: the change fixes the session and provider owners that alter signed prefixes rather than masking rejected requests downstream.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8afdea07a152.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The PR addresses active agent-session and provider replay failures affecting Anthropic-family model use.
  • merge-risk: 🚨 compatibility: It changes persisted session-transcript retention and direct-provider request behavior for existing Anthropic-family sessions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.
  • proof: sufficient: Contributor real behavior proof is sufficient. Focused replay and session-reopen tests cover the changed owners, and the supplied PR evidence includes a redacted direct-provider trace through an isolated Gateway path; no local execution was performed in this read-only review.

Evidence

Acceptance criteria:

  • [P1] Review existing session export and retention behavior for durable hidden custom-message entries.
  • [P1] Wait for exact-head required CI to complete successfully.

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm the durable hidden-context retention and export contract before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-03T01:06:34.518Z sha 626e328 :: blocked before merge. :: [P2] Remove the unsupported Mythos 5.1 replay exception

Mythos 5.1 is not registered in the bundled catalog and has no cross-model
replay proof, so unregistered Mythos targets keep the existing drop path.
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up moves, resolved on head 8e731a0:

  • Remove the unsupported Mythos 5.1 replay exception (P2): done. readsPriorClaudeThinking in packages/ai/src/providers/anthropic-model-contract.ts now matches only fable:claude-fable-5-1; Mythos targets keep the existing cross-model drop until their replay contract is proven and registered.
  • Merge risk: unregistered target retaining reasoning (P1): resolved by the narrowing above; the only preserve target is the registered, live-verified Fable 5.1 identity.
  • Merge risk: no inspectable artifact for the live run (P1) and attach a redacted gateway trace (P2): the sanitized gateway/proxy trace is below. It is the recording proxy's per-request summary (no headers, no bodies) for the patched run, the pre-fix direct-API probe and pre-fix gateway 400/recovery lines, and the direct-API phase log lines where OpenClaw sent its own controls.
  • Add data-model compatibility proof: the only persisted change is that runtime-context carriers are now written as custom_message transcript entries with the pre-existing customType openclaw.runtime-context (display: false, details.runtimeContextCarrier: true). custom_message is an existing entry type (used by extension custom messages); no session schema version, SQLite schema, or entry codec changes. Downgrade safety: older runtimes already handled persisted carriers of this type through stripHistoricalRuntimeContextCustomMessages (they strip them as historical context), so a transcript written by this branch reads cleanly on previous versions, and transcripts from previous versions simply have no carriers. Verified by the unchanged session-manager-codec and the compaction planner, which already excluded this custom type.
Sanitized gateway trace (proxy summaries + direct-API log lines)
== proxy-phase capture summary (ids 52-60, no-merge build, /think max, proxy injected thinking-binding-controls with drop_block)
{"id":52,"model":"claude-fable-5-1","messages":2,"roles":"uu","thinkingBlocksReplayed":0,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"tool_use","input_transformations":[]}
{"id":53,"model":"claude-fable-5-1","messages":4,"roles":"uuau","thinkingBlocksReplayed":1,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"end_turn","input_transformations":[]}
{"id":54,"model":"claude-opus-5","messages":8,"roles":"uuauauuu","thinkingBlocksReplayed":0,"systemHash":"07fa01d0b33e","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"tool_use","input_transformations":[]}
{"id":55,"model":"claude-opus-5","messages":10,"roles":"uuauauuuau","thinkingBlocksReplayed":0,"systemHash":"07fa01d0b33e","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"end_turn","input_transformations":[]}
{"id":56,"model":"claude-fable-5-1","messages":14,"roles":"uuauauuuauauuu","thinkingBlocksReplayed":1,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"tool_use","input_transformations":[]}
{"id":57,"model":"claude-fable-5-1","messages":16,"roles":"uuauauuuauauuuau","thinkingBlocksReplayed":2,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"end_turn","input_transformations":[]}
{"id":58,"model":"claude-fable-5-1","messages":18,"roles":"uuauauuuauauuuauau","thinkingBlocksReplayed":3,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"end_turn","input_transformations":[]}
{"id":59,"model":"claude-fable-5-1","messages":20,"roles":"uuauauuuauauuuauauau","thinkingBlocksReplayed":3,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"tool_use","input_transformations":[]}
{"id":60,"model":"claude-fable-5-1","messages":22,"roles":"uuauauuuauauuuauauauau","thinkingBlocksReplayed":4,"systemHash":"ebf5b59b733f","thinking":{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},"status":200,"stop":"end_turn","input_transformations":[]}

== pre-fix carrier probe (direct API, enforcement error)
{"label":"create","status":200,"blocks":["thinking","text"],"input_transformations":[]}
{"label":"carrier-kept","messages":27,"carrierPresent":true,"status":200,"input_transformations":[],"text":"2026."}
{"label":"carrier-stripped","messages":26,"carrierPresent":false,"status":400,"error":"messages.7.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to \"drop_block\". Content that preceded this block when it was created is m"}

== pre-fix gateway (unpatched harness, proxy mode error): /think low then a turn
{"id":14,"mode":"error","model":"claude-fable-5-1","msgs":26,"thinking":3,"status":400,"err":"messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. ... The `system` prompt differs from the one this block was created with."}
{"id":15,"mode":"error","model":"claude-fable-5-1","msgs":26,"thinking":0,"status":200,"stop":"end_turn","it":[]}
[agent/embedded] [session-recovery] Anthropic thinking stream error; retrying once without thinking blocks
[agent/embedded] [session-recovery] stripped thinking blocks after provider rejected replay: repaired=4

== direct-API phase (patched, no proxy, OpenClaw's own controls): /think max, Fable turn, /think high, two Fable turns
2026-09-02T17:39:02.870-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-opus-5 status=200  dispatcher=reuse
2026-09-02T17:39:20.805-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-fable-5-1 status=200  dispatcher=re
2026-09-02T17:39:38.343-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-fable-5-1 status=200  dispatcher=re
2026-09-02T17:40:40.043-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-fable-5-1 status=200  dispatcher=re
2026-09-02T17:40:50.342-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-fable-5-1 status=200  dispatcher=re
2026-09-02T17:40:54.866-07:00 [anthropic] replayed thinking dropped: 1 block(s) (prefix_binding_mismatch at messages.2.content.0)
2026-09-02T17:40:58.413-07:00 [provider-transport-fetch] [model-fetch] response provider=anthropic api=anthropic-messages model=claude-fable-5-1 status=200  dispatcher=re
2026-09-02T17:40:59.442-07:00 [anthropic] replayed thinking dropped: 1 block(s) (prefix_binding_mismatch at messages.2.content.0)

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 3, 2026
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Maintainer decisions for the refreshed ClawSweeper items on head 8e731a0 (landing under the maintainer's explicit direction to build this design, live-test it, and land):

  • Durable hidden runtime/inbound context in Anthropic-family transcripts (P1 + P2): accepted. The carrier is stored as a display: false custom_message entry with the pre-existing openclaw.runtime-context type; it is excluded from chat.history, the TUI, and compaction/branch summaries, and it is part of session state the same way other custom entries already are (exports carry it like they carry cache-TTL and model-snapshot entries). Downgrade: older runtimes treat it as historical runtime context and strip it on replay; no schema or codec change.
  • Production growth (+214 net) (P1): accepted with justification. The lifecycle lives with its owners (session prompt path persists the carrier; the two Anthropic transports own the binding controls; the replay policy owns the append-only decision). The transient carrier path, the cache-breakpoint opt-out plumbing, and the load-time user-turn merge were narrowed or removed rather than duplicated; no existing owner could absorb the persistence without re-deriving it per request.
  • API beta and payload semantics not independently source-checked (P1): the contract is Anthropic's public documentation for preserved thinking and the Fable 5.1 migration guide (https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking, https://platform.claude.com/docs/en/models/fable-5-1/migration-guide), plus the live input_transformations responses in the attached trace; the controls are gated to the direct API-key endpoint with adaptive thinking, where they were exercised.
  • Data-model compatibility proof: see the previous comment; no migration is needed.

@steipete
steipete merged commit 30837ae into main Sep 3, 2026
207 checks passed
@steipete
steipete deleted the steipete/openclaw-model-switching-5cce5f branch September 3, 2026 01:28
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 3, 2026
…s and runtime events (openclaw#136782)

* fix(anthropic): keep Fable 5.1 thinking valid across model switches and runtime context

Claude Fable 5.1 binds each thinking block to the producing model and to the
exact request prefix that preceded it. Three harness behaviors conflicted with
that contract on Anthropic-family routes:

- Moving a session onto Fable 5.1 (from Opus 5, Sonnet 5, Opus 4.8, Fable 5)
  dropped readable reasoning client-side; the replay contract now preserves it
  while leaving Fable 5.1 still drops.
- The per-turn runtime-context carrier was injected transiently after the
  active user turn, stripped on the next request, relocated inside tool loops,
  and removed by the context-engine assembly. It is now persisted right after
  its user turn and replayed in place; inline inbound metadata stays in place
  too, and consecutive user turns are no longer merged at load for the
  Messages API because the merged form lost the second turn's timestamp stamp.
- Direct API-key requests with adaptive thinking send the
  thinking-binding-controls beta with prefix_mismatch_behavior=drop_block, so
  a residual mismatch degrades to a server-side unbilled drop with a warning
  listing the dropped paths instead of a 400, a duplicate request, and a
  transcript-wide thinking wipe. OAuth, proxies, Bedrock, Vertex, and Foundry
  keep the existing strip-and-retry recovery.

Live-verified against api.anthropic.com: nine-request Fable/Opus/Fable session
with tool loops and carriers reports input_transformations: [] on every
request with four retained thinking blocks; a /think change on the direct API
yields a logged server-side drop and no retry.

* fix(anthropic): limit the preserved-thinking replay target to Fable 5.1

Mythos 5.1 is not registered in the bundled catalog and has no cross-model
replay proof, so unregistered Mythos targets keep the existing drop path.
RomneyDa added a commit that referenced this pull request Sep 19, 2026
* feat(meta): add Muse Spark 1.3 models (#136553)

* feat(meta): add Muse Spark 1.3 models

* docs(meta): cite Muse Spark 1.3 recommendation

Co-authored-by: Tharun Tej Tammineni <[email protected]>

---------

Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit 194b7f2)

* feat(anthropic): support Fable 5.1 from shared model metadata (#135638)

* feat(anthropic): support Fable 5.1 from shared model metadata

* test(anthropic): keep alias coverage within the file limit

* fix(media): decouple image limits from catalog augmentation

(cherry picked from commit 0a9b08c)

* feat(openai): support GPT Image 2.5 variants (#143068)

* feat(openai): support GPT Image 2.5 variants

* docs(openai): correct GPT Image 2.5 section link

(cherry picked from commit f93881f)

* feat(fal): support GPT Image 2.5 variants (#143069)

* feat(fal): support GPT Image 2.5 variants

* test(agents): restore Windows media fixture isolation

(cherry picked from commit a57c799)

* fix(bedrock): preserve images returned by tools (#149336)

## What Problem This Solves
Tool-returned images make the next request fail with `ValidationException` on affected Bedrock routes. Fixes #149332.

## Why This Change Was Made
The serializer generates image labels from each tool-call ID; input images need no labels. All consecutive tool results come first, followed by image groups in the same tool order. Request state has one writer. `stream.runtime.ts`: +28/−1 for this conversion.

Growth accepted under the owner's standing acceptance (2026-09-15).

## User Impact
Image-reading turns can finish without losing image bytes, tool associations, or error status.

## Evidence
Authenticated `chat.send` → registered `read` on a synthetic PNG: main sent a nested image and failed; candidate sent a sibling image and completed with the scripted “Red square; blue circle.” Our run used a recording HTTP transport.

The [contributor's real two-tool run](#149336 (comment)) confirms image interpretation and association.

## Compatibility
Concrete route identities select the conversion. Opaque aliases keep their layout. The general schema permits nested images for some routes; this repair addresses the affected route’s observed rejection. No config or public interface changes.

## Consumers
All clients use the existing Bedrock serializer.

## Invalidation
Conversion is request-local. Stored transcript rows and original image bytes remain unchanged.

## Tests
`node scripts/run-vitest.mjs run --config test/vitest/vitest.extension-providers.config.ts extensions/amazon-bedrock`: 289 tests across 12 files passed on a fresh merge with main. Types, lint, formatting, file-size and assertion limits, and unused-export checks passed.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 115522a)

* fix: preserve Ultra across model runtime boundaries (#135397)

* fix: preserve Ultra across model runtime boundaries

Keep native Codex Ultra as a runtime mode instead of clamping it against
physical Responses effort tiers. Share the selected collaboration effort
between turn fields and remove the redundant forwarding wrapper.

Carry the active parent thinking level through existing spawn context so
one-shot overrides reach native subagents without changing saved preferences.
Keep explicit child overrides and configured child defaults authoritative.

Scope Control UI thinking catalog fallback to the selected runtime, sharing
one prepared entry for picker options and the inherited default. Document
the native orchestration/budget boundary and active-turn inheritance.

* refactor: simplify Ultra reasoning fixtures

* fix: preserve active thinking across shared tool contexts

* docs: clarify Off thinking for side questions

(cherry picked from commit ee9e22b)

* fix(anthropic): Fable 5.1 sessions lose reasoning after model switches and runtime events (#136782)

* fix(anthropic): keep Fable 5.1 thinking valid across model switches and runtime context

Claude Fable 5.1 binds each thinking block to the producing model and to the
exact request prefix that preceded it. Three harness behaviors conflicted with
that contract on Anthropic-family routes:

- Moving a session onto Fable 5.1 (from Opus 5, Sonnet 5, Opus 4.8, Fable 5)
  dropped readable reasoning client-side; the replay contract now preserves it
  while leaving Fable 5.1 still drops.
- The per-turn runtime-context carrier was injected transiently after the
  active user turn, stripped on the next request, relocated inside tool loops,
  and removed by the context-engine assembly. It is now persisted right after
  its user turn and replayed in place; inline inbound metadata stays in place
  too, and consecutive user turns are no longer merged at load for the
  Messages API because the merged form lost the second turn's timestamp stamp.
- Direct API-key requests with adaptive thinking send the
  thinking-binding-controls beta with prefix_mismatch_behavior=drop_block, so
  a residual mismatch degrades to a server-side unbilled drop with a warning
  listing the dropped paths instead of a 400, a duplicate request, and a
  transcript-wide thinking wipe. OAuth, proxies, Bedrock, Vertex, and Foundry
  keep the existing strip-and-retry recovery.

Live-verified against api.anthropic.com: nine-request Fable/Opus/Fable session
with tool loops and carriers reports input_transformations: [] on every
request with four retained thinking blocks; a /think change on the direct API
yields a logged server-side drop and no retry.

* fix(anthropic): limit the preserved-thinking replay target to Fable 5.1

Mythos 5.1 is not registered in the bundled catalog and has no cross-model
replay proof, so unregistered Mythos targets keep the existing drop path.

(cherry picked from commit 30837ae)

* feat(openai): support GPT-6 Astra (#137550)

* feat(openai): support GPT-6 Astra

* fix(models): preserve declared pricing tiers during catalog refresh

(cherry picked from commit eb72093)

* fix(openai): require discovery before offering Astra for OAuth (#137561)

(cherry picked from commit 8b1add5)

* fix(diagnostics-prometheus): reject unauthorized metric scrapes (#140903)

* fix(diagnostics-prometheus): require operator.read for metric scrapes

The Prometheus scrape route registers under the trusted-operator runtime
scope surface, so the Gateway authenticates the caller and applies its
named-role scope ceiling before dispatch. The handler never consulted
those scopes, so an authenticated identity whose role grants no operator
scopes still received the full diagnostics document with 200, while the
same caller was correctly refused on equivalent read operations.

Check the runtime request scopes inside the handler and fail closed with
403 "missing scope: operator.read" unless the caller holds operator.read,
operator.write, or operator.admin, mirroring the Gateway read implication
set. The guard runs before rendering so HEAD probes cannot disclose the
document size either.

* test(diagnostics-prometheus): prove role-limited scrape denial

(cherry picked from commit 0c9330b)

* fix(discord): enforce sender media policy on guild asset uploads (#140334)

The Discord emoji-upload, sticker-upload, and event-create branches dropped
the sender-scoped media access options before dispatching the action, so the
guild runtime loaded the requested host-local path with only a byte limit. A
sender permitted to run those actions could therefore place bytes from a file
outside their allowed media roots into an outbound Discord emoji, sticker, or
event-cover request.

Forward the resolved action options from all three branches, carry
mediaAccess/mediaLocalRoots/mediaReadFile through the guild runtime, and load
upload sources through buildOutboundMediaLoadOptions like every other outbound
Discord media path. Adds regression coverage that a source outside the sender
roots is rejected before any request is issued, with an in-roots control.

(cherry picked from commit e5e7764)

* fix(discord): preserve realtime speaker and playback ownership (#137433)

* fix(discord): preserve realtime speaker and playback ownership

Bind provider connections to one Discord principal so delayed transcripts
and native consultations cannot inherit another speaker's authority.
Keep the shared agent route and serialize response-owned audio on one
room player, preserving continuations and recovery after playback gaps.

Admit host-requested responses before dispatch and map Google Live turn
completion to canonical terminal outcomes so queued speech can finish.

Closes #137349
Related: #136982, #123243
Follow-up: #137417

* test(discord): preserve room capture across speaker recovery

(cherry picked from commit 85d510c)

* fix(doctor): preserve enabled skills during automatic updates (#138730)

Use runtime-repair approval for optional skill disabling. Keep standalone explicit repair and required config migrations unchanged.

(cherry picked from commit acc9a65)

* fix: generated images disappear after failed tool calls (#131226)

## What Problem This Solves

WebChat drops generated media when a later tool failure is the turn's only reply payload.

## Root cause

The embedded-run terminal projection assigned successful tool media to the first non-reasoning payload. A later error warning could become that owner. Gateway error projection then discarded the attached media.

## Fix

- Attach tool media only to a successful, non-reasoning reply.
- Emit a separate media-only payload when the turn has no successful reply.
- Preserve the newer host-owned and automatic-delivery media paths from current `main`.
- Keep regression coverage at the payload owner and physical-delivery boundaries.
- Remove the mocked browser test that manually inserted its expected result.

## Evidence

- Baseline: current `main` at `8544aed05a5dbffb871483be781f71351203319e`.
- Real path: branch-built Control UI → real Gateway → mock OpenAI Responses provider → successful image tool → later failing tool → terminal WebChat event.
- Red: current `main` rendered zero generated images.
- Green: `d2a10d40c633bfe796ad4ab19222aa831184a327` rendered one generated image.
- Anti-cheat: the proof recorded `image-success` before `later-failure` and verified that Chromium loaded the exact Gateway-served asset from the branch build.

## Validation

- Focused unit and integration tests: 19 passed across 2 Vitest shards.
- Real Gateway and built Control UI proof: passed on current `main` and the candidate head with opposite image assertions.
- Targeted format, Oxlint, conflict-marker, max-lines, assertion-safety, and diff checks passed.
- Type checks run in continuous integration because repository policy forbids them on this host.

Production change: `+3/-3`, net zero. Test change: `+23/-1`, net `+22`.

Co-authored-by: A28Hui <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 88be1b8)

* fix(matrix): refresh verification status before reporting device trust (#136226)

* fix(matrix): refresh verification status before reporting device trust

Refresh own-device keys after crypto preparation and before the authoritative trust read. Keep the missing-device preflight and use the Matrix SDK’s existing query contract.

* test(slack): remove core-coupled threading duplicate

---------

Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit a812054)

* chore(release): prepare extended-stable 2026.8.33

* fix(release): integrate model and Discord security backports

* docs(release): clarify extended-stable workflow baseline

* fix(release): complete stable-line backport integration

* fix(ios): restore dependency resolution with WebRTC 152 (#134942)

* fix(release): repair frozen validation inputs

* fix(discord): stop error replies after voice consult cancellation (#135380)

* fix(discord): stop error replies after voice consult cancellation

Treat host-cancelled Discord realtime consults as terminal cancellation, preserve late-call dedupe, and wait for every native delivery before returning forced playback ownership. Timeouts and genuine errors retain their normal handling.

Closes #135340. Related phone cancellation helper: #134924.

* test(acp): run CLI lifecycle checks against prepared runtime

* test(cli): cover selective runtime build admission

* test(ci): account for ACP runtime preparation

* fix(release): complete Discord cancellation backport

* test(release): keep candidate fixtures current

* test(update): isolate frozen release version

---------

Co-authored-by: tharuntejmeta <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: dclosefuturex <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Pavan Kumar Gondhi <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: CGlashu <[email protected]>
Co-authored-by: A28Hui <[email protected]>
obviyus added a commit that referenced this pull request Nov 27, 2026
## What Problem This Solves

Every chat turn on the embedded runtime adds a hidden runtime-context block to the conversation, with state snapshots: active exec sessions, active subagents, media-generation tasks, approved executables and the current date. Since #198100 these blocks stay in history on every route, so the model keeps seeing every earlier copy. The snapshots were re-sent on every turn even when nothing had changed, so each turn added the same 715–1,066 bytes again. By turn 8 of a plain chat, these repeated snapshots were 49–75% of the message history. They cost context on every later request.

## User Impact

Long sessions keep less repeated state in context. A chat turn where nothing changed adds no snapshot bytes. The model still sees the current state: a snapshot is sent again as soon as it changes (for example, when an exec session ends it gets "No active exec-tool sessions"), and after compaction, on a fresh session, or on a route that clears turn-scoped updates, every snapshot is sent in full. Earlier history stays byte-for-byte unchanged, so prompt caching behaves the same. No config, schema or stored-format change.

## Why This Change Was Made

- `buildRuntimeFactsContext` now owns one rule: send a snapshot only if it differs from the latest copy the request already carries. A snapshot the request does not carry counts as unknown and is sent in full, including its empty form.
- Snapshot identity comes from the headings each producer renders, exported next to the producer. No new stored field: the latest copy is read from the stored carrier, either from its producer fragments or from a projected system update.
- The diff base is what the request really sends. Routes that do not retain carriers send no earlier copies. The route that clears turn-scoped system updates (`clear_at: "next_user_message"` on Anthropic) drops those copies. That route fact moves into one function in `transcript-policy.ts`, which both callers use.
- `includeEmptySnapshots` is no longer derived from `appendOnlyRuntimeContext` in the embedded path. The CLI runner, the worker launch descriptor and the Codex app-server turn context have the same repetition with different owners; they are not changed here.
- I did not make snapshots transient (sent with the current request only and never stored). Prefix-binding Claude models bind each thinking block to the exact prefix before it (#136782), so removing or moving an earlier carrier breaks reasoning replay. It would also undo the append-only contract from #198100.
- Related direction: #172313 moves generated inbound metadata out of the system prompt into turn carriers. This change keeps those carriers from re-recording unchanged state.

## Evidence

- **Regression test, red on main and green here:** `attempt-prompt-context.test.ts` "does not replay unchanged state snapshots into the next turn's history". On main the turn-2 carrier repeats the temporal, subagent and exec snapshots.
- **New tests for the edge cases:**
  - a retry within one turn adds no second copy;
  - the first turn after compaction sends every snapshot, empty forms included;
  - a route that clears turn-scoped updates gets the snapshots again, and a route that keeps them does not;
  - the reader handles both stored carrier forms (`runtime-facts-prompt.test.ts`).
- **Touched and consumer tests green:** prompt context, runtime facts, internal runtime context, media hint cache boundary, `agent-tools.prefix-stability`, subagent active context and catch-up, transcript policy, context advancement, tool-result truncation, runtime marker. `pnpm check:changed` green after one assertion-ratchet fix.
- **History bytes per turn, main vs this branch.** Built product (`openclaw agent --local` and a scratch Gateway), 8-turn chat and 8-turn code task, isolated state, provider requests recorded at a TLS proxy. Message bytes of each turn's first request:

| Route | Surface | Turn 8 main → branch | Change |
|---|---|---|---|
| Anthropic Messages (fake provider) | `--local` chat | 7,544 → 2,364 B | −69% |
| Anthropic Messages (fake provider) | Gateway chat | 10,942 → 6,511 B | −40% |
| Anthropic Messages (fake provider) | `--local` code | 12,741 → 7,561 B | −41% |
| Anthropic Messages (fake provider) | Gateway code | 16,133 → 11,702 B | −27% |
| OpenAI gpt-5.4-mini, Completions route (served via Responses) | `--local` chat | 10,113 → 4,402 B | −56% |
| OpenAI gpt-5.4-mini, Completions route | Gateway chat | 13,365 → 8,842 B | −34% |
| OpenAI gpt-5.4-mini, Completions route | `--local` code | 14,378 → 9,489 B | −34% |
| OpenAI gpt-5.4-mini, Completions route | Gateway code | 18,157 → 12,938 B | −29% |
| OpenAI gpt-5.4-mini, Responses (embedded) | `--local` code | 35,330 → 21,837 B | −38% |
| OpenAI gpt-5.4-mini, Responses (embedded) | `--local` chat | carriers 5,680 → 710 B (total varies with encrypted reasoning) | |
| OpenAI gpt-5.4-mini, Responses (embedded) | Gateway (`previous_response_id`) | per-turn carrier delta 1,013 → 380 B | |

- **Prefix stability:** byte-prefix breaks were 0 on main and 0 on this branch for every full-request pair on all routes above. Real OpenAI cache loss per session was unchanged within noise (for example 820 → 844 and 2,147 → 1,882 tokens).
- The remaining Gateway carrier bytes per turn are the per-turn deferred-tool grant and the inbound sender block, which this change does not touch.
- **Not measured:** real Anthropic routes with in-history system updates (direct API-key prefix-binding models). They are covered by the cleared-route test only.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…law#206766)

## What Problem This Solves

Every chat turn on the embedded runtime adds a hidden runtime-context block to the conversation, with state snapshots: active exec sessions, active subagents, media-generation tasks, approved executables and the current date. Since openclaw#198100 these blocks stay in history on every route, so the model keeps seeing every earlier copy. The snapshots were re-sent on every turn even when nothing had changed, so each turn added the same 715–1,066 bytes again. By turn 8 of a plain chat, these repeated snapshots were 49–75% of the message history. They cost context on every later request.

## User Impact

Long sessions keep less repeated state in context. A chat turn where nothing changed adds no snapshot bytes. The model still sees the current state: a snapshot is sent again as soon as it changes (for example, when an exec session ends it gets "No active exec-tool sessions"), and after compaction, on a fresh session, or on a route that clears turn-scoped updates, every snapshot is sent in full. Earlier history stays byte-for-byte unchanged, so prompt caching behaves the same. No config, schema or stored-format change.

## Why This Change Was Made

- `buildRuntimeFactsContext` now owns one rule: send a snapshot only if it differs from the latest copy the request already carries. A snapshot the request does not carry counts as unknown and is sent in full, including its empty form.
- Snapshot identity comes from the headings each producer renders, exported next to the producer. No new stored field: the latest copy is read from the stored carrier, either from its producer fragments or from a projected system update.
- The diff base is what the request really sends. Routes that do not retain carriers send no earlier copies. The route that clears turn-scoped system updates (`clear_at: "next_user_message"` on Anthropic) drops those copies. That route fact moves into one function in `transcript-policy.ts`, which both callers use.
- `includeEmptySnapshots` is no longer derived from `appendOnlyRuntimeContext` in the embedded path. The CLI runner, the worker launch descriptor and the Codex app-server turn context have the same repetition with different owners; they are not changed here.
- I did not make snapshots transient (sent with the current request only and never stored). Prefix-binding Claude models bind each thinking block to the exact prefix before it (openclaw#136782), so removing or moving an earlier carrier breaks reasoning replay. It would also undo the append-only contract from openclaw#198100.
- Related direction: openclaw#172313 moves generated inbound metadata out of the system prompt into turn carriers. This change keeps those carriers from re-recording unchanged state.

## Evidence

- **Regression test, red on main and green here:** `attempt-prompt-context.test.ts` "does not replay unchanged state snapshots into the next turn's history". On main the turn-2 carrier repeats the temporal, subagent and exec snapshots.
- **New tests for the edge cases:**
  - a retry within one turn adds no second copy;
  - the first turn after compaction sends every snapshot, empty forms included;
  - a route that clears turn-scoped updates gets the snapshots again, and a route that keeps them does not;
  - the reader handles both stored carrier forms (`runtime-facts-prompt.test.ts`).
- **Touched and consumer tests green:** prompt context, runtime facts, internal runtime context, media hint cache boundary, `agent-tools.prefix-stability`, subagent active context and catch-up, transcript policy, context advancement, tool-result truncation, runtime marker. `pnpm check:changed` green after one assertion-ratchet fix.
- **History bytes per turn, main vs this branch.** Built product (`openclaw agent --local` and a scratch Gateway), 8-turn chat and 8-turn code task, isolated state, provider requests recorded at a TLS proxy. Message bytes of each turn's first request:

| Route | Surface | Turn 8 main → branch | Change |
|---|---|---|---|
| Anthropic Messages (fake provider) | `--local` chat | 7,544 → 2,364 B | −69% |
| Anthropic Messages (fake provider) | Gateway chat | 10,942 → 6,511 B | −40% |
| Anthropic Messages (fake provider) | `--local` code | 12,741 → 7,561 B | −41% |
| Anthropic Messages (fake provider) | Gateway code | 16,133 → 11,702 B | −27% |
| OpenAI gpt-5.4-mini, Completions route (served via Responses) | `--local` chat | 10,113 → 4,402 B | −56% |
| OpenAI gpt-5.4-mini, Completions route | Gateway chat | 13,365 → 8,842 B | −34% |
| OpenAI gpt-5.4-mini, Completions route | `--local` code | 14,378 → 9,489 B | −34% |
| OpenAI gpt-5.4-mini, Completions route | Gateway code | 18,157 → 12,938 B | −29% |
| OpenAI gpt-5.4-mini, Responses (embedded) | `--local` code | 35,330 → 21,837 B | −38% |
| OpenAI gpt-5.4-mini, Responses (embedded) | `--local` chat | carriers 5,680 → 710 B (total varies with encrypted reasoning) | |
| OpenAI gpt-5.4-mini, Responses (embedded) | Gateway (`previous_response_id`) | per-turn carrier delta 1,013 → 380 B | |

- **Prefix stability:** byte-prefix breaks were 0 on main and 0 on this branch for every full-request pair on all routes above. Real OpenAI cache loss per session was unchanged within noise (for example 820 → 844 and 2,147 → 1,882 tokens).
- The remaining Gateway carrier bytes per turn are the per-turn deferred-tool grant and the inbound sender block, which this change does not touch.
- **Not measured:** real Anthropic routes with in-history system updates (direct API-key prefix-binding models). They are covered by the cleared-route test only.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 30, 2026
…inking block bound to a different conversation" (#208704)

Root cause: `extensions/amazon-bedrock/stream.runtime.ts:1104` (`:1155` in 2026.11.10) builds adaptive Claude thinking for Bedrock Converse without `thinking.block_binding` or the `thinking-binding-controls-2026-08-01` beta, which the direct Anthropic route adds through the shared `applyAnthropicThinkingBindingControls`. So any replayed thinking block whose earlier history changed is rejected instead of dropped.

Fixes #208675. Thanks @michaeljgood71 for the report, the boto3 check and the patch that pointed straight at the fix.

## What Problem This Solves

Fixes: long Bedrock Claude sessions with adaptive thinking get the first request of a turn rejected ("Invalid `signature` in `thinking` block. The block is bound to a different conversation") whenever earlier history changed, for example after cache-TTL pruning, compaction or a model switch. OpenClaw then retries without thinking and drops the session's earlier reasoning.

## User Impact

Bedrock Claude requests with adaptive thinking now carry the same thinking-binding controls as direct Anthropic API-key requests. Bedrock drops only the stale thinking blocks, the turn succeeds on the first request, and the rest of the reasoning stays in the session. Budget-based Bedrock thinking, GovCloud (which already omits `thinking.display` for its older schema), and the direct Anthropic request are unchanged.

## Why This Change Was Made

#136782 added the controls for direct API-key requests only and left Bedrock on reject-and-retry. The reporter showed Bedrock Converse accepts both controls and drops the stale block. The Bedrock request builder now calls the shared helper on its adaptive branch, so it follows the same rule (adaptive thinking only) and the same beta value, sent as Converse `anthropic_beta`. The helper is re-exported from the existing private-local `provider-stream-shared` SDK seam; no new helper or policy copy. Docs updated where they listed Bedrock as excluded.

Not covered: #198838 (custom provider ids on api.anthropic.com). Its cause is the separate direct-route gate `isDirectAnthropicModel` requiring provider id `anthropic`, which this Bedrock path never goes through.

## Evidence

Isolated built Gateway, real `openclaw agent` turns in one session, `au.anthropic.claude-sonnet-5-5` on `amazon-bedrock` pointed at a local Converse stand-in. The stand-in signs each thinking block over the exact request prefix and rejects a replayed block whose prefix changed with Bedrock's ValidationException unless both `drop_block` and the beta are present. Turn 1 reads four files, turns 2-4 are plain, then the `contextPruning: cache-ttl` TTL expires and turn 5 trims turn 1's tool results (the reporter's setting), turn 6 is plain. Two runs per side, identical:

- main (46e0d90): turn 5 and turn 6 each rejected once (400), 4 `[session-recovery]` lines (`retrying once without thinking blocks`, `stripped thinking blocks ... repaired=5`, `unable to repair rejected thinking replay`), later requests replay 0 thinking blocks.
- this branch: 0 rejected requests, 0 `[session-recovery]` lines; turn 5 replays 5 blocks (4 stale dropped by the stand-in, 1 kept), turn 6 replays 6.

Controls: a Bedrock model without adaptive thinking (Haiku 4.5, budget thinking) sends identical requests on both builds (9/9 after normalizing temp paths and timestamps). The bundled `anthropic` provider, through a local TLS stand-in for api.anthropic.com, sends byte-identical requests and `anthropic-beta` headers on both builds (4/4); built `packages/ai/dist` is identical. Regression: the Bedrock request-composition table fails on main (8 cases, no `block_binding`/`anthropic_beta`) and passes here; GovCloud adaptive and budget rows assert no controls. `agent-tools.prefix-stability`, the Anthropic binding transport parity test and the Bedrock stream, replay and plugin tests pass.

Observed proof lines: #208704 (comment)

Merge danger: two-way door. A revert restores the old request shape; nothing is stored or migrated. Blast radius: Bedrock Claude requests with adaptive thinking outside GovCloud. If a Bedrock region rejected the controls, those requests would fail rather than fall back; the reporter's boto3 Converse checks on Bedrock accepted them.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
…inking block bound to a different conversation" (openclaw#208704)

Root cause: `extensions/amazon-bedrock/stream.runtime.ts:1104` (`:1155` in 2026.11.10) builds adaptive Claude thinking for Bedrock Converse without `thinking.block_binding` or the `thinking-binding-controls-2026-08-01` beta, which the direct Anthropic route adds through the shared `applyAnthropicThinkingBindingControls`. So any replayed thinking block whose earlier history changed is rejected instead of dropped.

Fixes openclaw#208675. Thanks @michaeljgood71 for the report, the boto3 check and the patch that pointed straight at the fix.

## What Problem This Solves

Fixes: long Bedrock Claude sessions with adaptive thinking get the first request of a turn rejected ("Invalid `signature` in `thinking` block. The block is bound to a different conversation") whenever earlier history changed, for example after cache-TTL pruning, compaction or a model switch. OpenClaw then retries without thinking and drops the session's earlier reasoning.

## User Impact

Bedrock Claude requests with adaptive thinking now carry the same thinking-binding controls as direct Anthropic API-key requests. Bedrock drops only the stale thinking blocks, the turn succeeds on the first request, and the rest of the reasoning stays in the session. Budget-based Bedrock thinking, GovCloud (which already omits `thinking.display` for its older schema), and the direct Anthropic request are unchanged.

## Why This Change Was Made

openclaw#136782 added the controls for direct API-key requests only and left Bedrock on reject-and-retry. The reporter showed Bedrock Converse accepts both controls and drops the stale block. The Bedrock request builder now calls the shared helper on its adaptive branch, so it follows the same rule (adaptive thinking only) and the same beta value, sent as Converse `anthropic_beta`. The helper is re-exported from the existing private-local `provider-stream-shared` SDK seam; no new helper or policy copy. Docs updated where they listed Bedrock as excluded.

Not covered: openclaw#198838 (custom provider ids on api.anthropic.com). Its cause is the separate direct-route gate `isDirectAnthropicModel` requiring provider id `anthropic`, which this Bedrock path never goes through.

## Evidence

Isolated built Gateway, real `openclaw agent` turns in one session, `au.anthropic.claude-sonnet-5-5` on `amazon-bedrock` pointed at a local Converse stand-in. The stand-in signs each thinking block over the exact request prefix and rejects a replayed block whose prefix changed with Bedrock's ValidationException unless both `drop_block` and the beta are present. Turn 1 reads four files, turns 2-4 are plain, then the `contextPruning: cache-ttl` TTL expires and turn 5 trims turn 1's tool results (the reporter's setting), turn 6 is plain. Two runs per side, identical:

- main (8e38da2): turn 5 and turn 6 each rejected once (400), 4 `[session-recovery]` lines (`retrying once without thinking blocks`, `stripped thinking blocks ... repaired=5`, `unable to repair rejected thinking replay`), later requests replay 0 thinking blocks.
- this branch: 0 rejected requests, 0 `[session-recovery]` lines; turn 5 replays 5 blocks (4 stale dropped by the stand-in, 1 kept), turn 6 replays 6.

Controls: a Bedrock model without adaptive thinking (Haiku 4.5, budget thinking) sends identical requests on both builds (9/9 after normalizing temp paths and timestamps). The bundled `anthropic` provider, through a local TLS stand-in for api.anthropic.com, sends byte-identical requests and `anthropic-beta` headers on both builds (4/4); built `packages/ai/dist` is identical. Regression: the Bedrock request-composition table fails on main (8 cases, no `block_binding`/`anthropic_beta`) and passes here; GovCloud adaptive and budget rows assert no controls. `agent-tools.prefix-stability`, the Anthropic binding transport parity test and the Bedrock stream, replay and plugin tests pass.

Observed proof lines: openclaw#208704 (comment)

Merge danger: two-way door. A revert restores the old request shape; nothing is stored or migrated. Blast radius: Bedrock Claude requests with adaptive thinking outside GovCloud. If a Bedrock region rejected the controls, those requests would fail rather than fall back; the reporter's boto3 Converse checks on Bedrock accepted them.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: amazon-bedrock extensions: anthropic extensions: anthropic-vertex extensions: github-copilot extensions: minimax maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant