Skip to content

Commit 696413a

Browse files
committed
fix(anthropic): normalize tool call ids so cross-provider history replays
Anthropic validates `tool_use.id` against `[a-zA-Z0-9_-]`. The Anthropic adapter forwarded ids verbatim, so a transcript carrying ids minted by a different provider path failed the whole request with a 400 — and since the bad id stays in the history, every subsequent Anthropic request in that session fails too, until the user discards the conversation. The reported ids concatenate a Responses-style call id and item id with a literal newline, which alone is enough to fail validation: call_5sNzuhhhfcuN91ysezpcwXjp\nfc_0c71abbccafaad67016a803ba3007487... google.ts already solved this for the Antigravity path, where the backend translates Gemini requests into Anthropic messages. Rather than copy the logic, this lifts it into src/adapters/tool-call-id.ts and points both adapters at it — one transform is easier to keep correct than two that can drift. Applied to both sides of the pair in anthropic.ts: the `tool_use.id` and the matching `tool_result.tool_use_id`. The transform is deterministic, so ids that were equal at the source stay equal after normalization and the pairing survives. The synthetic "missing tool_result" filler reuses the already normalized ids collected in toolUseIds, so it needs no change. Conforming ids are returned unchanged, so ids minted by Anthropic itself round-trip untouched and existing behaviour is unaffected. Refs #1767
1 parent 8ea6c08 commit 696413a

4 files changed

Lines changed: 76 additions & 13 deletions

File tree

‎src/adapters/anthropic.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { IncomingMeta, ProviderAdapter } from "./base";
2+
import { anthropicToolCallId } from "./tool-call-id";
23
import { debugDroppedFrame } from "../lib/debug";
34
import type {
45
AdapterEvent,
@@ -573,7 +574,7 @@ function toAnthropicToolResult(msg: OcxToolResultMessage): Record<string, unknow
573574
}
574575
return {
575576
type: "tool_result",
576-
tool_use_id: msg.toolCallId,
577+
tool_use_id: anthropicToolCallId(msg.toolCallId) ?? msg.toolCallId,
577578
content,
578579
...(msg.isError ? { is_error: true } : {}),
579580
};
@@ -642,8 +643,11 @@ function messagesToAnthropicFormat(
642643
} else if (part.type === "toolCall") {
643644
const tc = part as OcxToolCall;
644645
const flatName = namespacedToolName(tc.namespace, tc.name);
645-
toolUseIds.push(tc.id);
646-
toolUses.push({ type: "tool_use", id: tc.id, name: toolNames.toWire(flatName), input: tc.arguments });
646+
// Normalized here, and identically for the matching tool_result above, so a history
647+
// replayed from another provider path keeps its call/result pairing (#1767).
648+
const wireCallId = anthropicToolCallId(tc.id) ?? tc.id;
649+
toolUseIds.push(wireCallId);
650+
toolUses.push({ type: "tool_use", id: wireCallId, name: toolNames.toWire(flatName), input: tc.arguments });
647651
}
648652
}
649653
// Anthropic treats text/thinking after tool_use as ending the tool turn, which makes

