@mupt-ai/dari-gateway 1.0.318 → 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.
- package/dist/ingress/anthropic_messages.js +14 -2
- package/dist/interaction/capabilities.d.ts +3 -1
- package/dist/interaction/capabilities.js +10 -0
- package/dist/interaction/types.d.ts +5 -3
- package/dist/link/endpoints.js +23 -4
- package/dist/link/self_hosted.js +2 -0
- package/dist/link/service.d.ts +6 -0
- package/dist/link/service.js +3 -0
- package/dist/platform/platform.d.ts +1 -0
- package/dist/protocol/input/anthropic_messages.js +18 -1
- package/dist/protocol/output/anthropic_messages_output.js +7 -0
- package/dist/protocol/output/anthropic_messages_stream.js +29 -9
- package/dist/providers/anthropic_safeguards.d.ts +1 -0
- package/dist/providers/anthropic_safeguards.js +14 -7
- package/dist/providers/anthropic_web_search.d.ts +16 -0
- package/dist/providers/anthropic_web_search.js +67 -0
- package/dist/providers/execution.js +8 -6
- package/dist/providers/pi.js +15 -4
- package/dist/providers/pi_context.js +15 -1
- package/dist/providers/pi_options.js +5 -0
- package/dist/providers/pi_output.js +13 -0
- package/dist/providers/provider_call.js +2 -2
- package/dist/runtime/prepare_routed_completion.js +1 -1
- package/dist/self_host/platform.js +3 -3
- package/dist/self_host/resolve.js +26 -7
- package/dist/self_host/subscriptions/store.d.ts +1 -1
- package/dist/self_host/subscriptions/store.js +4 -3
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/ingress/anthropic_messages.ts +14 -2
- package/src/interaction/capabilities.ts +16 -1
- package/src/interaction/types.ts +10 -3
- package/src/link/endpoints.ts +25 -4
- package/src/link/self_hosted.ts +2 -0
- package/src/link/service.ts +9 -0
- package/src/platform/platform.ts +1 -0
- package/src/protocol/input/anthropic_messages.ts +17 -1
- package/src/protocol/output/anthropic_messages_output.ts +6 -0
- package/src/protocol/output/anthropic_messages_stream.ts +30 -7
- package/src/providers/anthropic_safeguards.ts +19 -9
- package/src/providers/anthropic_web_search.ts +99 -0
- package/src/providers/execution.ts +8 -6
- package/src/providers/pi.ts +23 -4
- package/src/providers/pi_context.ts +14 -1
- package/src/providers/pi_options.ts +5 -0
- package/src/providers/pi_output.ts +13 -0
- package/src/providers/provider_call.ts +2 -2
- package/src/runtime/prepare_routed_completion.ts +1 -1
- package/src/self_host/platform.ts +4 -3
- package/src/self_host/resolve.ts +28 -7
- package/src/self_host/subscriptions/store.ts +4 -2
- package/src/types.ts +3 -1
|
@@ -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:
|
|
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" | {
|
package/dist/link/endpoints.js
CHANGED
|
@@ -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:
|
|
288
|
-
//
|
|
289
|
-
//
|
|
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.
|
package/dist/link/self_hosted.js
CHANGED
|
@@ -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,
|
package/dist/link/service.d.ts
CHANGED
|
@@ -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.
|
package/dist/link/service.js
CHANGED
|
@@ -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 =
|
|
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 =
|
|
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
|
-
|
|
257
|
-
|
|
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 ===
|
|
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(
|
|
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
|
|
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
|
+
}
|
|
@@ -463,8 +463,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
|
|
|
463
463
|
// Retrying an exhausted plan cannot succeed. The platform learns about it
|
|
464
464
|
// before this request returns so the next resolve already serves the
|
|
465
465
|
// user's next subscription, or the model's API credential when the router
|
|
466
|
-
// allows subscription API fallback for it. A limit
|
|
467
|
-
//
|
|
466
|
+
// allows subscription API fallback for it. A model limit holds only that
|
|
467
|
+
// model on this plan; other plans may still serve it.
|
|
468
468
|
const switched = execution.subscriptionUserId !== undefined
|
|
469
469
|
&& await holdSubscription({
|
|
470
470
|
userId: execution.subscriptionUserId,
|
|
@@ -473,9 +473,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
|
|
|
473
473
|
...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
|
|
474
474
|
});
|
|
475
475
|
// Nothing reached the client yet, so the same request is retried on the
|
|
476
|
-
// next plan
|
|
477
|
-
|
|
478
|
-
const nextSubscription = switched && limit.model === undefined
|
|
476
|
+
// next plan with quota for this model, including model-specific limits.
|
|
477
|
+
const nextSubscription = switched
|
|
479
478
|
? await nextSubscriptionFor(execution)
|
|
480
479
|
: undefined;
|
|
481
480
|
return {
|
|
@@ -573,12 +572,15 @@ async function nextSubscriptionFor(execution) {
|
|
|
573
572
|
if (platform.nextSubscription === undefined || execution.subscriptionUserId === undefined)
|
|
574
573
|
return undefined;
|
|
575
574
|
try {
|
|
576
|
-
|
|
575
|
+
const next = await platform.nextSubscription({
|
|
577
576
|
userId: execution.subscriptionUserId,
|
|
578
577
|
provider: execution.provider,
|
|
578
|
+
model: execution.model,
|
|
579
579
|
conversationId: execution.conversationId,
|
|
580
580
|
...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
|
|
581
581
|
});
|
|
582
|
+
// Never retry a held credential, even if a stale lookup returns it.
|
|
583
|
+
return next?.credentialId === execution.subscriptionCredentialId ? undefined : next;
|
|
582
584
|
}
|
|
583
585
|
catch (error) {
|
|
584
586
|
console.error("next subscription lookup failed", error);
|
package/dist/providers/pi.js
CHANGED
|
@@ -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
|
|
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
|
|
124
|
-
|
|
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 === "
|
|
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) {
|