@mupt-ai/dari-gateway 1.0.322 → 1.0.324
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 +13 -7
- package/dist/ingress/codex.js +9 -4
- package/dist/providers/pi.js +13 -4
- package/dist/providers/web_search_fee.d.ts +11 -0
- package/dist/providers/web_search_fee.js +73 -0
- package/dist/runtime/harness_identity/extract.js +6 -1
- package/package.json +2 -2
- package/src/ingress/anthropic_messages.ts +13 -6
- package/src/ingress/codex.ts +8 -2
- package/src/providers/pi.ts +22 -10
- package/src/providers/web_search_fee.ts +93 -0
- package/src/runtime/harness_identity/extract.ts +6 -1
|
@@ -10,7 +10,7 @@ import { CANONICAL_ROUTER_MODEL, explicitModelId, isLinkToken, linkTokenModel }
|
|
|
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
|
-
import { claudeCodeConversationIdentity, } from "../runtime/harness_identity/index.js";
|
|
13
|
+
import { claudeCodeConversationIdentity, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
14
14
|
import { parseJsonRequest } from "./json.js";
|
|
15
15
|
import { anthropicWebSearchTool } from "../interaction/capabilities.js";
|
|
16
16
|
import { isBackgroundRequest } from "../interaction/types.js";
|
|
@@ -25,11 +25,15 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
25
25
|
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
26
26
|
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
27
27
|
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
28
|
-
|
|
28
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
29
|
+
// tool sends its search here, marked as Pi's.
|
|
30
|
+
const piContext = isClaudeCode ? undefined : piRequestContext(request.headers);
|
|
31
|
+
const agentContext = isClaudeCode ? claudeCodeRequestContext(request.headers) : piContext;
|
|
29
32
|
// Claude Code runs a web search as a background request that names one of
|
|
30
|
-
// the session's models
|
|
31
|
-
//
|
|
32
|
-
// Link token keeps the
|
|
33
|
+
// the session's models, and Pi's search tool as one that asks for routing.
|
|
34
|
+
// Like other background work, Dari serves it on the cheapest model that
|
|
35
|
+
// can: a Claude model on Anthropic's API. A Dari Link token keeps the
|
|
36
|
+
// model it names.
|
|
33
37
|
const backgroundWebSearch = agentContext !== undefined
|
|
34
38
|
&& isBackgroundRequest({ ...interaction, agentContext })
|
|
35
39
|
&& anthropicWebSearchTool(interaction) !== undefined
|
|
@@ -51,7 +55,7 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
51
55
|
? { requestPurpose: "tool_continuation" } : {}),
|
|
52
56
|
claudeCodeUserAgent: request.headers.get("user-agent").trim(),
|
|
53
57
|
}
|
|
54
|
-
: forwarded;
|
|
58
|
+
: { ...forwarded, ...(agentContext === undefined ? {} : { agentContext }) };
|
|
55
59
|
return await handleRoutedCompletion({
|
|
56
60
|
request,
|
|
57
61
|
routerId,
|
|
@@ -61,7 +65,9 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
61
65
|
streamBody: anthropicMessagesSseStream,
|
|
62
66
|
errorResponse: anthropicErrorResponse,
|
|
63
67
|
selectorBackend,
|
|
64
|
-
clientHarness: isClaudeCode ? "claude_code"
|
|
68
|
+
clientHarness: isClaudeCode ? "claude_code"
|
|
69
|
+
: piContext !== undefined ? "pi"
|
|
70
|
+
: claimedClientHarness(request.headers),
|
|
65
71
|
harnessConversationIdentity: isClaudeCode
|
|
66
72
|
? claudeCodeConversationIdentity(request.headers, payload.promptCacheKey)
|
|
67
73
|
: undefined,
|
package/dist/ingress/codex.js
CHANGED
|
@@ -9,14 +9,18 @@ import { claimedClientHarness } from "./client_harness.js";
|
|
|
9
9
|
import { parseJsonRequest } from "./json.js";
|
|
10
10
|
import { museCodeClientId } from "./muse_code.js";
|
|
11
11
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
12
|
-
import { codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, } from "../runtime/harness_identity/index.js";
|
|
12
|
+
import { codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
13
13
|
export async function handleResponses(request, routerId, selectorBackend) {
|
|
14
14
|
try {
|
|
15
15
|
const apiKey = bearerToken(request.headers);
|
|
16
16
|
const rawPayload = await parseJsonRequest(request);
|
|
17
17
|
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
18
18
|
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
19
|
-
const
|
|
19
|
+
const codexContext = codexRequestContext(request.headers, rawPayload);
|
|
20
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
21
|
+
// tool sends an OpenAI hosted search here, marked as Pi's.
|
|
22
|
+
const piContext = codexContext === undefined ? piRequestContext(request.headers) : undefined;
|
|
23
|
+
const agentContext = codexContext ?? piContext;
|
|
20
24
|
const museClientId = museCodeClientId(request.headers);
|
|
21
25
|
const payload = {
|
|
22
26
|
...interaction,
|
|
@@ -48,8 +52,9 @@ export async function handleResponses(request, routerId, selectorBackend) {
|
|
|
48
52
|
selectorBackend,
|
|
49
53
|
clientHarness: museClientId !== undefined ? "muse_code"
|
|
50
54
|
// Codex describes every request in its turn metadata.
|
|
51
|
-
:
|
|
52
|
-
:
|
|
55
|
+
: codexContext !== undefined ? "codex"
|
|
56
|
+
: piContext !== undefined ? "pi"
|
|
57
|
+
: claimedClientHarness(request.headers),
|
|
53
58
|
harnessConversationIdentity,
|
|
54
59
|
});
|
|
55
60
|
}
|
package/dist/providers/pi.js
CHANGED
|
@@ -20,6 +20,7 @@ import { providerIdentityFromModel } from "../interaction/provider_continuation_
|
|
|
20
20
|
import { buildOptions, supportedThinkingLevels } from "./pi_options.js";
|
|
21
21
|
import { eventsWithSafeguardResults, forwardsAnthropicSafeguards, messageWithSafeguardResults, safeguardResultsTap, } from "./anthropic_safeguards.js";
|
|
22
22
|
import { anthropicWebSearchFor, eventsWithWebSearchResults, messageWithWebSearchResults, webSearchResultsTap, } from "./anthropic_web_search.js";
|
|
23
|
+
import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
|
|
23
24
|
import { eventsWithProviderReportedCost, messageWithProviderReportedCost, providerReportedCostTap, reportsProviderCost, } from "./provider_reported_cost.js";
|
|
24
25
|
import { eventsWithSubscriptionCacheWrites, messageWithSubscriptionCacheWrites, modelPricingFromPiModel, } from "./subscription_usage.js";
|
|
25
26
|
// Pi's built-in providers stream through these API implementations unchanged.
|
|
@@ -64,13 +65,17 @@ export async function completeInteractionModel(args) {
|
|
|
64
65
|
const webSearch = anthropicWebSearchFor(args.request, model)
|
|
65
66
|
? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
66
67
|
: undefined;
|
|
67
|
-
const
|
|
68
|
+
const searchCount = chargesWebSearch(args.request)
|
|
69
|
+
? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
70
|
+
: undefined;
|
|
71
|
+
const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
|
|
68
72
|
const usageContext = subscriptionUsageContext(args.model, model, source);
|
|
69
73
|
const message = options.emitProviderEvents === true
|
|
70
74
|
? await completeProviderEventStream(pi.streamSimple(model, context, options))
|
|
71
75
|
: await pi.completeSimple(model, context, options);
|
|
72
76
|
return {
|
|
73
|
-
|
|
77
|
+
// The search fee goes on last, over whatever cost the steps before set.
|
|
78
|
+
message: messageWithWebSearchFee(messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()), searchCount?.searches() ?? 0),
|
|
74
79
|
source,
|
|
75
80
|
};
|
|
76
81
|
}
|
|
@@ -127,14 +132,18 @@ export async function streamInteractionModel(args) {
|
|
|
127
132
|
const webSearch = anthropicWebSearchFor(args.request, model)
|
|
128
133
|
? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
129
134
|
: undefined;
|
|
130
|
-
const
|
|
135
|
+
const searchCount = chargesWebSearch(args.request)
|
|
136
|
+
? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
137
|
+
: undefined;
|
|
138
|
+
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, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
|
|
131
139
|
const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
|
|
132
140
|
const withWebSearchResults = webSearch
|
|
133
141
|
? eventsWithWebSearchResults(withSafeguardResults, webSearch)
|
|
134
142
|
: withSafeguardResults;
|
|
135
143
|
const withCacheWrites = eventsWithSubscriptionCacheWrites(withWebSearchResults, subscriptionUsageContext(args.model, model, source));
|
|
144
|
+
const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
|
|
136
145
|
return {
|
|
137
|
-
events:
|
|
146
|
+
events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
|
|
138
147
|
source,
|
|
139
148
|
};
|
|
140
149
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { InteractionRequest } from "../interaction/types.js";
|
|
2
|
+
import type { ProviderFetch } from "./response_capture.js";
|
|
3
|
+
export declare const WEB_SEARCH_USD_PER_SEARCH = 0.01;
|
|
4
|
+
export declare function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean;
|
|
5
|
+
export type WebSearchCountTap = {
|
|
6
|
+
fetch: ProviderFetch;
|
|
7
|
+
searches: () => number;
|
|
8
|
+
};
|
|
9
|
+
export declare function webSearchCountTap(fetch?: ProviderFetch): WebSearchCountTap;
|
|
10
|
+
export declare function messageWithWebSearchFee(message: Record<string, unknown>, searches: number): Record<string, unknown>;
|
|
11
|
+
export declare function eventsWithWebSearchFee(events: AsyncIterable<Record<string, unknown>>, tap: WebSearchCountTap): AsyncIterable<Record<string, unknown>>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
|
|
3
|
+
import { sseEventScanner } from "./anthropic_safeguards.js";
|
|
4
|
+
// Anthropic and OpenAI charge for each web search on top of tokens: $10 per
|
|
5
|
+
// 1,000 searches, a search that fails is not charged.
|
|
6
|
+
// https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
|
|
7
|
+
// https://developers.openai.com/api/docs/pricing
|
|
8
|
+
export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
|
|
9
|
+
// Whether the request can make the provider run a web search it charges for.
|
|
10
|
+
export function chargesWebSearch(request) {
|
|
11
|
+
const capabilities = requiredCapabilitiesFor(request);
|
|
12
|
+
return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
|
|
13
|
+
}
|
|
14
|
+
// Counts the searches the provider charged for, from its own stream:
|
|
15
|
+
// Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
|
|
16
|
+
// running total for the response), and OpenAI lists each completed
|
|
17
|
+
// `web_search_call`.
|
|
18
|
+
export function webSearchCountTap(fetch = globalThis.fetch) {
|
|
19
|
+
let anthropic = 0;
|
|
20
|
+
let openai = new Set();
|
|
21
|
+
return {
|
|
22
|
+
searches: () => anthropic + openai.size,
|
|
23
|
+
fetch: async (input, init) => {
|
|
24
|
+
const response = await fetch(input, init);
|
|
25
|
+
if (!response.ok || response.body === null)
|
|
26
|
+
return response;
|
|
27
|
+
anthropic = 0;
|
|
28
|
+
openai = new Set();
|
|
29
|
+
return new Response(response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
|
|
30
|
+
const usage = event.type === "message_delta" ? event.usage
|
|
31
|
+
: event.type === "message_start" && isRecord(event.message) ? event.message.usage
|
|
32
|
+
: undefined;
|
|
33
|
+
const requests = isRecord(usage) && isRecord(usage.server_tool_use)
|
|
34
|
+
? usage.server_tool_use.web_search_requests
|
|
35
|
+
: undefined;
|
|
36
|
+
if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
|
|
37
|
+
anthropic = Math.max(anthropic, Math.trunc(requests));
|
|
38
|
+
}
|
|
39
|
+
const item = event.type === "response.output_item.done" ? event.item : undefined;
|
|
40
|
+
if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
|
|
41
|
+
openai.add(item.id);
|
|
42
|
+
}
|
|
43
|
+
})), { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// Adds the searches' fee to the message's cost, which is what a managed key
|
|
48
|
+
// is billed. Keys the customer owns and subscriptions are not billed here.
|
|
49
|
+
export function messageWithWebSearchFee(message, searches) {
|
|
50
|
+
if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost))
|
|
51
|
+
return message;
|
|
52
|
+
const cost = message.usage.cost;
|
|
53
|
+
const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
|
|
54
|
+
return {
|
|
55
|
+
...message,
|
|
56
|
+
usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// Aborted and failed calls end in an error event carrying the partial
|
|
60
|
+
// message; a search the provider completed before the end is still charged.
|
|
61
|
+
export async function* eventsWithWebSearchFee(events, tap) {
|
|
62
|
+
for await (const event of events) {
|
|
63
|
+
if (event.type === "done" && isRecord(event.message)) {
|
|
64
|
+
yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (event.type === "error" && isRecord(event.error)) {
|
|
68
|
+
yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
yield event;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -24,7 +24,12 @@ export function piRequestContext(headers) {
|
|
|
24
24
|
}
|
|
25
25
|
const kind = headers.get("x-pi-request-kind")?.trim();
|
|
26
26
|
return {
|
|
27
|
-
requestClass: kind === "turn" ? "main"
|
|
27
|
+
requestClass: kind === "turn" ? "main"
|
|
28
|
+
: kind === "compaction" ? "compaction"
|
|
29
|
+
// The Dari extension's web search tool: one request beside the turn,
|
|
30
|
+
// served as background work like Claude Code's own search.
|
|
31
|
+
: kind === "search" ? "auxiliary"
|
|
32
|
+
: "unknown",
|
|
28
33
|
};
|
|
29
34
|
}
|
|
30
35
|
// OpenCode names the session behind every request, and a subagent's parent
|
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.324",
|
|
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.324",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -13,6 +13,7 @@ import { claudeCodeRequestContext } from "./claude_code/request_context.js";
|
|
|
13
13
|
import { claimedClientHarness } from "./client_harness.js";
|
|
14
14
|
import {
|
|
15
15
|
claudeCodeConversationIdentity,
|
|
16
|
+
piRequestContext,
|
|
16
17
|
} from "../runtime/harness_identity/index.js";
|
|
17
18
|
import { parseJsonRequest } from "./json.js";
|
|
18
19
|
import { anthropicWebSearchTool } from "../interaction/capabilities.js";
|
|
@@ -43,11 +44,15 @@ export async function handleAnthropicMessages(
|
|
|
43
44
|
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
44
45
|
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
45
46
|
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
46
|
-
|
|
47
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
48
|
+
// tool sends its search here, marked as Pi's.
|
|
49
|
+
const piContext = isClaudeCode ? undefined : piRequestContext(request.headers);
|
|
50
|
+
const agentContext = isClaudeCode ? claudeCodeRequestContext(request.headers) : piContext;
|
|
47
51
|
// Claude Code runs a web search as a background request that names one of
|
|
48
|
-
// the session's models
|
|
49
|
-
//
|
|
50
|
-
// Link token keeps the
|
|
52
|
+
// the session's models, and Pi's search tool as one that asks for routing.
|
|
53
|
+
// Like other background work, Dari serves it on the cheapest model that
|
|
54
|
+
// can: a Claude model on Anthropic's API. A Dari Link token keeps the
|
|
55
|
+
// model it names.
|
|
51
56
|
const backgroundWebSearch = agentContext !== undefined
|
|
52
57
|
&& isBackgroundRequest({ ...interaction, agentContext })
|
|
53
58
|
&& anthropicWebSearchTool(interaction) !== undefined
|
|
@@ -69,7 +74,7 @@ export async function handleAnthropicMessages(
|
|
|
69
74
|
? { requestPurpose: "tool_continuation" as const } : {}),
|
|
70
75
|
claudeCodeUserAgent: request.headers.get("user-agent")!.trim(),
|
|
71
76
|
}
|
|
72
|
-
: forwarded;
|
|
77
|
+
: { ...forwarded, ...(agentContext === undefined ? {} : { agentContext }) };
|
|
73
78
|
return await handleRoutedCompletion({
|
|
74
79
|
request,
|
|
75
80
|
routerId,
|
|
@@ -79,7 +84,9 @@ export async function handleAnthropicMessages(
|
|
|
79
84
|
streamBody: anthropicMessagesSseStream,
|
|
80
85
|
errorResponse: anthropicErrorResponse,
|
|
81
86
|
selectorBackend,
|
|
82
|
-
clientHarness: isClaudeCode ? "claude_code"
|
|
87
|
+
clientHarness: isClaudeCode ? "claude_code"
|
|
88
|
+
: piContext !== undefined ? "pi"
|
|
89
|
+
: claimedClientHarness(request.headers),
|
|
83
90
|
harnessConversationIdentity: isClaudeCode
|
|
84
91
|
? claudeCodeConversationIdentity(
|
|
85
92
|
request.headers,
|
package/src/ingress/codex.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
codexRequestPurpose,
|
|
16
16
|
codexRequestContext,
|
|
17
17
|
museCodeConversationIdentity,
|
|
18
|
+
piRequestContext,
|
|
18
19
|
} from "../runtime/harness_identity/index.js";
|
|
19
20
|
|
|
20
21
|
export async function handleResponses(
|
|
@@ -27,7 +28,11 @@ export async function handleResponses(
|
|
|
27
28
|
const rawPayload = await parseJsonRequest<Record<string, unknown>>(request);
|
|
28
29
|
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
29
30
|
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
30
|
-
const
|
|
31
|
+
const codexContext = codexRequestContext(request.headers, rawPayload);
|
|
32
|
+
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
33
|
+
// tool sends an OpenAI hosted search here, marked as Pi's.
|
|
34
|
+
const piContext = codexContext === undefined ? piRequestContext(request.headers) : undefined;
|
|
35
|
+
const agentContext = codexContext ?? piContext;
|
|
31
36
|
const museClientId = museCodeClientId(request.headers);
|
|
32
37
|
const payload = {
|
|
33
38
|
...interaction,
|
|
@@ -59,7 +64,8 @@ export async function handleResponses(
|
|
|
59
64
|
selectorBackend,
|
|
60
65
|
clientHarness: museClientId !== undefined ? "muse_code"
|
|
61
66
|
// Codex describes every request in its turn metadata.
|
|
62
|
-
:
|
|
67
|
+
: codexContext !== undefined ? "codex"
|
|
68
|
+
: piContext !== undefined ? "pi"
|
|
63
69
|
: claimedClientHarness(request.headers),
|
|
64
70
|
harnessConversationIdentity,
|
|
65
71
|
});
|
package/src/providers/pi.ts
CHANGED
|
@@ -53,6 +53,7 @@ import {
|
|
|
53
53
|
messageWithWebSearchResults,
|
|
54
54
|
webSearchResultsTap,
|
|
55
55
|
} from "./anthropic_web_search.js";
|
|
56
|
+
import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
|
|
56
57
|
import {
|
|
57
58
|
eventsWithProviderReportedCost,
|
|
58
59
|
messageWithProviderReportedCost,
|
|
@@ -161,6 +162,9 @@ export async function completeInteractionModel(args: {
|
|
|
161
162
|
const webSearch = anthropicWebSearchFor(args.request, model)
|
|
162
163
|
? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
163
164
|
: undefined;
|
|
165
|
+
const searchCount = chargesWebSearch(args.request)
|
|
166
|
+
? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
167
|
+
: undefined;
|
|
164
168
|
const options = buildOptions(
|
|
165
169
|
args.request,
|
|
166
170
|
args.auth ?? args.apiKey,
|
|
@@ -171,22 +175,26 @@ export async function completeInteractionModel(args: {
|
|
|
171
175
|
args.selectedReasoningEffort,
|
|
172
176
|
args.timeoutMs,
|
|
173
177
|
args.signal,
|
|
174
|
-
webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
|
|
178
|
+
searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
|
|
175
179
|
);
|
|
176
180
|
const usageContext = subscriptionUsageContext(args.model, model, source);
|
|
177
181
|
const message = options.emitProviderEvents === true
|
|
178
182
|
? await completeProviderEventStream(pi.streamSimple(model, context, options))
|
|
179
183
|
: await pi.completeSimple(model, context, options);
|
|
180
184
|
return {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
185
|
+
// The search fee goes on last, over whatever cost the steps before set.
|
|
186
|
+
message: messageWithWebSearchFee(
|
|
187
|
+
messageWithProviderReportedCost(
|
|
188
|
+
messageWithSubscriptionCacheWrites(
|
|
189
|
+
messageWithWebSearchResults(
|
|
190
|
+
messageWithSafeguardResults(message, safeguards?.results()),
|
|
191
|
+
webSearch?.results() ?? [],
|
|
192
|
+
),
|
|
193
|
+
usageContext
|
|
186
194
|
),
|
|
187
|
-
|
|
195
|
+
costTap?.cost(),
|
|
188
196
|
),
|
|
189
|
-
|
|
197
|
+
searchCount?.searches() ?? 0,
|
|
190
198
|
),
|
|
191
199
|
source,
|
|
192
200
|
};
|
|
@@ -266,6 +274,9 @@ export async function streamInteractionModel(args: {
|
|
|
266
274
|
const webSearch = anthropicWebSearchFor(args.request, model)
|
|
267
275
|
? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
268
276
|
: undefined;
|
|
277
|
+
const searchCount = chargesWebSearch(args.request)
|
|
278
|
+
? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
|
|
279
|
+
: undefined;
|
|
269
280
|
const events = pi.streamSimple(
|
|
270
281
|
model,
|
|
271
282
|
buildContext(args.request, source),
|
|
@@ -279,7 +290,7 @@ export async function streamInteractionModel(args: {
|
|
|
279
290
|
args.selectedReasoningEffort,
|
|
280
291
|
undefined,
|
|
281
292
|
args.signal,
|
|
282
|
-
webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
|
|
293
|
+
searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
|
|
283
294
|
)
|
|
284
295
|
);
|
|
285
296
|
const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
|
|
@@ -290,8 +301,9 @@ export async function streamInteractionModel(args: {
|
|
|
290
301
|
withWebSearchResults,
|
|
291
302
|
subscriptionUsageContext(args.model, model, source)
|
|
292
303
|
);
|
|
304
|
+
const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
|
|
293
305
|
return {
|
|
294
|
-
events:
|
|
306
|
+
events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
|
|
295
307
|
source,
|
|
296
308
|
};
|
|
297
309
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
|
|
3
|
+
import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
|
|
4
|
+
import type { InteractionRequest } from "../interaction/types.js";
|
|
5
|
+
import { sseEventScanner } from "./anthropic_safeguards.js";
|
|
6
|
+
import type { ProviderFetch } from "./response_capture.js";
|
|
7
|
+
|
|
8
|
+
// Anthropic and OpenAI charge for each web search on top of tokens: $10 per
|
|
9
|
+
// 1,000 searches, a search that fails is not charged.
|
|
10
|
+
// https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
|
|
11
|
+
// https://developers.openai.com/api/docs/pricing
|
|
12
|
+
export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
|
|
13
|
+
|
|
14
|
+
// Whether the request can make the provider run a web search it charges for.
|
|
15
|
+
export function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean {
|
|
16
|
+
const capabilities = requiredCapabilitiesFor(request);
|
|
17
|
+
return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type WebSearchCountTap = {
|
|
21
|
+
fetch: ProviderFetch;
|
|
22
|
+
searches: () => number;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Counts the searches the provider charged for, from its own stream:
|
|
26
|
+
// Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
|
|
27
|
+
// running total for the response), and OpenAI lists each completed
|
|
28
|
+
// `web_search_call`.
|
|
29
|
+
export function webSearchCountTap(fetch: ProviderFetch = globalThis.fetch): WebSearchCountTap {
|
|
30
|
+
let anthropic = 0;
|
|
31
|
+
let openai = new Set<string>();
|
|
32
|
+
return {
|
|
33
|
+
searches: () => anthropic + openai.size,
|
|
34
|
+
fetch: async (input, init) => {
|
|
35
|
+
const response = await fetch(input, init);
|
|
36
|
+
if (!response.ok || response.body === null) return response;
|
|
37
|
+
anthropic = 0;
|
|
38
|
+
openai = new Set();
|
|
39
|
+
return new Response(
|
|
40
|
+
response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
|
|
41
|
+
const usage = event.type === "message_delta" ? event.usage
|
|
42
|
+
: event.type === "message_start" && isRecord(event.message) ? event.message.usage
|
|
43
|
+
: undefined;
|
|
44
|
+
const requests = isRecord(usage) && isRecord(usage.server_tool_use)
|
|
45
|
+
? usage.server_tool_use.web_search_requests
|
|
46
|
+
: undefined;
|
|
47
|
+
if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
|
|
48
|
+
anthropic = Math.max(anthropic, Math.trunc(requests));
|
|
49
|
+
}
|
|
50
|
+
const item = event.type === "response.output_item.done" ? event.item : undefined;
|
|
51
|
+
if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
|
|
52
|
+
openai.add(item.id);
|
|
53
|
+
}
|
|
54
|
+
})),
|
|
55
|
+
{ status: response.status, statusText: response.statusText, headers: response.headers },
|
|
56
|
+
);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Adds the searches' fee to the message's cost, which is what a managed key
|
|
62
|
+
// is billed. Keys the customer owns and subscriptions are not billed here.
|
|
63
|
+
export function messageWithWebSearchFee(
|
|
64
|
+
message: Record<string, unknown>,
|
|
65
|
+
searches: number,
|
|
66
|
+
): Record<string, unknown> {
|
|
67
|
+
if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost)) return message;
|
|
68
|
+
const cost = message.usage.cost;
|
|
69
|
+
const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
|
|
70
|
+
return {
|
|
71
|
+
...message,
|
|
72
|
+
usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Aborted and failed calls end in an error event carrying the partial
|
|
77
|
+
// message; a search the provider completed before the end is still charged.
|
|
78
|
+
export async function* eventsWithWebSearchFee(
|
|
79
|
+
events: AsyncIterable<Record<string, unknown>>,
|
|
80
|
+
tap: WebSearchCountTap,
|
|
81
|
+
): AsyncIterable<Record<string, unknown>> {
|
|
82
|
+
for await (const event of events) {
|
|
83
|
+
if (event.type === "done" && isRecord(event.message)) {
|
|
84
|
+
yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (event.type === "error" && isRecord(event.error)) {
|
|
88
|
+
yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
yield event;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -39,7 +39,12 @@ export function piRequestContext(headers: Headers): AgentRequestContext | undefi
|
|
|
39
39
|
}
|
|
40
40
|
const kind = headers.get("x-pi-request-kind")?.trim();
|
|
41
41
|
return {
|
|
42
|
-
requestClass: kind === "turn" ? "main"
|
|
42
|
+
requestClass: kind === "turn" ? "main"
|
|
43
|
+
: kind === "compaction" ? "compaction"
|
|
44
|
+
// The Dari extension's web search tool: one request beside the turn,
|
|
45
|
+
// served as background work like Claude Code's own search.
|
|
46
|
+
: kind === "search" ? "auxiliary"
|
|
47
|
+
: "unknown",
|
|
43
48
|
};
|
|
44
49
|
}
|
|
45
50
|
|