Skip to content

Commit bcb82ca

Browse files
PierrunoYTclaude
andcommitted
fix(task): normalize tool_use/tool_result pairing in outgoing requests
Anthropic rejects requests where a tool_result is not directly after its tool_use, is preceded by other content, or has no matching tool_use. Shape the history sent to the API so results come first in tool_use order, interrupted calls get a synthetic error result, and orphan results are dropped, on every path rather than only after a summary. Fixes Zoo-Code-Org#2098 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent ca05b73 commit bcb82ca

3 files changed

Lines changed: 162 additions & 1 deletion

File tree

‎src/core/task/Task.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ import { type AutoDenyDetail, AutoApprovalHandler, checkAutoApproval } from "../
140140
import { MessageManager } from "../message-manager"
141141
import { validateAndFixToolResultIds } from "./validateToolResultIds"
142142
import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
143+
import { normalizeToolResultPairing } from "./normalizeToolResultPairing"
143144
import { prepareApiConversationMessage } from "./apiConversationHistory"
144145
import { shouldAddUserMessageToHistory } from "./messageCounting"
145146
import { type TaskExecutionContext } from "./providerHandoff"
@@ -5831,7 +5832,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
58315832
// For API only: merge consecutive user messages (excludes summary messages per
58325833
// mergeConsecutiveApiMessages implementation) without mutating stored history.
58335834
const mergedForApi = mergeConsecutiveApiMessages(messagesSinceLastSummary, { roles: ["user"] })
5834-
const messagesWithoutImages = maybeRemoveImageBlocks(mergedForApi, this.api)
5835+
const messagesWithoutImages = maybeRemoveImageBlocks(normalizeToolResultPairing(mergedForApi), this.api)
58355836
const cleanConversationHistory = this.buildCleanConversationHistory(
58365837
messagesWithoutImages as ApiMessage[],
58375838
requestModelInfo,
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import type { Anthropic } from "@anthropic-ai/sdk"
2+
3+
import type { ApiMessage } from "../../task-persistence"
4+
import { normalizeToolResultPairing } from "../normalizeToolResultPairing"
5+
6+
type Block = Anthropic.Messages.ContentBlockParam
7+
8+
const use = (id: string): Block => ({ type: "tool_use", id, name: "read_file", input: {} })
9+
const result = (id: string, content = `result ${id}`): Block => ({ type: "tool_result", tool_use_id: id, content })
10+
const text = (value: string): Block => ({ type: "text", text: value })
11+
const image: Block = { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } }
12+
const assistant = (...content: Block[]): ApiMessage => ({ role: "assistant", content })
13+
const user = (...content: Block[]): ApiMessage => ({ role: "user", content })
14+
15+
describe("normalizeToolResultPairing", () => {
16+
it("moves interleaved tool results ahead of other content", () => {
17+
const input = [
18+
user(text("go")),
19+
assistant(text("ok"), use("A"), use("B")),
20+
user(result("A"), image, result("B")),
21+
]
22+
23+
expect(normalizeToolResultPairing(input)[2].content).toEqual([result("A"), result("B"), image])
24+
})
25+
26+
it("orders results by tool_use order and drops duplicates", () => {
27+
const input = [assistant(use("A"), use("B")), user(result("B"), result("A"), result("A", "dup"))]
28+
29+
expect(normalizeToolResultPairing(input)[1].content).toEqual([result("A"), result("B")])
30+
})
31+
32+
it("adds a synthetic error result for an interrupted tool_use", () => {
33+
const input = [assistant(use("A"), use("B")), user(result("A"), text("next"))]
34+
35+
expect(normalizeToolResultPairing(input)[1].content).toEqual([
36+
result("A"),
37+
{ type: "tool_result", tool_use_id: "B", content: "Tool execution was interrupted before completion." },
38+
text("next"),
39+
])
40+
})
41+
42+
it("inserts a user turn when an assistant turn is followed by another assistant turn", () => {
43+
const out = normalizeToolResultPairing([assistant(use("A")), assistant(text("again"))])
44+
45+
expect(out.map((m) => m.role)).toEqual(["assistant", "user", "assistant"])
46+
expect(out[1].content).toMatchObject([{ type: "tool_result", tool_use_id: "A" }])
47+
})
48+
49+
it.each([
50+
{ name: "result for an unknown id", messages: [assistant(use("A")), user(result("A"), result("X"))] },
51+
{
52+
name: "result after a text-only assistant turn",
53+
messages: [assistant(text("hi")), user(result("X"), text("q"))],
54+
},
55+
])("drops orphan tool results: $name", ({ messages }) => {
56+
const ids = normalizeToolResultPairing(messages)
57+
.flatMap((m) => (Array.isArray(m.content) ? m.content : []))
58+
.flatMap((b) => (b.type === "tool_result" ? [b.tool_use_id] : []))
59+
60+
expect(ids).not.toContain("X")
61+
})
62+
63+
it("removes a user message that only held orphan results", () => {
64+
expect(normalizeToolResultPairing([assistant(text("hi")), user(result("X"))])).toHaveLength(1)
65+
})
66+
67+
it("leaves a trailing assistant tool_use and well-formed history unchanged", () => {
68+
const wellFormed = [user(text("go")), assistant(use("A")), user(result("A"), text("done")), assistant(use("B"))]
69+
70+
expect(normalizeToolResultPairing(wellFormed)).toEqual(wellFormed)
71+
})
72+
73+
it("does not mutate its input", () => {
74+
const input = [assistant(use("A")), user(image, result("A"))]
75+
const snapshot = structuredClone(input)
76+
77+
normalizeToolResultPairing(input)
78+
79+
expect(input).toEqual(snapshot)
80+
})
81+
})
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { Anthropic } from "@anthropic-ai/sdk"
2+
3+
import type { ApiMessage } from "../task-persistence"
4+
5+
type Block = Anthropic.Messages.ContentBlockParam
6+
type ToolResultBlock = Anthropic.Messages.ToolResultBlockParam
7+
8+
const INTERRUPTED_RESULT = "Tool execution was interrupted before completion."
9+
10+
function toBlocks(content: ApiMessage["content"]): Block[] {
11+
if (Array.isArray(content)) return content as Block[]
12+
if (content === undefined || content === null || content === "") return []
13+
return [{ type: "text", text: String(content) }]
14+
}
15+
16+
function toolUseIdsOf(message: ApiMessage): string[] {
17+
if (message.role !== "assistant" || !Array.isArray(message.content)) return []
18+
return (message.content as Block[]).flatMap((block) => (block.type === "tool_use" ? [block.id] : []))
19+
}
20+
21+
/**
22+
* Shapes outgoing history so tool results satisfy Anthropic's adjacency rule: every
23+
* `tool_use` in an assistant message is answered by a `tool_result` in the very next
24+
* user message, `tool_result` blocks come first, and no `tool_result` refers to a
25+
* `tool_use` outside the immediately preceding assistant message.
26+
*
27+
* - Results are moved ahead of other content, in `tool_use` order (duplicates dropped).
28+
* - Results without a matching `tool_use` are dropped.
29+
* - Interrupted calls get a synthetic error result.
30+
*
31+
* Used for API request shaping only; stored history is not mutated. A trailing assistant
32+
* message is left alone because its results have not been produced yet.
33+
*/
34+
export function normalizeToolResultPairing(messages: ApiMessage[]): ApiMessage[] {
35+
const out: ApiMessage[] = []
36+
37+
for (let i = 0; i < messages.length; i++) {
38+
const message = messages[i]
39+
40+
if (message.role === "assistant") {
41+
out.push(message)
42+
const toolUseIds = toolUseIdsOf(message)
43+
if (toolUseIds.length === 0 || i === messages.length - 1) continue
44+
45+
const next = messages[i + 1]
46+
const nextBlocks = next.role === "user" ? toBlocks(next.content) : []
47+
const resultsById = new Map<string, ToolResultBlock>()
48+
for (const block of nextBlocks) {
49+
if (block.type === "tool_result" && !resultsById.has(block.tool_use_id)) {
50+
resultsById.set(block.tool_use_id, block)
51+
}
52+
}
53+
54+
const results: ToolResultBlock[] = toolUseIds.map(
55+
(id) => resultsById.get(id) ?? { type: "tool_result", tool_use_id: id, content: INTERRUPTED_RESULT },
56+
)
57+
58+
if (next.role === "user") {
59+
const rest = nextBlocks.filter((block) => block.type !== "tool_result")
60+
out.push({ ...next, content: [...results, ...rest] })
61+
i++
62+
} else {
63+
// Another assistant message follows: answer the calls with a user turn of their own.
64+
out.push({ role: "user", content: results })
65+
}
66+
continue
67+
}
68+
69+
// A user message not directly after a tool_use turn cannot carry tool results.
70+
if (!Array.isArray(message.content) || !message.content.some((block) => block.type === "tool_result")) {
71+
out.push(message)
72+
continue
73+
}
74+
const kept = (message.content as Block[]).filter((block) => block.type !== "tool_result")
75+
if (kept.length > 0) out.push({ ...message, content: kept })
76+
}
77+
78+
return out
79+
}

0 commit comments

Comments
 (0)