@mupt-ai/dari-gateway 1.0.319 → 1.0.321
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/README.md +1 -1
- 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/protocol/input/anthropic_messages.js +18 -1
- package/dist/protocol/input/router_model.js +1 -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/pi.js +15 -4
- package/dist/providers/pi_context.js +15 -1
- package/dist/providers/pi_options.js +10 -0
- package/dist/providers/pi_output.js +13 -0
- package/dist/self_host/subscriptions/http.js +53 -7
- 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/protocol/input/anthropic_messages.ts +17 -1
- package/src/protocol/input/router_model.ts +1 -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/pi.ts +23 -4
- package/src/providers/pi_context.ts +14 -1
- package/src/providers/pi_options.ts +9 -0
- package/src/providers/pi_output.ts +13 -0
- package/src/self_host/subscriptions/http.ts +55 -7
|
@@ -151,13 +151,59 @@ async function completeSession(deps, body, now) {
|
|
|
151
151
|
function summary(store, credential, now) {
|
|
152
152
|
return credentialBody(credential, store.activeCredential(credential.provider, now)?.id === credential.id, now);
|
|
153
153
|
}
|
|
154
|
-
|
|
154
|
+
const FIVE_HOURS = 5 * 60;
|
|
155
|
+
const ONE_WEEK = 7 * 24 * 60;
|
|
156
|
+
const ONE_MONTH = 30 * 24 * 60;
|
|
157
|
+
// A model family's own window is named for the family's catalog models.
|
|
158
|
+
const MODEL_FAMILY_NAMES = { fable: "Claude Fable" };
|
|
159
|
+
/** What to call a window: 5 Hour, Weekly, Monthly, Claude Fable Weekly. */
|
|
160
|
+
function usageWindowLabel(window) {
|
|
161
|
+
const minutes = window.minutes;
|
|
162
|
+
const length = minutes === ONE_WEEK ? "Weekly"
|
|
163
|
+
: minutes === ONE_MONTH ? "Monthly"
|
|
164
|
+
: minutes % (24 * 60) === 0 ? `${minutes / (24 * 60)} Day`
|
|
165
|
+
: minutes % 60 === 0 ? `${minutes / 60} Hour`
|
|
166
|
+
: `${minutes} Minute`;
|
|
167
|
+
return window.modelFamily === undefined ? length : `${MODEL_FAMILY_NAMES[window.modelFamily]} ${length}`;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The usage to show, as the hosted API shows it: every running window, a
|
|
171
|
+
* held plan's window full. A hold ends when the window that ran out resets,
|
|
172
|
+
* so the shared window resetting with it shows full. Usage reported without
|
|
173
|
+
* per-window detail, and holds without a matching window, are named by how
|
|
174
|
+
* far off their reset is: only a weekly or monthly window resets more than
|
|
175
|
+
* five hours out, and only OpenCode Go's monthly one more than a week.
|
|
176
|
+
*/
|
|
155
177
|
function usageBody(credential, now) {
|
|
178
|
+
const inferred = (resetsAt) => {
|
|
179
|
+
const left = resetsAt.getTime() - now.getTime();
|
|
180
|
+
if (left > ONE_WEEK * 60_000)
|
|
181
|
+
return ONE_MONTH;
|
|
182
|
+
return left > FIVE_HOURS * 60_000 ? ONE_WEEK : FIVE_HOURS;
|
|
183
|
+
};
|
|
156
184
|
const usage = currentUsage(credential, now);
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
185
|
+
let windows = usage === null ? []
|
|
186
|
+
: usage.windows.length > 0 ? usage.windows
|
|
187
|
+
: [{ minutes: inferred(usage.resetsAt), utilization: usage.utilization, resetsAt: usage.resetsAt }];
|
|
188
|
+
if (isHeld(credential, now)) {
|
|
189
|
+
const held = credential.unavailableUntil;
|
|
190
|
+
const gap = (window) => Math.abs(window.resetsAt.getTime() - held.getTime());
|
|
191
|
+
// The hold is the plan's; it never fills a model family's window.
|
|
192
|
+
const closest = windows.filter((window) => window.modelFamily === undefined)
|
|
193
|
+
.reduce((best, window) => best === null || gap(window) < gap(best) ? window : best, null);
|
|
194
|
+
const minutes = closest !== null && gap(closest) < 15 * 60_000 ? closest.minutes : inferred(held);
|
|
195
|
+
windows = [
|
|
196
|
+
...windows.filter((window) => window.modelFamily !== undefined || window.minutes !== minutes),
|
|
197
|
+
{ minutes, utilization: 1, resetsAt: held },
|
|
198
|
+
].sort((a, b) => a.minutes - b.minutes || (a.modelFamily ?? "").localeCompare(b.modelFamily ?? ""));
|
|
199
|
+
}
|
|
200
|
+
if (windows.length === 0)
|
|
201
|
+
return null;
|
|
202
|
+
return {
|
|
203
|
+
utilization: usage?.utilization ?? 1,
|
|
204
|
+
resets_at: (usage?.resetsAt ?? windows[0].resetsAt).toISOString(),
|
|
205
|
+
windows: windows.map((window) => ({
|
|
206
|
+
label: usageWindowLabel(window),
|
|
161
207
|
...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
|
|
162
208
|
minutes: window.minutes,
|
|
163
209
|
utilization: window.utilization,
|
|
@@ -188,8 +234,8 @@ function credentialBody(credential, active, now) {
|
|
|
188
234
|
reason: hold.reason,
|
|
189
235
|
})),
|
|
190
236
|
subscription_active: active,
|
|
191
|
-
// The share of its tightest window the plan last reported used,
|
|
192
|
-
//
|
|
237
|
+
// The share of its tightest window the plan last reported used, and
|
|
238
|
+
// every window as shown; null when it reports none and is not held.
|
|
193
239
|
usage: usageBody(credential, now),
|
|
194
240
|
// Spending banked limit resets is hosted-only.
|
|
195
241
|
auto_redeem_resets: false,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.321",
|
|
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.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.321",
|
|
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:
|
|
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
|
|
package/src/interaction/types.ts
CHANGED
|
@@ -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;
|
package/src/link/endpoints.ts
CHANGED
|
@@ -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:
|
|
336
|
-
//
|
|
337
|
-
//
|
|
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,
|
package/src/link/self_hosted.ts
CHANGED
|
@@ -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,
|
package/src/link/service.ts
CHANGED
|
@@ -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(
|
|
@@ -22,7 +22,7 @@ const ANTHROPIC_ROUTER_MODELS = new Set<string>([CANONICAL_ROUTER_MODEL, ...ANTH
|
|
|
22
22
|
request leaves the client (wire-captured live: Task spawns emit
|
|
23
23
|
`claude-opus-5` even when the session model is dari/routing), so concrete
|
|
24
24
|
Claude-family ids are synonyms too — both bare (`claude-opus-5`) and
|
|
25
|
-
provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup`
|
|
25
|
+
provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup-desktop`
|
|
26
26
|
relies on this: the Claude app lists routing as `claude-dari-routing`. */
|
|
27
27
|
const ANTHROPIC_MODEL_ID_PATTERN = /^(anthropic\/)?claude-[a-z0-9][a-z0-9.-]*$/i;
|
|
28
28
|
|
|
@@ -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 =
|
|
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 =
|
|
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
|
-
|
|
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 ===
|
|
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(
|
|
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
|
+
}
|
package/src/providers/pi.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
290
|
+
withWebSearchResults,
|
|
272
291
|
subscriptionUsageContext(args.model, model, source)
|
|
273
292
|
);
|
|
274
293
|
return {
|