Skip to content

Bug: stripDanglingAnthropicToolUses checks wrong type ("toolUse" vs "toolCall") and empty assistant messages stored on LLM failure cause session corruption with thinking blocks #41571

Closed

Description

@Caml2001

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.

Activity

  1. Caml2001 commented on Mar 10, 2026

    @Caml2001
    Author

    Proposed fixes

    Fix 1 — stripDanglingAnthropicToolUses: wrong type string

    File: src/agents/pi-embedded-helpers/turns.ts

    pi-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.

    - if (block.type !== "toolUse") {
    + if (block.type !== "toolCall") {

    Also worth adding a test: create a history with a toolCall block in the last assistant message that has no matching toolResult, run validateAnthropicTurns, and assert the block is stripped.


    Fix 2 — Error-state assistant messages should not survive sanitizeSessionHistory

    Root 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:

    // pi-agent-core/dist/agent.js (inside the catch block)
    const errorMsg = {
      role: "assistant",
      content: [{ type: "text", text: "" }],  // ← empty text block
      stopReason: "error",
      errorMessage: err?.message || String(err),
      // ...
    };
    this.appendMessage(errorMsg);  // written to JSONL

    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 — sanitizeSessionHistory

    Add a filter step (before or after the existing dropThinkingBlocks step) that strips assistant messages that have stopReason === "error":

    // After: const droppedThinking = ...
    // Before: const sanitizedToolCalls = ...
    const withoutErrorMessages = droppedThinking.filter((msg) => {
      if (msg.role !== "assistant") return true;
      const assistantMsg = msg as { stopReason?: string };
      return assistantMsg.stopReason !== "error";
    });
    // then feed withoutErrorMessages into sanitizeToolCallInputs

    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

    1. Over a long session, limitHistoryTurns or compaction drops some toolResult entries.
    2. Because Bug 1 is a no-op, the corresponding toolCall blocks in the preceding assistant messages are NOT stripped — they become dangling.
    3. The Anthropic API rejects the request due to unmatched tool_use IDs.
    4. Because of Bug 2, the failed attempt is written to the JSONL as an error-state assistant message.
    5. On the next request, the sanitized transcript now has the dangling tool call plus the structural imbalance from the error messages, which together put the thinking blocks from the last good assistant turn in a position where the API considers them "modified".

    Regression test sketch

    it("strips error-state assistant messages from session history", async () => {
      const messages = [
        { role: "user", content: [...] },
        { role: "assistant", content: [{ type: "thinking", ... }, { type: "text", text: "ok" }] },
        { role: "user", content: [...] },
        { role: "assistant", content: [{ type: "text", text: "" }], stopReason: "error", errorMessage: "LLM request rejected" },
        { role: "user", content: [...] },
      ];
      const result = await sanitizeSessionHistory({ messages, /* anthropic config */ });
      // Error-state assistant message should be gone
      expect(result.filter(m => m.role === "assistant" && (m as any).stopReason === "error")).toHaveLength(0);
      // Remaining structure should alternate correctly
      expect(result.map(m => m.role)).toEqual(["user", "assistant", "user"]);
    });
  2. added 4 commits that reference this issue on Mar 15, 2026
    9d03fca
    59e4690
  3. steipete commented on Apr 24, 2026

    @steipete
    Contributor

    Closing this as implemented after Codex review.

    Current main already covers both reported failure modes: dangling Anthropic tool calls are stripped using a helper that recognizes toolCall, and errored/empty assistant turns are filtered out before Anthropic payload conversion so they do not corrupt replayed request history.

    What I checked:

    • Dangling tool-call stripping now matches toolCall: stripDanglingAnthropicToolUses no longer compares against the wrong literal; it calls isToolCallBlock(), which returns true for toolUse, toolCall, and functionCall, and the filter path uses that helper. (src/agents/pi-embedded-helpers/turns.ts:14)
    • Regression coverage for Anthropic replay stripping: Current tests cover validateAnthropicTurns preserving/stripping modern toolCall-style replay blocks, including standalone toolResult matching before the next assistant turn. (src/agents/pi-embedded-helpers.validate-turns.test.ts:498)
    • Errored assistant stubs are excluded from transport replay: Anthropic request building first runs all transcript messages through transformTransportMessages(...) before converting them to Anthropic payload blocks. (src/agents/anthropic-transport-stream.ts:257)
    • Transport transform drops errored assistant turns: transformTransportMessages explicitly skips assistant messages with stopReason === "error" or "aborted", so persisted empty error stubs are not sent back to Anthropic on replay. (src/agents/transport-message-transform.ts:116)
    • Shipped in latest tagged release: The v2026.4.22 tag contains the same toolCall handling in src/agents/pi-embedded-helpers/turns.ts and the same error-turn skip in src/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.

  4. locked as resolved and limited conversation to collaborators on Apr 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions