Repository navigation
Description
Summary
Two related bugs discovered after investigating a reproducible LLM request rejected: messages.3.content.2: thinking or redacted_thinking blocks in the latest assistant message cannot be modified error on a long-running Telegram DM session.
Reported by: @Caml2001 ([email protected])
Bug 1: stripDanglingAnthropicToolUses checks the wrong block type
File: src/agents/pi-embedded-helpers/turns.ts
The function stripDanglingAnthropicToolUses is supposed to remove tool_use blocks from assistant messages that have no matching tool_result in the following user message. However, it checks for block.type !== "toolUse", while pi-agent-core stores tool calls internally as type: "toolCall".
// turns.ts ~line 68
const filteredContent = originalContent.filter((block) => {
if (!block) return false;
if (block.type !== "toolUse") {
return true; // keeps "toolCall" blocks — should be filtering them!
}
return validToolUseIds.has(block.id || "");
});Because "toolCall" !== "toolUse" is always true, no dangling tool calls are ever removed. The function is effectively a no-op.
Impact: When context is truncated (e.g. after limitHistoryTurns or compaction), orphaned tool call blocks remain in assistant messages and are sent to the Anthropic API without matching tool_result blocks.
Bug 2: Failed LLM requests store empty assistant messages in the session
When an API request fails (e.g. the thinking-blocks error below), an empty assistant message (content: []) is still written to the session JSONL. Each retry compounds this:
[456] assistant: [thinking, text] ← last good response
[458] user: new attempt
[459] assistant: [] ← stored after API rejection
[461] user: retry
[462] assistant: [] ← stored after API rejection
[464] user: retry
[465] assistant: [] ← stored after API rejection
These empty messages persist in the session file and are included in the history on subsequent requests. When pi-ai converts the messages for the Anthropic API it skips empty assistant turns (if (blocks.length === 0) continue), which can create consecutive user turns in the sent payload, and generally leaves the session in a broken state that cannot self-recover without a /reset.
Observed error
LLM request rejected: messages.3.content.2: `thinking` or `redacted_thinking` blocks
in the latest assistant message cannot be modified. These blocks must remain as they
were in the original response.
This occurred on a Telegram DM session (agent:main:telegram:direct:*) with:
- Model:
anthropic/claude-sonnet-4-6 - Thinking level:
medium - Session size at time of error: 418 messages, ~1.79 MB JSONL
- Context pruning:
cache-ttl,keepLastAssistants: 3
The session had grown large enough to approach the 200k token context window. The error first appeared on a new user message following an assistant response that contained thinking blocks. Retrying sent the request repeatedly but each failure stored another empty assistant message, making recovery impossible without resetting the session.
The session was recovered via /reset (backup preserved as .jsonl.reset.*).
Suggested fixes
Bug 1: Change the type check in stripDanglingAnthropicToolUses from "toolUse" to "toolCall" to match pi-agent-core's internal representation.
Bug 2: Do not append an assistant message to the session JSONL when the LLM request fails before receiving any response content. Empty content: [] assistant entries should never be persisted.
Additional recommendation
The compaction.mode: "safeguard" did not trigger before the session reached this broken state (~400k+ estimated characters). Consider lowering the compaction threshold or documenting a recommended dmHistoryLimit for Telegram DM sessions with thinking enabled.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
Caml2001 commentedon Mar 10, 2026
Proposed fixes
Fix 1 —
stripDanglingAnthropicToolUses: wrong type stringFile:
src/agents/pi-embedded-helpers/turns.tspi-agent-core stores assistant tool calls as
type: "toolCall", not"toolUse". The current filter predicate therefore never matches anything, making the function a no-op.Also worth adding a test: create a history with a
toolCallblock in the last assistant message that has no matchingtoolResult, runvalidateAnthropicTurns, and assert the block is stripped.Fix 2 — Error-state assistant messages should not survive
sanitizeSessionHistoryRoot cause (traced in
@mariozechner/pi-agent-core):When the LLM request throws (including the Anthropic API rejection that triggered this issue), pi-agent-core catches the error and unconditionally persists a synthetic error message:
Every retry writes another one of these. After N retries the session JSONL contains N interleaved
user + assistant(error)pairs that cannot self-heal.Fix location:
src/agents/pi-embedded-runner/google.ts—sanitizeSessionHistoryAdd a filter step (before or after the existing
dropThinkingBlocksstep) that strips assistant messages that havestopReason === "error":This keeps the fix entirely in OpenClaw without requiring changes to pi-agent-core. The messages are already harmless at the JSONL level (pi-agent-core's own guard skips purely-empty content when replaying), but removing them from the sanitized transcript eliminates the user/assistant imbalance that can corrupt subsequent turns and confuse the Anthropic API.
Why these two bugs can combine to trigger the thinking-blocks error
limitHistoryTurnsor compaction drops sometoolResultentries.toolCallblocks in the preceding assistant messages are NOT stripped — they become dangling.tool_useIDs.Regression test sketch
fix: check "toolCall" instead of "toolUse" in stripDanglingAnthropicT…
fix: check "toolCall" instead of "toolUse" in stripDanglingAnthropicT…
steipete commentedon Apr 24, 2026
Closing this as implemented after Codex review.
Current
mainalready covers both reported failure modes: dangling Anthropic tool calls are stripped using a helper that recognizestoolCall, and errored/empty assistant turns are filtered out before Anthropic payload conversion so they do not corrupt replayed request history.What I checked:
toolCall:stripDanglingAnthropicToolUsesno longer compares against the wrong literal; it callsisToolCallBlock(), which returns true fortoolUse,toolCall, andfunctionCall, and the filter path uses that helper. (src/agents/pi-embedded-helpers/turns.ts:14)validateAnthropicTurnspreserving/stripping moderntoolCall-style replay blocks, including standalonetoolResultmatching before the next assistant turn. (src/agents/pi-embedded-helpers.validate-turns.test.ts:498)transformTransportMessages(...)before converting them to Anthropic payload blocks. (src/agents/anthropic-transport-stream.ts:257)transformTransportMessagesexplicitly skips assistant messages withstopReason === "error"or"aborted", so persisted empty error stubs are not sent back to Anthropic on replay. (src/agents/transport-message-transform.ts:116)v2026.4.22tag contains the sametoolCallhandling insrc/agents/pi-embedded-helpers/turns.tsand the same error-turn skip insrc/agents/transport-message-transform.ts, so this behavior is not only on HEAD. (00bd2cf7a376)So I’m closing this as already implemented rather than keeping a duplicate issue open.
Review notes: reviewed against bae7b54a85b1; fix evidence: release v2026.4.22, commit 00bd2cf7a376.