@mupt-ai/dari-gateway 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +135 -2
  3. package/dari-gateway.example.yaml +28 -0
  4. package/package.json +42 -4
  5. package/src/bun.ts +4 -0
  6. package/src/context/eval_catalog.ts +11 -0
  7. package/src/context/interaction_fingerprint.ts +691 -0
  8. package/src/context/interaction_fingerprint_format.ts +189 -0
  9. package/src/context/interaction_lease_depth.ts +150 -0
  10. package/src/context/lease_history.ts +200 -0
  11. package/src/context/pricing.ts +30 -0
  12. package/src/context/provider_prompt_accounting.ts +241 -0
  13. package/src/context/routing_context.ts +337 -0
  14. package/src/http/auth.ts +43 -0
  15. package/src/http/errors.ts +114 -0
  16. package/src/http/handler.ts +110 -0
  17. package/src/http/http2_server.ts +122 -0
  18. package/src/http/serve.ts +119 -0
  19. package/src/index.ts +22 -0
  20. package/src/ingress/anthropic_messages.ts +162 -0
  21. package/src/ingress/anthropic_models.ts +28 -0
  22. package/src/ingress/chat_completions.ts +49 -0
  23. package/src/ingress/claude_code/request_context.ts +36 -0
  24. package/src/ingress/codex.ts +81 -0
  25. package/src/ingress/codex_models.ts +113 -0
  26. package/src/ingress/json.ts +113 -0
  27. package/src/ingress/models.ts +55 -0
  28. package/src/interaction/capabilities.ts +30 -0
  29. package/src/interaction/image.ts +12 -0
  30. package/src/interaction/portable_reasoning_state.ts +25 -0
  31. package/src/interaction/provider_continuation_state.ts +36 -0
  32. package/src/interaction/tool_identity.ts +65 -0
  33. package/src/interaction/types.ts +282 -0
  34. package/src/models/context_limits.ts +8 -0
  35. package/src/models/execution_provider.ts +22 -0
  36. package/src/models/gateways.ts +73 -0
  37. package/src/models/ids.ts +26 -0
  38. package/src/models/provider_defaults.ts +47 -0
  39. package/src/models/runtime_overrides.ts +221 -0
  40. package/src/observability/errors.ts +25 -0
  41. package/src/platform/platform.ts +204 -0
  42. package/src/platform/routing_contract.ts +6 -0
  43. package/src/protocol/input/anthropic_messages.ts +531 -0
  44. package/src/protocol/input/chat_completions.ts +255 -0
  45. package/src/protocol/input/chat_completions_validation.ts +293 -0
  46. package/src/protocol/input/openai_responses.ts +749 -0
  47. package/src/protocol/input/router_model.ts +53 -0
  48. package/src/protocol/output/anthropic_messages.ts +32 -0
  49. package/src/protocol/output/anthropic_messages_output.ts +129 -0
  50. package/src/protocol/output/anthropic_messages_stream.ts +281 -0
  51. package/src/protocol/output/chat_completions.ts +451 -0
  52. package/src/protocol/output/chat_reasoning_detail.ts +19 -0
  53. package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
  54. package/src/protocol/output/openai_responses.ts +30 -0
  55. package/src/protocol/output/openai_responses_output.ts +159 -0
  56. package/src/protocol/output/openai_responses_stream.ts +631 -0
  57. package/src/protocol/output/sse_stream.ts +102 -0
  58. package/src/providers/anthropic_safeguards.ts +115 -0
  59. package/src/providers/aws_assume_role.ts +147 -0
  60. package/src/providers/cancel_estimate.ts +140 -0
  61. package/src/providers/execution.ts +800 -0
  62. package/src/providers/model_capabilities.ts +50 -0
  63. package/src/providers/pi.ts +499 -0
  64. package/src/providers/pi_context.ts +466 -0
  65. package/src/providers/pi_options.ts +416 -0
  66. package/src/providers/pi_output.ts +500 -0
  67. package/src/providers/provider_attempt_runner.ts +153 -0
  68. package/src/providers/provider_call.ts +433 -0
  69. package/src/providers/provider_reported_cost.ts +138 -0
  70. package/src/providers/reasoning.ts +59 -0
  71. package/src/providers/response_capture.ts +65 -0
  72. package/src/providers/stream_finalization.ts +264 -0
  73. package/src/providers/subscription_limits.ts +208 -0
  74. package/src/providers/subscription_usage.ts +99 -0
  75. package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
  76. package/src/runtime/customer_disconnect.ts +66 -0
  77. package/src/runtime/explicit_model.ts +86 -0
  78. package/src/runtime/harness_identity/conversation.ts +87 -0
  79. package/src/runtime/harness_identity/extract.ts +323 -0
  80. package/src/runtime/harness_identity/index.ts +14 -0
  81. package/src/runtime/prepare_routed_completion.ts +224 -0
  82. package/src/runtime/provider_stream_lifecycle.ts +105 -0
  83. package/src/runtime/provider_stream_outcome.ts +83 -0
  84. package/src/runtime/request_tags.ts +34 -0
  85. package/src/runtime/routed_completion.ts +102 -0
  86. package/src/runtime/routed_protocol.ts +33 -0
  87. package/src/runtime/routed_runtime.ts +722 -0
  88. package/src/runtime/routing_lease.ts +273 -0
  89. package/src/runtime/runtime_reporter.ts +115 -0
  90. package/src/self_host/config.ts +173 -0
  91. package/src/self_host/main.ts +104 -0
  92. package/src/self_host/platform.ts +63 -0
  93. package/src/self_host/prefix_store.ts +315 -0
  94. package/src/self_host/resolve.ts +240 -0
  95. package/src/self_host/subscriptions/access.ts +43 -0
  96. package/src/self_host/subscriptions/http.ts +204 -0
  97. package/src/self_host/subscriptions/index.ts +43 -0
  98. package/src/self_host/subscriptions/oauth.ts +395 -0
  99. package/src/self_host/subscriptions/store.ts +339 -0
  100. package/src/strategies/auto_routing_selector.ts +72 -0
  101. package/src/strategies/eval_relevance.ts +57 -0
  102. package/src/strategies/fallback_decision.ts +30 -0
  103. package/src/strategies/priority_selector.ts +40 -0
  104. package/src/strategies/route_decision.ts +106 -0
  105. package/src/strategies/routing.ts +455 -0
  106. package/src/strategies/selector_projection.ts +207 -0
  107. package/src/telemetry/background.ts +40 -0
  108. package/src/telemetry/benchmark_replay.ts +160 -0
  109. package/src/telemetry/billing_finalization.ts +167 -0
  110. package/src/telemetry/ingest_values.ts +15 -0
  111. package/src/telemetry/model_cost.ts +14 -0
  112. package/src/telemetry/prefix_state.ts +183 -0
  113. package/src/telemetry/report.ts +832 -0
  114. package/src/telemetry/requests/interaction_observability.ts +258 -0
  115. package/src/telemetry/requests/retained_interaction_request.ts +20 -0
  116. package/src/telemetry/scrub.ts +38 -0
  117. package/src/telemetry/skills/claude/catalog.ts +119 -0
  118. package/src/telemetry/skills/claude/file_reads.ts +153 -0
  119. package/src/telemetry/skills/claude/observations.ts +450 -0
  120. package/src/telemetry/skills/codex/catalog.ts +171 -0
  121. package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
  122. package/src/telemetry/skills/codex/explicit.ts +116 -0
  123. package/src/telemetry/skills/codex/file_reads.ts +51 -0
  124. package/src/telemetry/skills/codex/identity.ts +21 -0
  125. package/src/telemetry/skills/observations.ts +94 -0
  126. package/src/telemetry/skills/paths.ts +82 -0
  127. package/src/telemetry/skills/pi.ts +276 -0
  128. package/src/telemetry/skills/shell_file_reads.ts +267 -0
  129. package/src/telemetry/skills/shell_words.ts +202 -0
  130. package/src/telemetry/tools/input.ts +16 -0
  131. package/src/telemetry/tools/observations.ts +349 -0
  132. package/src/telemetry/usage.ts +173 -0
  133. package/src/types.ts +150 -0
