claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[Bug] Anthropic API Error: Cannot modify thinking blocks in assistant messages

Open officialtaras opened this issue 6 months ago • 11 comments

Bug Description API Error: 400 messages.1.content.56: thinking or redacted_thinking blocks in the latest assistant message cannot be modified. These blocks must remain as they were in the original response

Dup of https://github.com/anthropics/claude-code/issues/12311

Environment Info

  • Platform: darwin
  • Terminal: ghostty
  • Version: 2.1.153
  • Feedback ID: ac8742c0-36c5-484d-8067-90e42143ddfd

Errors

[{"error":"Error: 400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.1.content.56: `thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified. These blocks must remain as they were in the original response.\"},\"request_id\":\"req_011CbUkDBr3ffjhp9ajPrr8k\"}\n    at generate (/$bunfs/root/src/entrypoints/cli.js:11:63764)\n    at makeRequest (/$bunfs/root/src/entrypoints/cli.js:51:7694)\n    at processTicksAndRejections (native:7:39)","timestamp":"2026-05-28T09:40:16.218Z"},{"error":"Error: 400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.1.content.56: `thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified. These blocks must remain as they were in the original response.\"},\"request_id\":\"req_011CbUmqgsfZG65nyj7scwE5\"}\n    at generate (/$bunfs/root/src/entrypoints/cli.js:11:63764)\n    at makeRequest (/$bunfs/root/src/entrypoints/cli.js:51:7694)\n    at processTicksAndRejections (native:7:39)","timestamp":"2026-05-28T10:01:38.483Z"}]

officialtaras avatar May 28 '26 10:05 officialtaras

same error

Jorgemunera avatar May 28 '26 17:05 Jorgemunera

same error

icheremisov avatar May 28 '26 17:05 icheremisov

Also hitting this today on the Claude desktop app. Same error: API Error: 400 messages.X.content.Y: thinking or redacted_thinking blocks in the latest assistant message cannot be modified. These blocks must remain as they were in the original response. Environment:

Platform: macOS App version: latest Model: Opus 4.7 and 4.8

Repro: long conversation The conversation becomes unrecoverable after this — have to start a new session to continue.

diakonazari avatar May 28 '26 18:05 diakonazari

Even very fresh conversation affected.

AppVersion: latest (2.1.154) OS: Windows 10. Model: Opus 4.8

Ingerdev avatar May 28 '26 18:05 Ingerdev

Confirming this reproduces on the current latest build and cross-platform (Windows), and that it is not exclusively an auto-compact bug.

