@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,800 @@
1
+ import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
2
+ import { HttpError } from "../http/errors";
3
+ import { piMessageToInteractionOutput } from "./pi_output";
4
+ import type { InteractionRequest } from "../interaction/types";
5
+ import { captureOperationalError } from "../observability/errors";
6
+ import {
7
+ CustomerDisconnectedError,
8
+ customerCanceledProviderMessage,
9
+ } from "../runtime/customer_disconnect";
10
+ import {
11
+ isProviderFailureMessage,
12
+ providerFailureFromCaught,
13
+ providerFailureFromTerminal,
14
+ providerFailureMessage,
15
+ } from "../runtime/provider_stream_outcome";
16
+ import {
17
+ reportedExecution,
18
+ type ReportableProviderOutcome,
19
+ type RoutedRuntimeReporter,
20
+ } from "../runtime/runtime_reporter";
21
+ import type { RoutedProtocol } from "../runtime/routed_protocol";
22
+ import { trackBackgroundTelemetry } from "../telemetry/background";
23
+ import { gatewayPlatform, type SubscriptionHold } from "../platform/platform";
24
+ import { reportRoutingUsage } from "../telemetry/usage";
25
+ import {
26
+ prepareProviderExecution,
27
+ primeProviderStream,
28
+ scrubProviderMessage,
29
+ startProviderCompletion,
30
+ startProviderStream,
31
+ type CompletedProviderCall,
32
+ type ProviderExecution,
33
+ type StartedCompletion,
34
+ type StartedStream,
35
+ } from "./provider_call";
36
+ import {
37
+ runProviderAttemptPlan,
38
+ type ProviderAttemptFailure,
39
+ type ProviderAttemptPlanResult,
40
+ type ProviderAttemptResult,
41
+ } from "./provider_attempt_runner";
42
+ import {
43
+ estimatedCancelUsage,
44
+ NO_DELIVERED_OUTPUT,
45
+ observeDeliveredOutput,
46
+ } from "./cancel_estimate";
47
+ import { providerResponseCaptureFromError, type ProviderResponseCapture } from "./response_capture";
48
+ import { createStreamFinalizer } from "./stream_finalization";
49
+ import {
50
+ detectSubscriptionUsageLimit,
51
+ failureWithSubscriptionUsageLimit,
52
+ retryAfterSeconds,
53
+ subscriptionUsageLimitFromFailure,
54
+ subscriptionSwitchedMessage,
55
+ subscriptionUsageLimitMessage,
56
+ } from "./subscription_limits";
57
+
58
+ export type ProviderChoice = {
59
+ decision: RoutingDecision;
60
+ execution: ProviderExecution;
61
+ role: "primary" | "fallback";
62
+ };
63
+
64
+ export type ResolveFallbackChoice = () => Promise<ProviderChoice | null>;
65
+
66
+ export type PreparedStreamExecution = {
67
+ choice: ProviderChoice;
68
+ started: StartedStream;
69
+ attempt: number;
70
+ failedSetupLatencyMs: number;
71
+ };
72
+
73
+ export type CompletedNonStreamingExecution = {
74
+ choice: ProviderChoice;
75
+ output: ReturnType<typeof piMessageToInteractionOutput>;
76
+ responseBody: Record<string, unknown>;
77
+ reportBarrierError?: unknown;
78
+ };
79
+
80
+ type CompletedNonStreamingAttempt = {
81
+ completion: CompletedProviderCall;
82
+ };
83
+
84
+ export async function executeNonStreaming(args: {
85
+ requestId: string;
86
+ interaction: InteractionRequest;
87
+ primary: ProviderChoice;
88
+ primaryRetries: number;
89
+ resolveFallback: ResolveFallbackChoice;
90
+ reporter: RoutedRuntimeReporter;
91
+ protocol: RoutedProtocol;
92
+ startedCompletion?: StartedCompletion;
93
+ reportBarrier?: Promise<unknown>;
94
+ clientSignal?: AbortSignal;
95
+ }): Promise<Response> {
96
+ const result = await completeNonStreaming(args);
97
+ if (result.reportBarrierError !== undefined) {
98
+ captureOperationalError(result.reportBarrierError, {
99
+ code: "routing_report_barrier_failed",
100
+ requestId: args.requestId,
101
+ routerId: result.choice.execution.usageContext?.routerId,
102
+ });
103
+ }
104
+ return Response.json(result.responseBody, {
105
+ headers: result.choice.execution.headers,
106
+ });
107
+ }
108
+
109
+ export async function completeNonStreaming(args: {
110
+ requestId: string;
111
+ interaction: InteractionRequest;
112
+ primary: ProviderChoice;
113
+ primaryRetries: number;
114
+ resolveFallback: ResolveFallbackChoice;
115
+ reporter: RoutedRuntimeReporter;
116
+ protocol: RoutedProtocol;
117
+ startedCompletion?: StartedCompletion;
118
+ reportBarrier?: Promise<unknown>;
119
+ clientSignal?: AbortSignal;
120
+ }): Promise<CompletedNonStreamingExecution> {
121
+ const result = await completeWithRetries(args);
122
+ args.reporter.attachServingDecision(result.choice.decision);
123
+ if (result.kind === "customer_canceled") {
124
+ return reportCustomerCancellation({
125
+ requestId: args.requestId,
126
+ reporter: args.reporter,
127
+ choice: result.choice,
128
+ providerLatencyMs: result.latencyMs,
129
+ providerMessage: result.failure,
130
+ reportBarrier: args.reportBarrier,
131
+ });
132
+ }
133
+ if (result.kind === "provider_failed") {
134
+ return throwProviderFailure({
135
+ requestId: args.requestId,
136
+ reporter: args.reporter,
137
+ reportBarrier: args.reportBarrier,
138
+ result,
139
+ });
140
+ }
141
+
142
+ const {
143
+ value: { completion },
144
+ choice,
145
+ } = result;
146
+ let output: ReturnType<typeof piMessageToInteractionOutput>;
147
+ let responseBody: Record<string, unknown>;
148
+ try {
149
+ output = piMessageToInteractionOutput(
150
+ completion.message,
151
+ completion.source,
152
+ args.interaction,
153
+ );
154
+ responseBody = args.protocol.responseBody({
155
+ id: args.requestId,
156
+ model: choice.execution.model,
157
+ output,
158
+ modelCost: args.reporter.modelCost({
159
+ model: choice.decision.selectedModel, reasoning_effort: choice.decision.reasoningEffort,
160
+ role: choice.role, attempt: result.attempt, outcome: "completed", billingOutcome: "completed",
161
+ execution: reportedExecution(choice.execution), message: completion.message,
162
+ }),
163
+ request: args.interaction,
164
+ routing: choice.decision,
165
+ conversationId: choice.execution.conversationId,
166
+ });
167
+ } catch (error) {
168
+ await reportTerminalProviderFailure({
169
+ requestId: args.requestId,
170
+ reporter: args.reporter,
171
+ choice,
172
+ attempt: result.attempt,
173
+ providerLatencyMs: result.latencyMs,
174
+ providerMessage: completion.message,
175
+ reportBarrier: args.reportBarrier,
176
+ error,
177
+ });
178
+ // reportTerminalProviderFailure always throws the original translation
179
+ // error after settling exact billing. Keep this explicit for TypeScript's
180
+ // definite-assignment analysis.
181
+ throw error;
182
+ }
183
+ recordProviderAttempt(
184
+ args.reporter,
185
+ choice,
186
+ result.attempt,
187
+ "completed",
188
+ "completed",
189
+ completion.message,
190
+ );
191
+ const providerOutcome = {
192
+ status: "completed",
193
+ output,
194
+ message: completion.message,
195
+ responseBody,
196
+ providerLatencyMs: result.latencyMs,
197
+ execution: reportedExecution(choice.execution),
198
+ } as const;
199
+ // Provider economics are terminal now. Register them before the speculative
200
+ // selector/report barrier so the frozen facts cannot change afterwards.
201
+ const terminal = args.reporter.freezeProviderTerminal(providerOutcome);
202
+ // Settle the speculative selector before reporting, mirroring the stream
203
+ // path: the report builds the prefix entry, whose next_model must carry
204
+ // the selector's next-turn choice (and its trace), not the speculative
205
+ // serving pick that happened to win the provider race.
206
+ let reportBarrierError: unknown;
207
+ try {
208
+ await args.reportBarrier;
209
+ } catch (error) {
210
+ reportBarrierError = error;
211
+ }
212
+ terminal.report();
213
+ // Every turn — speculative or not — holds its response on the fast
214
+ // prefix-state write, so an immediate continuation always resolves this
215
+ // turn's entry. Bounded by PREFIX_STATE_WRITE_WAIT_MS.
216
+ await args.reporter.waitForPrefixEntryWrite();
217
+ return {
218
+ choice,
219
+ output,
220
+ responseBody,
221
+ ...(reportBarrierError === undefined ? {} : { reportBarrierError }),
222
+ };
223
+ }
224
+
225
+ type CompletionRetryResult = ProviderAttemptPlanResult<
226
+ ProviderChoice,
227
+ CompletedNonStreamingAttempt
228
+ >;
229
+
230
+ async function completeWithRetries(args: {
231
+ interaction: InteractionRequest;
232
+ primary: ProviderChoice;
233
+ primaryRetries: number;
234
+ resolveFallback: ResolveFallbackChoice;
235
+ reporter: RoutedRuntimeReporter;
236
+ startedCompletion?: StartedCompletion;
237
+ clientSignal?: AbortSignal;
238
+ }): Promise<CompletionRetryResult> {
239
+ return runProviderAttemptPlan({
240
+ primary: args.primary,
241
+ retries: args.primaryRetries,
242
+ resolveFallback: args.resolveFallback,
243
+ primaryInitial: args.startedCompletion,
244
+ isCustomerCanceled: () => customerAbortRequested(args.clientSignal),
245
+ canceledFailure: customerCanceledProviderMessage,
246
+ runAttempt: ({ choice, initial }) => runCompletionAttempt({
247
+ interaction: args.interaction,
248
+ choice,
249
+ reporter: args.reporter,
250
+ startedCompletion: initial,
251
+ clientSignal: args.clientSignal,
252
+ }),
253
+ recordFailedAttempt: ({ choice, attempt, result }) =>
254
+ recordSettledFailure(args.reporter, choice, attempt, result),
255
+ });
256
+ }
257
+
258
+ async function runCompletionAttempt(args: {
259
+ interaction: InteractionRequest;
260
+ choice: ProviderChoice;
261
+ reporter: RoutedRuntimeReporter;
262
+ startedCompletion?: StartedCompletion;
263
+ clientSignal?: AbortSignal;
264
+ }): Promise<ProviderAttemptResult<CompletedNonStreamingAttempt>> {
265
+ const startedAt = Date.now();
266
+ const started = args.startedCompletion ?? startProviderCompletion({
267
+ interaction: args.interaction,
268
+ execution: args.choice.execution,
269
+ clientSignal: args.clientSignal,
270
+ });
271
+ try {
272
+ const completion = await started.promise;
273
+ if (started.customerAbort.aborted) {
274
+ return customerCanceledAttempt(
275
+ completion.providerLatencyMs,
276
+ args.choice.execution,
277
+ completion.message,
278
+ );
279
+ }
280
+ if (isProviderFailureMessage(completion.message)) {
281
+ return providerFailedAttempt(
282
+ completion.message,
283
+ completion.providerLatencyMs,
284
+ args.choice.execution,
285
+ started.responseCapture,
286
+ );
287
+ }
288
+ if (args.choice.execution.usageContext && hasUsage(completion.message)) {
289
+ await reportRoutingUsage(
290
+ {
291
+ ...args.choice.execution.usageContext,
292
+ startedAt: completion.providerStartedAt,
293
+ },
294
+ completion.message,
295
+ );
296
+ }
297
+ return {
298
+ kind: "succeeded",
299
+ value: { completion },
300
+ latencyMs: completion.providerLatencyMs,
301
+ };
302
+ } catch (error) {
303
+ const latencyMs = Date.now() - startedAt;
304
+ if (
305
+ started.customerAbort.aborted ||
306
+ error instanceof CustomerDisconnectedError
307
+ ) {
308
+ return customerCanceledAttempt(latencyMs, args.choice.execution);
309
+ }
310
+ return providerFailedAttempt(
311
+ scrubProviderMessage(
312
+ providerFailureFromCaught(error),
313
+ args.choice.execution.auth,
314
+ ),
315
+ latencyMs,
316
+ args.choice.execution,
317
+ started.responseCapture,
318
+ );
319
+ }
320
+ }
321
+
322
+ async function settleTerminal(args: {
323
+ reporter: RoutedRuntimeReporter;
324
+ outcome: ReportableProviderOutcome;
325
+ requestId: string;
326
+ routerId?: string;
327
+ reportBarrier?: Promise<unknown>;
328
+ }): Promise<void> {
329
+ const terminal = args.reporter.freezeProviderTerminal(args.outcome);
330
+ try {
331
+ await args.reportBarrier;
332
+ } catch (error) {
333
+ captureOperationalError(error, {
334
+ code: "routing_report_barrier_failed",
335
+ requestId: args.requestId,
336
+ routerId: args.routerId,
337
+ });
338
+ }
339
+ terminal.report();
340
+ }
341
+
342
+ async function reportTerminalProviderFailure(args: {
343
+ requestId: string;
344
+ reporter: RoutedRuntimeReporter;
345
+ choice: ProviderChoice;
346
+ attempt: number;
347
+ providerLatencyMs: number;
348
+ providerMessage: Record<string, unknown>;
349
+ reportBarrier?: Promise<unknown>;
350
+ error: unknown;
351
+ }): Promise<never> {
352
+ const failure = scrubProviderMessage(
353
+ providerFailureFromTerminal(args.error, args.providerMessage),
354
+ args.choice.execution.auth,
355
+ );
356
+ recordProviderAttempt(
357
+ args.reporter,
358
+ args.choice,
359
+ args.attempt,
360
+ "terminal_error",
361
+ "provider_failed",
362
+ failure,
363
+ );
364
+ await settleTerminal({
365
+ reporter: args.reporter,
366
+ outcome: {
367
+ status: "provider_error",
368
+ message: failure,
369
+ providerLatencyMs: args.providerLatencyMs,
370
+ execution: reportedExecution(args.choice.execution),
371
+ },
372
+ requestId: args.requestId,
373
+ routerId: args.choice.execution.usageContext?.routerId,
374
+ reportBarrier: args.reportBarrier,
375
+ });
376
+ throw args.error;
377
+ }
378
+
379
+ async function reportCustomerCancellation(args: {
380
+ requestId: string;
381
+ reporter: RoutedRuntimeReporter;
382
+ choice: ProviderChoice;
383
+ providerLatencyMs: number;
384
+ providerMessage: Record<string, unknown>;
385
+ reportBarrier?: Promise<unknown>;
386
+ }): Promise<never> {
387
+ const usageContext = args.choice.execution.usageContext;
388
+ if (usageContext && hasUsage(args.providerMessage)) {
389
+ await reportRoutingUsage(usageContext, args.providerMessage);
390
+ }
391
+ await settleTerminal({
392
+ reporter: args.reporter,
393
+ outcome: {
394
+ status: "customer_canceled",
395
+ message: args.providerMessage,
396
+ responseBody: null,
397
+ providerLatencyMs: args.providerLatencyMs,
398
+ execution: reportedExecution(args.choice.execution),
399
+ },
400
+ requestId: args.requestId,
401
+ routerId: args.choice.execution.usageContext?.routerId,
402
+ reportBarrier: args.reportBarrier,
403
+ });
404
+ throw new CustomerDisconnectedError();
405
+ }
406
+
407
+ async function throwProviderFailure(args: {
408
+ requestId: string;
409
+ reporter: RoutedRuntimeReporter;
410
+ reportBarrier?: Promise<unknown>;
411
+ result: {
412
+ choice: ProviderChoice;
413
+ failure: Record<string, unknown>;
414
+ latencyMs: number;
415
+ };
416
+ }): Promise<never> {
417
+ const { result } = args;
418
+ await settleTerminal({
419
+ reporter: args.reporter,
420
+ outcome: {
421
+ status: "provider_error",
422
+ message: result.failure,
423
+ providerLatencyMs: result.latencyMs,
424
+ execution: reportedExecution(result.choice.execution),
425
+ },
426
+ requestId: args.requestId,
427
+ routerId: result.choice.execution.usageContext?.routerId,
428
+ reportBarrier: args.reportBarrier,
429
+ });
430
+ const limit = subscriptionUsageLimitFromFailure(result.failure);
431
+ if (limit?.switched === true) {
432
+ // The client's retry is served by the user's next subscription.
433
+ throw new HttpError(
434
+ 503,
435
+ subscriptionSwitchedMessage(limit),
436
+ "subscription_switched",
437
+ undefined,
438
+ { "retry-after": "1" },
439
+ );
440
+ }
441
+ if (limit !== null) {
442
+ throw new HttpError(
443
+ 429,
444
+ subscriptionUsageLimitMessage(limit),
445
+ "subscription_usage_limit",
446
+ undefined,
447
+ { "retry-after": String(retryAfterSeconds(limit)) },
448
+ );
449
+ }
450
+ throw new HttpError(
451
+ 502,
452
+ providerFailureMessage(result.failure),
453
+ "provider_execution_failed",
454
+ );
455
+ }
456
+
457
+ export async function prepareStreamingExecution(args: {
458
+ requestId: string;
459
+ interaction: InteractionRequest;
460
+ primary: ProviderChoice;
461
+ primaryRetries: number;
462
+ resolveFallback: ResolveFallbackChoice;
463
+ reporter: RoutedRuntimeReporter;
464
+ startedStream?: StartedStream;
465
+ initialError?: unknown;
466
+ reportBarrier?: Promise<unknown>;
467
+ clientSignal?: AbortSignal;
468
+ }): Promise<PreparedStreamExecution> {
469
+ const primaryInitial: InitialStreamAttempt | undefined =
470
+ args.initialError !== undefined
471
+ ? { kind: "error", error: args.initialError }
472
+ : args.startedStream === undefined
473
+ ? undefined
474
+ : { kind: "started", started: args.startedStream };
475
+ const result = await runProviderAttemptPlan({
476
+ primary: args.primary,
477
+ retries: args.primaryRetries,
478
+ resolveFallback: args.resolveFallback,
479
+ primaryInitial,
480
+ isCustomerCanceled: () => customerAbortRequested(args.clientSignal),
481
+ canceledFailure: customerCanceledProviderMessage,
482
+ runAttempt: ({ choice, initial }) => runStreamSetupAttempt({
483
+ interaction: args.interaction,
484
+ choice,
485
+ initial,
486
+ clientSignal: args.clientSignal,
487
+ }),
488
+ recordFailedAttempt: ({ choice, attempt, result }) =>
489
+ recordSettledFailure(args.reporter, choice, attempt, result),
490
+ });
491
+ args.reporter.attachServingDecision(result.choice.decision);
492
+ if (result.kind === "customer_canceled") {
493
+ return reportCustomerCancellation({
494
+ requestId: args.requestId,
495
+ reporter: args.reporter,
496
+ choice: result.choice,
497
+ providerLatencyMs: result.latencyMs,
498
+ providerMessage: result.failure,
499
+ reportBarrier: args.reportBarrier,
500
+ });
501
+ }
502
+ if (result.kind === "provider_failed") {
503
+ return throwProviderFailure({
504
+ requestId: args.requestId,
505
+ reporter: args.reporter,
506
+ reportBarrier: args.reportBarrier,
507
+ result,
508
+ });
509
+ }
510
+ return {
511
+ choice: result.choice,
512
+ started: result.value,
513
+ attempt: result.attempt,
514
+ failedSetupLatencyMs: result.latencyMs,
515
+ };
516
+ }
517
+
518
+ type InitialStreamAttempt =
519
+ | { kind: "started"; started: StartedStream }
520
+ | { kind: "error"; error: unknown };
521
+
522
+ async function runStreamSetupAttempt(args: {
523
+ interaction: InteractionRequest;
524
+ choice: ProviderChoice;
525
+ initial: InitialStreamAttempt | undefined;
526
+ clientSignal?: AbortSignal;
527
+ }): Promise<ProviderAttemptResult<StartedStream>> {
528
+ const startedAt = Date.now();
529
+ let started: StartedStream | undefined;
530
+ try {
531
+ if (args.initial?.kind === "error") throw args.initial.error;
532
+ started = args.initial?.kind === "started"
533
+ ? args.initial.started
534
+ : await startProviderStream({
535
+ interaction: args.interaction,
536
+ execution: args.choice.execution,
537
+ clientSignal: args.clientSignal,
538
+ });
539
+ // Prime before committing so connection failures and prompt rejections
540
+ // stay inside the one shared retry/fallback state machine.
541
+ const primed = await primeProviderStream(
542
+ started.providerStream.events,
543
+ started.customerAbort,
544
+ );
545
+ if (primed.outcome === "error") {
546
+ started.customerAbort.dispose();
547
+ return providerFailedAttempt(
548
+ scrubProviderMessage(primed.failure, args.choice.execution.auth),
549
+ Date.now() - startedAt,
550
+ args.choice.execution,
551
+ started.responseCapture,
552
+ );
553
+ }
554
+ return {
555
+ kind: "succeeded",
556
+ value: {
557
+ providerStartedMs: started.providerStartedMs,
558
+ providerStream: {
559
+ events: primed.events,
560
+ source: started.providerStream.source,
561
+ },
562
+ customerAbort: started.customerAbort,
563
+ },
564
+ latencyMs: 0,
565
+ };
566
+ } catch (error) {
567
+ const customerCanceled =
568
+ started?.customerAbort.aborted === true ||
569
+ error instanceof CustomerDisconnectedError;
570
+ started?.customerAbort.dispose();
571
+ if (customerCanceled) {
572
+ return customerCanceledAttempt(
573
+ Date.now() - startedAt,
574
+ args.choice.execution,
575
+ );
576
+ }
577
+ return providerFailedAttempt(
578
+ scrubProviderMessage(
579
+ providerFailureFromCaught(error),
580
+ args.choice.execution.auth,
581
+ ),
582
+ Date.now() - startedAt,
583
+ args.choice.execution,
584
+ started?.responseCapture ?? providerResponseCaptureFromError(error),
585
+ );
586
+ }
587
+ }
588
+
589
+ export async function executeStreaming(args: {
590
+ requestId: string;
591
+ interaction: InteractionRequest;
592
+ choice: ProviderChoice;
593
+ reporter: RoutedRuntimeReporter;
594
+ protocol: RoutedProtocol;
595
+ startedStream: StartedStream;
596
+ attempt: number;
597
+ failedSetupLatencyMs: number;
598
+ reportBarrier?: Promise<unknown>;
599
+ clientSignal?: AbortSignal;
600
+ }): Promise<Response> {
601
+ const { execution } = args.choice;
602
+ const started = args.startedStream;
603
+ args.reporter.attachServingDecision(args.choice.decision);
604
+ const observed = observeDeliveredOutput(started.providerStream.events);
605
+ const finalizer = createStreamFinalizer({
606
+ requestId: args.requestId,
607
+ interaction: args.interaction,
608
+ decision: args.choice.decision,
609
+ execution,
610
+ reporter: args.reporter,
611
+ protocol: args.protocol,
612
+ providerLatencyMs: () =>
613
+ args.failedSetupLatencyMs + Date.now() - started.providerStartedMs,
614
+ role: args.choice.role,
615
+ attempt: args.attempt,
616
+ reportBarrier: args.reportBarrier,
617
+ delivered: observed.delivered,
618
+ source: started.providerStream.source,
619
+ startedAtMs: started.providerStartedMs,
620
+ });
621
+ return new Response(
622
+ args.protocol.streamBody({
623
+ id: args.requestId,
624
+ model: execution.model,
625
+ routing: args.choice.decision,
626
+ events: observed.events,
627
+ source: started.providerStream.source,
628
+ request: args.interaction,
629
+ conversationId: execution.conversationId,
630
+ clientSignal: args.clientSignal,
631
+ modelCost: (message, failed) => args.reporter.modelCost({
632
+ model: args.choice.decision.selectedModel, reasoning_effort: args.choice.decision.reasoningEffort,
633
+ role: args.choice.role, attempt: args.attempt,
634
+ outcome: failed ? "terminal_error" : "completed",
635
+ billingOutcome: failed ? "provider_failed" : "completed",
636
+ execution: reportedExecution(execution), message,
637
+ }),
638
+ onAbort: () => started.customerAbort.abort(),
639
+ beforeClose: finalizer.beforeResponseClose,
640
+ onFinal: (outcome) => {
641
+ started.customerAbort.dispose();
642
+ trackBackgroundTelemetry(finalizer.afterResponseDetached(outcome));
643
+ },
644
+ }),
645
+ { headers: streamHeaders(execution) },
646
+ );
647
+ }
648
+
649
+ function streamHeaders(execution: ProviderExecution): Record<string, string> {
650
+ return {
651
+ "Content-Type": "text/event-stream",
652
+ "Cache-Control": "no-cache",
653
+ "Connection": "keep-alive",
654
+ ...execution.headers,
655
+ };
656
+ }
657
+
658
+ function customerAbortRequested(
659
+ clientSignal: AbortSignal | undefined,
660
+ ): boolean {
661
+ // A disconnected client never starts new paid work that nobody can receive.
662
+ return clientSignal?.aborted === true;
663
+ }
664
+
665
+ function recordProviderAttempt(
666
+ reporter: RoutedRuntimeReporter,
667
+ choice: ProviderChoice,
668
+ attempt: number,
669
+ outcome: "completed" | "error" | "terminal_error" | "canceled",
670
+ billingOutcome: "completed" | "provider_failed" | "customer_canceled",
671
+ message: Record<string, unknown>,
672
+ ): void {
673
+ reporter.recordProviderAttempt({
674
+ model: choice.decision.selectedModel,
675
+ reasoning_effort: choice.decision.reasoningEffort,
676
+ role: choice.role,
677
+ attempt,
678
+ outcome,
679
+ execution: reportedExecution(choice.execution),
680
+ message,
681
+ billingOutcome,
682
+ });
683
+ }
684
+
685
+ function recordSettledFailure(
686
+ reporter: RoutedRuntimeReporter,
687
+ choice: ProviderChoice,
688
+ attempt: number,
689
+ result: ProviderAttemptFailure,
690
+ ): void {
691
+ recordProviderAttempt(
692
+ reporter,
693
+ choice,
694
+ attempt,
695
+ result.kind === "customer_canceled" ? "canceled" : "error",
696
+ result.kind,
697
+ result.message,
698
+ );
699
+ }
700
+
701
+ async function providerFailedAttempt(
702
+ message: Record<string, unknown>,
703
+ latencyMs: number,
704
+ execution: ProviderExecution,
705
+ responseCapture: ProviderResponseCapture | undefined,
706
+ ): Promise<ProviderAttemptFailure> {
707
+ const limit = detectSubscriptionUsageLimit({
708
+ provider: execution.provider,
709
+ keySource: execution.providerKeySource,
710
+ captured: responseCapture?.last,
711
+ failure: message,
712
+ });
713
+ if (limit === null) {
714
+ return {
715
+ kind: "provider_failed",
716
+ message,
717
+ latencyMs,
718
+ retryable: !isPromptPolicyRejection(message),
719
+ };
720
+ }
721
+ // Retrying an exhausted plan cannot succeed. The platform learns about it
722
+ // before this request returns so the next resolve already serves the
723
+ // user's next subscription, or the router's subscription fallback model.
724
+ const switched = execution.subscriptionUserId !== undefined
725
+ && await holdSubscription({
726
+ userId: execution.subscriptionUserId,
727
+ credentialId: execution.subscriptionCredentialId,
728
+ limit,
729
+ });
730
+ return {
731
+ kind: "provider_failed",
732
+ message: failureWithSubscriptionUsageLimit(message, { ...limit, switched }),
733
+ latencyMs,
734
+ retryable: false,
735
+ };
736
+ }
737
+
738
+ // The provider call was in flight, so the prompt was paid for. A completion
739
+ // that returned before the abort was observed carries exact usage; otherwise
740
+ // the prompt is estimated and nothing was delivered. A usage object with no
741
+ // tokens at all is the SDK's placeholder for an interrupted call, not a
742
+ // measurement, so it falls back to the estimate too.
743
+ function customerCanceledAttempt(
744
+ latencyMs: number,
745
+ execution: ProviderExecution,
746
+ completed?: Record<string, unknown>,
747
+ ): ProviderAttemptFailure {
748
+ const exactUsage =
749
+ completed !== undefined && hasUsage(completed) && usageHasTokens(completed.usage)
750
+ ? (completed.usage as Record<string, unknown>)
751
+ : null;
752
+ return {
753
+ kind: "customer_canceled",
754
+ message: customerCanceledProviderMessage(
755
+ exactUsage ??
756
+ estimatedCancelUsage({
757
+ pricing: execution.pricing,
758
+ promptEstimate: execution.promptEstimate,
759
+ delivered: NO_DELIVERED_OUTPUT,
760
+ }),
761
+ typeof completed?.responseId === "string" ? completed.responseId : undefined,
762
+ ),
763
+ latencyMs,
764
+ retryable: false,
765
+ };
766
+ }
767
+
768
+ function hasUsage(message: Record<string, unknown>): boolean {
769
+ return (
770
+ typeof message.usage === "object" &&
771
+ message.usage !== null &&
772
+ !Array.isArray(message.usage)
773
+ );
774
+ }
775
+
776
+ function usageHasTokens(usage: unknown): boolean {
777
+ if (typeof usage !== "object" || usage === null) return false;
778
+ const counts = usage as Record<string, unknown>;
779
+ return ["input", "output", "cacheRead", "cacheWrite"].some((key) => {
780
+ const value = counts[key];
781
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
782
+ });
783
+ }
784
+
785
+ function isPromptPolicyRejection(message: Record<string, unknown>): boolean {
786
+ const text = providerFailureMessage(message).toLowerCase();
787
+ return text.includes("invalid prompt") && text.includes("usage policy");
788
+ }
789
+
790
+ // Never fails the request: the provider already refused. Resolves whether
791
+ // another subscription now serves.
792
+ async function holdSubscription(hold: SubscriptionHold): Promise<boolean> {
793
+ try {
794
+ return await gatewayPlatform().markSubscriptionUnavailable(hold);
795
+ } catch (error) {
796
+ console.error("subscription-unavailable write failed", error);
797
+ captureOperationalError(error, { code: "subscription_unavailable_ingest_failed" });
798
+ return false;
799
+ }
800
+ }