Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

add anthropic web search result compatibility

Raine Virta5e112a7fe1be
diff --git a/README.md b/README.md
index 1799414..e9ee47f 100644
--- a/README.md
+++ b/README.md
@@ -267,7 +267,10 @@ the UI as `◐ medium · /effort`) is forwarded as Codex `reasoning.effort` (`lo
precedence and can also force `none`.
Claude Code's hosted `web_search_20250305` tool is translated to Codex's native
-Responses `web_search` tool, including non-empty domain filters.
+Responses `web_search` tool, including non-empty domain filters. Codex hosted
+search calls are emitted back to Claude Code as Anthropic `server_tool_use` and
+`web_search_tool_result` blocks with `usage.server_tool_use.web_search_requests`
+so Claude Code can account for completed searches.
Confirmed working on **Plus**:
diff --git a/src/anthropic/schema.ts b/src/anthropic/schema.ts
index b24d8e9..054fc5c 100644
--- a/src/anthropic/schema.ts
+++ b/src/anthropic/schema.ts
@@ -29,6 +29,29 @@ export interface AnthropicThinkingBlock {
signature?: string;
}
+export interface AnthropicServerToolUseBlock {
+ type: "server_tool_use";
+ id: string;
+ name: string;
+ input: unknown;
+}
+
+export interface AnthropicWebSearchResultBlock {
+ type: "web_search_result";
+ url: string;
+ title: string;
+ encrypted_content?: string;
+ page_age?: string | null;
+}
+
+export interface AnthropicWebSearchToolResultBlock {
+ type: "web_search_tool_result";
+ tool_use_id: string;
+ content:
+ | AnthropicWebSearchResultBlock[]
+ | { type: "web_search_tool_result_error"; error_code: string };
+}
+
export type AnthropicToolResultContentBlock =
| AnthropicTextBlock
| AnthropicImageBlock
@@ -42,7 +65,9 @@ export type AnthropicContentBlock =
| AnthropicImageBlock
| AnthropicToolUseBlock
| AnthropicToolResultBlock
- | AnthropicThinkingBlock;
+ | AnthropicThinkingBlock
+ | AnthropicServerToolUseBlock
+ | AnthropicWebSearchToolResultBlock;
export interface AnthropicMessage {
role: "user" | "assistant" | "system";
diff --git a/src/providers/codex/translate/accumulate.test.ts b/src/providers/codex/translate/accumulate.test.ts
new file mode 100644
index 0000000..c5433c6
--- /dev/null
+++ b/src/providers/codex/translate/accumulate.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "bun:test";
+import { accumulateResponse } from "./accumulate.ts";
+import { sse, silentLog, upstreamFromChunks } from "./test-helpers.ts";
+
+describe("accumulateResponse", () => {
+ it("returns Anthropic web search blocks and usage for Codex hosted web search", async () => {
+ const result = await accumulateResponse(
+ upstreamFromChunks([
+ sse("response.output_item.added", {
+ output_index: 0,
+ item: { type: "web_search_call", id: "ws_1", status: "in_progress" },
+ }),
+ sse("response.web_search_call.in_progress", { output_index: 0, item_id: "ws_1" }),
+ sse("response.web_search_call.searching", { output_index: 0, item_id: "ws_1" }),
+ sse("response.web_search_call.completed", { output_index: 0, item_id: "ws_1" }),
+ sse("response.output_item.done", {
+ output_index: 0,
+ item: {
+ type: "web_search_call",
+ id: "ws_1",
+ status: "completed",
+ action: {
+ type: "search",
+ query: "claude-code-proxy github",
+ queries: ["claude-code-proxy github"],
+ },
+ },
+ }),
+ sse("response.output_item.added", {
+ output_index: 1,
+ item: { type: "message", id: "msg_upstream" },
+ }),
+ sse("response.output_text.delta", {
+ output_index: 1,
+ delta:
+ "1. **TechRadar security article** - warns about malware.\n https://www.techradar.com/pro/security/example",
+ }),
+ sse("response.output_item.done", {
+ output_index: 1,
+ item: { type: "message", id: "msg_upstream" },
+ }),
+ sse("response.completed", { response: { id: "resp_1", usage: { input_tokens: 10 } } }),
+ ]),
+ { messageId: "msg_1", model: "gpt-5.5", log: silentLog },
+ );
+
+ expect(result.response.content).toEqual([
+ {
+ type: "server_tool_use",
+ id: "srvtoolu_ws_1",
+ name: "web_search",
+ input: { query: "claude-code-proxy github" },
+ },
+ {
+ type: "web_search_tool_result",
+ tool_use_id: "srvtoolu_ws_1",
+ content: [
+ {
+ type: "web_search_result",
+ title: "TechRadar security article",
+ url: "https://www.techradar.com/pro/security/example",
+ },
+ ],
+ },
+ {
+ type: "text",
+ text: "1. **TechRadar security article** - warns about malware.\n https://www.techradar.com/pro/security/example",
+ },
+ ]);
+ expect(result.response.usage.server_tool_use).toEqual({ web_search_requests: 1 });
+ });
+});
diff --git a/src/providers/codex/translate/accumulate.ts b/src/providers/codex/translate/accumulate.ts
index 627d949..7f30648 100644
--- a/src/providers/codex/translate/accumulate.ts
+++ b/src/providers/codex/translate/accumulate.ts
@@ -4,12 +4,13 @@ import type { Logger } from "../../../log.ts";
import type { TrafficCapture } from "../../types.ts";
import { attachTrafficCapture, createUpstreamStreamDiagnostics } from "./reducer.ts";
import {
- collectAnthropicContentFromAccumulatedBlocks,
AnthropicNonStreamResponse,
+ type AnthropicNonStreamContent,
createBlockAccumulator,
defaultAnthropicNonStreamUsage,
parseToolInputJsonOrRaw,
} from "../../translate/accumulate.ts";
+import { buildWebSearchCompatBlocks } from "./web-search-compat.ts";
export { UpstreamStreamError } from "./reducer.ts";
@@ -42,6 +43,7 @@ export async function accumulateResponse(
let continuationEligible = false;
let responseId: string | undefined;
let outputItems: FinishEvent["outputItems"] = [];
+ const webSearchEvents: Array<Extract<ReducerEvent, { kind: "web-search" }>> = [];
const diagnostics = attachTrafficCapture(createUpstreamStreamDiagnostics(), opts.traffic);
@@ -61,13 +63,16 @@ export async function accumulateResponse(
blockAccumulator.onToolDelta(e.index, e.partialJson);
break;
}
+ case "web-search":
+ webSearchEvents.push(e);
+ break;
case "text-stop":
case "tool-stop":
break;
case "finish":
stopReason = e.stopReason;
rawUsage = e.usage;
- usage = mapUsageToAnthropic(e.usage);
+ usage = mapUsageToAnthropic(e.usage, { webSearchRequests: e.webSearchRequests });
terminalType = e.terminalType;
continuationEligible = e.continuationEligible;
responseId = e.responseId;
@@ -76,18 +81,30 @@ export async function accumulateResponse(
}
}
- const content = collectAnthropicContentFromAccumulatedBlocks<AnthropicNonStreamResponse["content"][number]>(
- blockAccumulator.orderedBlocks(),
- {
- onText: (_index, text) => (text ? { type: "text", text } : undefined),
- onTool: (_index, id, name, args) => ({
- type: "tool_use",
- id,
- name,
- input: parseToolInputJsonOrRaw(args),
- }),
- },
- );
+ const accumulatedBlocks = blockAccumulator.orderedBlocks();
+ const text = accumulatedBlocks
+ .flatMap((block) => (block.kind === "text" ? [block.text] : []))
+ .join("");
+ const indexedContent: Array<{ index: number; content: AnthropicNonStreamContent }> = [
+ ...buildWebSearchCompatBlocks(webSearchEvents, text),
+ ];
+ for (const block of accumulatedBlocks) {
+ if (block.kind === "text") {
+ if (block.text)
+ indexedContent.push({ index: block.index, content: { type: "text", text: block.text } });
+ } else if (block.kind === "tool") {
+ indexedContent.push({
+ index: block.index,
+ content: {
+ type: "tool_use",
+ id: block.id,
+ name: block.name,
+ input: parseToolInputJsonOrRaw(block.args),
+ },
+ });
+ }
+ }
+ const content = indexedContent.sort((a, b) => a.index - b.index).map((item) => item.content);
return {
rawUsage,
diff --git a/src/providers/codex/translate/reducer.test.ts b/src/providers/codex/translate/reducer.test.ts
index cda3676..a529431 100644
--- a/src/providers/codex/translate/reducer.test.ts
+++ b/src/providers/codex/translate/reducer.test.ts
@@ -38,6 +38,7 @@ describe("reduceUpstream finish metadata", () => {
terminalType: "response.completed",
continuationEligible: true,
usage: { input_tokens: 3 },
+ webSearchRequests: 0,
responseId: "resp_1",
outputItems: [
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "hello" }] },
@@ -72,6 +73,7 @@ describe("reduceUpstream finish metadata", () => {
stopReason: "tool_use",
terminalType: "response.completed",
continuationEligible: true,
+ webSearchRequests: 0,
responseId: "resp_1",
outputItems: [
{
@@ -109,13 +111,21 @@ describe("reduceUpstream finish metadata", () => {
sse("response.completed", { response: { id: "resp_1", usage: { input_tokens: 3 } } }),
]);
- expect(out.filter((event) => event.kind === "progress").length).toBeGreaterThanOrEqual(4);
+ expect(out.filter((event) => event.kind === "progress").length).toBeGreaterThanOrEqual(3);
+ expect(out).toContainEqual({
+ kind: "web-search",
+ index: 0,
+ resultIndex: 1,
+ id: "srvtoolu_ws_1",
+ query: "",
+ });
expect(out.at(-1)).toEqual({
kind: "finish",
stopReason: "end_turn",
terminalType: "response.completed",
continuationEligible: true,
usage: { input_tokens: 3 },
+ webSearchRequests: 1,
responseId: "resp_1",
outputItems: [
{
@@ -159,6 +169,7 @@ describe("reduceUpstream finish metadata", () => {
terminalType: "response.incomplete",
continuationEligible: false,
usage: undefined,
+ webSearchRequests: 0,
responseId: undefined,
outputItems: [
{
@@ -186,6 +197,7 @@ describe("reduceUpstream finish metadata", () => {
stopReason: "end_turn",
terminalType: "response.done",
continuationEligible: true,
+ webSearchRequests: 0,
responseId: "resp_1",
outputItems: [],
});
@@ -208,6 +220,7 @@ describe("reduceUpstream finish metadata", () => {
stopReason: "max_tokens",
terminalType: "response.incomplete",
continuationEligible: false,
+ webSearchRequests: 0,
responseId: "resp_1",
outputItems: [],
});
diff --git a/src/providers/codex/translate/reducer.ts b/src/providers/codex/translate/reducer.ts
index 0f175cb..73e125d 100644
--- a/src/providers/codex/translate/reducer.ts
+++ b/src/providers/codex/translate/reducer.ts
@@ -5,6 +5,7 @@ import type { TrafficCapture } from "../../types.ts";
import type { TextToolReducerEvent } from "../../translate/accumulate.ts";
import { mapCachedInputUsageToAnthropicUsage } from "../../translate/accumulate.ts";
import type { ResponsesInputItem } from "./request.ts";
+import { serverToolUseIdFromCodexWebSearchId } from "./web-search-compat.ts";
export class UpstreamStreamError extends Error {
constructor(
@@ -31,12 +32,20 @@ export type ReducerEvent =
| TextToolReducerEvent
| { kind: "tool-progress"; index: number }
| { kind: "progress" }
+ | {
+ kind: "web-search";
+ index: number;
+ resultIndex: number;
+ id: string;
+ query: string;
+ }
| {
kind: "finish";
stopReason: StopReason;
terminalType: TerminalType;
continuationEligible: boolean;
usage: CodexUsage | undefined;
+ webSearchRequests: number;
responseId?: string;
outputItems: ResponsesInputItem[];
};
@@ -233,6 +242,7 @@ export async function* reduceUpstream(
let terminalType: TerminalType | undefined;
let continuationEligible = false;
let incomplete = false;
+ let webSearchRequests = 0;
function canFinishAfterClosedCompletedToolCall(err: unknown): boolean {
return (
@@ -431,6 +441,19 @@ export async function* reduceUpstream(
if (t === "response.output_item.done") {
const item = p.item;
+ if (item?.type === "web_search_call") {
+ const idx = anthropicIndex++;
+ const resultIndex = anthropicIndex++;
+ webSearchRequests += 1;
+ yield {
+ kind: "web-search",
+ index: idx,
+ resultIndex,
+ id: serverToolUseIdFromCodexWebSearchId(item.id),
+ query: webSearchQuery(item),
+ };
+ continue;
+ }
const state = blocksByOutputIndex.get(p.output_index);
if (!state) continue;
if (!item) {
@@ -530,11 +553,26 @@ export async function* reduceUpstream(
terminalType: terminalType ?? "response.incomplete",
continuationEligible,
usage: finalUsage,
+ webSearchRequests,
responseId,
outputItems,
};
}
+function webSearchQuery(item: unknown): string {
+ if (!item || typeof item !== "object") return "";
+ const action = (item as { action?: unknown }).action;
+ if (!action || typeof action !== "object") return "";
+ const query = (action as { query?: unknown }).query;
+ if (typeof query === "string") return query;
+ const queries = (action as { queries?: unknown }).queries;
+ if (Array.isArray(queries)) {
+ const first = queries.find((value): value is string => typeof value === "string");
+ return first ?? "";
+ }
+ return "";
+}
+
function isCodexWebSocketCloseError(err: unknown): boolean {
const message = err instanceof Error ? err.message : String(err);
return (
@@ -549,20 +587,28 @@ function upstreamReadError(err: unknown): Error {
return new UpstreamStreamError("failed", `Upstream stream read failed: ${message}`);
}
-export function mapUsageToAnthropic(u: CodexUsage | undefined): {
+export function mapUsageToAnthropic(
+ u: CodexUsage | undefined,
+ opts: { webSearchRequests?: number } = {},
+): {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens: number;
cache_read_input_tokens: number;
+ server_tool_use?: { web_search_requests?: number };
} {
// OpenAI-style usage reports cached prompt tokens inside input_tokens.
// Anthropic-style usage reports cache reads separately, and Claude Code
// sums input_tokens + cache_read_input_tokens when deciding context size.
// Subtract cached reads here so the downstream total matches the real
// prompt window instead of double-counting cached context.
- return mapCachedInputUsageToAnthropicUsage({
+ const usage = mapCachedInputUsageToAnthropicUsage({
inputTokens: u?.input_tokens,
outputTokens: u?.output_tokens,
cachedInputTokens: u?.input_tokens_details?.cached_tokens,
});
+ if (opts.webSearchRequests && opts.webSearchRequests > 0) {
+ usage.server_tool_use = { web_search_requests: opts.webSearchRequests };
+ }
+ return usage;
}
diff --git a/src/providers/codex/translate/stream.test.ts b/src/providers/codex/translate/stream.test.ts
index 63fe594..d4b29fc 100644
--- a/src/providers/codex/translate/stream.test.ts
+++ b/src/providers/codex/translate/stream.test.ts
@@ -73,6 +73,50 @@ function collectWithTime(chunks: string[]): Promise<string> {
);
}
+function webSearchChunks(): string[] {
+ return [
+ sse("response.output_item.added", {
+ output_index: 0,
+ item: { type: "web_search_call", id: "ws_1", status: "in_progress" },
+ }),
+ sse("response.web_search_call.in_progress", { output_index: 0, item_id: "ws_1" }),
+ sse("response.web_search_call.searching", { output_index: 0, item_id: "ws_1" }),
+ sse("response.web_search_call.completed", { output_index: 0, item_id: "ws_1" }),
+ sse("response.output_item.done", {
+ output_index: 0,
+ item: {
+ type: "web_search_call",
+ id: "ws_1",
+ status: "completed",
+ action: {
+ type: "search",
+ query: "claude-code-proxy github",
+ queries: ["claude-code-proxy github"],
+ },
+ },
+ }),
+ sse("response.output_item.added", {
+ output_index: 1,
+ item: { type: "message", id: "msg_upstream" },
+ }),
+ sse("response.output_text.delta", {
+ output_index: 1,
+ delta:
+ "1. **TechRadar security article** - warns about malware.\n https://www.techradar.com/pro/security/example\n",
+ }),
+ sse("response.output_text.delta", {
+ output_index: 1,
+ delta:
+ "2. **The Verge GitHub Claude/Codex agents article** - covers agents.\n https://www.theverge.com/news/873665/github-claude-codex-ai-agents",
+ }),
+ sse("response.output_item.done", {
+ output_index: 1,
+ item: { type: "message", id: "msg_upstream" },
+ }),
+ sse("response.completed", { response: { usage: { input_tokens: 10, output_tokens: 5 } } }),
+ ];
+}
+
describe("translateStream", () => {
it("emits keepalive pings while Read arguments are buffered", async () => {
const chunks = [
@@ -187,6 +231,25 @@ describe("translateStream", () => {
expect(output).not.toContain("event: error");
});
+ it("emits Anthropic web search blocks and usage for Codex hosted web search", async () => {
+ const output = await collectFromChunks(webSearchChunks());
+
+ expect(output).toContain('"type":"server_tool_use"');
+ expect(output).toContain('"id":"srvtoolu_ws_1"');
+ expect(output).toContain('"name":"web_search"');
+ expect(output).toContain('"partial_json":"{\\"query\\":\\"claude-code-proxy github\\"}"');
+ expect(output).toContain('"type":"web_search_tool_result"');
+ expect(output).toContain('"tool_use_id":"srvtoolu_ws_1"');
+ expect(output).toContain('"title":"TechRadar security article"');
+ expect(output).toContain('"url":"https://www.techradar.com/pro/security/example"');
+ expect(output).toContain('"web_search_requests":1');
+ expect(output).toContain("event: message_stop");
+ expect(output).not.toContain("event: error");
+ expect(output.indexOf('"type":"web_search_tool_result"')).toBeLessThan(
+ output.indexOf('"type":"text_delta"'),
+ );
+ });
+
it("fails buffered Read arguments that exceed the safe duration", async () => {
const chunks = readChunks(['{"file_path"', ':"/tmp/a"'], false);
diff --git a/src/providers/codex/translate/stream.ts b/src/providers/codex/translate/stream.ts
index 4d0e47c..83555bf 100644
--- a/src/providers/codex/translate/stream.ts
+++ b/src/providers/codex/translate/stream.ts
@@ -14,6 +14,7 @@ import {
type ReducerEvent,
} from "./reducer.ts";
import { emitMessageStart } from "../../shared/anthropic-sse.ts";
+import { buildWebSearchCompatBlocks } from "./web-search-compat.ts";
/**
* Translate a Codex Responses SSE stream into Anthropic SSE events.
@@ -51,6 +52,8 @@ export function translateStream(
let lastEmitAt = 0;
let lastEmitEvent: string | undefined;
let lastReducerEvent: string | undefined;
+ const webSearchEvents: Array<Extract<ReducerEvent, { kind: "web-search" }>> = [];
+ const deferredContentEvents: ReducerEvent[] = [];
const startedAt = Date.now();
const safeClose = () => {
if (closed) return;
@@ -112,61 +115,136 @@ export function translateStream(
messageStarted = true;
emitMessageStart(emit, { messageId: opts.messageId, model: opts.model });
};
+ const textFromDeferredContent = () =>
+ deferredContentEvents
+ .flatMap((event) => (event.kind === "text-delta" ? [event.text] : []))
+ .join("");
+ const emitWebSearchCompatBlocks = () => {
+ if (!webSearchEvents.length) return;
+ ensureMessageStart();
+ for (const block of buildWebSearchCompatBlocks(
+ webSearchEvents,
+ textFromDeferredContent(),
+ )) {
+ if (block.content.type === "server_tool_use") {
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: block.index,
+ content_block: {
+ type: "server_tool_use",
+ id: block.content.id,
+ name: block.content.name,
+ input: {},
+ },
+ });
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: block.index,
+ delta: {
+ type: "input_json_delta",
+ partial_json: JSON.stringify(block.content.input),
+ },
+ });
+ emit("content_block_stop", { type: "content_block_stop", index: block.index });
+ continue;
+ }
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: block.index,
+ content_block: block.content,
+ });
+ emit("content_block_stop", { type: "content_block_stop", index: block.index });
+ }
+ };
+ const isContentEvent = (event: ReducerEvent): boolean =>
+ event.kind === "text-start" ||
+ event.kind === "text-delta" ||
+ event.kind === "text-stop" ||
+ event.kind === "tool-start" ||
+ event.kind === "tool-delta" ||
+ event.kind === "tool-stop";
+ const emitContentEvent = (e: ReducerEvent) => {
+ switch (e.kind) {
+ case "text-start":
+ openBlocks.set(e.index, { type: "text" });
+ ensureMessageStart();
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: e.index,
+ content_block: { type: "text", text: "" },
+ });
+ break;
+ case "text-delta":
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: e.index,
+ delta: { type: "text_delta", text: e.text },
+ });
+ break;
+ case "text-stop":
+ openBlocks.delete(e.index);
+ emit("content_block_stop", { type: "content_block_stop", index: e.index });
+ break;
+ case "tool-start":
+ openBlocks.set(e.index, { type: "tool", id: e.id, name: e.name });
+ ensureMessageStart();
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: e.index,
+ content_block: {
+ type: "tool_use",
+ id: e.id,
+ name: e.name,
+ input: {},
+ },
+ });
+ break;
+ case "tool-delta":
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: e.index,
+ delta: { type: "input_json_delta", partial_json: e.partialJson },
+ });
+ break;
+ case "tool-stop":
+ openBlocks.delete(e.index);
+ emit("content_block_stop", { type: "content_block_stop", index: e.index });
+ break;
+ }
+ };
try {
for await (const e of reduceUpstream(upstream, opts.log, diagnostics)) {
lastReducerEvent = e.kind;
+ if (e.kind === "web-search") {
+ webSearchEvents.push(e);
+ continue;
+ }
+ if (webSearchEvents.length && isContentEvent(e)) {
+ deferredContentEvents.push(e);
+ continue;
+ }
switch (e.kind) {
case "text-start":
- openBlocks.set(e.index, { type: "text" });
- ensureMessageStart();
- emit("content_block_start", {
- type: "content_block_start",
- index: e.index,
- content_block: { type: "text", text: "" },
- });
- break;
case "text-delta":
- emit("content_block_delta", {
- type: "content_block_delta",
- index: e.index,
- delta: { type: "text_delta", text: e.text },
- });
- break;
case "text-stop":
- openBlocks.delete(e.index);
- emit("content_block_stop", { type: "content_block_stop", index: e.index });
- break;
case "tool-start":
- openBlocks.set(e.index, { type: "tool", id: e.id, name: e.name });
- ensureMessageStart();
- emit("content_block_start", {
- type: "content_block_start",
- index: e.index,
- content_block: {
- type: "tool_use",
- id: e.id,
- name: e.name,
- input: {},
- },
- });
- break;
case "tool-delta":
- emit("content_block_delta", {
- type: "content_block_delta",
- index: e.index,
- delta: { type: "input_json_delta", partial_json: e.partialJson },
- });
+ case "tool-stop":
+ emitContentEvent(e);
break;
case "tool-progress":
case "progress":
emitPingIfStale();
break;
- case "tool-stop":
- openBlocks.delete(e.index);
- emit("content_block_stop", { type: "content_block_stop", index: e.index });
- break;
case "finish":
+ if (openBlocks.size) {
+ throw new UpstreamStreamError("failed", "Stream finished with open content blocks");
+ }
+ emitWebSearchCompatBlocks();
+ for (const event of deferredContentEvents) {
+ emitContentEvent(event);
+ }
if (openBlocks.size) {
throw new UpstreamStreamError("failed", "Stream finished with open content blocks");
}
@@ -175,7 +253,9 @@ export function translateStream(
emit("message_delta", {
type: "message_delta",
delta: { stop_reason: e.stopReason, stop_sequence: null },
- usage: mapUsageToAnthropic(e.usage),
+ usage: mapUsageToAnthropic(e.usage, {
+ webSearchRequests: e.webSearchRequests,
+ }),
});
emit("message_stop", { type: "message_stop" });
break;
diff --git a/src/providers/codex/translate/web-search-compat.ts b/src/providers/codex/translate/web-search-compat.ts
new file mode 100644
index 0000000..02bd2b4
--- /dev/null
+++ b/src/providers/codex/translate/web-search-compat.ts
@@ -0,0 +1,119 @@
+export interface AnthropicWebSearchResult {
+ type: "web_search_result";
+ title: string;
+ url: string;
+ page_age?: string | null;
+}
+
+export interface AnthropicServerToolUseContent {
+ type: "server_tool_use";
+ id: string;
+ name: "web_search";
+ input: { query: string };
+}
+
+export interface AnthropicWebSearchToolResultContent {
+ type: "web_search_tool_result";
+ tool_use_id: string;
+ content: AnthropicWebSearchResult[];
+}
+
+export interface WebSearchCompatBlock {
+ index: number;
+ content: AnthropicServerToolUseContent | AnthropicWebSearchToolResultContent;
+}
+
+export function serverToolUseIdFromCodexWebSearchId(id: string | undefined): string {
+ const suffix = (id || crypto.randomUUID()).replace(/[^A-Za-z0-9_]/g, "_");
+ return `srvtoolu_${suffix}`;
+}
+
+export function extractWebSearchResultsFromText(text: string): AnthropicWebSearchResult[] {
+ const results = new Map<string, AnthropicWebSearchResult>();
+ for (const match of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g)) {
+ const title = cleanTitle(match[1] ?? "");
+ const url = cleanUrl(match[2] ?? "");
+ if (!url || results.has(url)) continue;
+ results.set(url, { type: "web_search_result", title: title || fallbackTitle(url), url });
+ }
+
+ for (const match of text.matchAll(/\bhttps?:\/\/[^\s<>"')\]]+/g)) {
+ const rawUrl = match[0] ?? "";
+ const url = cleanUrl(rawUrl);
+ if (!url || results.has(url)) continue;
+ const title = titleNearUrl(text, match.index ?? 0, url);
+ results.set(url, { type: "web_search_result", title: title || fallbackTitle(url), url });
+ }
+
+ return Array.from(results.values());
+}
+
+export function buildWebSearchCompatBlocks(
+ searches: Array<{ index: number; resultIndex: number; id: string; query: string }>,
+ text: string,
+): WebSearchCompatBlock[] {
+ const results = extractWebSearchResultsFromText(text);
+ return searches.flatMap((search) => [
+ {
+ index: search.index,
+ content: {
+ type: "server_tool_use" as const,
+ id: search.id,
+ name: "web_search" as const,
+ input: { query: search.query },
+ },
+ },
+ {
+ index: search.resultIndex,
+ content: {
+ type: "web_search_tool_result" as const,
+ tool_use_id: search.id,
+ content: results,
+ },
+ },
+ ]);
+}
+
+function cleanUrl(value: string): string {
+ let out = value.trim();
+ while (/[.,;:!?]$/.test(out)) out = out.slice(0, -1);
+ try {
+ return new URL(out).toString();
+ } catch {
+ return "";
+ }
+}
+
+function titleNearUrl(text: string, urlStart: number, url: string): string {
+ const before = text
+ .slice(0, urlStart)
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .filter((line) => !line.includes("http"))
+ .slice(-3)
+ .reverse();
+ for (const line of before) {
+ const title = cleanTitle(line);
+ if (title) return title;
+ }
+ return fallbackTitle(url);
+}
+
+function cleanTitle(value: string): string {
+ const noListMarker = value
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "")
+ .replace(/\*\*/g, "")
+ .replace(/`/g, "")
+ .trim();
+ const [prefix] = noListMarker.split(/\s(?:-|\u2013|\u2014)\s/);
+ return (prefix ?? noListMarker).trim();
+}
+
+function fallbackTitle(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
diff --git a/src/providers/cursor/translate/request.ts b/src/providers/cursor/translate/request.ts
index ec32422..d29c27e 100644
--- a/src/providers/cursor/translate/request.ts
+++ b/src/providers/cursor/translate/request.ts
@@ -91,6 +91,10 @@ function renderBlock(block: AnthropicContentBlock): string {
return `<tool_use id="${block.id}" name="${block.name}">\n${JSON.stringify(block.input ?? {})}\n</tool_use>`;
case "tool_result":
return `<tool_result tool_use_id="${block.tool_use_id}"${block.is_error ? ' is_error="true"' : ""}>\n${renderToolResult(block.content)}\n</tool_result>`;
+ case "server_tool_use":
+ return `<server_tool_use id="${block.id}" name="${block.name}">\n${JSON.stringify(block.input ?? {})}\n</server_tool_use>`;
+ case "web_search_tool_result":
+ return `<web_search_tool_result tool_use_id="${block.tool_use_id}">\n${JSON.stringify(block.content)}\n</web_search_tool_result>`;
}
}
diff --git a/src/providers/translate/accumulate.ts b/src/providers/translate/accumulate.ts
index 964e78c..30d5e66 100644
--- a/src/providers/translate/accumulate.ts
+++ b/src/providers/translate/accumulate.ts
@@ -38,16 +38,43 @@ export interface AnthropicNonStreamUsage {
output_tokens: number;
cache_creation_input_tokens: number;
cache_read_input_tokens: number;
+ server_tool_use?: {
+ web_search_requests?: number;
+ };
}
export type AnthropicTextContent = { type: "text"; text: string };
export type AnthropicThinkingContent = { type: "thinking"; thinking: string; signature: string };
-export type AnthropicToolUseContent = { type: "tool_use"; id: string; name: string; input: unknown };
+export type AnthropicToolUseContent = {
+ type: "tool_use";
+ id: string;
+ name: string;
+ input: unknown;
+};
+export type AnthropicServerToolUseContent = {
+ type: "server_tool_use";
+ id: string;
+ name: "web_search";
+ input: { query: string };
+};
+export type AnthropicWebSearchResultContent = {
+ type: "web_search_result";
+ title: string;
+ url: string;
+ page_age?: string | null;
+};
+export type AnthropicWebSearchToolResultContent = {
+ type: "web_search_tool_result";
+ tool_use_id: string;
+ content: AnthropicWebSearchResultContent[];
+};
export type AnthropicNonStreamContent =
| AnthropicTextContent
| AnthropicThinkingContent
- | AnthropicToolUseContent;
+ | AnthropicToolUseContent
+ | AnthropicServerToolUseContent
+ | AnthropicWebSearchToolResultContent;
export interface AnthropicNonStreamResponse<ContentType = AnthropicNonStreamContent> {
id: string;