Environment (reproduced)

  • Claude Code v2.1.154 (current npm latest; stable = 2.1.145), model Opus 4.8, Windows 11.
  • This issue is filed on macOS / 2.1.153, so the bug is cross-platform and present in the newest release. Reports span 2.0.55 → 2.1.154 — no fixed version exists yet (canonical tracking issue is #12311).

Observations that may help triage

  1. Not only a compaction bug. I hit it in a short session that never compacted (~90 transcript lines, no compact-summary event). The post-tool-call history-reconstruction path triggers it on its own, so a fix scoped only to compaction will not fully cover it.
  2. The error always cites the latest assistant message at a high content index (content.14, content.28, …). Those map to one assistant message that, after reconstruction, holds 15–29 content blocks — a tool-use turn with interleaved thinking (thinking, tool_use, thinking, tool_use, …). Opus 4.x adaptive thinking auto-enables interleaved thinking, so any tool-heavy turn emits many signed thinking blocks that must be replayed verbatim.
  3. Frequency scales with reasoning effort × tools-per-turn. High effort + many tool calls per turn (e.g. many MCP tools) → more/larger signed thinking blocks to preserve → higher hit rate.
  4. Unrecoverable in-app: once wedged, every retry re-sends the same reconstructed message; /compact and rewind also fail because they re-send the same history.

Why a user-side fix is possible

During tool-use continuation the API requires the latest assistant message's thinking / redacted_thinking blocks to be replayed byte-for-byte (text + signature + order; no merge/split/move across tool boundaries). The 400 means the reconstruction altered one before resending. Crucially the constraint applies only to the latest assistant message — earlier turns may be dropped or modified freely.

Recovery that works today

Edit the session transcript JSONL (~/.claude/projects/<encoded-cwd>/<session-id>.jsonl) to truncate it back to the last human user message before the error, then claude --resume <session-id>. The next assistant turn regenerates from a clean user-message boundary, so its thinking blocks get fresh signatures and the wedge clears — all earlier turns are preserved. Do not strip thinking blocks in place; that orphans tool_use / tool_result pairs.

I scripted this for Windows (PowerShell). It auto-detects wedged sessions (only those whose last assistant turn is literally the API Error: 400 … cannot be modified event, so it never touches a healthy session that merely mentions the phrase), backs up first, truncates to the last clean prompt, and prints the resume command. The same idea ports to macOS/Linux with jq/sed.

repair-claude-session.ps1 (Windows PowerShell) — auto-detect, backup, truncate, print resume cmd
<#
  Repair Claude Session
  --------------------------------------------------------------------------
  Fixes a Claude Code session wedged by the API 400:
    "thinking / redacted_thinking blocks in the latest assistant message
     cannot be modified."

  How it works: trims the stuck session's transcript back to the last clean
  prompt you typed (taking a timestamped .bak first), so that
  `claude --resume <id>` regenerates a fresh, valid assistant turn.
  Everything you typed before the break is preserved.

  Run with no arguments to auto-detect wedged sessions and pick from a list,
  or pass -Uuid <session-id> to repair one directly.
#>
[CmdletBinding()]
param(
  [string]$Uuid,
  [int]$RecentDays = 14
)

$projDir = Join-Path $env:USERPROFILE '.claude\projects'

function Find-CutPoint {
  param([string[]]$Lines)
  $tot = $Lines.Count
  $errAt = $tot
  for ($i = 0; $i -lt $tot; $i++) {
    try { $o = $Lines[$i] | ConvertFrom-Json } catch { continue }
    if ($o.type -eq 'assistant') {
      $t = ($o.message.content | Where-Object { $_.type -eq 'text' } | Select-Object -First 1).text
      if ($t -match '^API Error: 400.*(cannot be modified|redacted_thinking)') { $errAt = $i; break }
    }
  }
  $cut = -1
  for ($i = $errAt - 1; $i -ge 0; $i--) {
    try { $o = $Lines[$i] | ConvertFrom-Json } catch { continue }
    if ($o.type -eq 'user' -and $o.message.role -eq 'user' -and -not $o.isMeta -and -not $o.isCompactSummary) {
      $c = $o.message.content
      $isTool = ($c -isnot [string]) -and ($c | Where-Object { $_.type -eq 'tool_result' })
      if (-not $isTool) { $cut = $i; break }
    }
  }
  return [pscustomobject]@{ ErrAt = $errAt; Cut = $cut }
}

function Get-Prompt {
  param($Obj)
  $c = $Obj.message.content
  if ($c -is [string]) { return $c }
  return ($c | Where-Object { $_.type -eq 'text' } | Select-Object -First 1).text
}

# A session is "wedged" only if its LAST assistant turn IS the recorded 400 error
# event (text begins with "API Error: 400 ..."). Sessions that merely discuss the
# error in prose are healthy and must never be touched.
function Test-Wedged {
  param([string[]]$Lines)
  for ($i = $Lines.Count - 1; $i -ge 0; $i--) {
    try { $o = $Lines[$i] | ConvertFrom-Json } catch { continue }
    if ($o.type -eq 'assistant') {
      $t = ($o.message.content | Where-Object { $_.type -eq 'text' } | Select-Object -First 1).text
      return [bool]($t -match '^API Error: 400.*(cannot be modified|redacted_thinking)')
    }
  }
  return $false
}

function Repair-One {
  param([System.IO.FileInfo]$File)
  $f = $File.FullName
  Write-Host ""
  Write-Host ("Session: " + $File.BaseName) -ForegroundColor Cyan
  try {
    $age = (New-TimeSpan -Start $File.LastWriteTime).TotalSeconds
    if ($age -lt 120) {
      Write-Host "  SKIPPED - written <2 min ago; that window is probably still open. Close it and re-run." -ForegroundColor Yellow
      return
    }
    $lines = Get-Content $f
    $cp = Find-CutPoint -Lines $lines
    if ($cp.ErrAt -ge $lines.Count) {
      Write-Host "  No wedge error found here - this session looks healthy. Skipping (refusing to truncate)." -ForegroundColor Yellow
      return
    }
    if ($cp.Cut -lt 0) {
      Write-Host "  Could not find a clean prompt to cut back to. Start a fresh session instead." -ForegroundColor Yellow
      return
    }
    $bak = "$f.bak-$(Get-Date -Format yyyyMMdd-HHmmss)"
    Copy-Item -LiteralPath $f -Destination $bak
    $raw = [IO.File]::ReadAllText($f)
    $eol = if ($raw -match "`r`n") { "`r`n" } else { "`n" }
    $keep = ([regex]::Split($raw, "`r?`n"))[0..$cp.Cut]
    [IO.File]::WriteAllText($f, (($keep -join $eol) + $eol), [Text.UTF8Encoding]::new($false))
    $last = (Get-Content $f)[-1] | ConvertFrom-Json
    $p = Get-Prompt $last
    if ($p) { $p = ($p -replace '\s+', ' '); if ($p.Length -gt 70) { $p = $p.Substring(0, 70) } }
    Write-Host ("  Repaired: {0} -> {1} lines. Backup saved." -f $lines.Count, ($cp.Cut + 1)) -ForegroundColor Green
    Write-Host ("  Now ends on your prompt: " + $p)
    Write-Host ("  Backup: " + $bak) -ForegroundColor DarkGray
    Write-Host ("  Reopen with:  claude --resume {0} --bare --effort medium" -f $File.BaseName) -ForegroundColor White
  }
  catch {
    Write-Host ("  ERROR repairing this session: " + $_.Exception.Message) -ForegroundColor Red
    Write-Host "  Your .bak backup (if created) is safe to restore." -ForegroundColor DarkGray
  }
}

Write-Host "=== Repair Claude Session ===" -ForegroundColor Magenta

if ($Uuid) {
  $file = Get-ChildItem (Join-Path $projDir "*\$Uuid.jsonl") -ErrorAction SilentlyContinue | Select-Object -First 1
  if (-not $file) { Write-Host "No session file found for $Uuid" -ForegroundColor Red }
  else { Repair-One -File $file }
}
else {
  Write-Host ("Scanning sessions modified in the last {0} days for the wedge error..." -f $RecentDays)
  $cutoff = (Get-Date).AddDays(-$RecentDays)
  $cands = @()
  Get-ChildItem (Join-Path $projDir '*\*.jsonl') -ErrorAction SilentlyContinue |
    Where-Object { $_.LastWriteTime -ge $cutoff } |
    ForEach-Object {
      try {
        if (Select-String -Path $_.FullName -Pattern 'cannot be modified' -SimpleMatch -Quiet -ErrorAction SilentlyContinue) {
          if (Test-Wedged -Lines (Get-Content $_.FullName)) { $cands += $_ }
        }
      } catch { }
    }
  $cands = @($cands | Sort-Object LastWriteTime -Descending)
  if ($cands.Count -eq 0) {
    Write-Host "No wedged sessions found. Nothing to repair." -ForegroundColor Green
  }
  else {
    Write-Host ""
    Write-Host "Wedged sessions found:" -ForegroundColor Yellow
    for ($i = 0; $i -lt $cands.Count; $i++) {
      $preview = ''
      try {
        $lines = Get-Content $cands[$i].FullName
        $cp = Find-CutPoint -Lines $lines
        if ($cp.Cut -ge 0) { $preview = Get-Prompt ($lines[$cp.Cut] | ConvertFrom-Json) }
      } catch { }
      if ($preview) { $preview = ($preview -replace '\s+', ' '); if ($preview.Length -gt 55) { $preview = $preview.Substring(0, 55) } }
      Write-Host ("  [{0}] {1}  {2}  `"{3}`"" -f ($i + 1), $cands[$i].BaseName, $cands[$i].LastWriteTime.ToString('MM-dd HH:mm'), $preview)
    }
    Write-Host ""
    $sel = Read-Host "Enter number(s) to repair (e.g. 1,3), 'A' for all, or Enter to cancel"
    if ($sel) {
      if ($sel -match '^[Aa]') {
        foreach ($c in $cands) { Repair-One -File $c }
      }
      else {
        foreach ($tok in ($sel -split '[,\s]+')) {
          if ($tok -match '^\d+$') {
            $idx = [int]$tok - 1
            if ($idx -ge 0 -and $idx -lt $cands.Count) { Repair-One -File $cands[$idx] }
          }
        }
      }
    }
    else { Write-Host "Cancelled." }
  }
}

Write-Host ""
[void](Read-Host "Done. Press Enter to close")

Tip: first reopen with claude --resume <id> --bare --effort medium to avoid immediately re-wedging on the regenerated turn.

arm3n avatar May 28 '26 19:05 arm3n

Same issue here with opus 4.8, really annoying!

mayerwin avatar May 28 '26 21:05 mayerwin

Same here, so annoying

ton731 avatar May 30 '26 03:05 ton731

same error xd

DAVIDAROCA27 avatar May 30 '26 19:05 DAVIDAROCA27

For anyone tracking this: the canonical issue #12311 was fixed in v2.1.156 ("Fixed an issue when using Opus 4.8 where thinking blocks were modified, leading to API errors"). This report (#63072) is against v2.1.153, which is pre-fix.

However, the same 400 still reproduces after the fix, on v2.1.158 with claude-opus-4-8 during auto-compact. I've filed that as a regression with post-fix evidence: #64066. If you're still hitting this on 2.1.156+, please add your repro there so it doesn't get triaged away as already-fixed.

dolovegitlove avatar May 30 '26 20:05 dolovegitlove

FWIW, I don't believe this has anything to do with auto-compact, as I and my colleagues all experienced this early into fresh sessions.

arm3n avatar May 30 '26 20:05 arm3n

This is fixed as of Claude Code 2.1.259, so we're closing this issue. If you disagree, let us know here and we can re-open it. Thanks for reporting!

bpasero-ant avatar Nov 29 '26 17:11 bpasero-ant