‎src/adapters/google.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { AdapterFetchContext, AdapterRequest, ProviderAdapter } from "./base";
22
import { debugDroppedFrame } from "../lib/debug";
3-
import { createHash } from "node:crypto";
3+
import { anthropicToolCallId } from "./tool-call-id";
44
import { createImageBudget, materializeInlineImage, MAX_ENCODED_BYTES_PER_IMAGE, artifactHttpUrl } from "../images/artifacts";
55
import type {
66
AdapterEvent,
@@ -94,15 +94,7 @@ function vertexReplaySessionId(parsed: OcxParsedRequest): string {
9494
* the call/response pairing is preserved. Returns `undefined` for an empty id so the caller omits the
9595
* field entirely rather than inventing a non-matching one.
9696
*/
97-
function geminiToolCallId(rawId: string | undefined): string | undefined {
98-
const raw = rawId ?? "";
99-
if (raw.length === 0) return undefined;
100-
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
101-
if (cleaned === raw) return cleaned;
102-
// Lossy rewrite happened: disambiguate with a deterministic suffix derived from the raw id.
103-
const suffix = createHash("sha256").update(raw).digest("hex").slice(0, 8);
104-
return `${cleaned}_${suffix}`;
105-
}
97+
const geminiToolCallId = anthropicToolCallId;
10698

10799
/**
108100
* Inline image parts (Gemini `inline_data`) extracted from tool-result content. Only base64 data URLs

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { createHash } from "node:crypto";
2+
3+
/**
4+
* Normalize a tool call id into the character set Anthropic accepts.
5+
*
6+
* Anthropic validates `tool_use.id` against `[a-zA-Z0-9_-]`, so non-conforming characters are mapped
7+
* to `_`. To keep the mapping injective (so two distinct raw ids like `call:a` and `call/a` cannot
8+
* collide into one `tool_use.id` within a request), a short hash of the original raw id is appended
9+
* whenever any character had to be rewritten. The transform is deterministic, so a call id and its
10+
* matching result id — equal at the source, since the client pairs them — still normalize identically
11+
* and the call/result pairing is preserved. Returns `undefined` for an empty id so the caller can omit
12+
* the field entirely rather than inventing a non-matching one.
13+
*
14+
* Ids that already conform are returned unchanged, which is the common case: ids minted by Anthropic
15+
* itself round-trip untouched.
16+
*/
17+
export function anthropicToolCallId(rawId: string | undefined): string | undefined {
18+
const raw = rawId ?? "";
19+
if (raw.length === 0) return undefined;
20+
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
21+
if (cleaned === raw) return cleaned;
22+
// Lossy rewrite happened: disambiguate with a deterministic suffix derived from the raw id.
23+
const suffix = createHash("sha256").update(raw).digest("hex").slice(0, 8);
24+
return `${cleaned}_${suffix}`;
25+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { anthropicToolCallId } from "../src/adapters/tool-call-id";
3+
4+
// #1767: Anthropic validates tool_use.id against [a-zA-Z0-9_-]. A history replayed from another
5+
// provider path can carry ids that do not conform, and one of them anywhere in the transcript
6+
// fails the whole request with a 400.
7+
describe("anthropicToolCallId", () => {
8+
test("leaves a conforming id untouched", () => {
9+
expect(anthropicToolCallId("call_5sNzuhhhfcuN91ysezpcwXjp")).toBe("call_5sNzuhhhfcuN91ysezpcwXjp");
10+
expect(anthropicToolCallId("call-9f1c2d3e-4")).toBe("call-9f1c2d3e-4");
11+
expect(anthropicToolCallId("toolu_01A2b3C4")).toBe("toolu_01A2b3C4");
12+
});
13+
14+
test("rewrites the composite id from the report", () => {
15+
const raw = "call_5sNzuhhhfcuN91ysezpcwXjp\nfc_0c71abbccafaad67016a803ba3007487d2afa509a7ca8c9687";
16+
const out = anthropicToolCallId(raw)!;
17+
18+
expect(out).toMatch(/^[a-zA-Z0-9_-]+$/);
19+
expect(out).not.toContain("\n");
20+
expect(out.startsWith("call_5sNzuhhhfcuN91ysezpcwXjp_fc_")).toBe(true);
21+
});
22+
23+
test("is deterministic, so a call and its result still pair up", () => {
24+
const raw = "call:a/b c";
25+
expect(anthropicToolCallId(raw)).toBe(anthropicToolCallId(raw));
26+
});
27+
28+
test("keeps distinct raw ids distinct after rewriting", () => {
29+
// Without the hash suffix both of these would collapse to "call_a".
30+
const a = anthropicToolCallId("call:a");
31+
const b = anthropicToolCallId("call/a");
32+
33+
expect(a).not.toBe(b);
34+
expect(a).toMatch(/^[a-zA-Z0-9_-]+$/);
35+
expect(b).toMatch(/^[a-zA-Z0-9_-]+$/);
36+
});
37+
38+
test("returns undefined for an empty id so the caller can omit the field", () => {
39+
expect(anthropicToolCallId("")).toBeUndefined();
40+
expect(anthropicToolCallId(undefined)).toBeUndefined();
41+
});
42+
});

0 commit comments

Comments
 (0)