Skip to content

Commit b758556

Browse files
authored
Merge pull request #383 from lidge-jun/fix/claude-websearch-domains
fix(claude): sanitize WebSearch domain filters for routed models
2 parents 3b766d9 + ed9e4ee commit b758556

2 files changed

Lines changed: 185 additions & 6 deletions

File tree

‎src/claude/outbound.ts‎

Lines changed: 91 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,43 @@ function sseFrame(name: string, data: Rec): string {
7676
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
7777
}
7878

79+
/**
80+
* Claude Code / Anthropic WebSearch domain filters are optional and mutually exclusive.
81+
* Empty arrays are rejected ("ambiguous"); both fields together are rejected. Routed models
82+
* often emit both shapes — sanitize before Claude Code sees the tool_use / server_tool_use
83+
* input (issue #381).
84+
*/
85+
export function isClaudeWebSearchToolName(name: string): boolean {
86+
const trimmed = name.trim();
87+
return trimmed === "WebSearch" || /^web_search/i.test(trimmed);
88+
}
89+
90+
function normalizeWebSearchDomainList(value: unknown): string[] | undefined {
91+
if (!Array.isArray(value)) return undefined;
92+
const domains = value
93+
.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0)
94+
.map(entry => entry.trim());
95+
return domains.length > 0 ? domains : undefined;
96+
}
97+
98+
/** Strip empty domain filters; if both remain, keep `allowed_domains` and drop `blocked_domains`. */
99+
export function sanitizeWebSearchInput(input: unknown): Rec {
100+
const src: Rec = isRec(input) ? { ...input } : {};
101+
const allowed = normalizeWebSearchDomainList(src.allowed_domains);
102+
const blocked = normalizeWebSearchDomainList(src.blocked_domains);
103+
delete src.allowed_domains;
104+
delete src.blocked_domains;
105+
if (allowed && blocked) {
106+
// Prefer allow-list (restrict-to) when a routed model sets both non-empty fields.
107+
src.allowed_domains = allowed;
108+
} else if (allowed) {
109+
src.allowed_domains = allowed;
110+
} else if (blocked) {
111+
src.blocked_domains = blocked;
112+
}
113+
return src;
114+
}
115+
79116
/**
80117
* Map a Responses `web_search_call` item to its Anthropic pair: the server_tool_use
81118
* input (query/queries) and the web_search_tool_result content (hits, or the error
@@ -87,7 +124,9 @@ function webSearchPairFromItem(item: Rec): { id: string; input: Rec; resultConte
87124
? action.queries.filter((q): q is string => typeof q === "string" && q.length > 0)
88125
: [];
89126
const query = typeof action.query === "string" ? action.query : "";
90-
const input: Rec = queries.length > 1 ? { queries } : { query: queries[0] ?? query };
127+
const input = sanitizeWebSearchInput(
128+
queries.length > 1 ? { queries } : { query: queries[0] ?? query },
129+
);
91130
const completed = item.status !== "failed";
92131
let resultContent: unknown;
93132
if (completed) {
@@ -125,6 +164,10 @@ interface OpenBlock {
125164
index: number;
126165
/** Responses item_id (tool calls) so output_item.done can match. */
127166
itemId?: string;
167+
/** Buffer WebSearch args and emit one sanitized input_json_delta on close (#381). */
168+
bufferWebSearchArgs?: boolean;
169+
argsBuf?: string;
170+
webSearchArgsEmitted?: boolean;
128171
}
129172

