Skip to content

fix(agents): handle stopReason 'aborted' in transcript repair to prevent session corruption #4597

@aisling404

Description

@aisling404

Summary

When an assistant message has stopReason: "aborted" (in addition to "error"), the repairToolUseResultPairing() function incorrectly creates synthetic tool_result entries for incomplete tool calls. This causes all subsequent API requests to fail with:

unexpected tool_use_id found in tool_result blocks: toolu_XXXXX.
Each tool_result block must have a corresponding tool_use block in the previous message.

Root Cause

When a request is aborted mid-stream:

  1. The assistant message is saved with stopReason: "aborted" and incomplete tool_use blocks (often with partialJson: true)
  2. repairToolUseResultPairing() sees a tool_use without a matching tool_result
  3. It creates a synthetic tool_result to "fix" the pairing
  4. During API serialization, the incomplete tool_use may be filtered out
  5. Result: orphaned tool_result → API rejects with 400 error

Evidence

A corrupted session had the following stopReason distribution:

  1 "stopReason":"aborted"    <-- caused the corruption
  3 "stopReason":"error"
121 "stopReason":"stop"
521 "stopReason":"toolUse"

The single "aborted" message corrupted the entire session.

Proposed Fix

Skip tool call extraction for assistant messages with stopReason: "error" OR stopReason: "aborted":

const stopReason = (assistant as { stopReason?: string }).stopReason;
if (stopReason === "error" || stopReason === "aborted") {
  out.push(msg);
  continue;
}

Related Issues

Impact

  • Without fix: Any aborted request during a tool call permanently corrupts the session
  • With fix: Sessions remain usable after interruptions

I have a PR ready with the fix and tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions