@mupt-ai/dari-gateway 1.0.344 → 1.0.346
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/activity/conversation_detail.js +4 -2
- package/dist/activity/conversation_records.d.ts +2 -0
- package/dist/activity/conversation_records.js +5 -2
- package/dist/http/handler.js +48 -15
- package/dist/link/client.d.ts +1 -1
- package/dist/link/endpoints.js +11 -6
- package/dist/link/service.js +13 -7
- package/dist/platform/platform.d.ts +1 -1
- package/dist/protocol/input/openai_responses.js +18 -1
- package/dist/protocol/output/anthropic_messages.d.ts +1 -0
- package/dist/protocol/output/anthropic_messages.js +2 -1
- package/dist/protocol/output/anthropic_messages_stream.d.ts +1 -0
- package/dist/protocol/output/anthropic_messages_stream.js +3 -2
- package/dist/protocol/output/openai_responses.d.ts +1 -0
- package/dist/protocol/output/openai_responses.js +2 -1
- package/dist/protocol/output/openai_responses_stream.d.ts +1 -0
- package/dist/protocol/output/openai_responses_stream.js +6 -4
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +4 -2
- package/src/activity/conversation_records.ts +6 -2
- package/src/http/handler.ts +53 -26
- package/src/link/client.ts +1 -1
- package/src/link/endpoints.ts +11 -7
- package/src/link/service.ts +13 -7
- package/src/platform/platform.ts +3 -0
- package/src/protocol/input/openai_responses.ts +18 -0
- package/src/protocol/output/anthropic_messages.ts +3 -1
- package/src/protocol/output/anthropic_messages_stream.ts +4 -2
- package/src/protocol/output/openai_responses.ts +3 -1
- package/src/protocol/output/openai_responses_stream.ts +9 -4
package/README.md
CHANGED
|
@@ -258,7 +258,7 @@ The gateway refuses a model the grant cannot serve, a plan at its limit, a spent
|
|
|
258
258
|
}
|
|
259
259
|
```
|
|
260
260
|
|
|
261
|
-
`serves` is `any_app`, `claude_code_only`, or `muse_code_only`. A plan's `state` is the one answer to "can this plan serve the app now": `ready
|
|
261
|
+
`serves` is `any_app`, `claude_code_only`, or `muse_code_only`. A plan's `state` is the one answer to "can this plan serve the app now": `ready`; `plan_limit`, the plan is at its own usage limit; or `user_limit`, the plan or key is at the limit the user set for this app. `available_at` is when it serves again (null when ready or unknown). The grant's own `state` is `budget_limit` while a window of its budget is at its cap, until `available_at` (see **Budgets**). `label` is the user's name for the plan, else its account. `usage` lists the quota windows the plan last reported (five hours and a week for these plans), each with the share used from 0 to 1 and when it resets; it is empty until the plan has served a request through Dari (any request, not only this app's, including the user's own Claude Code or Codex through Dari), because plans report their windows only on responses. Dari does not read a fresh plan's windows when it connects: that takes a call to the provider with the user's credential that neither Claude nor ChatGPT documents for third parties, so a just-connected plan shows no usage until its first request. A plan's `models` are those it serves its clients now, each with the name a request uses (`id`) and the catalog's display name (`name`); the top-level `models` are what a plain API client can name now, and `routes` says whether `dari/routing` serves it. `GET /v1/models` with a link token lists the same models in the OpenAI list shape, empty when none can serve. `GET /v1/link/grant` makes no provider call, so it is the cheap check before a long run: a dead grant answers 401, and `unavailable_until` and `usage` say whether the plans have room.
|
|
262
262
|
|
|
263
263
|
**Budgets.** A user can cap the tokens an app may use per five hours and per week: on the connections page, or with `PUT /v1/link/grants/<id>/budget` and `{"budget": [{"window_minutes": 10080, "max_tokens": 5000000}]}` (the user's key; `window_minutes` is `300` or `10080`; `[]` removes it). The budget covers the whole grant: all its plans and API keys together.
|
|
264
264
|
|
|
@@ -168,7 +168,9 @@ function conversationStep(record, organizationId, currentRouterZdr, skillEvents)
|
|
|
168
168
|
}
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
const
|
|
171
|
+
const zdr = record.zdr || currentRouterZdr;
|
|
172
|
+
// ZDR content is never served, even when an older blob is still stored.
|
|
173
|
+
const available = (key) => !zdr && Boolean(record.blobBucket) && Boolean(key);
|
|
172
174
|
const url = (name) => `/v1/organizations/${organizationId}/routing/activity/requests/${record.id}/${name}`;
|
|
173
175
|
return {
|
|
174
176
|
id: record.id,
|
|
@@ -199,7 +201,7 @@ function conversationStep(record, organizationId, currentRouterZdr, skillEvents)
|
|
|
199
201
|
has_declared_tools: record.hasTools,
|
|
200
202
|
received_at: formatInstant(record.receivedAt),
|
|
201
203
|
completed_at: record.completedAt === null ? null : formatInstant(record.completedAt),
|
|
202
|
-
zdr
|
|
204
|
+
zdr,
|
|
203
205
|
decision_source: typeof details?.decision_source === "string" ? details.decision_source : null,
|
|
204
206
|
selector_reason: record.selectorReason,
|
|
205
207
|
selector_policy_bypassed: bypassed,
|
|
@@ -92,6 +92,8 @@ export declare function consecutivePath(values: ReadonlyArray<string | null>): s
|
|
|
92
92
|
export declare function decisionDetails(record: ConversationRecord): Record<string, unknown> | null;
|
|
93
93
|
export declare function selectedEffort(record: ConversationRecord): ReasoningEffort | null;
|
|
94
94
|
/** The conversation summary over its steps, oldest first. */
|
|
95
|
+
/** Titles are model-generated from content, so ZDR sessions get a fixed one. */
|
|
96
|
+
export declare const ZDR_SESSION_TITLE = "Zero Data Retention Session";
|
|
95
97
|
export declare function conversationSummary(records: readonly ConversationRecord[], entities: Entities, title: string | undefined, switches: number | null): {
|
|
96
98
|
conversation_ref: string;
|
|
97
99
|
conversation_id: string | null;
|
|
@@ -203,6 +203,8 @@ export function selectedEffort(record) {
|
|
|
203
203
|
return thinkingLevelValue(decisionDetails(record)?.selected_reasoning_effort);
|
|
204
204
|
}
|
|
205
205
|
/** The conversation summary over its steps, oldest first. */
|
|
206
|
+
/** Titles are model-generated from content, so ZDR sessions get a fixed one. */
|
|
207
|
+
export const ZDR_SESSION_TITLE = "Zero Data Retention Session";
|
|
206
208
|
export function conversationSummary(records, entities, title, switches) {
|
|
207
209
|
const first = records[0];
|
|
208
210
|
const last = records.at(-1);
|
|
@@ -240,13 +242,14 @@ export function conversationSummary(records, entities, title, switches) {
|
|
|
240
242
|
allZdr &&= record.zdr;
|
|
241
243
|
anyZdr ||= record.zdr;
|
|
242
244
|
}
|
|
245
|
+
const retention = router?.zdr || allZdr ? "zdr" : anyZdr ? "mixed" : "retained";
|
|
243
246
|
return {
|
|
244
247
|
conversation_ref: first.id,
|
|
245
248
|
conversation_id: first.conversationId || null,
|
|
246
249
|
agent_session_id: first.agentSessionId || null,
|
|
247
250
|
context_runs: runs.size,
|
|
248
251
|
source_protocol: first.sourceProtocol,
|
|
249
|
-
title: title || ([...records].reverse().find((record) => record.conversationTitle)?.conversationTitle ?? null),
|
|
252
|
+
title: retention === "zdr" ? ZDR_SESSION_TITLE : title || ([...records].reverse().find((record) => record.conversationTitle)?.conversationTitle ?? null),
|
|
250
253
|
router_id: first.routerId,
|
|
251
254
|
router_name: router?.name ?? null,
|
|
252
255
|
api_key_id: first.apiKeyId,
|
|
@@ -269,7 +272,7 @@ export function conversationSummary(records, entities, title, switches) {
|
|
|
269
272
|
has_error: hasError,
|
|
270
273
|
has_aborted: hasAborted,
|
|
271
274
|
terminal_status: last.status,
|
|
272
|
-
retention
|
|
275
|
+
retention,
|
|
273
276
|
};
|
|
274
277
|
}
|
|
275
278
|
/** Model changes within each context run. */
|
package/dist/http/handler.js
CHANGED
|
@@ -48,21 +48,15 @@ export function createRequestHandler(options) {
|
|
|
48
48
|
return await handleGitEvents(request, gitEvents[1] ?? DEFAULT_ROUTER_ALIAS, options.platform.activity);
|
|
49
49
|
}
|
|
50
50
|
const endpoint = routedEndpoint(url.pathname);
|
|
51
|
-
if (endpoint
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (request.method === "
|
|
56
|
-
return
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
if (endpoint?.protocol === "messages" && request.method === "POST") {
|
|
62
|
-
return await handleAnthropicMessages(request, endpoint.routerId, selectorBackend);
|
|
63
|
-
}
|
|
64
|
-
if (endpoint?.protocol === "models" && request.method === "GET") {
|
|
65
|
-
return await handleModels(request, endpoint.routerId);
|
|
51
|
+
if (endpoint !== null) {
|
|
52
|
+
// Browsers send Origin on every cross-origin call; a request without
|
|
53
|
+
// one (a server, a coding agent) is served exactly as before.
|
|
54
|
+
const fromBrowser = request.headers.has("Origin");
|
|
55
|
+
if (fromBrowser && request.method === "OPTIONS")
|
|
56
|
+
return withCors(request, new Response(null, { status: 204 }));
|
|
57
|
+
const response = await serveEndpoint(request, endpoint, selectorBackend);
|
|
58
|
+
if (response !== null)
|
|
59
|
+
return fromBrowser ? withCors(request, response) : response;
|
|
66
60
|
}
|
|
67
61
|
// The gateway counts no tokens. Claude Code calls this for any Anthropic
|
|
68
62
|
// base URL and estimates locally when it fails, so it gets an error it parses.
|
|
@@ -72,6 +66,45 @@ export function createRequestHandler(options) {
|
|
|
72
66
|
return errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
73
67
|
};
|
|
74
68
|
}
|
|
69
|
+
async function serveEndpoint(request, endpoint, selectorBackend) {
|
|
70
|
+
if (endpoint.protocol === "chat" && request.method === "POST") {
|
|
71
|
+
return await handleChatCompletions(request, endpoint.routerId, selectorBackend);
|
|
72
|
+
}
|
|
73
|
+
if (endpoint.protocol === "responses") {
|
|
74
|
+
if (request.method === "GET")
|
|
75
|
+
return handleResponsesWebSocketFallback();
|
|
76
|
+
if (request.method === "POST")
|
|
77
|
+
return await handleResponses(request, endpoint.routerId, selectorBackend);
|
|
78
|
+
}
|
|
79
|
+
if (endpoint.protocol === "messages" && request.method === "POST") {
|
|
80
|
+
return await handleAnthropicMessages(request, endpoint.routerId, selectorBackend);
|
|
81
|
+
}
|
|
82
|
+
if (endpoint.protocol === "models" && request.method === "GET") {
|
|
83
|
+
return await handleModels(request, endpoint.routerId);
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* A browser app calls the model endpoints from its own origin, with a Dari
|
|
89
|
+
* Link token or a key. Neither is a cookie or other ambient credential, so
|
|
90
|
+
* any origin may call, as with Dari Link's own endpoints.
|
|
91
|
+
*
|
|
92
|
+
* The preflight allows the headers it asks for, since clients differ:
|
|
93
|
+
* `x-api-key` and `anthropic-version` from Anthropic's SDK, `x-stainless-*`
|
|
94
|
+
* from OpenAI's, `X-Dari-Tags`. Every response header is exposed, so a page
|
|
95
|
+
* can read `X-Request-Id`, `X-Dari-Usage`, and `Retry-After`.
|
|
96
|
+
*/
|
|
97
|
+
function withCors(request, response) {
|
|
98
|
+
const headers = new Headers(response.headers);
|
|
99
|
+
headers.set("Access-Control-Allow-Origin", "*");
|
|
100
|
+
headers.set("Access-Control-Expose-Headers", "*");
|
|
101
|
+
if (request.method === "OPTIONS") {
|
|
102
|
+
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
103
|
+
headers.set("Access-Control-Allow-Headers", request.headers.get("Access-Control-Request-Headers") ?? "Authorization, Content-Type");
|
|
104
|
+
headers.set("Access-Control-Max-Age", "600");
|
|
105
|
+
}
|
|
106
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
107
|
+
}
|
|
75
108
|
function routedEndpoint(pathname) {
|
|
76
109
|
const defaultProtocol = protocolForSuffix(pathname, "/v1");
|
|
77
110
|
if (defaultProtocol !== null) {
|
package/dist/link/client.d.ts
CHANGED
package/dist/link/endpoints.js
CHANGED
|
@@ -883,7 +883,7 @@ async function grantBody(platform, request, accessToken, detail) {
|
|
|
883
883
|
const kind = subscription.provider;
|
|
884
884
|
const client = keyFor === undefined ? subscriptionClient(kind) : undefined;
|
|
885
885
|
return {
|
|
886
|
-
...planState(subscription, now),
|
|
886
|
+
...planState(subscription, detail.spend.find((entry) => entry.credentialId === subscription.id), now),
|
|
887
887
|
id: subscription.id,
|
|
888
888
|
kind: keyFor === undefined ? kind : API_KEY,
|
|
889
889
|
// What to call it on screen: "Claude", "ChatGPT", "OpenRouter".
|
|
@@ -918,16 +918,21 @@ function latest(times) {
|
|
|
918
918
|
return times.reduce((last, time) => last === null || Date.parse(time) > Date.parse(last) ? time : last, null);
|
|
919
919
|
}
|
|
920
920
|
/**
|
|
921
|
-
* Whether a granted plan serves the app now. `plan_limit`: the plan is
|
|
922
|
-
* own usage limit
|
|
923
|
-
*
|
|
921
|
+
* Whether a granted plan or key serves the app now. `plan_limit`: the plan is
|
|
922
|
+
* at its own usage limit. `user_limit`: it is at the limit the user set for
|
|
923
|
+
* this app. Either way it is available again at `available_at` (null when
|
|
924
|
+
* ready or not known).
|
|
924
925
|
*/
|
|
925
|
-
function planState(subscription, now) {
|
|
926
|
+
function planState(subscription, spend, now) {
|
|
926
927
|
const planTimes = [
|
|
927
928
|
...(subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? [subscription.unavailableUntil] : []),
|
|
928
929
|
...subscription.usage.filter((window) => window.modelFamily === undefined && window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
|
|
929
930
|
];
|
|
930
|
-
|
|
931
|
+
if (planTimes.length > 0)
|
|
932
|
+
return { state: "plan_limit", available_at: latest(planTimes) };
|
|
933
|
+
if (spend?.reached)
|
|
934
|
+
return { state: "user_limit", available_at: spend.resetsAt };
|
|
935
|
+
return { state: "ready", available_at: null };
|
|
931
936
|
}
|
|
932
937
|
/** Whether the grant is within its budget: `budget_limit` until every window at its cap rolls on. */
|
|
933
938
|
function grantState(budget) {
|
package/dist/link/service.js
CHANGED
|
@@ -143,12 +143,11 @@ export function linkPlatform(store, users) {
|
|
|
143
143
|
const grants = await store.grants(subject);
|
|
144
144
|
// One lookup for every grant's plans, not one per grant per use.
|
|
145
145
|
const plans = await users.plansWithIds([...new Set(grants.flatMap((grant) => grant.credentialIds))]);
|
|
146
|
-
|
|
146
|
+
// One grant, and one step of it, at a time: a hosted store holds a pooled connection per call.
|
|
147
|
+
return await inSeries(grants, async (grant) => {
|
|
147
148
|
const shared = plans.filter((plan) => grant.credentialIds.includes(plan.id));
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
standings(grant, shared),
|
|
151
|
-
]);
|
|
149
|
+
const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
|
|
150
|
+
const standing = await standings(grant, shared);
|
|
152
151
|
return {
|
|
153
152
|
id: grant.id,
|
|
154
153
|
clientId: grant.clientId,
|
|
@@ -159,7 +158,7 @@ export function linkPlatform(store, users) {
|
|
|
159
158
|
subscriptions: shared,
|
|
160
159
|
usage,
|
|
161
160
|
};
|
|
162
|
-
})
|
|
161
|
+
});
|
|
163
162
|
},
|
|
164
163
|
async disconnect(subject, grantId) {
|
|
165
164
|
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
@@ -220,7 +219,7 @@ export function linkPlatform(store, users) {
|
|
|
220
219
|
},
|
|
221
220
|
async grants(apiKey) {
|
|
222
221
|
const subject = await users.manager(apiKey);
|
|
223
|
-
return await
|
|
222
|
+
return await inSeries(await store.grants(subject), managedGrant);
|
|
224
223
|
},
|
|
225
224
|
async plans(apiKey) {
|
|
226
225
|
return await users.plans(await endpointOwner(apiKey));
|
|
@@ -362,3 +361,10 @@ function endpointName(name) {
|
|
|
362
361
|
}
|
|
363
362
|
return trimmed;
|
|
364
363
|
}
|
|
364
|
+
// Each item in turn, so a store that holds a connection per call holds one at a time.
|
|
365
|
+
async function inSeries(items, each) {
|
|
366
|
+
const results = [];
|
|
367
|
+
for (const item of items)
|
|
368
|
+
results.push(await each(item));
|
|
369
|
+
return results;
|
|
370
|
+
}
|
|
@@ -616,7 +616,7 @@ export type RequestErrorContext = {
|
|
|
616
616
|
sourceProtocol: SourceProtocol | "openai_models" | "anthropic_models";
|
|
617
617
|
status: number;
|
|
618
618
|
};
|
|
619
|
-
export type OperationalErrorCode = "background_drain_timeout" | "billing_usage_report_failed" | "routing_report_assembly_failed" | "routing_report_barrier_failed" | "server_force_stop_failed" | "session_pin_write_failed" | "stream_report_finalization_failed" | "subscription_unavailable_ingest_failed" | "subscription_usage_record_failed" | "next_subscription_lookup_failed";
|
|
619
|
+
export type OperationalErrorCode = "background_drain_timeout" | "billing_usage_report_failed" | "routing_report_assembly_failed" | "routing_report_barrier_failed" | "routing_resolve_failed" | "routing_resolve_shadow_failed" | "routing_resolve_shadow_mismatch" | "server_force_stop_failed" | "session_pin_write_failed" | "stream_report_finalization_failed" | "subscription_unavailable_ingest_failed" | "subscription_usage_record_failed" | "next_subscription_lookup_failed";
|
|
620
620
|
export type OperationalErrorContext = {
|
|
621
621
|
code: OperationalErrorCode;
|
|
622
622
|
requestId?: string;
|
|
@@ -4,7 +4,7 @@ import { HttpError } from "../../http/errors.js";
|
|
|
4
4
|
import { parseDataImageUrl } from "../../interaction/image.js";
|
|
5
5
|
import { decodeUntrustedProviderContinuationState } from "../../interaction/provider_continuation_state.js";
|
|
6
6
|
import { CANONICAL_ROUTER_MODEL, explicitModelId, unsupportedModelMessage } from "./router_model.js";
|
|
7
|
-
import { isProtocolToolCallId, TOOL_CALL_ID_MAX_LENGTH, toolsByWireName, } from "../../interaction/tool_identity.js";
|
|
7
|
+
import { isProtocolToolCallId, TOOL_CALL_ID_MAX_LENGTH, toolsByWireName, toolWireName, } from "../../interaction/tool_identity.js";
|
|
8
8
|
import { parsePdfDataUrl } from "../../interaction/document.js";
|
|
9
9
|
const UNSUPPORTED_INPUT_ITEM_TYPES = new Set([
|
|
10
10
|
"additional_tools",
|
|
@@ -198,6 +198,8 @@ function responseItem(value, itemIndex, hostedReplayId) {
|
|
|
198
198
|
if (type === "function_call" || type === "custom_tool_call")
|
|
199
199
|
return toolCallItem(value, type === "function_call" ? "function" : "custom");
|
|
200
200
|
if (type === "function_call_output" || type === "custom_tool_call_output") {
|
|
201
|
+
if (value.call_id === undefined || value.call_id === null)
|
|
202
|
+
return callIdlessToolOutputNote(value, `input.${type}`);
|
|
201
203
|
return toolResultItem(value, type === "function_call_output" ? "function" : "custom");
|
|
202
204
|
}
|
|
203
205
|
if (type === "message" || typeof value.role === "string")
|
|
@@ -357,6 +359,21 @@ function toolResultItem(value, kind) {
|
|
|
357
359
|
outputShape: responseContentShape(value.output),
|
|
358
360
|
};
|
|
359
361
|
}
|
|
362
|
+
// Codex appends outputs that answer no call, such as its goal objective
|
|
363
|
+
// (`agent` / `goal_objective`) after `create_goal`; they reach the model as a
|
|
364
|
+
// developer note.
|
|
365
|
+
function callIdlessToolOutputNote(value, prefix) {
|
|
366
|
+
const name = optionalString(value.name, `${prefix}.name`);
|
|
367
|
+
const namespace = optionalString(value.namespace, `${prefix}.namespace`);
|
|
368
|
+
const output = responseContent(value.output, `${prefix}.output`);
|
|
369
|
+
return {
|
|
370
|
+
type: "message",
|
|
371
|
+
id: optionalString(value.id, `${prefix}.id`),
|
|
372
|
+
role: "developer",
|
|
373
|
+
content: name ? [{ type: "text", text: `${toolWireName(namespace, name)}:` }, ...output] : output,
|
|
374
|
+
contentShape: "parts",
|
|
375
|
+
};
|
|
376
|
+
}
|
|
360
377
|
function responseToolOutput(value, param) {
|
|
361
378
|
if (value === undefined || value === null || typeof value === "string")
|
|
362
379
|
return value ?? null;
|
|
@@ -8,7 +8,8 @@ export function anthropicMessagesResponse(args) {
|
|
|
8
8
|
content: anthropicContent(args.output),
|
|
9
9
|
stop_reason: anthropicStopReason(args.output),
|
|
10
10
|
stop_sequence: null,
|
|
11
|
-
|
|
11
|
+
// As on Chat Completions. Null means unpriced, never a fabricated free request.
|
|
12
|
+
usage: { ...anthropicUsage(args.output), cost: args.modelCost ?? null },
|
|
12
13
|
...(args.output.safeguardResults ? { safeguard_results: args.output.safeguardResults } : {}),
|
|
13
14
|
dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
|
|
14
15
|
};
|
|
@@ -9,6 +9,7 @@ export declare function anthropicMessagesSseStream(args: {
|
|
|
9
9
|
request: InteractionRequest;
|
|
10
10
|
conversationId?: string;
|
|
11
11
|
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
12
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
12
13
|
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
13
14
|
clientSignal?: AbortSignal;
|
|
14
15
|
onAbort?: () => void;
|
|
@@ -244,8 +244,9 @@ export function anthropicMessagesSseStream(args) {
|
|
|
244
244
|
},
|
|
245
245
|
// message_start goes out before the provider answers, so the
|
|
246
246
|
// cumulative input and cache counts ride here, as on Anthropic.
|
|
247
|
-
// Claude Code sizes its context window from them.
|
|
248
|
-
|
|
247
|
+
// Claude Code sizes its context window from them. `cost` as on
|
|
248
|
+
// Chat Completions: null means unpriced.
|
|
249
|
+
usage: { ...anthropicUsage(output), cost: args.modelCost?.(event.message, false) ?? null },
|
|
249
250
|
});
|
|
250
251
|
}
|
|
251
252
|
break;
|
|
@@ -7,7 +7,8 @@ export function openAIResponsesResponse(args) {
|
|
|
7
7
|
...openAIResponsesTerminal(args.output),
|
|
8
8
|
model: args.model,
|
|
9
9
|
output: openAIResponsesOutputItems(args.output),
|
|
10
|
-
|
|
10
|
+
// As on Chat Completions. Null means unpriced, never a fabricated free request.
|
|
11
|
+
usage: { ...openAIResponsesUsage(args.output), cost: args.modelCost ?? null },
|
|
11
12
|
parallel_tool_calls: args.request.parallelToolCalls ?? true,
|
|
12
13
|
dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
|
|
13
14
|
};
|
|
@@ -9,6 +9,7 @@ type StreamArgs = {
|
|
|
9
9
|
request: InteractionRequest;
|
|
10
10
|
conversationId?: string;
|
|
11
11
|
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
12
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
12
13
|
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
13
14
|
clientSignal?: AbortSignal;
|
|
14
15
|
onAbort?: () => void;
|
|
@@ -46,9 +46,10 @@ export function openAIResponsesSseStream(args) {
|
|
|
46
46
|
const output = accumulator.complete(event.message, send);
|
|
47
47
|
settle({ status: "completed", message: event.message, output });
|
|
48
48
|
const terminal = openAIResponsesTerminal(output);
|
|
49
|
+
const cost = args.modelCost?.(event.message, false);
|
|
49
50
|
emitTerminal = () => {
|
|
50
51
|
send(`response.${terminal.status}`, {
|
|
51
|
-
response: responseEnvelope(args, responseId, createdAt, terminal.status, openAIResponsesOutputItems(output), output),
|
|
52
|
+
response: responseEnvelope(args, responseId, createdAt, terminal.status, openAIResponsesOutputItems(output), output, cost),
|
|
52
53
|
});
|
|
53
54
|
};
|
|
54
55
|
break;
|
|
@@ -534,7 +535,7 @@ function sameOutputIdentity(left, right) {
|
|
|
534
535
|
&& left.name === right.name
|
|
535
536
|
&& left.namespace === right.namespace;
|
|
536
537
|
}
|
|
537
|
-
function responseEnvelope(args, id, createdAt, status, output, interaction) {
|
|
538
|
+
function responseEnvelope(args, id, createdAt, status, output, interaction, cost) {
|
|
538
539
|
return {
|
|
539
540
|
id,
|
|
540
541
|
object: "response",
|
|
@@ -544,7 +545,8 @@ function responseEnvelope(args, id, createdAt, status, output, interaction) {
|
|
|
544
545
|
model: args.model,
|
|
545
546
|
output,
|
|
546
547
|
parallel_tool_calls: args.request.parallelToolCalls ?? true,
|
|
547
|
-
|
|
548
|
+
// `cost` as on Chat Completions: null means unpriced.
|
|
549
|
+
...(interaction ? { usage: { ...openAIResponsesUsage(interaction), cost: cost ?? null } } : {}),
|
|
548
550
|
dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
|
|
549
551
|
};
|
|
550
552
|
}
|
|
@@ -552,7 +554,7 @@ function sendFailure(send, args, responseId, createdAt, accumulator, error) {
|
|
|
552
554
|
send("response.failed", {
|
|
553
555
|
response: {
|
|
554
556
|
...responseEnvelope(args, responseId, createdAt, "failed", accumulator.currentOutputItems(), undefined),
|
|
555
|
-
usage: accumulator.currentUsage(),
|
|
557
|
+
usage: { ...accumulator.currentUsage(), cost: args.modelCost?.(error, true) ?? null },
|
|
556
558
|
error: {
|
|
557
559
|
message: providerFailureMessage(error),
|
|
558
560
|
type: "server_error",
|
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.346",
|
|
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.346",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -192,7 +192,9 @@ function conversationStep(record: ConversationRecord, organizationId: string, cu
|
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
}
|
|
195
|
-
const
|
|
195
|
+
const zdr = record.zdr || currentRouterZdr;
|
|
196
|
+
// ZDR content is never served, even when an older blob is still stored.
|
|
197
|
+
const available = (key: string | null) => !zdr && Boolean(record.blobBucket) && Boolean(key);
|
|
196
198
|
const url = (name: string) => `/v1/organizations/${organizationId}/routing/activity/requests/${record.id}/${name}`;
|
|
197
199
|
return {
|
|
198
200
|
id: record.id,
|
|
@@ -223,7 +225,7 @@ function conversationStep(record: ConversationRecord, organizationId: string, cu
|
|
|
223
225
|
has_declared_tools: record.hasTools,
|
|
224
226
|
received_at: formatInstant(record.receivedAt),
|
|
225
227
|
completed_at: record.completedAt === null ? null : formatInstant(record.completedAt),
|
|
226
|
-
zdr
|
|
228
|
+
zdr,
|
|
227
229
|
decision_source: typeof details?.decision_source === "string" ? details.decision_source : null,
|
|
228
230
|
selector_reason: record.selectorReason,
|
|
229
231
|
selector_policy_bypassed: bypassed,
|
|
@@ -292,6 +292,9 @@ export function selectedEffort(record: ConversationRecord): ReasoningEffort | nu
|
|
|
292
292
|
}
|
|
293
293
|
|
|
294
294
|
/** The conversation summary over its steps, oldest first. */
|
|
295
|
+
/** Titles are model-generated from content, so ZDR sessions get a fixed one. */
|
|
296
|
+
export const ZDR_SESSION_TITLE = "Zero Data Retention Session";
|
|
297
|
+
|
|
295
298
|
export function conversationSummary(
|
|
296
299
|
records: readonly ConversationRecord[],
|
|
297
300
|
entities: Entities,
|
|
@@ -329,13 +332,14 @@ export function conversationSummary(
|
|
|
329
332
|
allZdr &&= record.zdr;
|
|
330
333
|
anyZdr ||= record.zdr;
|
|
331
334
|
}
|
|
335
|
+
const retention = router?.zdr || allZdr ? "zdr" : anyZdr ? "mixed" : "retained";
|
|
332
336
|
return {
|
|
333
337
|
conversation_ref: first.id,
|
|
334
338
|
conversation_id: first.conversationId || null,
|
|
335
339
|
agent_session_id: first.agentSessionId || null,
|
|
336
340
|
context_runs: runs.size,
|
|
337
341
|
source_protocol: first.sourceProtocol,
|
|
338
|
-
title: title || ([...records].reverse().find((record) => record.conversationTitle)?.conversationTitle ?? null),
|
|
342
|
+
title: retention === "zdr" ? ZDR_SESSION_TITLE : title || ([...records].reverse().find((record) => record.conversationTitle)?.conversationTitle ?? null),
|
|
339
343
|
router_id: first.routerId,
|
|
340
344
|
router_name: router?.name ?? null,
|
|
341
345
|
api_key_id: first.apiKeyId,
|
|
@@ -358,7 +362,7 @@ export function conversationSummary(
|
|
|
358
362
|
has_error: hasError,
|
|
359
363
|
has_aborted: hasAborted,
|
|
360
364
|
terminal_status: last.status,
|
|
361
|
-
retention
|
|
365
|
+
retention,
|
|
362
366
|
};
|
|
363
367
|
}
|
|
364
368
|
|
package/src/http/handler.ts
CHANGED
|
@@ -60,32 +60,13 @@ export function createRequestHandler(options: GatewayHandlerOptions) {
|
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
const endpoint = routedEndpoint(url.pathname);
|
|
63
|
-
if (endpoint
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
);
|
|
69
|
-
|
|
70
|
-
if (endpoint?.protocol === "responses") {
|
|
71
|
-
if (request.method === "GET") return handleResponsesWebSocketFallback();
|
|
72
|
-
if (request.method === "POST") {
|
|
73
|
-
return await handleResponses(
|
|
74
|
-
request,
|
|
75
|
-
endpoint.routerId,
|
|
76
|
-
selectorBackend,
|
|
77
|
-
);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
if (endpoint?.protocol === "messages" && request.method === "POST") {
|
|
81
|
-
return await handleAnthropicMessages(
|
|
82
|
-
request,
|
|
83
|
-
endpoint.routerId,
|
|
84
|
-
selectorBackend,
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
if (endpoint?.protocol === "models" && request.method === "GET") {
|
|
88
|
-
return await handleModels(request, endpoint.routerId);
|
|
63
|
+
if (endpoint !== null) {
|
|
64
|
+
// Browsers send Origin on every cross-origin call; a request without
|
|
65
|
+
// one (a server, a coding agent) is served exactly as before.
|
|
66
|
+
const fromBrowser = request.headers.has("Origin");
|
|
67
|
+
if (fromBrowser && request.method === "OPTIONS") return withCors(request, new Response(null, { status: 204 }));
|
|
68
|
+
const response = await serveEndpoint(request, endpoint, selectorBackend);
|
|
69
|
+
if (response !== null) return fromBrowser ? withCors(request, response) : response;
|
|
89
70
|
}
|
|
90
71
|
// The gateway counts no tokens. Claude Code calls this for any Anthropic
|
|
91
72
|
// base URL and estimates locally when it fails, so it gets an error it parses.
|
|
@@ -104,6 +85,52 @@ type RoutedEndpoint = {
|
|
|
104
85
|
protocol: "chat" | "responses" | "messages" | "models";
|
|
105
86
|
};
|
|
106
87
|
|
|
88
|
+
async function serveEndpoint(
|
|
89
|
+
request: Request,
|
|
90
|
+
endpoint: RoutedEndpoint,
|
|
91
|
+
selectorBackend: SelectorBackend,
|
|
92
|
+
): Promise<Response | null> {
|
|
93
|
+
if (endpoint.protocol === "chat" && request.method === "POST") {
|
|
94
|
+
return await handleChatCompletions(request, endpoint.routerId, selectorBackend);
|
|
95
|
+
}
|
|
96
|
+
if (endpoint.protocol === "responses") {
|
|
97
|
+
if (request.method === "GET") return handleResponsesWebSocketFallback();
|
|
98
|
+
if (request.method === "POST") return await handleResponses(request, endpoint.routerId, selectorBackend);
|
|
99
|
+
}
|
|
100
|
+
if (endpoint.protocol === "messages" && request.method === "POST") {
|
|
101
|
+
return await handleAnthropicMessages(request, endpoint.routerId, selectorBackend);
|
|
102
|
+
}
|
|
103
|
+
if (endpoint.protocol === "models" && request.method === "GET") {
|
|
104
|
+
return await handleModels(request, endpoint.routerId);
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A browser app calls the model endpoints from its own origin, with a Dari
|
|
111
|
+
* Link token or a key. Neither is a cookie or other ambient credential, so
|
|
112
|
+
* any origin may call, as with Dari Link's own endpoints.
|
|
113
|
+
*
|
|
114
|
+
* The preflight allows the headers it asks for, since clients differ:
|
|
115
|
+
* `x-api-key` and `anthropic-version` from Anthropic's SDK, `x-stainless-*`
|
|
116
|
+
* from OpenAI's, `X-Dari-Tags`. Every response header is exposed, so a page
|
|
117
|
+
* can read `X-Request-Id`, `X-Dari-Usage`, and `Retry-After`.
|
|
118
|
+
*/
|
|
119
|
+
function withCors(request: Request, response: Response): Response {
|
|
120
|
+
const headers = new Headers(response.headers);
|
|
121
|
+
headers.set("Access-Control-Allow-Origin", "*");
|
|
122
|
+
headers.set("Access-Control-Expose-Headers", "*");
|
|
123
|
+
if (request.method === "OPTIONS") {
|
|
124
|
+
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
125
|
+
headers.set(
|
|
126
|
+
"Access-Control-Allow-Headers",
|
|
127
|
+
request.headers.get("Access-Control-Request-Headers") ?? "Authorization, Content-Type",
|
|
128
|
+
);
|
|
129
|
+
headers.set("Access-Control-Max-Age", "600");
|
|
130
|
+
}
|
|
131
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
132
|
+
}
|
|
133
|
+
|
|
107
134
|
function routedEndpoint(pathname: string): RoutedEndpoint | null {
|
|
108
135
|
const defaultProtocol = protocolForSuffix(pathname, "/v1");
|
|
109
136
|
if (defaultProtocol !== null) {
|
package/src/link/client.ts
CHANGED
|
@@ -72,7 +72,7 @@ export type LinkPlan = {
|
|
|
72
72
|
// Quota windows the plan last reported, shortest first; empty when unknown.
|
|
73
73
|
usage: Array<{ window_minutes: number; utilization: number; resets_at: string; model_family?: "fable" }>;
|
|
74
74
|
// Why the plan does or does not serve the app now, and when it will again.
|
|
75
|
-
state: "ready" | "plan_limit";
|
|
75
|
+
state: "ready" | "plan_limit" | "user_limit";
|
|
76
76
|
available_at: string | null;
|
|
77
77
|
// The models the plan serves its clients now: the name a request uses, and the display name.
|
|
78
78
|
models: LinkModel[];
|
package/src/link/endpoints.ts
CHANGED
|
@@ -73,6 +73,7 @@ import type {
|
|
|
73
73
|
LinkConnection,
|
|
74
74
|
LinkPlanAdded,
|
|
75
75
|
LinkGrantDetail,
|
|
76
|
+
LinkSpend,
|
|
76
77
|
LinkKeyProvider,
|
|
77
78
|
LinkManagedGrant,
|
|
78
79
|
LinkUsageTotals,
|
|
@@ -980,7 +981,7 @@ async function grantBody(platform: GatewayPlatform, request: Request, accessToke
|
|
|
980
981
|
const kind = subscription.provider as SubscriptionKind;
|
|
981
982
|
const client = keyFor === undefined ? subscriptionClient(kind) : undefined;
|
|
982
983
|
return {
|
|
983
|
-
...planState(subscription, now),
|
|
984
|
+
...planState(subscription, detail.spend.find((entry) => entry.credentialId === subscription.id), now),
|
|
984
985
|
id: subscription.id,
|
|
985
986
|
kind: keyFor === undefined ? kind : API_KEY,
|
|
986
987
|
// What to call it on screen: "Claude", "ChatGPT", "OpenRouter".
|
|
@@ -1017,19 +1018,22 @@ function latest(times: readonly string[]): string | null {
|
|
|
1017
1018
|
}
|
|
1018
1019
|
|
|
1019
1020
|
/**
|
|
1020
|
-
* Whether a granted plan serves the app now. `plan_limit`: the plan is
|
|
1021
|
-
* own usage limit
|
|
1022
|
-
*
|
|
1021
|
+
* Whether a granted plan or key serves the app now. `plan_limit`: the plan is
|
|
1022
|
+
* at its own usage limit. `user_limit`: it is at the limit the user set for
|
|
1023
|
+
* this app. Either way it is available again at `available_at` (null when
|
|
1024
|
+
* ready or not known).
|
|
1023
1025
|
*/
|
|
1024
|
-
function planState(subscription: LinkSubscription, now: number): {
|
|
1025
|
-
state: "ready" | "plan_limit";
|
|
1026
|
+
function planState(subscription: LinkSubscription, spend: LinkSpend | undefined, now: number): {
|
|
1027
|
+
state: "ready" | "plan_limit" | "user_limit";
|
|
1026
1028
|
available_at: string | null;
|
|
1027
1029
|
} {
|
|
1028
1030
|
const planTimes = [
|
|
1029
1031
|
...(subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? [subscription.unavailableUntil] : []),
|
|
1030
1032
|
...subscription.usage.filter((window) => window.modelFamily === undefined && window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
|
|
1031
1033
|
];
|
|
1032
|
-
|
|
1034
|
+
if (planTimes.length > 0) return { state: "plan_limit", available_at: latest(planTimes) };
|
|
1035
|
+
if (spend?.reached) return { state: "user_limit", available_at: spend.resetsAt };
|
|
1036
|
+
return { state: "ready", available_at: null };
|
|
1033
1037
|
}
|
|
1034
1038
|
|
|
1035
1039
|
/** Whether the grant is within its budget: `budget_limit` until every window at its cap rolls on. */
|
package/src/link/service.ts
CHANGED
|
@@ -295,12 +295,11 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
295
295
|
const grants = await store.grants(subject);
|
|
296
296
|
// One lookup for every grant's plans, not one per grant per use.
|
|
297
297
|
const plans = await users.plansWithIds([...new Set(grants.flatMap((grant) => grant.credentialIds))]);
|
|
298
|
-
|
|
298
|
+
// One grant, and one step of it, at a time: a hosted store holds a pooled connection per call.
|
|
299
|
+
return await inSeries(grants, async (grant) => {
|
|
299
300
|
const shared = plans.filter((plan) => grant.credentialIds.includes(plan.id));
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
standings(grant, shared),
|
|
303
|
-
]);
|
|
301
|
+
const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
|
|
302
|
+
const standing = await standings(grant, shared);
|
|
304
303
|
return {
|
|
305
304
|
id: grant.id,
|
|
306
305
|
clientId: grant.clientId,
|
|
@@ -311,7 +310,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
311
310
|
subscriptions: shared,
|
|
312
311
|
usage,
|
|
313
312
|
};
|
|
314
|
-
})
|
|
313
|
+
});
|
|
315
314
|
},
|
|
316
315
|
async disconnect(subject, grantId) {
|
|
317
316
|
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
@@ -369,7 +368,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
369
368
|
},
|
|
370
369
|
async grants(apiKey) {
|
|
371
370
|
const subject = await users.manager(apiKey);
|
|
372
|
-
return await
|
|
371
|
+
return await inSeries(await store.grants(subject), managedGrant);
|
|
373
372
|
},
|
|
374
373
|
async plans(apiKey) {
|
|
375
374
|
return await users.plans(await endpointOwner(apiKey));
|
|
@@ -513,3 +512,10 @@ function endpointName(name: string): string {
|
|
|
513
512
|
}
|
|
514
513
|
return trimmed;
|
|
515
514
|
}
|
|
515
|
+
|
|
516
|
+
// Each item in turn, so a store that holds a connection per call holds one at a time.
|
|
517
|
+
async function inSeries<T, R>(items: readonly T[], each: (item: T) => Promise<R>): Promise<R[]> {
|
|
518
|
+
const results: R[] = [];
|
|
519
|
+
for (const item of items) results.push(await each(item));
|
|
520
|
+
return results;
|
|
521
|
+
}
|
package/src/platform/platform.ts
CHANGED
|
@@ -682,6 +682,9 @@ export type OperationalErrorCode =
|
|
|
682
682
|
| "billing_usage_report_failed"
|
|
683
683
|
| "routing_report_assembly_failed"
|
|
684
684
|
| "routing_report_barrier_failed"
|
|
685
|
+
| "routing_resolve_failed"
|
|
686
|
+
| "routing_resolve_shadow_failed"
|
|
687
|
+
| "routing_resolve_shadow_mismatch"
|
|
685
688
|
| "server_force_stop_failed"
|
|
686
689
|
| "session_pin_write_failed"
|
|
687
690
|
| "stream_report_finalization_failed"
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
isProtocolToolCallId,
|
|
11
11
|
TOOL_CALL_ID_MAX_LENGTH,
|
|
12
12
|
toolsByWireName,
|
|
13
|
+
toolWireName,
|
|
13
14
|
} from "../../interaction/tool_identity.js";
|
|
14
15
|
import type {
|
|
15
16
|
InteractionContent,
|
|
@@ -236,6 +237,7 @@ function responseItem(value: unknown, itemIndex: number, hostedReplayId?: string
|
|
|
236
237
|
if (type === "web_search_call") return hostedWebSearchCallItem(value, itemIndex, hostedReplayId);
|
|
237
238
|
if (type === "function_call" || type === "custom_tool_call") return toolCallItem(value, type === "function_call" ? "function" : "custom");
|
|
238
239
|
if (type === "function_call_output" || type === "custom_tool_call_output") {
|
|
240
|
+
if (value.call_id === undefined || value.call_id === null) return callIdlessToolOutputNote(value, `input.${type}`);
|
|
239
241
|
return toolResultItem(value, type === "function_call_output" ? "function" : "custom");
|
|
240
242
|
}
|
|
241
243
|
if (type === "message" || typeof value.role === "string") return messageItem(value);
|
|
@@ -441,6 +443,22 @@ function toolResultItem(value: Record<string, unknown>, kind: ToolKind): Interac
|
|
|
441
443
|
};
|
|
442
444
|
}
|
|
443
445
|
|
|
446
|
+
// Codex appends outputs that answer no call, such as its goal objective
|
|
447
|
+
// (`agent` / `goal_objective`) after `create_goal`; they reach the model as a
|
|
448
|
+
// developer note.
|
|
449
|
+
function callIdlessToolOutputNote(value: Record<string, unknown>, prefix: string): InteractionMessage {
|
|
450
|
+
const name = optionalString(value.name, `${prefix}.name`);
|
|
451
|
+
const namespace = optionalString(value.namespace, `${prefix}.namespace`);
|
|
452
|
+
const output = responseContent(value.output, `${prefix}.output`);
|
|
453
|
+
return {
|
|
454
|
+
type: "message",
|
|
455
|
+
id: optionalString(value.id, `${prefix}.id`),
|
|
456
|
+
role: "developer",
|
|
457
|
+
content: name ? [{ type: "text", text: `${toolWireName(namespace, name)}:` }, ...output] : output,
|
|
458
|
+
contentShape: "parts",
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
444
462
|
function responseToolOutput(value: unknown, param: string): string | InteractionContent[] | null {
|
|
445
463
|
if (value === undefined || value === null || typeof value === "string") return value ?? null;
|
|
446
464
|
return responseContent(value, param);
|
|
@@ -13,6 +13,7 @@ export function anthropicMessagesResponse(args: {
|
|
|
13
13
|
id: string;
|
|
14
14
|
model: string;
|
|
15
15
|
output: InteractionOutput;
|
|
16
|
+
modelCost?: number | null;
|
|
16
17
|
request: InteractionRequest;
|
|
17
18
|
routing: RoutingDecision;
|
|
18
19
|
conversationId?: string;
|
|
@@ -25,7 +26,8 @@ export function anthropicMessagesResponse(args: {
|
|
|
25
26
|
content: anthropicContent(args.output),
|
|
26
27
|
stop_reason: anthropicStopReason(args.output),
|
|
27
28
|
stop_sequence: null,
|
|
28
|
-
|
|
29
|
+
// As on Chat Completions. Null means unpriced, never a fabricated free request.
|
|
30
|
+
usage: { ...anthropicUsage(args.output), cost: args.modelCost ?? null },
|
|
29
31
|
...(args.output.safeguardResults ? { safeguard_results: args.output.safeguardResults } : {}),
|
|
30
32
|
dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
|
|
31
33
|
};
|
|
@@ -25,6 +25,7 @@ export function anthropicMessagesSseStream(args: {
|
|
|
25
25
|
request: InteractionRequest;
|
|
26
26
|
conversationId?: string;
|
|
27
27
|
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
28
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
28
29
|
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
29
30
|
clientSignal?: AbortSignal;
|
|
30
31
|
onAbort?: () => void;
|
|
@@ -254,8 +255,9 @@ export function anthropicMessagesSseStream(args: {
|
|
|
254
255
|
},
|
|
255
256
|
// message_start goes out before the provider answers, so the
|
|
256
257
|
// cumulative input and cache counts ride here, as on Anthropic.
|
|
257
|
-
// Claude Code sizes its context window from them.
|
|
258
|
-
|
|
258
|
+
// Claude Code sizes its context window from them. `cost` as on
|
|
259
|
+
// Chat Completions: null means unpriced.
|
|
260
|
+
usage: { ...anthropicUsage(output), cost: args.modelCost?.(event.message, false) ?? null },
|
|
259
261
|
});
|
|
260
262
|
}
|
|
261
263
|
break;
|
|
@@ -11,6 +11,7 @@ export function openAIResponsesResponse(args: {
|
|
|
11
11
|
id: string;
|
|
12
12
|
model: string;
|
|
13
13
|
output: InteractionOutput;
|
|
14
|
+
modelCost?: number | null;
|
|
14
15
|
request: InteractionRequest;
|
|
15
16
|
routing: RoutingDecision;
|
|
16
17
|
conversationId?: string;
|
|
@@ -22,7 +23,8 @@ export function openAIResponsesResponse(args: {
|
|
|
22
23
|
...openAIResponsesTerminal(args.output),
|
|
23
24
|
model: args.model,
|
|
24
25
|
output: openAIResponsesOutputItems(args.output),
|
|
25
|
-
|
|
26
|
+
// As on Chat Completions. Null means unpriced, never a fabricated free request.
|
|
27
|
+
usage: { ...openAIResponsesUsage(args.output), cost: args.modelCost ?? null },
|
|
26
28
|
parallel_tool_calls: args.request.parallelToolCalls ?? true,
|
|
27
29
|
dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
|
|
28
30
|
};
|
|
@@ -30,6 +30,7 @@ type StreamArgs = {
|
|
|
30
30
|
request: InteractionRequest;
|
|
31
31
|
conversationId?: string;
|
|
32
32
|
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
33
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
33
34
|
// Optional terminal barrier. Streaming deltas are unaffected, but the
|
|
34
35
|
// terminal Responses event and EOF are held until this settles.
|
|
35
36
|
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
@@ -81,6 +82,7 @@ export function openAIResponsesSseStream(args: StreamArgs): ReadableStream<Uint8
|
|
|
81
82
|
const output = accumulator.complete(event.message, send);
|
|
82
83
|
settle({ status: "completed", message: event.message, output });
|
|
83
84
|
const terminal = openAIResponsesTerminal(output);
|
|
85
|
+
const cost = args.modelCost?.(event.message, false);
|
|
84
86
|
emitTerminal = () => {
|
|
85
87
|
send(`response.${terminal.status}`, {
|
|
86
88
|
response: responseEnvelope(
|
|
@@ -89,7 +91,8 @@ export function openAIResponsesSseStream(args: StreamArgs): ReadableStream<Uint8
|
|
|
89
91
|
createdAt,
|
|
90
92
|
terminal.status,
|
|
91
93
|
openAIResponsesOutputItems(output),
|
|
92
|
-
output
|
|
94
|
+
output,
|
|
95
|
+
cost
|
|
93
96
|
),
|
|
94
97
|
});
|
|
95
98
|
};
|
|
@@ -606,7 +609,8 @@ function responseEnvelope(
|
|
|
606
609
|
createdAt: number,
|
|
607
610
|
status: "in_progress" | "completed" | "incomplete" | "failed",
|
|
608
611
|
output: Array<Record<string, unknown>>,
|
|
609
|
-
interaction: InteractionOutput | undefined
|
|
612
|
+
interaction: InteractionOutput | undefined,
|
|
613
|
+
cost?: number | null
|
|
610
614
|
): Record<string, unknown> {
|
|
611
615
|
return {
|
|
612
616
|
id,
|
|
@@ -617,7 +621,8 @@ function responseEnvelope(
|
|
|
617
621
|
model: args.model,
|
|
618
622
|
output,
|
|
619
623
|
parallel_tool_calls: args.request.parallelToolCalls ?? true,
|
|
620
|
-
|
|
624
|
+
// `cost` as on Chat Completions: null means unpriced.
|
|
625
|
+
...(interaction ? { usage: { ...openAIResponsesUsage(interaction), cost: cost ?? null } } : {}),
|
|
621
626
|
dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
|
|
622
627
|
};
|
|
623
628
|
}
|
|
@@ -633,7 +638,7 @@ function sendFailure(
|
|
|
633
638
|
send("response.failed", {
|
|
634
639
|
response: {
|
|
635
640
|
...responseEnvelope(args, responseId, createdAt, "failed", accumulator.currentOutputItems(), undefined),
|
|
636
|
-
usage: accumulator.currentUsage(),
|
|
641
|
+
usage: { ...accumulator.currentUsage(), cost: args.modelCost?.(error, true) ?? null },
|
|
637
642
|
error: {
|
|
638
643
|
message: providerFailureMessage(error),
|
|
639
644
|
type: "server_error",
|