Skip to content

Commit 5c5c64b

Browse files
xaeon2026frankekn
andauthored
Deduplicate repeated tool call IDs for OpenAI-compatible APIs (#40996)
Merged via squash. Prepared head SHA: 38d8048 Co-authored-by: xaeon2026 <[email protected]> Co-authored-by: frankekn <[email protected]> Reviewed-by: @frankekn
1 parent 9d3e653 commit 5c5c64b

7 files changed

Lines changed: 216 additions & 29 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Docs: https://docs.openclaw.ai
3232
- Models/openai-completions: default non-native OpenAI-compatible providers to omit tool-definition `strict` fields unless users explicitly opt back in, so tool calling keeps working on providers that reject that option. (#45497) Thanks @sahancava.
3333
- WhatsApp/reconnect: restore the append recency filter in the extension inbox monitor and handle protobuf `Long` timestamps correctly, so fresh post-reconnect append messages are processed while stale history sync stays suppressed. (#42588) thanks @MonkeyLeeT.
3434
- WhatsApp/login: wait for pending creds writes before reopening after Baileys `515` pairing restarts in both QR login and `channels login` flows, and keep the restart coverage pinned to the real wrapped error shape plus per-account creds queues. (#27910) Thanks @asyncjason.
35+
- Agents/openai-compatible tool calls: deduplicate repeated tool call ids across live assistant messages and replayed history so OpenAI-compatible backends no longer reject duplicate `tool_call_id` values with HTTP 400. (#40996) Thanks @xaeon2026.
3536

3637
### Fixes
3738

‎src/agents/pi-embedded-runner.sanitize-session-history.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@mariozechner/pi-agent-core";
22
import type { AssistantMessage, UserMessage, Usage } from "@mariozechner/pi-ai";
33
import { beforeEach, describe, expect, it, vi } from "vitest";
44
import {
5+
expectOpenAIResponsesStrictSanitizeCall,
56
loadSanitizeSessionHistoryWithCleanMocks,
67
makeMockSessionManager,
78
makeInMemorySessionManager,
@@ -247,7 +248,24 @@ describe("sanitizeSessionHistory", () => {
247248
expect(result).toEqual(mockMessages);
248249
});
249250

250-
it("passes simple user-only history through for openai-completions", async () => {
251+
it("sanitizes tool call ids for OpenAI-compatible responses providers", async () => {
252+
setNonGoogleModelApi();
253+
254+
await sanitizeSessionHistory({
255+
messages: mockMessages,
256+
modelApi: "openai-responses",
257+
provider: "custom",
258+
sessionManager: mockSessionManager,
259+
sessionId: TEST_SESSION_ID,
260+
});
261+
262+
expectOpenAIResponsesStrictSanitizeCall(
263+
mockedHelpers.sanitizeSessionMessagesImages,
264+
mockMessages,
265+
);
266+
});
267+
268+
it("sanitizes tool call ids for openai-completions", async () => {
251269
setNonGoogleModelApi();
252270

253271
const result = await sanitizeSessionHistory({

‎src/agents/pi-embedded-runner/run/attempt.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,26 @@ describe("wrapStreamFnTrimToolCallNames", () => {
702702
expect(finalToolCall.name).toBe("read");
703703
expect(finalToolCall.id).toBe("call_42");
704704
});
705+
706+
it("reassigns duplicate tool call ids within a message to unique fallbacks", async () => {
707+
const finalToolCallA = { type: "toolCall", name: " read ", id: " edit:22 " };
708+
const finalToolCallB = { type: "toolCall", name: " write ", id: "edit:22" };
709+
const finalMessage = { role: "assistant", content: [finalToolCallA, finalToolCallB] };
710+
const baseFn = vi.fn(() =>
711+
createFakeStream({
712+
events: [],
713+
resultMessage: finalMessage,
714+
}),
715+
);
716+
717+
const stream = await invokeWrappedStream(baseFn);
718+
await stream.result();
719+
720+
expect(finalToolCallA.name).toBe("read");
721+
expect(finalToolCallB.name).toBe("write");
722+
expect(finalToolCallA.id).toBe("edit:22");
723+
expect(finalToolCallB.id).toBe("call_auto_1");
724+
});
705725
});
706726

707727
describe("wrapStreamFnRepairMalformedToolCallArguments", () => {

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,7 @@ function normalizeToolCallIdsInMessage(message: unknown): void {
667667
}
668668

669669
let fallbackIndex = 1;
670+
const assignedIds = new Set<string>();
670671
for (const block of content) {
671672
if (!block || typeof block !== "object") {
672673
continue;
@@ -678,20 +679,23 @@ function normalizeToolCallIdsInMessage(message: unknown): void {
678679
if (typeof typedBlock.id === "string") {
679680
const trimmedId = typedBlock.id.trim();
680681
if (trimmedId) {
681-
if (typedBlock.id !== trimmedId) {
682-
typedBlock.id = trimmedId;
682+
if (!assignedIds.has(trimmedId)) {
683+
if (typedBlock.id !== trimmedId) {
684+
typedBlock.id = trimmedId;
685+
}
686+
assignedIds.add(trimmedId);
687+
continue;
683688
}
684-
usedIds.add(trimmedId);
685-
continue;
686689
}
687690
}
688691

689692
let fallbackId = "";
690-
while (!fallbackId || usedIds.has(fallbackId)) {
693+
while (!fallbackId || usedIds.has(fallbackId) || assignedIds.has(fallbackId)) {
691694
fallbackId = `call_auto_${fallbackIndex++}`;
692695
}
693696
typedBlock.id = fallbackId;
694697
usedIds.add(fallbackId);
698+
assignedIds.add(fallbackId);
695699
}
696700
}
697701

‎src/agents/tool-call-id.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,54 @@ const buildDuplicateIdCollisionInput = () =>
2929
},
3030
]);
3131

32+
const buildRepeatedRawIdInput = () =>
33+
castAgentMessages([
34+
{
35+
role: "assistant",
36+
content: [
37+
{ type: "toolCall", id: "edit:22", name: "edit", arguments: {} },
38+
{ type: "toolCall", id: "edit:22", name: "edit", arguments: {} },
39+
],
40+
},
41+
{
42+
role: "toolResult",
43+
toolCallId: "edit:22",
44+
toolName: "edit",
45+
content: [{ type: "text", text: "one" }],
46+
},
47+
{
48+
role: "toolResult",
49+
toolCallId: "edit:22",
50+
toolName: "edit",
51+
content: [{ type: "text", text: "two" }],
52+
},
53+
]);
54+
55+
const buildRepeatedSharedToolResultIdInput = () =>
56+
castAgentMessages([
57+
{
58+
role: "assistant",
59+
content: [
60+
{ type: "toolCall", id: "edit:22", name: "edit", arguments: {} },
61+
{ type: "toolCall", id: "edit:22", name: "edit", arguments: {} },
62+
],
63+
},
64+
{
65+
role: "toolResult",
66+
toolCallId: "edit:22",
67+
toolUseId: "edit:22",
68+
toolName: "edit",
69+
content: [{ type: "text", text: "one" }],
70+
},
71+
{
72+
role: "toolResult",
73+
toolCallId: "edit:22",
74+
toolUseId: "edit:22",
75+
toolName: "edit",
76+
content: [{ type: "text", text: "two" }],
77+
},
78+
]);
79+
3280
function expectCollisionIdsRemainDistinct(
3381
out: AgentMessage[],
3482
mode: "strict" | "strict9",
@@ -111,6 +159,26 @@ describe("sanitizeToolCallIdsForCloudCodeAssist", () => {
111159
expectCollisionIdsRemainDistinct(out, "strict");
112160
});
113161

162+
it("reuses one rewritten id when a tool result carries matching toolCallId and toolUseId", () => {
163+
const input = buildRepeatedSharedToolResultIdInput();
164+
165+
const out = sanitizeToolCallIdsForCloudCodeAssist(input);
166+
expect(out).not.toBe(input);
167+
const { aId, bId } = expectCollisionIdsRemainDistinct(out, "strict");
168+
const r1 = out[1] as Extract<AgentMessage, { role: "toolResult" }> & { toolUseId?: string };
169+
const r2 = out[2] as Extract<AgentMessage, { role: "toolResult" }> & { toolUseId?: string };
170+
expect(r1.toolUseId).toBe(aId);
171+
expect(r2.toolUseId).toBe(bId);
172+
});
173+
174+
it("assigns distinct IDs when identical raw tool call ids repeat", () => {
175+
const input = buildRepeatedRawIdInput();
176+
177+
const out = sanitizeToolCallIdsForCloudCodeAssist(input);
178+
expect(out).not.toBe(input);
179+
expectCollisionIdsRemainDistinct(out, "strict");
180+
});
181+
114182
it("caps tool call IDs at 40 chars while preserving uniqueness", () => {
115183
const longA = `call_${"a".repeat(60)}`;
116184
const longB = `call_${"a".repeat(59)}b`;
@@ -181,6 +249,16 @@ describe("sanitizeToolCallIdsForCloudCodeAssist", () => {
181249
expect(aId).not.toMatch(/[_-]/);
182250
expect(bId).not.toMatch(/[_-]/);
183251
});
252+
253+
it("assigns distinct strict IDs when identical raw tool call ids repeat", () => {
254+
const input = buildRepeatedRawIdInput();
255+
256+
const out = sanitizeToolCallIdsForCloudCodeAssist(input, "strict");
257+
expect(out).not.toBe(input);
258+
const { aId, bId } = expectCollisionIdsRemainDistinct(out, "strict");
259+
expect(aId).not.toMatch(/[_-]/);
260+
expect(bId).not.toMatch(/[_-]/);
261+
});
184262
});
185263

186264
describe("strict9 mode (Mistral tool call IDs)", () => {
@@ -231,5 +309,27 @@ describe("sanitizeToolCallIdsForCloudCodeAssist", () => {
231309
expect(aId.length).toBe(9);
232310
expect(bId.length).toBe(9);
233311
});
312+
313+
it("assigns distinct strict9 IDs when identical raw tool call ids repeat", () => {
314+
const input = buildRepeatedRawIdInput();
315+
316+
const out = sanitizeToolCallIdsForCloudCodeAssist(input, "strict9");
317+
expect(out).not.toBe(input);
318+
const { aId, bId } = expectCollisionIdsRemainDistinct(out, "strict9");
319+
expect(aId.length).toBe(9);
320+
expect(bId.length).toBe(9);
321+
});
322+
323+
it("reuses one rewritten strict9 id when a tool result carries matching toolCallId and toolUseId", () => {
324+
const input = buildRepeatedSharedToolResultIdInput();
325+
326+
const out = sanitizeToolCallIdsForCloudCodeAssist(input, "strict9");
327+
expect(out).not.toBe(input);
328+
const { aId, bId } = expectCollisionIdsRemainDistinct(out, "strict9");
329+
const r1 = out[1] as Extract<AgentMessage, { role: "toolResult" }> & { toolUseId?: string };
330+
const r2 = out[2] as Extract<AgentMessage, { role: "toolResult" }> & { toolUseId?: string };
331+
expect(r1.toolUseId).toBe(aId);
332+
expect(r2.toolUseId).toBe(bId);
333+
});
234334
});
235335
});

‎src/agents/tool-call-id.ts‎

Lines changed: 63 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,55 @@ function makeUniqueToolId(params: { id: string; used: Set<string>; mode: ToolCal
144144
return `${candidate.slice(0, MAX_LEN - ts.length)}${ts}`;
145145
}
146146

147+
function createOccurrenceAwareResolver(mode: ToolCallIdMode): {
148+
resolveAssistantId: (id: string) => string;
149+
resolveToolResultId: (id: string) => string;
150+
} {
151+
const used = new Set<string>();
152+
const assistantOccurrences = new Map<string, number>();
153+
const orphanToolResultOccurrences = new Map<string, number>();
154+
const pendingByRawId = new Map<string, string[]>();
155+
156+
const allocate = (seed: string): string => {
157+
const next = makeUniqueToolId({ id: seed, used, mode });
158+
used.add(next);
159+
return next;
160+
};
161+
162+
const resolveAssistantId = (id: string): string => {
163+
const occurrence = (assistantOccurrences.get(id) ?? 0) + 1;
164+
assistantOccurrences.set(id, occurrence);
165+
const next = allocate(occurrence === 1 ? id : `${id}:${occurrence}`);
166+
const pending = pendingByRawId.get(id);
167+
if (pending) {
168+
pending.push(next);
169+
} else {
170+
pendingByRawId.set(id, [next]);
171+
}
172+
return next;
173+
};
174+
175+
const resolveToolResultId = (id: string): string => {
176+
const pending = pendingByRawId.get(id);
177+
if (pending && pending.length > 0) {
178+
const next = pending.shift()!;
179+
if (pending.length === 0) {
180+
pendingByRawId.delete(id);
181+
}
182+
return next;
183+
}
184+
185+
const occurrence = (orphanToolResultOccurrences.get(id) ?? 0) + 1;
186+
orphanToolResultOccurrences.set(id, occurrence);
187+
return allocate(`${id}:tool_result:${occurrence}`);
188+
};
189+
190+
return { resolveAssistantId, resolveToolResultId };
191+
}
192+
147193
function rewriteAssistantToolCallIds(params: {
148194
message: Extract<AgentMessage, { role: "assistant" }>;
149-
resolve: (id: string) => string;
195+
resolveId: (id: string) => string;
150196
}): Extract<AgentMessage, { role: "assistant" }> {
151197
const content = params.message.content;
152198
if (!Array.isArray(content)) {
@@ -168,7 +214,7 @@ function rewriteAssistantToolCallIds(params: {
168214
) {
169215
return block;
170216
}
171-
const nextId = params.resolve(id);
217+
const nextId = params.resolveId(id);
172218
if (nextId === id) {
173219
return block;
174220
}
@@ -184,17 +230,22 @@ function rewriteAssistantToolCallIds(params: {
184230

185231
function rewriteToolResultIds(params: {
186232
message: Extract<AgentMessage, { role: "toolResult" }>;
187-
resolve: (id: string) => string;
233+
resolveId: (id: string) => string;
188234
}): Extract<AgentMessage, { role: "toolResult" }> {
189235
const toolCallId =
190236
typeof params.message.toolCallId === "string" && params.message.toolCallId
191237
? params.message.toolCallId
192238
: undefined;
193239
const toolUseId = (params.message as { toolUseId?: unknown }).toolUseId;
194240
const toolUseIdStr = typeof toolUseId === "string" && toolUseId ? toolUseId : undefined;
241+
const sharedRawId =
242+
toolCallId && toolUseIdStr && toolCallId === toolUseIdStr ? toolCallId : undefined;
195243

196-
const nextToolCallId = toolCallId ? params.resolve(toolCallId) : undefined;
197-
const nextToolUseId = toolUseIdStr ? params.resolve(toolUseIdStr) : undefined;
244+
const sharedResolvedId = sharedRawId ? params.resolveId(sharedRawId) : undefined;
245+
const nextToolCallId =
246+
sharedResolvedId ?? (toolCallId ? params.resolveId(toolCallId) : undefined);
247+
const nextToolUseId =
248+
sharedResolvedId ?? (toolUseIdStr ? params.resolveId(toolUseIdStr) : undefined);
198249

199250
if (nextToolCallId === toolCallId && nextToolUseId === toolUseIdStr) {
200251
return params.message;
@@ -219,21 +270,11 @@ export function sanitizeToolCallIdsForCloudCodeAssist(
219270
): AgentMessage[] {
220271
// Strict mode: only [a-zA-Z0-9]
221272
// Strict9 mode: only [a-zA-Z0-9], length 9 (Mistral tool call requirement)
222-
// Sanitization can introduce collisions (e.g. `a|b` and `a:b` -> `ab`).
223-
// Fix by applying a stable, transcript-wide mapping and de-duping via suffix.
224-
const map = new Map<string, string>();
225-
const used = new Set<string>();
226-
227-
const resolve = (id: string) => {
228-
const existing = map.get(id);
229-
if (existing) {
230-
return existing;
231-
}
232-
const next = makeUniqueToolId({ id, used, mode });
233-
map.set(id, next);
234-
used.add(next);
235-
return next;
236-
};
273+
// Sanitization can introduce collisions, and some providers also reject raw
274+
// duplicate tool-call IDs. Track assistant occurrences in-order so repeated
275+
// raw IDs receive distinct rewritten IDs, while matching tool results consume
276+
// the same rewritten IDs in encounter order.
277+
const { resolveAssistantId, resolveToolResultId } = createOccurrenceAwareResolver(mode);
237278

238279
let changed = false;
239280
const out = messages.map((msg) => {
@@ -244,7 +285,7 @@ export function sanitizeToolCallIdsForCloudCodeAssist(
244285
if (role === "assistant") {
245286
const next = rewriteAssistantToolCallIds({
246287
message: msg as Extract<AgentMessage, { role: "assistant" }>,
247-
resolve,
288+
resolveId: resolveAssistantId,
248289
});
249290
if (next !== msg) {
250291
changed = true;
@@ -254,7 +295,7 @@ export function sanitizeToolCallIdsForCloudCodeAssist(
254295
if (role === "toolResult") {
255296
const next = rewriteToolResultIds({
256297
message: msg as Extract<AgentMessage, { role: "toolResult" }>,
257-
resolve,
298+
resolveId: resolveToolResultId,
258299
});
259300
if (next !== msg) {
260301
changed = true;

‎src/agents/transcript-policy.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ export function resolveTranscriptPolicy(params: {
7878
provider,
7979
modelId,
8080
});
81-
const requiresOpenAiCompatibleToolIdSanitization = params.modelApi === "openai-completions";
81+
const requiresOpenAiCompatibleToolIdSanitization =
82+
params.modelApi === "openai-completions" ||
83+
(!isOpenAi &&
84+
(params.modelApi === "openai-responses" || params.modelApi === "openai-codex-responses"));
8285

8386
// Anthropic Claude endpoints can reject replayed `thinking` blocks unless the
8487
// original signatures are preserved byte-for-byte. Drop them at send-time to

0 commit comments

Comments
 (0)