@@ -0,0 +1,349 @@
1
+ import { isRecord, stableStringify } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { interactionPrefixChain } from "../../context/interaction_fingerprint";
4
+ import type {
5
+ InteractionContent,
6
+ InteractionItem,
7
+ InteractionOutput,
8
+ InteractionRequest,
9
+ InteractionToolResult,
10
+ } from "../../interaction/types";
11
+ import { isProtocolToolCallId } from "../../interaction/tool_identity";
12
+ import { anthropicMessagesToInteraction } from "../../protocol/input/anthropic_messages";
13
+ import { internalChatCompletionsToInteraction } from "../../protocol/input/chat_completions";
14
+ import { anthropicContent } from "../../protocol/output/anthropic_messages_output";
15
+ import { assistantMessagePayload } from "../../protocol/output/chat_completions";
16
+ import type { HarnessConversationIdentity } from "../../runtime/harness_identity";
17
+ import {
18
+ inputSkillObservations,
19
+ outputSkillObservations,
20
+ } from "../skills/observations";
21
+
22
+ const MAX_TOOL_SKILL_EVENTS = 1000;
23
+
24
+ export type ToolSkillEventReport = {
25
+ event_type: "tool_call" | "skill_use" | "skill_load";
26
+ tool_call_id: string | null;
27
+ exchange_context_hash: string | null;
28
+ capability_id: string;
29
+ observed_name: string;
30
+ skill_version: null;
31
+ evidence_source:
32
+ | "model_tool_call"
33
+ | "skill_content_injection"
34
+ | "skill_command_expansion"
35
+ | "skill_tool_activation"
36
+ | "skill_file_read";
37
+ ordinal: number;
38
+ };
39
+
40
+ export type ToolResultObservationReport = {
41
+ tool_call_id: string;
42
+ exchange_context_hash: string | null;
43
+ ordinal: number;
44
+ };
45
+
46
+ export function toolSkillEvents(args: {
47
+ routerId: string;
48
+ request: InteractionRequest;
49
+ output: InteractionOutput | undefined;
50
+ harnessConversationIdentity?: HarnessConversationIdentity;
51
+ zdr: boolean;
52
+ }): ToolSkillEventReport[] {
53
+ if (args.zdr) return [];
54
+ const outputEvents = (args.output?.items ?? [])
55
+ .flatMap((item, ordinal) =>
56
+ item.type === "tool_call"
57
+ && isProtocolToolCallId(item.callId)
58
+ ? [{ item, ordinal }]
59
+ : []
60
+ )
61
+ .slice(0, MAX_TOOL_SKILL_EVENTS);
62
+ const explicitSkills = inputSkillObservations({
63
+ ...args,
64
+ limit: MAX_TOOL_SKILL_EVENTS - outputEvents.length,
65
+ });
66
+ const outputCallIds = new Set(outputEvents.map(({ item }) => item.callId));
67
+ const automaticSkills = args.output === undefined
68
+ ? []
69
+ : outputSkillObservations({
70
+ request: args.request,
71
+ output: args.output,
72
+ harnessConversationIdentity: args.harnessConversationIdentity,
73
+ limit: MAX_TOOL_SKILL_EVENTS,
74
+ }).filter(
75
+ (skill) =>
76
+ skill.toolCallId !== null
77
+ && outputCallIds.has(skill.toolCallId),
78
+ ).slice(
79
+ 0,
80
+ MAX_TOOL_SKILL_EVENTS - outputEvents.length - explicitSkills.length,
81
+ );
82
+ if (
83
+ explicitSkills.length === 0
84
+ && automaticSkills.length === 0
85
+ && outputEvents.length === 0
86
+ ) return [];
87
+
88
+ const exchangeContextHash = outputEvents.length === 0 || args.output === undefined
89
+ ? null
90
+ : outputExchangeContextHash(args.routerId, args.request, args.output);
91
+ const reportedExplicitSkills = explicitSkills.map((skill, ordinal) => ({
92
+ event_type: skill.eventType,
93
+ tool_call_id: skill.toolCallId,
94
+ exchange_context_hash: null,
95
+ capability_id: skill.capabilityId,
96
+ observed_name: skill.observedName,
97
+ skill_version: null,
98
+ evidence_source: skill.evidenceSource,
99
+ ordinal,
100
+ }));
101
+ const reportedAutomaticSkills = automaticSkills.map((skill, ordinal) => ({
102
+ event_type: skill.eventType,
103
+ tool_call_id: skill.toolCallId,
104
+ exchange_context_hash: exchangeContextHash,
105
+ capability_id: skill.capabilityId,
106
+ observed_name: skill.observedName,
107
+ skill_version: null,
108
+ evidence_source: skill.evidenceSource,
109
+ ordinal: explicitSkills.length + ordinal,
110
+ }));
111
+ const skillCount = explicitSkills.length + automaticSkills.length;
112
+ const reportedOutputEvents = outputEvents.map(({ item, ordinal }) => {
113
+ const observedName = item.namespace
114
+ ? `${item.namespace}.${item.name}`
115
+ : item.name;
116
+ return {
117
+ event_type: "tool_call" as const,
118
+ tool_call_id: item.callId,
119
+ exchange_context_hash: exchangeContextHash,
120
+ capability_id: observedName,
121
+ observed_name: observedName,
122
+ skill_version: null,
123
+ evidence_source: "model_tool_call" as const,
124
+ ordinal: skillCount + ordinal,
125
+ };
126
+ });
127
+ return [
128
+ ...reportedExplicitSkills,
129
+ ...reportedAutomaticSkills,
130
+ ...reportedOutputEvents,
131
+ ];
132
+ }
133
+
134
+ export function toolResultObservations(args: {
135
+ routerId: string;
136
+ request: InteractionRequest;
137
+ zdr: boolean;
138
+ }): ToolResultObservationReport[] {
139
+ if (args.zdr) return [];
140
+ const submitted = newlySubmittedToolResults(args.request);
141
+ if (submitted.results.length === 0) return [];
142
+
143
+ const requestBeforeResults: InteractionRequest = {
144
+ ...args.request,
145
+ items: args.request.items.slice(0, submitted.contextEnd),
146
+ };
147
+ const exchangeContextHash =
148
+ interactionPrefixChain(
149
+ args.routerId,
150
+ normalizeExchangeRequest(requestBeforeResults),
151
+ null,
152
+ ).at(-1) ??
153
+ null;
154
+
155
+ return submitted.results.slice(0, 1000).map(({ item, ordinal }) => ({
156
+ tool_call_id: item.callId,
157
+ exchange_context_hash: exchangeContextHash,
158
+ ordinal,
159
+ }));
160
+ }
161
+
162
+ function newlySubmittedToolResults(
163
+ request: InteractionRequest
164
+ ): {
165
+ results: Array<{ item: InteractionToolResult; ordinal: number }>;
166
+ contextEnd: number;
167
+ } {
168
+ if (request.sourceProtocol === "anthropic_messages") {
169
+ return currentAnthropicUserTurnResults(request.items);
170
+ }
171
+
172
+ const results: Array<{ item: InteractionToolResult; ordinal: number }> = [];
173
+ for (let ordinal = request.items.length - 1; ordinal >= 0; ordinal -= 1) {
174
+ const item = request.items[ordinal];
175
+ if (item.type !== "tool_result") break;
176
+ if (isProtocolToolCallId(item.callId)) results.push({ item, ordinal });
177
+ }
178
+ const ordered = results.reverse();
179
+ return {
180
+ results: ordered,
181
+ contextEnd: ordered[0]?.ordinal ?? request.items.length,
182
+ };
183
+ }
184
+
185
+ function currentAnthropicUserTurnResults(
186
+ items: InteractionItem[]
187
+ ): {
188
+ results: Array<{ item: InteractionToolResult; ordinal: number }>;
189
+ contextEnd: number;
190
+ } {
191
+ const results: Array<{ item: InteractionToolResult; ordinal: number }> = [];
192
+ let contextEnd = 0;
193
+ for (let ordinal = items.length - 1; ordinal >= 0; ordinal -= 1) {
194
+ const item = items[ordinal];
195
+ if (isAssistantOutputItem(item)) {
196
+ contextEnd = ordinal + 1;
197
+ break;
198
+ }
199
+ if (item.type === "tool_result" && isProtocolToolCallId(item.callId)) {
200
+ results.push({ item, ordinal });
201
+ }
202
+ }
203
+ return { results: results.reverse(), contextEnd };
204
+ }
205
+
206
+ function isAssistantOutputItem(item: InteractionItem): boolean {
207
+ return item.type === "reasoning"
208
+ || item.type === "tool_call"
209
+ || item.type === "hosted_tool_call"
210
+ || (item.type === "message" && item.role === "assistant");
211
+ }
212
+
213
+ function outputExchangeContextHash(
214
+ routerId: string,
215
+ request: InteractionRequest,
216
+ output: InteractionOutput
217
+ ): string | null {
218
+ const outputItems = clientVisibleOutputItems(request.sourceProtocol, output);
219
+ const completedRequest = normalizeExchangeRequest({
220
+ ...request,
221
+ items: [...request.items, ...outputItems],
222
+ });
223
+ return interactionPrefixChain(routerId, completedRequest, null).at(-1) ?? null;
224
+ }
225
+
226
+ function clientVisibleOutputItems(
227
+ sourceProtocol: InteractionRequest["sourceProtocol"],
228
+ output: InteractionOutput,
229
+ ): InteractionItem[] {
230
+ if (sourceProtocol === "openai_chat") {
231
+ return internalChatCompletionsToInteraction({
232
+ model: "dari/routing",
233
+ messages: [assistantMessagePayload(output)],
234
+ }).items;
235
+ }
236
+ if (sourceProtocol === "anthropic_messages") {
237
+ return anthropicMessagesToInteraction({
238
+ model: "dari/routing",
239
+ max_tokens: 1,
240
+ messages: [{ role: "assistant", content: anthropicContent(output) }],
241
+ }).items;
242
+ }
243
+ return output.items;
244
+ }
245
+
246
+ function normalizeExchangeRequest(request: InteractionRequest): InteractionRequest {
247
+ // Claude Code may omit thinking blocks when it submits tool results even
248
+ // though those blocks were present in the preceding Anthropic response.
249
+ const items = request.sourceProtocol === "anthropic_messages"
250
+ ? request.items.filter((item) => item.type !== "reasoning")
251
+ : request.items;
252
+ return {
253
+ ...request,
254
+ instructions: undefined,
255
+ tools: [],
256
+ items: items.map(normalizeExchangeItem),
257
+ };
258
+ }
259
+
260
+ // Correlation follows semantic tool history, not wire-only item IDs, message
261
+ // phases, content container shapes, or JSON object insertion order.
262
+ function normalizeExchangeItem(item: InteractionItem): InteractionItem {
263
+ if (item.type === "reasoning") {
264
+ const { id: _id, ...rest } = item;
265
+ return rest;
266
+ }
267
+ if (item.type === "message") {
268
+ const { id: _id, phase: _phase, ...rest } = item;
269
+ return {
270
+ ...rest,
271
+ ...normalizeContent(item.content, item.contentShape, item.role === "assistant"),
272
+ };
273
+ }
274
+ if (item.type === "tool_call") {
275
+ const { id: _id, ...rest } = item;
276
+ return {
277
+ ...rest,
278
+ input: normalizeFunctionInput(item.kind, item.input),
279
+ };
280
+ }
281
+ if (item.type === "tool_result") {
282
+ const { id: _id, ...rest } = item;
283
+ if (!Array.isArray(item.output)) return rest;
284
+ const normalized = normalizeContent(item.output, item.outputShape);
285
+ return { ...rest, output: normalized.content, outputShape: normalized.contentShape };
286
+ }
287
+ if (item.type === "hosted_tool_call") {
288
+ const {
289
+ id: _id,
290
+ source: _source,
291
+ payload: { id: _payloadId, status: _payloadStatus, ...payload },
292
+ ...rest
293
+ } = item;
294
+ return {
295
+ ...rest,
296
+ id: "",
297
+ payload: item.status ? { ...payload, status: item.status } : payload,
298
+ };
299
+ }
300
+ return item;
301
+ }
302
+
303
+ function normalizeContent(
304
+ content: InteractionContent[],
305
+ contentShape: "string" | "parts" | "null" | "absent",
306
+ collapseEmpty = false,
307
+ ): { content: InteractionContent[]; contentShape: "string" | "parts" | "null" | "absent" } {
308
+ if (
309
+ collapseEmpty
310
+ && content.every(
311
+ (part) => part.type === "text" && part.text.length === 0 && !part.annotations?.length,
312
+ )
313
+ ) {
314
+ return { content: [], contentShape: "null" };
315
+ }
316
+ if (contentShape === "null" || contentShape === "absent") {
317
+ return { content, contentShape };
318
+ }
319
+ if (
320
+ content.every(
321
+ (part) => part.type === "text" && !part.annotations?.length,
322
+ )
323
+ ) {
324
+ return {
325
+ content: [{
326
+ type: "text",
327
+ text: content
328
+ .map((part) => (part.type === "text" ? part.text : ""))
329
+ .join(""),
330
+ }],
331
+ contentShape: "string",
332
+ };
333
+ }
334
+ return { content, contentShape: "parts" };
335
+ }
336
+
337
+ function normalizeFunctionInput(
338
+ kind: "function" | "custom",
339
+ input: string | Record<string, unknown> | undefined
340
+ ): string | Record<string, unknown> | undefined {
341
+ if (kind === "custom" || input === undefined) return input;
342
+ if (isRecord(input)) return stableStringify(input);
343
+ try {
344
+ const parsed: unknown = JSON.parse(input);
345
+ return isRecord(parsed) ? stableStringify(parsed) : input;
346
+ } catch {
347
+ return input;
348
+ }
349
+ }
@@ -0,0 +1,173 @@
1
+ import type { Provider } from "@mupt-ai/dari-router/policy-engine";
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ import { HttpError } from "../http/errors";
5
+ import { executionProviderForModel, keySourceForModel } from "../models/execution_provider";
6
+ import { captureOperationalError } from "../observability/errors";
7
+ import { gatewayPlatform, type RequestTags } from "../platform/platform";
8
+ import type { ProviderKeySource, ResolvedRouter } from "../types";
9
+
10
+ export type RoutingUsageContext = {
11
+ organizationId: string;
12
+ routerId: string;
13
+ provider: Provider;
14
+ model: string;
15
+ tags: RequestTags;
16
+ startedAt: Date;
17
+ };
18
+
19
+ /**
20
+ * Reject requests that need model selection when the organization is not on
21
+ * the Autorouting plan. Without it, Gateway serves only routers with a single
22
+ * model and thinking level, which never invoke the selector.
23
+ */
24
+ export function assertAutoroutingAllowed(credentials: ResolvedRouter, selects: boolean): void {
25
+ if (selects && credentials.autorouting_enabled === false) {
26
+ throw new HttpError(
27
+ 402,
28
+ "Autorouting requires the Autorouting plan. Subscribe at https://app.dari.dev/usage, or keep one model and thinking level on this router.",
29
+ "autorouting_plan_required",
30
+ );
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Whether the router offers more than one model/thinking-level pair. A model
36
+ * without listed levels serves every level it supports, so it counts as
37
+ * selecting, matching candidate preparation and the CLI.
38
+ */
39
+ export function routerSelectsModels(credentials: ResolvedRouter): boolean {
40
+ let pairs = 0;
41
+ for (const model of credentials.enabled_models) {
42
+ const levels = credentials.model_thinking_levels?.[model]?.length ?? 0;
43
+ if (levels === 0) return true;
44
+ pairs += levels;
45
+ }
46
+ return pairs > 1;
47
+ }
48
+
49
+ /**
50
+ * Reject billable requests before the routing decision once the org's
51
+ * credits are exhausted, unless a personal subscription serves one of the
52
+ * router's models: those owe no credits, so they keep serving and routing
53
+ * narrows to them. Managed and own-key requests stay gated (own-key requests
54
+ * owe the router fee), and refusing before selection keeps an exhausted org
55
+ * from burning selector-model spend.
56
+ */
57
+ export function assertCreditAvailableBeforeRouting(billable: boolean, credentials: ResolvedRouter): void {
58
+ if (
59
+ billable &&
60
+ credentials.credit_exhausted &&
61
+ !credentials.enabled_models.some((model) => keySourceForModel(credentials, model) === "subscription")
62
+ ) {
63
+ throw creditExhaustedError();
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Decide whether this routed call bills org credits: returns the usage
69
+ * context for billable managed-key selections and undefined otherwise.
70
+ * Throws 402 when the selection needs a managed key while the org's
71
+ * credits are exhausted.
72
+ */
73
+ export function usageContextFor(args: {
74
+ billable: boolean;
75
+ credentials: ResolvedRouter;
76
+ routerId: string;
77
+ selectedModel: string;
78
+ keySource: ProviderKeySource;
79
+ tags: RequestTags;
80
+ }): RoutingUsageContext | undefined {
81
+ if (!args.billable || args.keySource !== "managed") return undefined;
82
+ if (args.credentials.credit_exhausted) throw creditExhaustedError();
83
+ return {
84
+ organizationId: args.credentials.organization_id,
85
+ routerId: args.routerId,
86
+ provider: executionProviderForModel(args.credentials, args.selectedModel),
87
+ model: args.selectedModel,
88
+ tags: args.tags,
89
+ startedAt: new Date(),
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Bill one managed-key routed call to the org's credits through the
95
+ * platform. Stream billing calls this from the protocol stream's onFinal hook; the
96
+ * non-stream path awaits it before responding. Never throws: the provider
97
+ * spend already happened, so a recording failure must not fail an
98
+ * otherwise-successful completion — it is logged and reported operationally
99
+ * instead.
100
+ */
101
+ export async function reportRoutingUsage(context: RoutingUsageContext, message: Record<string, unknown>): Promise<void> {
102
+ const payload = usagePayload(context, message);
103
+ if (payload.total_cost_usd === "0") {
104
+ console.error("Routing usage billed at zero cost; model pricing may be missing.", usageLogFields(payload));
105
+ }
106
+ try {
107
+ await gatewayPlatform().recordUsage(payload);
108
+ } catch (error) {
109
+ reportUsageFailure(error, payload);
110
+ }
111
+ }
112
+
113
+ function reportUsageFailure(
114
+ error: unknown,
115
+ payload: Record<string, unknown>,
116
+ ): void {
117
+ console.error("Routing usage not recorded.", usageLogFields(payload));
118
+ captureOperationalError(error, {
119
+ code: "billing_usage_report_failed",
120
+ routerId:
121
+ typeof payload.router_id === "string" ? payload.router_id : undefined,
122
+ });
123
+ }
124
+
125
+ export function creditExhaustedError(): HttpError {
126
+ return new HttpError(402, "Organization credits are exhausted.", "credit_exhausted");
127
+ }
128
+
129
+ function usagePayload(context: RoutingUsageContext, message: Record<string, unknown>): Record<string, unknown> {
130
+ const usage = isRecord(message.usage) ? message.usage : {};
131
+ const cost = isRecord(usage.cost) ? usage.cost : {};
132
+ const responseId = typeof message.responseId === "string" && message.responseId ? message.responseId : undefined;
133
+ return {
134
+ organization_id: context.organizationId,
135
+ router_id: context.routerId,
136
+ provider: context.provider,
137
+ model: context.model,
138
+ provider_request_id: responseId ?? `routing-${randomUUID()}`,
139
+ input_tokens: tokens(usage.input),
140
+ cached_input_tokens: tokens(usage.cacheRead),
141
+ output_tokens: tokens(usage.output),
142
+ usage_estimated: usage.estimated === true,
143
+ input_cost_usd: usd(cost.input),
144
+ cached_input_cost_usd: usd(cost.cacheRead),
145
+ output_cost_usd: usd(cost.output),
146
+ total_cost_usd: usd(cost.total) ?? "0",
147
+ started_at: context.startedAt.toISOString(),
148
+ ended_at: new Date().toISOString(),
149
+ tags: context.tags,
150
+ };
151
+ }
152
+
153
+ function usageLogFields(payload: Record<string, unknown>): Record<string, unknown> {
154
+ return {
155
+ organization_id: payload.organization_id,
156
+ router_id: payload.router_id,
157
+ provider_request_id: payload.provider_request_id,
158
+ model: payload.model,
159
+ total_cost_usd: payload.total_cost_usd,
160
+ };
161
+ }
162
+
163
+ function tokens(value: unknown): number {
164
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
165
+ }
166
+
167
+ function usd(value: unknown): string | null {
168
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? String(value) : null;
169
+ }
170
+
171
+ function isRecord(value: unknown): value is Record<string, unknown> {
172
+ return typeof value === "object" && value !== null && !Array.isArray(value);
173
+ }
package/src/types.ts ADDED
@@ -0,0 +1,150 @@
1
+ import type {
2
+ CustomRouterConfig,
3
+ Provider,
4
+ ReasoningEffort,
5
+ RouterEval,
6
+ RouterEvalScore,
7
+ RouterModelPrice,
8
+ RouterPrefixHit,
9
+ RoutingStrategy,
10
+ } from "@mupt-ai/dari-router/policy-engine";
11
+ // The router resolution contract between the gateway runtime and its
12
+ // platform. All algorithmic routing types live in @mupt-ai/dari-router.
13
+
14
+ // "subscription" is a personal Codex/Claude Code plan serving the request in
15
+ // place of the router's configured key. It bills no tokens, so it never takes
16
+ // the managed-key billing path, and telemetry reports it as its own source.
17
+ export type ProviderKeySource = "user" | "managed" | "subscription";
18
+
19
+ export type BearerProviderAuth = {
20
+ type: "bearer";
21
+ apiKey: string;
22
+ };
23
+
24
+ export type AwsSigV4ProviderAuth = {
25
+ type: "aws_sigv4";
26
+ access_key_id: string;
27
+ secret_access_key: string;
28
+ session_token?: string | null;
29
+ region: string;
30
+ };
31
+
32
+ // A customer IAM role the routing runtime assumes with Dari's own AWS
33
+ // identity before signing Bedrock requests; the resolve payload carries no
34
+ // customer secret for this type.
35
+ export type AwsAssumeRoleProviderAuth = {
36
+ type: "aws_assume_role";
37
+ role_arn: string;
38
+ external_id: string;
39
+ region: string;
40
+ };
41
+
42
+ // Authentication a provider call can use directly.
43
+ export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
44
+
45
+ // A bearer credential an embedding platform supplies for one request through
46
+ // GatewayPlatform.resolveProviderCredential, optionally with its own endpoint.
47
+ export type ProviderCredential = {
48
+ apiKey: string;
49
+ baseUrl?: string;
50
+ headers?: Record<string, string>;
51
+ };
52
+
53
+ export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
54
+
55
+ export type AwsProviderAuth = AwsSigV4ProviderAuth | AwsAssumeRoleProviderAuth;
56
+
57
+ export type PublicEvalCatalogScore = RouterEvalScore & {
58
+ source_row_name?: string | null;
59
+ source_date?: string | null;
60
+ last_synced_at?: string | null;
61
+ sample_count?: number | null;
62
+ };
63
+
64
+ export type PublicEvalCatalogCard = Omit<RouterEval, "scores"> & {
65
+ source_id: string;
66
+ source_name: string;
67
+ source_url: string;
68
+ harness: string;
69
+ updated_at: string | null;
70
+ scores: PublicEvalCatalogScore[];
71
+ };
72
+
73
+ export type ClientHarness = "claude_code";
74
+
75
+ export type ResolvedRouterModelConfig = {
76
+ provider: string;
77
+ native_model_id: string;
78
+ api: string;
79
+ base_url?: string | null;
80
+ context_window?: number | null;
81
+ standard_context_limit?: number | null;
82
+ allow_long_context?: boolean;
83
+ max_output_tokens?: number | null;
84
+ supported_thinking_levels?: ReasoningEffort[] | null;
85
+ default_thinking_level?: ReasoningEffort | null;
86
+ average_output_tokens?: Partial<Record<ReasoningEffort, number>> | null;
87
+ cost: RouterModelPrice;
88
+ supports_managed_key?: boolean;
89
+ fast_mode?: boolean;
90
+ fast_mode_cost?: RouterModelPrice | null;
91
+ // Copied from the router at execution time, like allow_long_context.
92
+ zdr?: boolean;
93
+ };
94
+
95
+ export type ResolvedRouter = {
96
+ router_id: string;
97
+ organization_id: string;
98
+ api_key_id: string | null;
99
+ attributed_user_id: string | null;
100
+ enabled_models: string[];
101
+ provider_keys: Partial<Record<Provider, string>>;
102
+ provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
103
+ provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
104
+ // Model -> the platform-supplied credential that replaces the provider key
105
+ // above for this request. Filled from resolveProviderCredential.
106
+ provider_credentials?: Record<string, ProviderCredential>;
107
+ // Execution provider -> the user's subscription credential serving it.
108
+ subscription_credential_ids?: Partial<Record<Provider, string>>;
109
+ zdr?: boolean;
110
+ allow_long_context?: boolean;
111
+ speculative_routing?: boolean;
112
+ primary_retries?: number;
113
+ // Serve only the requested `dari/model/<id>` at the requested thinking
114
+ // level: no selector, lease, fallback, or personal subscription, and an
115
+ // error for anything else, whatever the client sends.
116
+ strict?: boolean;
117
+ model_fallback_enabled?: boolean;
118
+ fallback_requires_different_provider?: boolean;
119
+ evals?: RouterEval[];
120
+ // When true, fill missing eval scores using thinking-level ratios or an
121
+ // explicitly mapped predecessor model.
122
+ eval_score_imputation?: boolean;
123
+ // Absent means ON: image-bearing requests exclude candidates whose model
124
+ // cannot accept image input before strategy resolution.
125
+ image_capability_filtering?: boolean;
126
+ // Absent means ON — deliberate: resolutions captured before the key existed
127
+ // must keep lease-context behavior, so platforms send an explicit value
128
+ // (the self-hosted platform sends false). When off, selector
129
+ // inputs carry no task or lease_history keys and no lease history is
130
+ // reconstructed, matching the pre-lease-context wire shape exactly.
131
+ lease_context_enabled?: boolean;
132
+ // Absent means OFF: the selector sees `<image omitted>` placeholders. When
133
+ // true, request images are numbered in the selector prompt and attached to
134
+ // the policy call as image parts, provided the deployed policy accepts them.
135
+ selector_image_input_enabled?: boolean;
136
+ public_eval_catalog?: PublicEvalCatalogCard[] | null;
137
+ prefix_hits?: RouterPrefixHit[];
138
+ routing_strategy?: RoutingStrategy;
139
+ custom_config?: CustomRouterConfig | null;
140
+ model_thinking_levels?: Record<string, ReasoningEffort[]>;
141
+ fast_models?: string[];
142
+ model_prices?: Record<string, RouterModelPrice>;
143
+ model_configs?: Record<string, ResolvedRouterModelConfig>;
144
+ // The organization's credits are exhausted: only models a personal
145
+ // subscription serves keep serving; every other billable request is refused.
146
+ credit_exhausted?: boolean;
147
+ // False when the organization is not on the Autorouting plan. A missing
148
+ // value is treated as enabled.
149
+ autorouting_enabled?: boolean;
150
+ };