130173
/** Streaming: Responses SSE bytes -> Anthropic Messages SSE bytes. */
@@ -170,6 +213,19 @@ export function responsesSseToAnthropicSse(
170213
}
171214
const closeOpenBlock = () => {
172215
if (!open) return;
216+
if (open.kind === "tool_use" && open.bufferWebSearchArgs && !open.webSearchArgsEmitted) {
217+
// Emit sanitized args even if output_item.done never supplied a full arguments field
218+
// (finish/fail paths, or deltas-only streams).
219+
let parsed: unknown = {};
220+
const rawArgs = open.argsBuf ?? "";
221+
try { parsed = rawArgs.length > 0 ? JSON.parse(rawArgs) : {}; } catch { parsed = {}; }
222+
emit("content_block_delta", {
223+
type: "content_block_delta",
224+
index: open.index,
225+
delta: { type: "input_json_delta", partial_json: JSON.stringify(sanitizeWebSearchInput(parsed)) },
226+
});
227+
open.webSearchArgsEmitted = true;
228+
}
173229
if (open.kind === "thinking") {
174230
// Synthetic signature: Claude Code accepts it (003 E6); inbound drops replays anyway.
175231
emit("content_block_delta", {
@@ -253,21 +309,34 @@ export function responsesSseToAnthropicSse(
253309
closeOpenBlock();
254310
sawToolUse = true;
255311
const index = blockIndex++;
312+
const name = typeof item.name === "string" ? item.name : "";
313+
const bufferWebSearchArgs = isClaudeWebSearchToolName(name);
256314
emit("content_block_start", {
257315
type: "content_block_start", index,
258316
content_block: {
259317
type: "tool_use",
260318
id: typeof item.call_id === "string" ? item.call_id : `toolu_${uuid()}`,
261-
name: typeof item.name === "string" ? item.name : "",
319+
name,
262320
input: {},
263321
},
264322
});
265-
open = { kind: "tool_use", index, itemId: typeof item.id === "string" ? item.id : undefined };
323+
open = {
324+
kind: "tool_use",
325+
index,
326+
itemId: typeof item.id === "string" ? item.id : undefined,
327+
bufferWebSearchArgs,
328+
argsBuf: "",
329+
webSearchArgsEmitted: false,
330+
};
266331
break;
267332
}
268333
case "response.function_call_arguments.delta": {
269334
if (typeof data.delta !== "string" || data.delta.length === 0) break;
270335
if (!open || open.kind !== "tool_use") break;
336+
if (open.bufferWebSearchArgs) {
337+
open.argsBuf = `${open.argsBuf ?? ""}${data.delta}`;
338+
break;
339+
}
271340
emit("content_block_delta", {
272341
type: "content_block_delta", index: open.index,
273342
delta: { type: "input_json_delta", partial_json: data.delta },
@@ -307,7 +376,22 @@ export function responsesSseToAnthropicSse(
307376
if (!open) break;
308377
// Close the matching open block (message/reasoning items close implicitly on
309378
// the next block; function_call items must close here so tool input parses).
310-
if (open.kind === "tool_use" && item.type === "function_call") closeOpenBlock();
379+
if (open.kind === "tool_use" && item.type === "function_call") {
380+
if (open.bufferWebSearchArgs && !open.webSearchArgsEmitted) {
381+
const rawArgs = typeof item.arguments === "string" && item.arguments.length > 0
382+
? item.arguments
383+
: (open.argsBuf ?? "");
384+
let parsed: unknown = {};
385+
try { parsed = rawArgs.length > 0 ? JSON.parse(rawArgs) : {}; } catch { parsed = {}; }
386+
emit("content_block_delta", {
387+
type: "content_block_delta",
388+
index: open.index,
389+
delta: { type: "input_json_delta", partial_json: JSON.stringify(sanitizeWebSearchInput(parsed)) },
390+
});
391+
open.webSearchArgsEmitted = true;
392+
}
393+
closeOpenBlock();
394+
}
311395
else if (open.kind === "text" && item.type === "message") closeOpenBlock();
312396
else if (open.kind === "thinking" && item.type === "reasoning") closeOpenBlock();
313397
break;
@@ -442,11 +526,12 @@ export function responsesJsonToAnthropicMessage(json: unknown, model: string): R
442526
if (typeof raw.arguments === "string" && raw.arguments.length > 0) {
443527
try { input = JSON.parse(raw.arguments); } catch { input = {}; }
444528
}
529+
const name = typeof raw.name === "string" ? raw.name : "";
445530
content.push({
446531
type: "tool_use",
447532
id: typeof raw.call_id === "string" ? raw.call_id : `toolu_${uuid()}`,
448-
name: typeof raw.name === "string" ? raw.name : "",
449-
input,
533+
name,
534+
input: isClaudeWebSearchToolName(name) ? sanitizeWebSearchInput(input) : input,
450535
});
451536
break;
452537
}

‎tests/claude-outbound.test.ts‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
collectAnthropicMessage,
77
responsesJsonToAnthropicMessage,
88
responsesSseToAnthropicSse,
9+
sanitizeWebSearchInput,
910
} from "../src/claude/outbound";
1011

1112
function sse(name: string, data: Record<string, unknown>): string {
@@ -434,3 +435,96 @@ describe("claude outbound web_search translation", () => {
434435
expect(msg.usage.server_tool_use).toEqual({ web_search_requests: 1 });
435436
});
436437
});
438+
439+
describe("sanitizeWebSearchInput (#381)", () => {
440+
test("omits empty allowed_domains and blocked_domains arrays", () => {
441+
expect(sanitizeWebSearchInput({
442+
query: "CLAUDE.md practices",
443+
allowed_domains: ["code.claude.com"],
444+
blocked_domains: [],
445+
})).toEqual({
446+
query: "CLAUDE.md practices",
447+
allowed_domains: ["code.claude.com"],
448+
});
449+
expect(sanitizeWebSearchInput({
450+
query: "community",
451+
allowed_domains: [],
452+
blocked_domains: ["example.com"],
453+
})).toEqual({
454+
query: "community",
455+
blocked_domains: ["example.com"],
456+
});
457+
expect(sanitizeWebSearchInput({
458+
query: "open",
459+
allowed_domains: [],
460+
blocked_domains: [],
461+
})).toEqual({ query: "open" });
462+
});
463+
464+
test("keeps allowed_domains and drops blocked_domains when both are non-empty", () => {
465+
expect(sanitizeWebSearchInput({
466+
query: "docs",
467+
allowed_domains: ["code.claude.com"],
468+
blocked_domains: ["example.com"],
469+
})).toEqual({
470+
query: "docs",
471+
allowed_domains: ["code.claude.com"],
472+
});
473+
});
474+
475+
test("JSON path sanitizes WebSearch function_call arguments", () => {
476+
const msg = responsesJsonToAnthropicMessage({
477+
status: "completed",
478+
output: [{
479+
type: "function_call",
480+
call_id: "toolu_ws",
481+
name: "WebSearch",
482+
arguments: JSON.stringify({
483+
query: "site:code.claude.com memory",
484+
allowed_domains: ["code.claude.com"],
485+
blocked_domains: [],
486+
}),
487+
}],
488+
usage: { input_tokens: 3, output_tokens: 1 },
489+
}, "claude-ocx-native--gpt-5.6-sol") as Record<string, any>;
490+
expect(msg.stop_reason).toBe("tool_use");
491+
expect(msg.content[0]).toEqual({
492+
type: "tool_use",
493+
id: "toolu_ws",
494+
name: "WebSearch",
495+
input: {
496+
query: "site:code.claude.com memory",
497+
allowed_domains: ["code.claude.com"],
498+
},
499+
});
500+
});
501+
502+
test("SSE path buffers WebSearch args and emits one sanitized input_json_delta", async () => {
503+
const args = JSON.stringify({
504+
query: "CLAUDE.md token cost",
505+
allowed_domains: [],
506+
blocked_domains: ["example.com"],
507+
});
508+
const upstream = [
509+
sse("response.created", { response: {} }),
510+
sse("response.output_item.added", {
511+
output_index: 0,
512+
item: { type: "function_call", id: "fc_ws", call_id: "toolu_ws", name: "WebSearch", arguments: "", status: "in_progress" },
513+
}),
514+
sse("response.function_call_arguments.delta", { item_id: "fc_ws", output_index: 0, delta: args.slice(0, 20) }),
515+
sse("response.function_call_arguments.delta", { item_id: "fc_ws", output_index: 0, delta: args.slice(20) }),
516+
sse("response.output_item.done", {
517+
output_index: 0,
518+
item: { type: "function_call", id: "fc_ws", call_id: "toolu_ws", name: "WebSearch", arguments: args },
519+
}),
520+
sse("response.completed", { response: { status: "completed", usage: { input_tokens: 2, output_tokens: 1 } } }),
521+
].join("");
522+
const events = await collectEvents(responsesSseToAnthropicSse(streamFrom(upstream), "m"));
523+
const deltas = events.filter(e => e.name === "content_block_delta" && e.data.delta?.type === "input_json_delta");
524+
expect(deltas).toHaveLength(1);
525+
expect(JSON.parse(deltas[0].data.delta.partial_json)).toEqual({
526+
query: "CLAUDE.md token cost",
527+
blocked_domains: ["example.com"],
528+
});
529+
});
530+
});

0 commit comments

Comments
 (0)