fix: skip tool_use blocks with stopReason error in transcript repair

Fixes #1826

When an assistant message has stopReason: error, the tool_use blocks
within it are incomplete/terminated and were never actually executed.
The transcript repair mechanism was incorrectly creating synthetic
tool_results for these errored tool calls, causing all subsequent
API requests to fail with:

  invalid_request_error: unexpected tool_use_id found in tool_result blocks

Changes:
- Check stopReason before extracting tool calls in repairToolUseResultPairing()
- Skip tool call extraction when stopReason is error
- Prevents synthetic tool_results for incomplete/terminated tool calls

This ensures sessions remain usable after tool execution errors or
interruptions, without requiring manual JSONL editing.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
sid1943 2026-01-27 20:22:48 -05:00
parent 72a3046541
commit e7021c8119

View File

@ -116,6 +116,16 @@ export function repairToolUseResultPairing(messages: AgentMessage[]): ToolUseRep
}
const assistant = msg as Extract<AgentMessage, { role: "assistant" }>;
// Skip tool call extraction if the assistant turn errored/terminated.
// When stopReason is "error", the tool_use blocks are incomplete and were never executed,
// so we should not create synthetic tool_results for them.
const stopReason = (assistant as { stopReason?: unknown }).stopReason;
if (stopReason === "error") {
out.push(msg);
continue;
}
const toolCalls = extractToolCallsFromAssistant(assistant);
if (toolCalls.length === 0) {
out.push(msg);