@mupt-ai/dari-gateway 1.0.319 → 1.0.320

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/ingress/anthropic_messages.js +14 -2
  2. package/dist/interaction/capabilities.d.ts +3 -1
  3. package/dist/interaction/capabilities.js +10 -0
  4. package/dist/interaction/types.d.ts +5 -3
  5. package/dist/link/endpoints.js +23 -4
  6. package/dist/link/self_hosted.js +2 -0
  7. package/dist/link/service.d.ts +6 -0
  8. package/dist/link/service.js +3 -0
  9. package/dist/protocol/input/anthropic_messages.js +18 -1
  10. package/dist/protocol/output/anthropic_messages_output.js +7 -0
  11. package/dist/protocol/output/anthropic_messages_stream.js +29 -9
  12. package/dist/providers/anthropic_safeguards.d.ts +1 -0
  13. package/dist/providers/anthropic_safeguards.js +14 -7
  14. package/dist/providers/anthropic_web_search.d.ts +16 -0
  15. package/dist/providers/anthropic_web_search.js +67 -0
  16. package/dist/providers/pi.js +15 -4
  17. package/dist/providers/pi_context.js +15 -1
  18. package/dist/providers/pi_options.js +5 -0
  19. package/dist/providers/pi_output.js +13 -0
  20. package/package.json +2 -2
  21. package/src/ingress/anthropic_messages.ts +14 -2
  22. package/src/interaction/capabilities.ts +16 -1
  23. package/src/interaction/types.ts +10 -3
  24. package/src/link/endpoints.ts +25 -4
  25. package/src/link/self_hosted.ts +2 -0
  26. package/src/link/service.ts +9 -0
  27. package/src/protocol/input/anthropic_messages.ts +17 -1
  28. package/src/protocol/output/anthropic_messages_output.ts +6 -0
  29. package/src/protocol/output/anthropic_messages_stream.ts +30 -7
  30. package/src/providers/anthropic_safeguards.ts +19 -9
  31. package/src/providers/anthropic_web_search.ts +99 -0
  32. package/src/providers/pi.ts +23 -4
  33. package/src/providers/pi_context.ts +14 -1
  34. package/src/providers/pi_options.ts +5 -0
  35. package/src/providers/pi_output.ts +13 -0
@@ -6,12 +6,14 @@ import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.
6
6
  import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../link/errors.js";
7
7
  import { captureRequestError } from "../observability/errors.js";
8
8
  import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
9
- import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
9
+ import { CANONICAL_ROUTER_MODEL, explicitModelId, isLinkToken, linkTokenModel } from "../protocol/input/router_model.js";
10
10
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
11
11
  import { claudeCodeRequestContext } from "./claude_code/request_context.js";
12
12
  import { claimedClientHarness } from "./client_harness.js";
13
13
  import { claudeCodeConversationIdentity, } from "../runtime/harness_identity/index.js";
14
14
  import { parseJsonRequest } from "./json.js";
15
+ import { anthropicWebSearchTool } from "../interaction/capabilities.js";
16
+ import { isBackgroundRequest } from "../interaction/types.js";
15
17
  const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
16
18
  const SAFEGUARDS_BETA_PREFIX = "dangerous-tool-use-";
17
19
  const CONTEXT_MANAGEMENT_BETA_PREFIX = "context-management-";
@@ -23,8 +25,18 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
23
25
  const isClaudeCode = isClaudeCodeRequest(request.headers);
24
26
  const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
25
27
  const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
28
+ const agentContext = isClaudeCode ? claudeCodeRequestContext(request.headers) : undefined;
29
+ // Claude Code runs a web search as a background request that names one of
30
+ // the session's models. Like its other background work, Dari serves it on
31
+ // the cheapest model that can: a Claude model on Anthropic's API. A Dari
32
+ // Link token keeps the model it names.
33
+ const backgroundWebSearch = agentContext !== undefined
34
+ && isBackgroundRequest({ ...interaction, agentContext })
35
+ && anthropicWebSearchTool(interaction) !== undefined
36
+ && !isLinkToken(apiKey);
26
37
  const forwarded = {
27
38
  ...interaction,
39
+ ...(backgroundWebSearch ? { model: CANONICAL_ROUTER_MODEL } : {}),
28
40
  ...(anthropicSafeguards === undefined ? {} : { anthropicSafeguards }),
29
41
  ...(anthropicContextManagement === undefined ? {} : { anthropicContextManagement }),
30
42
  };
