Skip to content

Commit 16860ad

Browse files
committed
fix(anthropic): address CodeRabbit URL and tool-id review
Use pathname-based /v1/messages normalization without query/hash, static malformed-baseUrl errors, usableToolUseId for blank IDs, and EOF+stop_reason test coverage.
1 parent 0bb36b6 commit 16860ad

2 files changed

Lines changed: 74 additions & 7 deletions

File tree

‎src/adapters/anthropic.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -250,22 +250,34 @@ function usesNativeAnthropicEndpoint(provider: OcxProviderConfig): boolean {
250250
}
251251
}
252252

253+
const MALFORMED_ANTHROPIC_BASE_URL = "anthropic provider has malformed baseUrl";
254+
253255
/** Normalize provider baseUrl paths ending in `/`, `/v1`, or `/v1/messages` to `{origin}/v1/messages`. */
254256
export function anthropicMessagesUrl(baseUrl: string): string {
257+
let parsed: URL;
255258
try {
256-
new URL(baseUrl);
259+
parsed = new URL(baseUrl.trim());
257260
} catch {
258-
throw new Error(`anthropic provider has malformed baseUrl: ${baseUrl}`);
261+
throw new Error(MALFORMED_ANTHROPIC_BASE_URL);
262+
}
263+
if (parsed.search || parsed.hash) {
264+
throw new Error(MALFORMED_ANTHROPIC_BASE_URL);
259265
}
260-
const trimmed = baseUrl.trim().replace(/\/+$/, "");
261-
const root = trimmed.replace(/\/v1\/messages\/?$/i, "").replace(/\/v1\/?$/i, "").replace(/\/+$/, "");
262-
return `${root}/v1/messages`;
266+
let path = parsed.pathname.replace(/\/+$/, "");
267+
path = path.replace(/\/v1\/messages\/?$/i, "").replace(/\/v1\/?$/i, "").replace(/\/+$/, "");
268+
const suffix = path ? `${path}/v1/messages` : "/v1/messages";
269+
return `${parsed.origin}${suffix}`;
263270
}
264271

265272
function synthesizeToolUseId(): string {
266273
return `toolu_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
267274
}
268275

276+
function usableToolUseId(id: string | undefined): string {
277+
const trimmed = id?.trim();
278+
return trimmed || synthesizeToolUseId();
279+
}
280+
269281
function toolUseArguments(input: unknown): string {
270282
if (typeof input === "string") {
271283
const trimmed = input.trim();
@@ -802,7 +814,7 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti
802814
if (!block) break;
803815
currentBlockType = block.type;
804816
if (block.type === "tool_use") {
805-
currentToolCallId = block.id ?? synthesizeToolUseId();
817+
currentToolCallId = usableToolUseId(block.id);
806818
currentToolCallName = toolNames.fromWire(block.name ?? "");
807819
yield { type: "tool_call_start", id: currentToolCallId, name: currentToolCallName };
808820
}
@@ -897,7 +909,7 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti
897909
} else if (block.type === "redacted_thinking" && typeof block.data === "string") {
898910
events.push({ type: "redacted_thinking", data: block.data });
899911
} else if (block.type === "tool_use") {
900-
const id = block.id ?? synthesizeToolUseId();
912+
const id = usableToolUseId(block.id);
901913
events.push({ type: "tool_call_start", id, name: toolNames.fromWire(block.name ?? "") });
902914
events.push({ type: "tool_call_delta", arguments: toolUseArguments(block.input) });
903915
events.push({ type: "tool_call_end" });

‎tests/anthropic-stream-hardening.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,25 @@ describe("anthropicMessagesUrl", () => {
2121
] as const)("normalizes %s", (input, expected) => {
2222
expect(anthropicMessagesUrl(input)).toBe(expected);
2323
});
24+
25+
test("malformed baseUrl throws without echoing the URL", () => {
26+
const sensitive = "https://user:[email protected]/v1?token=abc";
27+
expect(() => anthropicMessagesUrl(sensitive)).toThrow("anthropic provider has malformed baseUrl");
28+
try {
29+
anthropicMessagesUrl(sensitive);
30+
} catch (err) {
31+
expect(String(err)).not.toContain("secret");
32+
expect(String(err)).not.toContain("token=abc");
33+
}
34+
});
35+
36+
test.each([
37+
"https://example.test/v1?tenant=a",
38+
"https://example.test/v1#frag",
39+
"https://example.test/v1/messages?stream=1",
40+
] as const)("rejects search/hash in %s", (input) => {
41+
expect(() => anthropicMessagesUrl(input)).toThrow("anthropic provider has malformed baseUrl");
42+
});
2443
});
2544

2645
describe("anthropic stream hardening", () => {
@@ -36,6 +55,18 @@ describe("anthropic stream hardening", () => {
3655
expect(events.some(e => e.type === "done")).toBe(false);
3756
});
3857

58+
test("EOF after message_delta stop_reason completes without message_stop", async () => {
59+
const response = new Response([
60+
"event: content_block_delta\n",
61+
'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hi"}}\n\n',
62+
"event: message_delta\n",
63+
'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}\n\n',
64+
].join(""));
65+
const events = await collect(createAnthropicAdapter(provider).parseStream(response));
66+
expect(events.at(-1)).toMatchObject({ type: "done", stopReason: "end_turn" });
67+
expect(events.some(e => e.type === "error")).toBe(false);
68+
});
69+
3970
test("input_json_delta outside tool_use is ignored", async () => {
4071
const response = new Response([
4172
"event: content_block_start\n",
@@ -67,6 +98,20 @@ describe("anthropic stream hardening", () => {
6798
expect(start && "id" in start && start.id.startsWith("toolu_")).toBe(true);
6899
});
69100

101+
test("whitespace tool_use id is treated as missing", async () => {
102+
const response = new Response([
103+
"event: content_block_start\n",
104+
'data: {"type":"content_block_start","content_block":{"type":"tool_use","id":" ","name":"get_weather"}}\n\n',
105+
"event: content_block_stop\n",
106+
'data: {"type":"content_block_stop"}\n\n',
107+
"event: message_stop\n",
108+
'data: {"type":"message_stop"}\n\n',
109+
].join(""));
110+
const events = await collect(createAnthropicAdapter(provider).parseStream(response));
111+
const start = events.find(e => e.type === "tool_call_start");
112+
expect(start && "id" in start && start.id.startsWith("toolu_")).toBe(true);
113+
});
114+
70115
test("empty EOF without content still errors", async () => {
71116
const response = new Response("");
72117
const events = await collect(createAnthropicAdapter(provider).parseStream(response));
@@ -88,4 +133,14 @@ describe("anthropic non-stream tool_use input", () => {
88133
});
89134
expect(events.at(-1)?.type).toBe("done");
90135
});
136+
137+
test("whitespace tool_use id synthesizes in non-stream response", async () => {
138+
const adapter = createAnthropicAdapter(provider);
139+
const events = await adapter.parseResponse!(new Response(JSON.stringify({
140+
content: [{ type: "tool_use", id: " ", name: "get_weather", input: {} }],
141+
stop_reason: "tool_use",
142+
})));
143+
const start = events.find(e => e.type === "tool_call_start");
144+
expect(start && "id" in start && start.id.startsWith("toolu_")).toBe(true);
145+
});
91146
});

0 commit comments

Comments
 (0)