@@ -32,7 +44,7 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
32
44
  ? {
33
45
  ...forwarded,
34
46
  reasoning: routedReasoning(forwarded),
35
- agentContext: claudeCodeRequestContext(request.headers),
47
+ agentContext: agentContext,
36
48
  // Native tool results may be followed by harness-injected text.
37
49
  // Preserve their structural continuation semantics, not prompt inference.
38
50
  ...(latestMessageHasToolResult(rawPayload.messages)
@@ -1,4 +1,6 @@
1
1
  import type { HardCapability } from "@mupt-ai/dari-router/policy-engine";
2
- import type { InteractionRequest } from "./types.js";
2
+ import type { AnthropicWebSearchToolType, InteractionRequest, ServerTool } from "./types.js";
3
+ export declare function isAnthropicWebSearchToolType(type: string): type is AnthropicWebSearchToolType;
4
+ export declare function anthropicWebSearchTool(request: Pick<InteractionRequest, "tools">): ServerTool | undefined;
3
5
  export declare function requiredCapabilitiesFor(request: Pick<InteractionRequest, "items" | "responseFormat" | "toolChoice" | "tools">): HardCapability[];
4
6
  export declare function requestHasDocument(request: Pick<InteractionRequest, "items">): boolean;
@@ -1,3 +1,11 @@
1
+ export function isAnthropicWebSearchToolType(type) {
2
+ return /^web_search_\d{8}$/.test(type);
3
+ }
4
+ // The request's Anthropic web search tool. Anthropic runs it inside the Claude
5
+ // API, so only a Claude model there can serve the request.
6
+ export function anthropicWebSearchTool(request) {
7
+ return request.tools.find((tool) => tool.kind === "server_tool" && isAnthropicWebSearchToolType(tool.type));
8
+ }
1
9
  export function requiredCapabilitiesFor(request) {
2
10
  const capabilities = new Set();
3
11
  if (request.items.some(itemHasImage))
@@ -12,6 +20,8 @@ export function requiredCapabilitiesFor(request) {
12
20
  || (typeof request.toolChoice === "object" && request.toolChoice.kind === "hosted")) {
13
21
  capabilities.add("openai_hosted_web_search");
14
22
  }
23
+ if (anthropicWebSearchTool(request) !== undefined)
24
+ capabilities.add("anthropic_web_search");
15
25
  return [...capabilities];
16
26
  }
17
27
  function requiresWebSearch(item) {
@@ -90,8 +90,8 @@ export type InteractionReasoningConfiguration = {
90
90
  export type InteractionHostedToolCall = {
91
91
  type: "hosted_tool_call";
92
92
  id: string;
93
- tool: "web_search" | "server_tool_use" | "tool_search";
94
- providerType: "web_search_call" | "server_tool_use" | "tool_search_result";
93
+ tool: "web_search" | "server_tool_use" | "tool_search" | "web_search_result";
94
+ providerType: "web_search_call" | "server_tool_use" | "tool_search_result" | "web_search_tool_result";
95
95
  status?: "in_progress" | "searching" | "completed" | "incomplete" | "failed";
96
96
  payload: Record<string, unknown>;
97
97
  source?: ProviderIdentity;
@@ -107,7 +107,8 @@ export type InteractionCompaction = {
107
107
  };
108
108
  export type InteractionItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionToolResult | InteractionReasoningConfiguration | InteractionHostedToolCall;
109
109
  export type InteractionOutputItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionHostedToolCall;
110
- export type ServerToolKind = "bash_20250124" | "text_editor_20250124" | "tool_search_tool_20250919" | "tool_search_tool_regex_20250919" | "tool_search_tool_regex" | "tool_search_tool_regex_20251119" | "tool_search_tool_bm25" | "tool_search_tool_bm25_20251119";
110
+ export type ServerToolKind = "bash_20250124" | "text_editor_20250124" | "tool_search_tool_20250919" | "tool_search_tool_regex_20250919" | "tool_search_tool_regex" | "tool_search_tool_regex_20251119" | "tool_search_tool_bm25" | "tool_search_tool_bm25_20251119" | AnthropicWebSearchToolType;
111
+ export type AnthropicWebSearchToolType = `web_search_${number}`;
111
112
  export type ClientTool = {
112
113
  kind: "client_tool";
113
114
  name: string;
@@ -140,6 +141,7 @@ export type ServerTool = {
140
141
  name: string;
141
142
  type: ServerToolKind;
142
143
  description?: string;
144
+ definition?: Record<string, unknown>;
143
145
  };
144
146
  export type InteractionTool = FunctionTool | CustomTool | HostedTool | ServerTool | ClientTool;
145
147
  export type InteractionToolChoice = "none" | "auto" | "required" | "any" | {
@@ -284,9 +284,10 @@ async function registerApp(link, request) {
284
284
  { ...appBody(app), ...(app.clientSecret === undefined ? {} : { client_secret: app.clientSecret }) }, { status: 201, headers: { "Cache-Control": "no-store" } });
285
285
  }
286
286
  let registrationWindow = { startedAt: 0, count: 0 };
287
- // RFC 7591: any app registers itself with no key: a public client (PKCE, no
288
- // secret), or with `client_secret_basic` a confidential one, whose secret is
289
- // returned this once. Either way the user still approves every grant.
287
+ // RFC 7591: an app registers itself: a public client (PKCE, no secret), or with
288
+ // `client_secret_basic` a confidential one, whose secret is returned this once.
289
+ // Either way the user still approves every grant. Hosted Dari needs the
290
+ // organization's key as a Bearer token, so the app belongs to that organization.
290
291
  async function registerClient(link, request) {
291
292
  const now = Date.now();
292
293
  if (now - registrationWindow.startedAt >= 60_000)
@@ -323,8 +324,26 @@ async function registerClient(link, request) {
323
324
  return registrationError(error.code, error.message);
324
325
  throw error;
325
326
  }
327
+ let app;
328
+ try {
329
+ app = await link.registerApp({
330
+ ...client,
331
+ // No header is no key; a malformed one is refused.
332
+ apiKey: request.headers.has("authorization") ? bearerToken(request.headers) : undefined,
333
+ confidential: authMethod === "client_secret_basic",
334
+ });
335
+ }
336
+ catch (error) {
337
+ // A refused request is the caller's to fix; a server failure goes to the
338
+ // same masked response as every other Link request.
339
+ if (error instanceof HttpError && error.status < 500) {
340
+ return Response.json({ error: error.code, error_description: error.message }, { status: error.status, headers: { "Cache-Control": "no-store" } });
341
+ }
342
+ throw error;
343
+ }
344
+ // Only apps actually created count against the cap, so refused keys cannot
345
+ // exhaust it for everyone else.
326
346
  registrationWindow.count += 1;
327
- const app = await link.registerApp({ ...client, confidential: authMethod === "client_secret_basic" });
328
347
  return Response.json({
329
348
  client_id: app.clientId,
330
349
  // The secret is shown this once; only its hash is stored.
@@ -39,6 +39,8 @@ export function selfHostedLink(deps) {
39
39
  const newSubject = () => `lu_${randomUUID().replaceAll("-", "")}`;
40
40
  return linkPlatform(deps.links, {
41
41
  httpRedirectHosts: deps.config.link?.allowHttpRedirectHosts ?? [],
42
+ // A self-hosted gateway's operator owns its apps; registration stays open.
43
+ openRegistration: true,
42
44
  sessionSecret: () => sessionSecret,
43
45
  connectable: SUBSCRIPTION_PROVIDERS,
44
46
  keyProviders,
@@ -52,6 +52,12 @@ export type LinkUsers = {
52
52
  keyProviders: readonly LinkKeyProvider[];
53
53
  /** See `LinkPlatform.httpRedirectHosts`. */
54
54
  httpRedirectHosts?: readonly string[];
55
+ /**
56
+ * Whether an app may register with no API key (RFC 7591). Hosted Dari says no,
57
+ * so every app belongs to an organization; a self-hosted gateway's operator
58
+ * decides.
59
+ */
60
+ openRegistration: boolean;
55
61
  /**
56
62
  * Store a registered app; with `apiKey`, owned by whoever that key is.
57
63
  * Throws HttpError(401 or 403) for a key that may not register apps.
@@ -105,6 +105,9 @@ export function linkPlatform(store, users) {
105
105
  },
106
106
  },
107
107
  async registerApp({ apiKey, name, redirectUris, confidential }) {
108
+ if (apiKey === undefined && !users.openRegistration) {
109
+ throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
110
+ }
108
111
  const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
109
112
  const app = {
110
113
  clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
@@ -1,5 +1,6 @@
1
1
  import { isReasoningEffort, isRecord } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { HttpError } from "../../http/errors.js";
3
+ import { isAnthropicWebSearchToolType } from "../../interaction/capabilities.js";
3
4
  import { parseDataImageUrl } from "../../interaction/image.js";
4
5
  import { decodeUntrustedProviderContinuationState } from "../../interaction/provider_continuation_state.js";
5
6
  import { decodeUntrustedPortableReasoningState } from "../../interaction/portable_reasoning_state.js";
@@ -15,7 +16,7 @@ const SUPPORTED_SERVER_TOOL_TYPES = [
15
16
  "tool_search_tool_bm25",
16
17
  "tool_search_tool_bm25_20251119",
17
18
  ];
18
- const isServerToolType = (type) => SUPPORTED_SERVER_TOOL_TYPES.includes(type);
19
+ const isServerToolType = (type) => SUPPORTED_SERVER_TOOL_TYPES.includes(type) || isAnthropicWebSearchToolType(type);
19
20
  export function anthropicMessagesToInteraction(payload) {
20
21
  const model = requiredString(payload.model, "model");
21
22
  if (!isAnthropicRouterModel(model) && explicitModelId(model) === null) {
@@ -197,6 +198,21 @@ function appendAnthropicMessage(items, role, value, messageIndex) {
197
198
  });
198
199
  continue;
199
200
  }
201
+ if (type === "web_search_tool_result") {
202
+ if (role !== "assistant")
203
+ throw invalidRequest("web_search_tool_result blocks require the assistant role.", param);
204
+ flushMessage();
205
+ const toolUseId = requiredString(rawBlock.tool_use_id, `${param}.tool_use_id`);
206
+ items.push({
207
+ type: "hosted_tool_call",
208
+ id: `${toolUseId}_result`,
209
+ tool: "web_search_result",
210
+ providerType: "web_search_tool_result",
211
+ payload: { tool_use_id: toolUseId, content: rawBlock.content },
212
+ serverToolUseId: toolUseId,
213
+ });
214
+ continue;
215
+ }
200
216
  if (type === "tool_result") {
201
217
  if (role !== "user")
202
218
  throw invalidRequest("tool_result blocks require the user role.", param);
@@ -395,6 +411,7 @@ function anthropicTools(value) {
395
411
  name: requiredString(rawTool.name, `tools.${index}.name`),
396
412
  type,
397
413
  description: optionalString(rawTool.description, `tools.${index}.description`),
414
+ ...(isAnthropicWebSearchToolType(type) ? { definition: rawTool } : {}),
398
415
  };
399
416
  }
400
417
  throw new HttpError(400, `Anthropic tool type '${String(type)}' is not supported by this router.`, "unsupported_tool", `tools.${index}.type`);
@@ -43,6 +43,13 @@ export function anthropicContent(output) {
43
43
  })),
44
44
  });
45
45
  }
46
+ else if (item.tool === "web_search_result") {
47
+ content.push({
48
+ type: "web_search_tool_result",
49
+ tool_use_id: item.serverToolUseId ?? item.id,
50
+ content: item.payload.content,
51
+ });
52
+ }
46
53
  continue;
47
54
  }
48
55
  for (const part of item.content) {
@@ -151,18 +151,21 @@ export function anthropicMessagesSseStream(args) {
151
151
  send("content_block_stop", { type: "content_block_stop", index });
152
152
  }
153
153
  else if (type === "server_tool_call_start" && index !== null) {
154
- const serverToolCall = isRecord(event.serverToolCall) ? event.serverToolCall : {};
155
- const id = stringValue(serverToolCall.id) ?? `st_${index}`;
154
+ const serverToolCall = blockFromEvent(event, "serverToolCall");
156
155
  send("content_block_start", {
157
156
  type: "content_block_start",
158
157
  index,
159
158
  content_block: {
160
159
  type: "server_tool_use",
161
- id,
160
+ id: stringValue(serverToolCall.id) ?? `st_${index}`,
162
161
  name: stringValue(serverToolCall.name) ?? "tool_search_tool",
163
162
  input: {},
164
163
  },
165
164
  });
165
+ }
166
+ else if (type === "server_tool_call_end" && index !== null) {
167
+ // The call's input is complete only once its block ends.
168
+ const serverToolCall = blockFromEvent(event, "serverToolCall");
166
169
  send("content_block_delta", {
167
170
  type: "content_block_delta",
168
171
  index,
@@ -171,12 +174,10 @@ export function anthropicMessagesSseStream(args) {
171
174
  partial_json: JSON.stringify(isRecord(serverToolCall.arguments) ? serverToolCall.arguments : {}),
172
175
  },
173
176
  });
174
- }
175
- else if (type === "server_tool_call_end" && index !== null) {
176
177
  send("content_block_stop", { type: "content_block_stop", index });
177
178
  }
178
179
  else if (type === "tool_search_result_start" && index !== null) {
179
- const result = isRecord(event.toolSearchResult) ? event.toolSearchResult : {};
180
+ const result = blockFromEvent(event, "toolSearchResult");
180
181
  const content = Array.isArray(result.content) ? result.content.map((ref) => {
181
182
  if (isRecord(ref))
182
183
  return { type: "tool_reference", tool_name: String(ref.tool_name ?? "") };
@@ -195,6 +196,20 @@ export function anthropicMessagesSseStream(args) {
195
196
  else if (type === "tool_search_result_end" && index !== null) {
196
197
  send("content_block_stop", { type: "content_block_stop", index });
197
198
  }
199
+ else if (type === "web_search_result" && index !== null) {
200
+ // Anthropic sends a web search result whole in its block start.
201
+ const result = isRecord(event.webSearchResult) ? event.webSearchResult : {};
202
+ send("content_block_start", {
203
+ type: "content_block_start",
204
+ index,
205
+ content_block: {
206
+ type: "web_search_tool_result",
207
+ tool_use_id: String(result.toolUseId ?? ""),
208
+ content: result.content,
209
+ },
210
+ });
211
+ send("content_block_stop", { type: "content_block_stop", index });
212
+ }
198
213
  else if (type === "done") {
199
214
  if (!isRecord(event.message))
200
215
  throw new Error("Provider stream ended without a terminal message.");
@@ -253,13 +268,18 @@ function contentIndex(event) {
253
268
  return typeof event.index === "number" ? event.index : null;
254
269
  }
255
270
  function toolCallFromEvent(event) {
256
- if (isRecord(event.toolCall))
257
- return event.toolCall;
271
+ return blockFromEvent(event, "toolCall");
272
+ }
273
+ // The content block an event is about: the one it carries, else the one at its
274
+ // index in the partial message. Pi's start events carry only the partial.
275
+ function blockFromEvent(event, type) {
276
+ if (isRecord(event[type]))
277
+ return event[type];
258
278
  if (!isRecord(event.partial) || !Array.isArray(event.partial.content))
259
279
  return {};
260
280
  const index = contentIndex(event);
261
281
  const block = index === null ? undefined : event.partial.content[index];
262
- return isRecord(block) && block.type === "toolCall" ? block : {};
282
+ return isRecord(block) && block.type === type ? block : {};
263
283
  }
264
284
  function stringValue(value) {
265
285
  return typeof value === "string" && value ? value : undefined;
@@ -11,3 +11,4 @@ export type SafeguardResultsTap = {
11
11
  export declare function safeguardResultsTap(fetch?: ProviderFetch): SafeguardResultsTap;
12
12
  export declare function messageWithSafeguardResults(message: Record<string, unknown>, results: unknown[] | undefined): Record<string, unknown>;
13
13
  export declare function eventsWithSafeguardResults(events: AsyncIterable<Record<string, unknown>>, tap: SafeguardResultsTap): AsyncIterable<Record<string, unknown>>;
14
+ export declare function sseEventScanner(marker: string, onEvent: (event: Record<string, unknown>) => void): TransformStream<Uint8Array, Uint8Array>;
@@ -63,10 +63,21 @@ export async function* eventsWithSafeguardResults(events, tap) {
63
63
  }
64
64
  }
65
65
  function safeguardResultsScanner(onResults) {
66
+ return sseEventScanner("\"safeguard_results\"", (event) => {
67
+ if (event.type === "message_delta" &&
68
+ isRecord(event.delta) &&
69
+ Array.isArray(event.delta.safeguard_results)) {
70
+ onResults(event.delta.safeguard_results);
71
+ }
72
+ });
73
+ }
74
+ // Passes an SSE body through unchanged and hands over each event whose data
75
+ // line mentions `marker`, for fields Pi does not carry.
76
+ export function sseEventScanner(marker, onEvent) {
66
77
  const decoder = new TextDecoder();
67
78
  let pending = "";
68
79
  const scan = (line) => {
69
- if (!line.startsWith("data:") || !line.includes("\"safeguard_results\""))
80
+ if (!line.startsWith("data:") || !line.includes(marker))
70
81
  return;
71
82
  let event;
72
83
  try {
@@ -75,12 +86,8 @@ function safeguardResultsScanner(onResults) {
75
86
  catch {
76
87
  return;
77
88
  }
78
- if (isRecord(event) &&
79
- event.type === "message_delta" &&
80
- isRecord(event.delta) &&
81
- Array.isArray(event.delta.safeguard_results)) {
82
- onResults(event.delta.safeguard_results);
83
- }
89
+ if (isRecord(event))
90
+ onEvent(event);
84
91
  };
85
92
  return new TransformStream({
86
93
  transform(chunk, controller) {
@@ -0,0 +1,16 @@
1
+ import type { InteractionRequest, ServerTool } from "../interaction/types.js";
2
+ import type { ProviderFetch } from "./response_capture.js";
3
+ export declare function anthropicWebSearchFor(request: Pick<InteractionRequest, "tools">, model: Record<string, unknown>): ServerTool | undefined;
4
+ export declare function payloadWithWebSearchTool(payload: Record<string, unknown>, tool: ServerTool): Record<string, unknown>;
5
+ type WebSearchResult = {
6
+ toolUseId: string;
7
+ content: unknown;
8
+ };
9
+ export type WebSearchResultsTap = {
10
+ fetch: ProviderFetch;
11
+ results: () => WebSearchResult[];
12
+ };
13
+ export declare function webSearchResultsTap(fetch?: ProviderFetch): WebSearchResultsTap;
14
+ export declare function messageWithWebSearchResults(message: Record<string, unknown>, results: WebSearchResult[]): Record<string, unknown>;
15
+ export declare function eventsWithWebSearchResults(events: AsyncIterable<Record<string, unknown>>, tap: WebSearchResultsTap): AsyncIterable<Record<string, unknown>>;
16
+ export {};
@@ -0,0 +1,67 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+ import { anthropicWebSearchTool } from "../interaction/capabilities.js";
3
+ import { sseEventScanner } from "./anthropic_safeguards.js";
4
+ // Anthropic runs web search inside the Claude API: the request carries the
5
+ // client's `web_search` tool, and the answer a `web_search_tool_result` block
6
+ // per search (titles, URLs, encrypted page content). Pi sends a server tool by
7
+ // type and name only and drops the result block, so the tool's own definition
8
+ // is restored at the payload boundary and the results are read off the raw SSE
9
+ // bytes. They are appended after the content Pi kept: clients such as Claude
10
+ // Code read them by type, not position.
11
+ // The request's web search tool when `model` is one Anthropic's API serves.
12
+ export function anthropicWebSearchFor(request, model) {
13
+ return model.provider === "anthropic" && model.api === "anthropic-messages"
14
+ ? anthropicWebSearchTool(request)
15
+ : undefined;
16
+ }
17
+ export function payloadWithWebSearchTool(payload, tool) {
18
+ if (!Array.isArray(payload.tools) || tool.definition === undefined)
19
+ return payload;
20
+ return {
21
+ ...payload,
22
+ tools: payload.tools.map((entry) => isRecord(entry) && entry.type === tool.type
23
+ ? { ...tool.definition, ...(entry.cache_control === undefined ? {} : { cache_control: entry.cache_control }) }
24
+ : entry),
25
+ };
26
+ }
27
+ export function webSearchResultsTap(fetch = globalThis.fetch) {
28
+ let results = [];
29
+ return {
30
+ results: () => results,
31
+ fetch: async (input, init) => {
32
+ const response = await fetch(input, init);
33
+ if (!response.ok || response.body === null)
34
+ return response;
35
+ results = [];
36
+ return new Response(response.body.pipeThrough(sseEventScanner("\"web_search_tool_result\"", (event) => {
37
+ const block = event.type === "content_block_start" ? event.content_block : undefined;
38
+ if (isRecord(block) && block.type === "web_search_tool_result" && typeof block.tool_use_id === "string") {
39
+ results.push({ toolUseId: block.tool_use_id, content: block.content });
40
+ }
41
+ })), { status: response.status, statusText: response.statusText, headers: response.headers });
42
+ },
43
+ };
44
+ }
45
+ export function messageWithWebSearchResults(message, results) {
46
+ if (results.length === 0 || !Array.isArray(message.content))
47
+ return message;
48
+ return {
49
+ ...message,
50
+ content: [...message.content, ...results.map((result) => ({ type: "webSearchResult", ...result }))],
51
+ };
52
+ }
53
+ // Emits each result as its own content block just before the stream ends.
54
+ export async function* eventsWithWebSearchResults(events, tap) {
55
+ for await (const event of events) {
56
+ if (event.type === "done" && isRecord(event.message) && Array.isArray(event.message.content)) {
57
+ const first = event.message.content.length;
58
+ const message = messageWithWebSearchResults(event.message, tap.results());
59
+ for (const [offset, webSearchResult] of tap.results().entries()) {
60
+ yield { type: "web_search_result", contentIndex: first + offset, webSearchResult, partial: message };
61
+ }
62
+ yield { ...event, message };
63
+ continue;
64
+ }
65
+ yield event;
66
+ }
67
+ }
@@ -19,6 +19,7 @@ import { buildContext } from "./pi_context.js";
19
19
  import { providerIdentityFromModel } from "../interaction/provider_continuation_state.js";
20
20
  import { buildOptions, supportedThinkingLevels } from "./pi_options.js";
21
21
  import { eventsWithSafeguardResults, forwardsAnthropicSafeguards, messageWithSafeguardResults, safeguardResultsTap, } from "./anthropic_safeguards.js";
22
+ import { anthropicWebSearchFor, eventsWithWebSearchResults, messageWithWebSearchResults, webSearchResultsTap, } from "./anthropic_web_search.js";
22
23
  import { eventsWithProviderReportedCost, messageWithProviderReportedCost, providerReportedCostTap, reportsProviderCost, } from "./provider_reported_cost.js";
23
24
  import { eventsWithSubscriptionCacheWrites, messageWithSubscriptionCacheWrites, modelPricingFromPiModel, } from "./subscription_usage.js";
24
25
  // Pi's built-in providers stream through these API implementations unchanged.
@@ -60,13 +61,16 @@ export async function completeInteractionModel(args) {
60
61
  const safeguards = forwardsAnthropicSafeguards(args.request, model)
61
62
  ? safeguardResultsTap(costTap?.fetch ?? args.fetch)
62
63
  : undefined;
63
- const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
64
+ const webSearch = anthropicWebSearchFor(args.request, model)
65
+ ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
66
+ : undefined;
67
+ const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
64
68
  const usageContext = subscriptionUsageContext(args.model, model, source);
65
69
  const message = options.emitProviderEvents === true
66
70
  ? await completeProviderEventStream(pi.streamSimple(model, context, options))
67
71
  : await pi.completeSimple(model, context, options);
68
72
  return {
69
- message: messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithSafeguardResults(message, safeguards?.results()), usageContext), costTap?.cost()),
73
+ message: messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()),
70
74
  source,
71
75
  };
72
76
  }
@@ -120,8 +124,15 @@ export async function streamInteractionModel(args) {
120
124
  const safeguards = forwardsAnthropicSafeguards(args.request, model)
121
125
  ? safeguardResultsTap(costTap?.fetch ?? args.fetch)
122
126
  : undefined;
123
- const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
124
- const withCacheWrites = eventsWithSubscriptionCacheWrites(safeguards ? eventsWithSafeguardResults(events, safeguards) : events, subscriptionUsageContext(args.model, model, source));
127
+ const webSearch = anthropicWebSearchFor(args.request, model)
128
+ ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
129
+ : undefined;
130
+ const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
131
+ const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
132
+ const withWebSearchResults = webSearch
133
+ ? eventsWithWebSearchResults(withSafeguardResults, webSearch)
134
+ : withSafeguardResults;
135
+ const withCacheWrites = eventsWithSubscriptionCacheWrites(withWebSearchResults, subscriptionUsageContext(args.model, model, source));
125
136
  return {
126
137
  events: costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites,
127
138
  source,
@@ -160,7 +160,10 @@ export function buildContext(request, target) {
160
160
  continue;
161
161
  }
162
162
  if (item.type === "hosted_tool_call") {
163
- if (item.tool === "server_tool_use" || item.tool === "tool_search") {
163
+ if (item.tool === "web_search_result" || (item.tool === "server_tool_use" && item.serverToolName === "web_search")) {
164
+ assistantFor(item.source ?? target).content.push({ type: "text", text: webSearchHistoryText(item) });
165
+ }
166
+ else if (item.tool === "server_tool_use" || item.tool === "tool_search") {
164
167
  // Server tool use and tool search results are Anthropic-specific.
165
168
  // Handle them before the generic OpenAI Responses branch to avoid
166
169
  // emitting Anthropic-shaped payloads as Responses provider items.
@@ -345,6 +348,17 @@ function portableReasoningText(items, itemIndex, readable, target) {
345
348
  }
346
349
  return readable;
347
350
  }
351
+ // Pi cannot replay Anthropic's web search blocks, so a past search goes back
352
+ // as text: its query, then each result's title and URL.
353
+ function webSearchHistoryText(item) {
354
+ if (item.tool === "server_tool_use")
355
+ return `[Web search: ${JSON.stringify(item.serverToolInput ?? {})}]`;
356
+ const content = item.payload.content;
357
+ const results = Array.isArray(content)
358
+ ? content.filter(isRecord).map((result) => `${String(result.title ?? "")} ${String(result.url ?? "")}`.trim())
359
+ : [JSON.stringify(content)];
360
+ return `[Web search results: ${results.join("; ")}]`;
361
+ }
348
362
  function readableContent(content) {
349
363
  return content.map((part) => (part.type === "text" ? part.text : "(image omitted)")).join("\n");
350
364
  }
@@ -6,6 +6,7 @@ import { offRequiresWireNone } from "../models/runtime_overrides.js";
6
6
  import { effectiveReasoningForModel, validateReasoningEffortForModel } from "./reasoning.js";
7
7
  import { isBedrockApi, isOpenAIResponsesApi } from "./model_capabilities.js";
8
8
  import { forwardsAnthropicContextManagement, forwardsAnthropicSafeguards, payloadWithContextManagement, payloadWithSafeguards, } from "./anthropic_safeguards.js";
9
+ import { anthropicWebSearchFor, payloadWithWebSearchTool } from "./anthropic_web_search.js";
9
10
  const ANTHROPIC_FAST_MODE_BETA = "fast-mode-2026-02-01";
10
11
  const ANTHROPIC_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
11
12
  // Anthropic rejects newer models from older Claude Code versions, so forward
@@ -91,6 +92,10 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
91
92
  if (contextManagement !== undefined && forwardsAnthropicContextManagement(request, model)) {
92
93
  patches.push((payload) => payloadWithContextManagement(payload, contextManagement));
93
94
  }
95
+ const webSearch = anthropicWebSearchFor(request, model);
96
+ if (webSearch !== undefined) {
97
+ patches.push((payload) => payloadWithWebSearchTool(payload, webSearch));
98
+ }
94
99
  // Pi keeps only the content it models, so native compaction output reaches
95
100
  // the client from the provider's own output items.
96
101
  if (isOpenAIResponsesApi(api) && request.items.some((item) => item.type === "compaction")) {
@@ -83,6 +83,19 @@ export function piMessageToInteractionOutput(message, source, request) {
83
83
  });
84
84
  continue;
85
85
  }
86
+ if (block.type === "webSearchResult") {
87
+ const toolUseId = requiredString(block.toolUseId, "web search result tool_use_id");
88
+ items.push({
89
+ type: "hosted_tool_call",
90
+ id: `${toolUseId}_result`,
91
+ tool: "web_search_result",
92
+ providerType: "web_search_tool_result",
93
+ payload: { tool_use_id: toolUseId, content: block.content },
94
+ serverToolUseId: toolUseId,
95
+ source,
96
+ });
97
+ continue;
98
+ }
86
99
  throw invalidProviderOutput(`content block type '${String(block.type ?? "unknown")}' is not supported.`);
87
100
  }
88
101
  if (items.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.319",
3
+ "version": "1.0.320",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.319",
55
+ "@mupt-ai/dari-router": "1.0.320",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -6,7 +6,7 @@ import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.
6
6
  import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../link/errors.js";
7
7
  import { captureRequestError } from "../observability/errors.js";
8
8
  import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
9
- import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
9
+ import { CANONICAL_ROUTER_MODEL, explicitModelId, isLinkToken, linkTokenModel } from "../protocol/input/router_model.js";
10
10
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
11
11
  import type { SelectorBackend } from "../strategies/routing.js";
12
12
  import { claudeCodeRequestContext } from "./claude_code/request_context.js";
@@ -15,6 +15,8 @@ import {
15
15
  claudeCodeConversationIdentity,
16
16
  } from "../runtime/harness_identity/index.js";
17
17
  import { parseJsonRequest } from "./json.js";
18
+ import { anthropicWebSearchTool } from "../interaction/capabilities.js";
19
+ import { isBackgroundRequest } from "../interaction/types.js";
18
20
  import type { AnthropicContextManagement, AnthropicSafeguards, ReasoningControls } from "../interaction/types.js";
19
21
 
20
22
  type AnthropicErrorType =
@@ -41,8 +43,18 @@ export async function handleAnthropicMessages(
41
43
  const isClaudeCode = isClaudeCodeRequest(request.headers);
42
44
  const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
43
45
  const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
46
+ const agentContext = isClaudeCode ? claudeCodeRequestContext(request.headers) : undefined;
47
+ // Claude Code runs a web search as a background request that names one of
48
+ // the session's models. Like its other background work, Dari serves it on
49
+ // the cheapest model that can: a Claude model on Anthropic's API. A Dari
50
+ // Link token keeps the model it names.
51
+ const backgroundWebSearch = agentContext !== undefined
52
+ && isBackgroundRequest({ ...interaction, agentContext })
53
+ && anthropicWebSearchTool(interaction) !== undefined
54
+ && !isLinkToken(apiKey);
44
55
  const forwarded = {
45
56
  ...interaction,
57
+ ...(backgroundWebSearch ? { model: CANONICAL_ROUTER_MODEL } : {}),
46
58
  ...(anthropicSafeguards === undefined ? {} : { anthropicSafeguards }),
47
59
  ...(anthropicContextManagement === undefined ? {} : { anthropicContextManagement }),
48
60
  };
@@ -50,7 +62,7 @@ export async function handleAnthropicMessages(
50
62
  ? {
51
63
  ...forwarded,
52
64
  reasoning: routedReasoning(forwarded),
53
- agentContext: claudeCodeRequestContext(request.headers),
65
+ agentContext: agentContext!,
54
66
  // Native tool results may be followed by harness-injected text.
55
67
  // Preserve their structural continuation semantics, not prompt inference.
56
68
  ...(latestMessageHasToolResult(rawPayload.messages)
@@ -1,5 +1,19 @@
1
1
  import type { HardCapability } from "@mupt-ai/dari-router/policy-engine";
2
- import type { InteractionItem, InteractionRequest } from "./types.js";
2
+ import type { AnthropicWebSearchToolType, InteractionItem, InteractionRequest, ServerTool } from "./types.js";
3
+
4
+ export function isAnthropicWebSearchToolType(type: string): type is AnthropicWebSearchToolType {
5
+ return /^web_search_\d{8}$/.test(type);
6
+ }
7
+
8
+ // The request's Anthropic web search tool. Anthropic runs it inside the Claude
9
+ // API, so only a Claude model there can serve the request.
10
+ export function anthropicWebSearchTool(
11
+ request: Pick<InteractionRequest, "tools">,
12
+ ): ServerTool | undefined {
13
+ return request.tools.find((tool): tool is ServerTool =>
14
+ tool.kind === "server_tool" && isAnthropicWebSearchToolType(tool.type)
15
+ );
16
+ }
3
17
 
4
18
  export function requiredCapabilitiesFor(
5
19
  request: Pick<InteractionRequest, "items" | "responseFormat" | "toolChoice" | "tools">
@@ -17,6 +31,7 @@ export function requiredCapabilitiesFor(
17
31
  ) {
18
32
  capabilities.add("openai_hosted_web_search");
19
33
  }
34
+ if (anthropicWebSearchTool(request) !== undefined) capabilities.add("anthropic_web_search");
20
35
  return [...capabilities];
21
36
  }
22
37
 
@@ -120,8 +120,8 @@ export type InteractionReasoningConfiguration = {
120
120
  export type InteractionHostedToolCall = {
121
121
  type: "hosted_tool_call";
122
122
  id: string;
123
- tool: "web_search" | "server_tool_use" | "tool_search";
124
- providerType: "web_search_call" | "server_tool_use" | "tool_search_result";
123
+ tool: "web_search" | "server_tool_use" | "tool_search" | "web_search_result";
124
+ providerType: "web_search_call" | "server_tool_use" | "tool_search_result" | "web_search_tool_result";
125
125
  status?: "in_progress" | "searching" | "completed" | "incomplete" | "failed";
126
126
  payload: Record<string, unknown>;
127
127
  source?: ProviderIdentity;
@@ -164,7 +164,11 @@ export type ServerToolKind =
164
164
  | "tool_search_tool_regex"
165
165
  | "tool_search_tool_regex_20251119"
166
166
  | "tool_search_tool_bm25"
167
- | "tool_search_tool_bm25_20251119";
167
+ | "tool_search_tool_bm25_20251119"
168
+ | AnthropicWebSearchToolType;
169
+
170
+ // Anthropic's web search tool at any dated version, e.g. `web_search_20250305`.
171
+ export type AnthropicWebSearchToolType = `web_search_${number}`;
168
172
 
169
173
  export type ClientTool = {
170
174
  kind: "client_tool";
@@ -202,6 +206,9 @@ export type ServerTool = {
202
206
  name: string;
203
207
  type: ServerToolKind;
204
208
  description?: string;
209
+ // A web search tool as the client defined it (its domains and limits),
210
+ // sent to Anthropic verbatim.
211
+ definition?: Record<string, unknown>;
205
212
  };
206
213
 
207
214
  export type InteractionTool = FunctionTool | CustomTool | HostedTool | ServerTool | ClientTool;
@@ -332,9 +332,10 @@ async function registerApp(link: LinkPlatform, request: Request): Promise<Respon
332
332
 
333
333
  let registrationWindow = { startedAt: 0, count: 0 };
334
334
 
335
- // RFC 7591: any app registers itself with no key: a public client (PKCE, no
336
- // secret), or with `client_secret_basic` a confidential one, whose secret is
337
- // returned this once. Either way the user still approves every grant.
335
+ // RFC 7591: an app registers itself: a public client (PKCE, no secret), or with
336
+ // `client_secret_basic` a confidential one, whose secret is returned this once.
337
+ // Either way the user still approves every grant. Hosted Dari needs the
338
+ // organization's key as a Bearer token, so the app belongs to that organization.
338
339
  async function registerClient(link: LinkPlatform, request: Request): Promise<Response> {
339
340
  const now = Date.now();
340
341
  if (now - registrationWindow.startedAt >= 60_000) registrationWindow = { startedAt: now, count: 0 };
@@ -372,8 +373,28 @@ async function registerClient(link: LinkPlatform, request: Request): Promise<Res
372
373
  if (error instanceof HttpError) return registrationError(error.code, error.message);
373
374
  throw error;
374
375
  }
376
+ let app;
377
+ try {
378
+ app = await link.registerApp({
379
+ ...client,
380
+ // No header is no key; a malformed one is refused.
381
+ apiKey: request.headers.has("authorization") ? bearerToken(request.headers) : undefined,
382
+ confidential: authMethod === "client_secret_basic",
383
+ });
384
+ } catch (error) {
385
+ // A refused request is the caller's to fix; a server failure goes to the
386
+ // same masked response as every other Link request.
387
+ if (error instanceof HttpError && error.status < 500) {
388
+ return Response.json(
389
+ { error: error.code, error_description: error.message },
390
+ { status: error.status, headers: { "Cache-Control": "no-store" } },
391
+ );
392
+ }
393
+ throw error;
394
+ }
395
+ // Only apps actually created count against the cap, so refused keys cannot
396
+ // exhaust it for everyone else.
375
397
  registrationWindow.count += 1;
376
- const app = await link.registerApp({ ...client, confidential: authMethod === "client_secret_basic" });
377
398
  return Response.json(
378
399
  {
379
400
  client_id: app.clientId,
@@ -61,6 +61,8 @@ export function selfHostedLink(
61
61
  const newSubject = () => `lu_${randomUUID().replaceAll("-", "")}`;
62
62
  return linkPlatform(deps.links, {
63
63
  httpRedirectHosts: deps.config.link?.allowHttpRedirectHosts ?? [],
64
+ // A self-hosted gateway's operator owns its apps; registration stays open.
65
+ openRegistration: true,
64
66
  sessionSecret: () => sessionSecret,
65
67
  connectable: SUBSCRIPTION_PROVIDERS,
66
68
  keyProviders,
@@ -84,6 +84,12 @@ export type LinkUsers = {
84
84
  keyProviders: readonly LinkKeyProvider[];
85
85
  /** See `LinkPlatform.httpRedirectHosts`. */
86
86
  httpRedirectHosts?: readonly string[];
87
+ /**
88
+ * Whether an app may register with no API key (RFC 7591). Hosted Dari says no,
89
+ * so every app belongs to an organization; a self-hosted gateway's operator
90
+ * decides.
91
+ */
92
+ openRegistration: boolean;
87
93
  /**
88
94
  * Store a registered app; with `apiKey`, owned by whoever that key is.
89
95
  * Throws HttpError(401 or 403) for a key that may not register apps.
@@ -204,6 +210,9 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
204
210
  },
205
211
  },
206
212
  async registerApp({ apiKey, name, redirectUris, confidential }) {
213
+ if (apiKey === undefined && !users.openRegistration) {
214
+ throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
215
+ }
207
216
  const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
208
217
  const app: LinkApp = {
209
218
  clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
@@ -1,6 +1,7 @@
1
1
  import { isReasoningEffort, isRecord, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
2
 
3
3
  import { HttpError } from "../../http/errors.js";
4
+ import { isAnthropicWebSearchToolType } from "../../interaction/capabilities.js";
4
5
  import { parseDataImageUrl } from "../../interaction/image.js";
5
6
  import { decodeUntrustedProviderContinuationState } from "../../interaction/provider_continuation_state.js";
6
7
  import { decodeUntrustedPortableReasoningState } from "../../interaction/portable_reasoning_state.js";
@@ -32,7 +33,7 @@ const SUPPORTED_SERVER_TOOL_TYPES: readonly ServerToolKind[] = [
32
33
  ] as const;
33
34
 
34
35
  const isServerToolType = (type: string): type is ServerToolKind =>
35
- SUPPORTED_SERVER_TOOL_TYPES.includes(type as ServerToolKind);
36
+ SUPPORTED_SERVER_TOOL_TYPES.includes(type as ServerToolKind) || isAnthropicWebSearchToolType(type);
36
37
 
37
38
  export function anthropicMessagesToInteraction(
38
39
  payload: Record<string, unknown>,
@@ -222,6 +223,20 @@ function appendAnthropicMessage(
222
223
  });
223
224
  continue;
224
225
  }
226
+ if (type === "web_search_tool_result") {
227
+ if (role !== "assistant") throw invalidRequest("web_search_tool_result blocks require the assistant role.", param);
228
+ flushMessage();
229
+ const toolUseId = requiredString(rawBlock.tool_use_id, `${param}.tool_use_id`);
230
+ items.push({
231
+ type: "hosted_tool_call",
232
+ id: `${toolUseId}_result`,
233
+ tool: "web_search_result",
234
+ providerType: "web_search_tool_result",
235
+ payload: { tool_use_id: toolUseId, content: rawBlock.content },
236
+ serverToolUseId: toolUseId,
237
+ });
238
+ continue;
239
+ }
225
240
  if (type === "tool_result") {
226
241
  if (role !== "user") throw invalidRequest("tool_result blocks require the user role.", param);
227
242
  flushMessage();
@@ -433,6 +448,7 @@ function anthropicTools(value: unknown): InteractionTool[] {
433
448
  name: requiredString(rawTool.name, `tools.${index}.name`),
434
449
  type,
435
450
  description: optionalString(rawTool.description, `tools.${index}.description`),
451
+ ...(isAnthropicWebSearchToolType(type) ? { definition: rawTool } : {}),
436
452
  };
437
453
  }
438
454
  throw new HttpError(
@@ -44,6 +44,12 @@ export function anthropicContent(output: InteractionOutput): Array<Record<string
44
44
  tool_name: ref.toolName,
45
45
  })),
46
46
  });
47
+ } else if (item.tool === "web_search_result") {
48
+ content.push({
49
+ type: "web_search_tool_result",
50
+ tool_use_id: item.serverToolUseId ?? item.id,
51
+ content: item.payload.content,
52
+ });
47
53
  }
48
54
  continue;
49
55
  }
@@ -167,18 +167,20 @@ export function anthropicMessagesSseStream(args: {
167
167
  }
168
168
  send("content_block_stop", { type: "content_block_stop", index });
169
169
  } else if (type === "server_tool_call_start" && index !== null) {
170
- const serverToolCall = isRecord(event.serverToolCall) ? event.serverToolCall : {};
171
- const id = stringValue(serverToolCall.id) ?? `st_${index}`;
170
+ const serverToolCall = blockFromEvent(event, "serverToolCall");
172
171
  send("content_block_start", {
173
172
  type: "content_block_start",
174
173
  index,
175
174
  content_block: {
176
175
  type: "server_tool_use",
177
- id,
176
+ id: stringValue(serverToolCall.id) ?? `st_${index}`,
178
177
  name: stringValue(serverToolCall.name) ?? "tool_search_tool",
179
178
  input: {},
180
179
  },
181
180
  });
181
+ } else if (type === "server_tool_call_end" && index !== null) {
182
+ // The call's input is complete only once its block ends.
183
+ const serverToolCall = blockFromEvent(event, "serverToolCall");
182
184
  send("content_block_delta", {
183
185
  type: "content_block_delta",
184
186
  index,
@@ -187,10 +189,9 @@ export function anthropicMessagesSseStream(args: {
187
189
  partial_json: JSON.stringify(isRecord(serverToolCall.arguments) ? serverToolCall.arguments : {}),
188
190
  },
189
191
  });
190
- } else if (type === "server_tool_call_end" && index !== null) {
191
192
  send("content_block_stop", { type: "content_block_stop", index });
192
193
  } else if (type === "tool_search_result_start" && index !== null) {
193
- const result = isRecord(event.toolSearchResult) ? event.toolSearchResult : {};
194
+ const result = blockFromEvent(event, "toolSearchResult");
194
195
  const content = Array.isArray(result.content) ? result.content.map((ref) => {
195
196
  if (isRecord(ref)) return { type: "tool_reference", tool_name: String(ref.tool_name ?? "") };
196
197
  return ref;
@@ -206,6 +207,19 @@ export function anthropicMessagesSseStream(args: {
206
207
  });
207
208
  } else if (type === "tool_search_result_end" && index !== null) {
208
209
  send("content_block_stop", { type: "content_block_stop", index });
210
+ } else if (type === "web_search_result" && index !== null) {
211
+ // Anthropic sends a web search result whole in its block start.
212
+ const result = isRecord(event.webSearchResult) ? event.webSearchResult : {};
213
+ send("content_block_start", {
214
+ type: "content_block_start",
215
+ index,
216
+ content_block: {
217
+ type: "web_search_tool_result",
218
+ tool_use_id: String(result.toolUseId ?? ""),
219
+ content: result.content,
220
+ },
221
+ });
222
+ send("content_block_stop", { type: "content_block_stop", index });
209
223
  } else if (type === "done") {
210
224
  if (!isRecord(event.message)) throw new Error("Provider stream ended without a terminal message.");
211
225
  observeTerminal(event.message);
@@ -267,11 +281,20 @@ function contentIndex(event: Record<string, unknown>): number | null {
267
281
  }
268
282
 
269
283
  function toolCallFromEvent(event: Record<string, unknown>): Record<string, unknown> {
270
- if (isRecord(event.toolCall)) return event.toolCall;
284
+ return blockFromEvent(event, "toolCall");
285
+ }
286
+
287
+ // The content block an event is about: the one it carries, else the one at its
288
+ // index in the partial message. Pi's start events carry only the partial.
289
+ function blockFromEvent(
290
+ event: Record<string, unknown>,
291
+ type: "toolCall" | "serverToolCall" | "toolSearchResult",
292
+ ): Record<string, unknown> {
293
+ if (isRecord(event[type])) return event[type];
271
294
  if (!isRecord(event.partial) || !Array.isArray(event.partial.content)) return {};
272
295
  const index = contentIndex(event);
273
296
  const block = index === null ? undefined : event.partial.content[index];
274
- return isRecord(block) && block.type === "toolCall" ? block : {};
297
+ return isRecord(block) && block.type === type ? block : {};
275
298
  }
276
299
 
277
300
  function stringValue(value: unknown): string | undefined {
@@ -107,25 +107,35 @@ export async function* eventsWithSafeguardResults(
107
107
 
108
108
  function safeguardResultsScanner(
109
109
  onResults: (results: unknown[]) => void,
110
+ ): TransformStream<Uint8Array, Uint8Array> {
111
+ return sseEventScanner("\"safeguard_results\"", (event) => {
112
+ if (
113
+ event.type === "message_delta" &&
114
+ isRecord(event.delta) &&
115
+ Array.isArray(event.delta.safeguard_results)
116
+ ) {
117
+ onResults(event.delta.safeguard_results);
118
+ }
119
+ });
120
+ }
121
+
122
+ // Passes an SSE body through unchanged and hands over each event whose data
123
+ // line mentions `marker`, for fields Pi does not carry.
124
+ export function sseEventScanner(
125
+ marker: string,
126
+ onEvent: (event: Record<string, unknown>) => void,
110
127
  ): TransformStream<Uint8Array, Uint8Array> {
111
128
  const decoder = new TextDecoder();
112
129
  let pending = "";
113
130
  const scan = (line: string) => {
114
- if (!line.startsWith("data:") || !line.includes("\"safeguard_results\"")) return;
131
+ if (!line.startsWith("data:") || !line.includes(marker)) return;
115
132
  let event: unknown;
116
133
  try {
117
134
  event = JSON.parse(line.slice("data:".length));
118
135
  } catch {
119
136
  return;
120
137
  }
121
- if (
122
- isRecord(event) &&
123
- event.type === "message_delta" &&
124
- isRecord(event.delta) &&
125
- Array.isArray(event.delta.safeguard_results)
126
- ) {
127
- onResults(event.delta.safeguard_results);
128
- }
138
+ if (isRecord(event)) onEvent(event);
129
139
  };
130
140
  return new TransformStream({
131
141
  transform(chunk, controller) {
@@ -0,0 +1,99 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { anthropicWebSearchTool } from "../interaction/capabilities.js";
4
+ import type { InteractionRequest, ServerTool } from "../interaction/types.js";
5
+ import { sseEventScanner } from "./anthropic_safeguards.js";
6
+ import type { ProviderFetch } from "./response_capture.js";
7
+
8
+ // Anthropic runs web search inside the Claude API: the request carries the
9
+ // client's `web_search` tool, and the answer a `web_search_tool_result` block
10
+ // per search (titles, URLs, encrypted page content). Pi sends a server tool by
11
+ // type and name only and drops the result block, so the tool's own definition
12
+ // is restored at the payload boundary and the results are read off the raw SSE
13
+ // bytes. They are appended after the content Pi kept: clients such as Claude
14
+ // Code read them by type, not position.
15
+
16
+ // The request's web search tool when `model` is one Anthropic's API serves.
17
+ export function anthropicWebSearchFor(
18
+ request: Pick<InteractionRequest, "tools">,
19
+ model: Record<string, unknown>,
20
+ ): ServerTool | undefined {
21
+ return model.provider === "anthropic" && model.api === "anthropic-messages"
22
+ ? anthropicWebSearchTool(request)
23
+ : undefined;
24
+ }
25
+
26
+ export function payloadWithWebSearchTool(
27
+ payload: Record<string, unknown>,
28
+ tool: ServerTool,
29
+ ): Record<string, unknown> {
30
+ if (!Array.isArray(payload.tools) || tool.definition === undefined) return payload;
31
+ return {
32
+ ...payload,
33
+ tools: payload.tools.map((entry) =>
34
+ isRecord(entry) && entry.type === tool.type
35
+ ? { ...tool.definition, ...(entry.cache_control === undefined ? {} : { cache_control: entry.cache_control }) }
36
+ : entry
37
+ ),
38
+ };
39
+ }
40
+
41
+ type WebSearchResult = { toolUseId: string; content: unknown };
42
+
43
+ export type WebSearchResultsTap = {
44
+ fetch: ProviderFetch;
45
+ results: () => WebSearchResult[];
46
+ };
47
+
48
+ export function webSearchResultsTap(
49
+ fetch: ProviderFetch = globalThis.fetch,
50
+ ): WebSearchResultsTap {
51
+ let results: WebSearchResult[] = [];
52
+ return {
53
+ results: () => results,
54
+ fetch: async (input, init) => {
55
+ const response = await fetch(input, init);
56
+ if (!response.ok || response.body === null) return response;
57
+ results = [];
58
+ return new Response(
59
+ response.body.pipeThrough(sseEventScanner("\"web_search_tool_result\"", (event) => {
60
+ const block = event.type === "content_block_start" ? event.content_block : undefined;
61
+ if (isRecord(block) && block.type === "web_search_tool_result" && typeof block.tool_use_id === "string") {
62
+ results.push({ toolUseId: block.tool_use_id, content: block.content });
63
+ }
64
+ })),
65
+ { status: response.status, statusText: response.statusText, headers: response.headers },
66
+ );
67
+ },
68
+ };
69
+ }
70
+
71
+ export function messageWithWebSearchResults(
72
+ message: Record<string, unknown>,
73
+ results: WebSearchResult[],
74
+ ): Record<string, unknown> {
75
+ if (results.length === 0 || !Array.isArray(message.content)) return message;
76
+ return {
77
+ ...message,
78
+ content: [...message.content, ...results.map((result) => ({ type: "webSearchResult", ...result }))],
79
+ };
80
+ }
81
+
82
+ // Emits each result as its own content block just before the stream ends.
83
+ export async function* eventsWithWebSearchResults(
84
+ events: AsyncIterable<Record<string, unknown>>,
85
+ tap: WebSearchResultsTap,
86
+ ): AsyncIterable<Record<string, unknown>> {
87
+ for await (const event of events) {
88
+ if (event.type === "done" && isRecord(event.message) && Array.isArray(event.message.content)) {
89
+ const first = event.message.content.length;
90
+ const message = messageWithWebSearchResults(event.message, tap.results());
91
+ for (const [offset, webSearchResult] of tap.results().entries()) {
92
+ yield { type: "web_search_result", contentIndex: first + offset, webSearchResult, partial: message };
93
+ }
94
+ yield { ...event, message };
95
+ continue;
96
+ }
97
+ yield event;
98
+ }
99
+ }
@@ -47,6 +47,12 @@ import {
47
47
  messageWithSafeguardResults,
48
48
  safeguardResultsTap,
49
49
  } from "./anthropic_safeguards.js";
50
+ import {
51
+ anthropicWebSearchFor,
52
+ eventsWithWebSearchResults,
53
+ messageWithWebSearchResults,
54
+ webSearchResultsTap,
55
+ } from "./anthropic_web_search.js";
50
56
  import {
51
57
  eventsWithProviderReportedCost,
52
58
  messageWithProviderReportedCost,
@@ -152,6 +158,9 @@ export async function completeInteractionModel(args: {
152
158
  const safeguards = forwardsAnthropicSafeguards(args.request, model)
153
159
  ? safeguardResultsTap(costTap?.fetch ?? args.fetch)
154
160
  : undefined;
161
+ const webSearch = anthropicWebSearchFor(args.request, model)
162
+ ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
163
+ : undefined;
155
164
  const options = buildOptions(
156
165
  args.request,
157
166
  args.auth ?? args.apiKey,
@@ -162,7 +171,7 @@ export async function completeInteractionModel(args: {
162
171
  args.selectedReasoningEffort,
163
172
  args.timeoutMs,
164
173
  args.signal,
165
- safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
174
+ webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
166
175
  );
167
176
  const usageContext = subscriptionUsageContext(args.model, model, source);
168
177
  const message = options.emitProviderEvents === true
@@ -171,7 +180,10 @@ export async function completeInteractionModel(args: {
171
180
  return {
172
181
  message: messageWithProviderReportedCost(
173
182
  messageWithSubscriptionCacheWrites(
174
- messageWithSafeguardResults(message, safeguards?.results()),
183
+ messageWithWebSearchResults(
184
+ messageWithSafeguardResults(message, safeguards?.results()),
185
+ webSearch?.results() ?? [],
186
+ ),
175
187
  usageContext
176
188
  ),
177
189
  costTap?.cost(),
@@ -251,6 +263,9 @@ export async function streamInteractionModel(args: {
251
263
  const safeguards = forwardsAnthropicSafeguards(args.request, model)
252
264
  ? safeguardResultsTap(costTap?.fetch ?? args.fetch)
253
265
  : undefined;
266
+ const webSearch = anthropicWebSearchFor(args.request, model)
267
+ ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
268
+ : undefined;
254
269
  const events = pi.streamSimple(
255
270
  model,
256
271
  buildContext(args.request, source),
@@ -264,11 +279,15 @@ export async function streamInteractionModel(args: {
264
279
  args.selectedReasoningEffort,
265
280
  undefined,
266
281
  args.signal,
267
- safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
282
+ webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
268
283
  )
269
284
  );
285
+ const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
286
+ const withWebSearchResults = webSearch
287
+ ? eventsWithWebSearchResults(withSafeguardResults, webSearch)
288
+ : withSafeguardResults;
270
289
  const withCacheWrites = eventsWithSubscriptionCacheWrites(
271
- safeguards ? eventsWithSafeguardResults(events, safeguards) : events,
290
+ withWebSearchResults,
272
291
  subscriptionUsageContext(args.model, model, source)
273
292
  );
274
293
  return {
@@ -200,7 +200,9 @@ export function buildContext(
200
200
  continue;
201
201
  }
202
202
  if (item.type === "hosted_tool_call") {
203
- if (item.tool === "server_tool_use" || item.tool === "tool_search") {
203
+ if (item.tool === "web_search_result" || (item.tool === "server_tool_use" && item.serverToolName === "web_search")) {
204
+ assistantFor(item.source ?? target).content.push({ type: "text", text: webSearchHistoryText(item) });
205
+ } else if (item.tool === "server_tool_use" || item.tool === "tool_search") {
204
206
  // Server tool use and tool search results are Anthropic-specific.
205
207
  // Handle them before the generic OpenAI Responses branch to avoid
206
208
  // emitting Anthropic-shaped payloads as Responses provider items.
@@ -407,6 +409,17 @@ function portableReasoningText(
407
409
  return readable;
408
410
  }
409
411
 
412
+ // Pi cannot replay Anthropic's web search blocks, so a past search goes back
413
+ // as text: its query, then each result's title and URL.
414
+ function webSearchHistoryText(item: Extract<InteractionItem, { type: "hosted_tool_call" }>): string {
415
+ if (item.tool === "server_tool_use") return `[Web search: ${JSON.stringify(item.serverToolInput ?? {})}]`;
416
+ const content = item.payload.content;
417
+ const results = Array.isArray(content)
418
+ ? content.filter(isRecord).map((result) => `${String(result.title ?? "")} ${String(result.url ?? "")}`.trim())
419
+ : [JSON.stringify(content)];
420
+ return `[Web search results: ${results.join("; ")}]`;
421
+ }
422
+
410
423
  function readableContent(content: InteractionContent[]): string {
411
424
  return content.map((part) => (part.type === "text" ? part.text : "(image omitted)")).join("\n");
412
425
  }
@@ -15,6 +15,7 @@ import {
15
15
  payloadWithContextManagement,
16
16
  payloadWithSafeguards,
17
17
  } from "./anthropic_safeguards.js";
18
+ import { anthropicWebSearchFor, payloadWithWebSearchTool } from "./anthropic_web_search.js";
18
19
 
19
20
  type PiOptionsSupport = {
20
21
  getSupportedThinkingLevels?: (model: Record<string, unknown>) => string[];
@@ -123,6 +124,10 @@ export function buildOptions(
123
124
  if (contextManagement !== undefined && forwardsAnthropicContextManagement(request, model)) {
124
125
  patches.push((payload) => payloadWithContextManagement(payload, contextManagement));
125
126
  }
127
+ const webSearch = anthropicWebSearchFor(request, model);
128
+ if (webSearch !== undefined) {
129
+ patches.push((payload) => payloadWithWebSearchTool(payload, webSearch));
130
+ }
126
131
 
127
132
  // Pi keeps only the content it models, so native compaction output reaches
128
133
  // the client from the provider's own output items.
@@ -98,6 +98,19 @@ export function piMessageToInteractionOutput(
98
98
  });
99
99
  continue;
100
100
  }
101
+ if (block.type === "webSearchResult") {
102
+ const toolUseId = requiredString(block.toolUseId, "web search result tool_use_id");
103
+ items.push({
104
+ type: "hosted_tool_call",
105
+ id: `${toolUseId}_result`,
106
+ tool: "web_search_result",
107
+ providerType: "web_search_tool_result",
108
+ payload: { tool_use_id: toolUseId, content: block.content },
109
+ serverToolUseId: toolUseId,
110
+ source,
111
+ });
112
+ continue;
113
+ }
101
114
  throw invalidProviderOutput(`content block type '${String(block.type ?? "unknown")}' is not supported.`);
102
115
  }
103
116