@mupt-ai/dari-gateway 1.0.339 → 1.0.340

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 (60) hide show
  1. package/README.md +9 -7
  2. package/dist/index.d.ts +1 -1
  3. package/dist/link/assets.js +7 -0
  4. package/dist/link/endpoints.js +26 -6
  5. package/dist/link/errors.js +3 -0
  6. package/dist/link/self_hosted.js +8 -2
  7. package/dist/models/catalog.js +1 -0
  8. package/dist/models/execution_provider.d.ts +6 -1
  9. package/dist/models/execution_provider.js +12 -0
  10. package/dist/models/provider_defaults.js +9 -0
  11. package/dist/models/provider_models.json +217 -0
  12. package/dist/models/subscriptions.d.ts +5 -0
  13. package/dist/models/subscriptions.js +21 -2
  14. package/dist/providers/execution.d.ts +5 -0
  15. package/dist/providers/execution.js +12 -2
  16. package/dist/providers/github_copilot.d.ts +8 -0
  17. package/dist/providers/github_copilot.js +21 -0
  18. package/dist/providers/pi.js +3 -0
  19. package/dist/providers/provider_attempt_runner.d.ts +2 -0
  20. package/dist/providers/provider_attempt_runner.js +9 -0
  21. package/dist/providers/provider_call.js +6 -2
  22. package/dist/providers/subscription_limits.d.ts +6 -5
  23. package/dist/providers/subscription_limits.js +20 -9
  24. package/dist/runtime/routed_runtime.js +68 -3
  25. package/dist/self_host/resolve.d.ts +11 -9
  26. package/dist/self_host/resolve.js +247 -181
  27. package/dist/self_host/subscriptions/index.d.ts +6 -5
  28. package/dist/self_host/subscriptions/index.js +6 -5
  29. package/dist/self_host/subscriptions/oauth.d.ts +7 -3
  30. package/dist/self_host/subscriptions/oauth.js +195 -5
  31. package/dist/self_host/subscriptions/store.js +3 -0
  32. package/dist/telemetry/prefix_state.d.ts +1 -0
  33. package/dist/telemetry/prefix_state.js +1 -1
  34. package/dist/telemetry/report.js +2 -3
  35. package/dist/types.d.ts +6 -2
  36. package/package.json +2 -2
  37. package/src/index.ts +1 -1
  38. package/src/link/assets.ts +7 -0
  39. package/src/link/endpoints.ts +27 -7
  40. package/src/link/errors.ts +3 -0
  41. package/src/link/self_hosted.ts +9 -1
  42. package/src/models/catalog.ts +1 -0
  43. package/src/models/execution_provider.ts +24 -1
  44. package/src/models/provider_defaults.ts +9 -0
  45. package/src/models/provider_models.json +217 -0
  46. package/src/models/subscriptions.ts +22 -2
  47. package/src/providers/execution.ts +22 -2
  48. package/src/providers/github_copilot.ts +24 -0
  49. package/src/providers/pi.ts +2 -0
  50. package/src/providers/provider_attempt_runner.ts +15 -0
  51. package/src/providers/provider_call.ts +6 -2
  52. package/src/providers/subscription_limits.ts +20 -10
  53. package/src/runtime/routed_runtime.ts +79 -3
  54. package/src/self_host/resolve.ts +253 -186
  55. package/src/self_host/subscriptions/index.ts +7 -4
  56. package/src/self_host/subscriptions/oauth.ts +264 -8
  57. package/src/self_host/subscriptions/store.ts +3 -0
  58. package/src/telemetry/prefix_state.ts +4 -1
  59. package/src/telemetry/report.ts +2 -3
  60. package/src/types.ts +27 -3
@@ -1,13 +1,21 @@
1
- import { nativeModelId } from "@mupt-ai/dari-router/policy-engine";
1
+ import { nativeModelId, providerForModel } from "@mupt-ai/dari-router/policy-engine";
2
+ import { providerModel } from "./canonical.js";
2
3
  const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
3
4
  // The execution providers whose models each kind of plan serves; a ChatGPT
4
5
  // plan's OpenAI models execute as `openai-codex` once resolve points them at
5
6
  // the Codex backend.
7
+ //
8
+ // The order is the order a model's plans serve it in, maker plans first, then
9
+ // the router's API credential. It matches the control plane's
10
+ // SUBSCRIPTION_OAUTH_PROVIDERS; keep the two in sync.
6
11
  const SUBSCRIPTION_MODEL_PROVIDERS = {
7
- openai_codex: ["openai", "openai-codex"],
8
12
  anthropic_claude_code: ["anthropic"],
13
+ openai_codex: ["openai", "openai-codex"],
14
+ xai_grok: ["xai"],
9
15
  meta_muse: ["meta"],
10
16
  opencode_go: ["opencode-go"],
17
+ github_copilot: ["github-copilot"],
18
+ vercel_token_pass: ["vercel-token-pass"],
11
19
  };
12
20
  // The client each plan is limited to, as its provider limits it: a Claude Code
13
21
  // plan serves only Claude Code, and a Muse Code plan only Muse Code.
@@ -19,6 +27,17 @@ const SUBSCRIPTION_CLIENTS = {
19
27
  export function subscriptionModelProvider(kind) {
20
28
  return SUBSCRIPTION_MODEL_PROVIDERS[kind][0];
21
29
  }
30
+ /**
31
+ * The plans that can serve a model, in the order they serve it: each whose
32
+ * provider is the model's maker or serves it as its own model.
33
+ */
34
+ export function modelSubscriptions(modelId) {
35
+ const maker = providerForModel(modelId);
36
+ return Object.keys(SUBSCRIPTION_MODEL_PROVIDERS).filter((kind) => {
37
+ const provider = subscriptionModelProvider(kind);
38
+ return provider === maker || providerModel(modelId, provider) !== undefined;
39
+ });
40
+ }
22
41
  /**
23
42
  * The only client a plan may serve, or undefined when it serves any client:
24
43
  * ChatGPT plans serve any client through the Codex backend.
@@ -7,7 +7,9 @@ import { type ProviderExecution, type StartedCompletion, type StartedStream } fr
7
7
  export type ProviderChoice = {
8
8
  decision: RoutingDecision;
9
9
  execution: ProviderExecution;
10
+ fallback?: number;
10
11
  };
12
+ export type NextProviderChoice = (choice: ProviderChoice) => Promise<ProviderChoice | undefined>;
11
13
  export type PreparedStreamExecution = {
12
14
  choice: ProviderChoice;
13
15
  started: StartedStream;
@@ -25,6 +27,7 @@ export declare function executeNonStreaming(args: {
25
27
  interaction: InteractionRequest;
26
28
  primary: ProviderChoice;
27
29
  primaryRetries: number;
30
+ nextChoice?: NextProviderChoice;
28
31
  reporter: RoutedRuntimeReporter;
29
32
  protocol: RoutedProtocol;
30
33
  startedCompletion?: StartedCompletion;
@@ -36,6 +39,7 @@ export declare function completeNonStreaming(args: {
36
39
  interaction: InteractionRequest;
37
40
  primary: ProviderChoice;
38
41
  primaryRetries: number;
42
+ nextChoice?: NextProviderChoice;
39
43
  reporter: RoutedRuntimeReporter;
40
44
  protocol: RoutedProtocol;
41
45
  startedCompletion?: StartedCompletion;
@@ -47,6 +51,7 @@ export declare function prepareStreamingExecution(args: {
47
51
  interaction: InteractionRequest;
48
52
  primary: ProviderChoice;
49
53
  primaryRetries: number;
54
+ nextChoice?: NextProviderChoice;
50
55
  reporter: RoutedRuntimeReporter;
51
56
  startedStream?: StartedStream;
52
57
  initialError?: unknown;
@@ -12,6 +12,7 @@ import { runProviderAttemptPlan, } from "./provider_attempt_runner.js";
12
12
  import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } from "./cancel_estimate.js";
13
13
  import { providerResponseCaptureFromError } from "./response_capture.js";
14
14
  import { createStreamFinalizer } from "./stream_finalization.js";
15
+ import { copilotEndpoint } from "./github_copilot.js";
15
16
  import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
16
17
  import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, museSubscriptionUsage, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
17
18
  export async function executeNonStreaming(args) {
@@ -150,6 +151,7 @@ async function completeWithRetries(args) {
150
151
  }),
151
152
  recordFailedAttempt: ({ choice, attempt, result }) => recordSettledFailure(args.reporter, choice, attempt, result),
152
153
  onSubscription: onNextSubscription,
154
+ nextChoice: args.nextChoice,
153
155
  });
154
156
  }
155
157
  async function runCompletionAttempt(args) {
@@ -293,6 +295,7 @@ export async function prepareStreamingExecution(args) {
293
295
  }),
294
296
  recordFailedAttempt: ({ choice, attempt, result }) => recordSettledFailure(args.reporter, choice, attempt, result),
295
297
  onSubscription: onNextSubscription,
298
+ nextChoice: args.nextChoice,
296
299
  });
297
300
  args.reporter.attachServingDecision(result.choice.decision);
298
301
  if (result.kind === "customer_canceled") {
@@ -447,6 +450,9 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
447
450
  logUnclassifiedRefusal(execution, responseCapture);
448
451
  // The customer's own key was refused: theirs to fix, not a gateway fault.
449
452
  const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
453
+ // A plan whose token is refused cannot serve; the model's next candidate
454
+ // may. The plan is not held: a refused token is not a usage limit.
455
+ const planRefused = execution.providerKeySource === "subscription" && (status === 401 || status === 403);
450
456
  return {
451
457
  kind: "provider_failed",
452
458
  message: rejected
@@ -454,6 +460,7 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
454
460
  : message,
455
461
  latencyMs,
456
462
  retryable: !isPromptPolicyRejection(message),
463
+ ...(planRefused ? { failover: true } : {}),
457
464
  };
458
465
  }
459
466
  const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
@@ -473,7 +480,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
473
480
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
474
481
  });
475
482
  // Nothing reached the client yet, so the same request is retried on the
476
- // next plan with quota for this model, including model-specific limits.
483
+ // next plan of this kind with quota for this model, including
484
+ // model-specific limits; with none, on the model's next candidate.
477
485
  const nextSubscription = switched
478
486
  ? await nextSubscriptionFor(execution)
479
487
  : undefined;
@@ -482,7 +490,7 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
482
490
  message: failureWithSubscriptionUsageLimit(message, { ...limit, switched }),
483
491
  latencyMs,
484
492
  retryable: false,
485
- ...(nextSubscription === undefined ? {} : { nextSubscription }),
493
+ ...(nextSubscription === undefined ? { failover: true } : { nextSubscription }),
486
494
  };
487
495
  }
488
496
  // The provider call was in flight, so the prompt was paid for. A completion
@@ -597,6 +605,8 @@ function onNextSubscription(choice, next) {
597
605
  apiKey: next.apiKey,
598
606
  auth: { type: "bearer", apiKey: next.apiKey },
599
607
  subscriptionCredentialId: next.credentialId,
608
+ // A Copilot token names its own account's API origin.
609
+ ...(choice.execution.provider === "github-copilot" ? { endpoint: copilotEndpoint(next.apiKey) } : {}),
600
610
  },
601
611
  };
602
612
  }
@@ -0,0 +1,8 @@
1
+ import type { ProviderEndpoint } from "./pi.js";
2
+ export declare const COPILOT_HEADERS: Readonly<Record<string, string>>;
3
+ /**
4
+ * Where a Copilot token is served: its account's API origin, which the token
5
+ * names as `proxy-ep=proxy.<host>` (`api.<host>` serves the models), with the
6
+ * Copilot headers. A token that names none keeps the configured origin.
7
+ */
8
+ export declare function copilotEndpoint(token: string): ProviderEndpoint;
@@ -0,0 +1,21 @@
1
+ // Copilot serves only editors that name themselves; these are VS Code's
2
+ // Copilot Chat, whose sign-in Dari runs.
3
+ export const COPILOT_HEADERS = {
4
+ "User-Agent": "GitHubCopilotChat/0.35.0",
5
+ "Editor-Version": "vscode/1.107.0",
6
+ "Editor-Plugin-Version": "copilot-chat/0.35.0",
7
+ "Copilot-Integration-Id": "vscode-chat",
8
+ };
9
+ /**
10
+ * Where a Copilot token is served: its account's API origin, which the token
11
+ * names as `proxy-ep=proxy.<host>` (`api.<host>` serves the models), with the
12
+ * Copilot headers. A token that names none keeps the configured origin.
13
+ */
14
+ export function copilotEndpoint(token) {
15
+ const proxy = /(?:^|;)proxy-ep=([^;]+)/.exec(token)?.[1];
16
+ const host = proxy?.replace(/^proxy\./, "api.");
17
+ return {
18
+ ...(host && /^[a-z0-9.-]+$/i.test(host) ? { baseUrl: `https://${host}` } : {}),
19
+ headers: { ...COPILOT_HEADERS },
20
+ };
21
+ }
@@ -280,7 +280,10 @@ function resolveModelMetadata(pi, provider, modelId, nativeId) {
280
280
  // Claude deployments through the Anthropic registry, whose model metadata
281
281
  // (input modalities, adaptive-thinking compat, thinking level maps) is the
282
282
  // same on Foundry; the resolved config still owns api, base URL, and cost.
283
+ // A Vercel Token Pass key serves Vercel AI Gateway's own models.
283
284
  function registryProvider(provider, modelId) {
285
+ if (provider === "vercel-token-pass")
286
+ return "vercel-ai-gateway";
284
287
  if (provider !== "azure")
285
288
  return provider;
286
289
  return providerForModel(modelId) === "anthropic" ? "anthropic" : "azure-openai-responses";
@@ -5,6 +5,7 @@ export type ProviderAttemptFailure = {
5
5
  latencyMs: number;
6
6
  retryable: boolean;
7
7
  nextSubscription?: NextSubscription;
8
+ failover?: true;
8
9
  } | {
9
10
  kind: "customer_canceled";
10
11
  message: Record<string, unknown>;
@@ -47,6 +48,7 @@ type RunProviderAttemptPlanArgs<TChoice, TValue, TInitial> = {
47
48
  result: ProviderAttemptFailure;
48
49
  }) => void;
49
50
  onSubscription?: (choice: TChoice, next: NextSubscription) => TChoice;
51
+ nextChoice?: (choice: TChoice) => Promise<TChoice | undefined>;
50
52
  };
51
53
  /**
52
54
  * Owns the order-sensitive provider plan shared by completion and stream setup:
@@ -66,6 +66,15 @@ async function runChoice(args, firstChoice, initial) {
66
66
  maxAttempts += 1;
67
67
  continue;
68
68
  }
69
+ if (result.kind === "provider_failed" && result.failover === true && args.nextChoice) {
70
+ const next = await args.nextChoice(choice);
71
+ if (next !== undefined) {
72
+ // The next candidate gets the router's full retry budget.
73
+ choice = next;
74
+ maxAttempts = attempt + args.retries + 1;
75
+ continue;
76
+ }
77
+ }
69
78
  if (!result.retryable)
70
79
  break;
71
80
  }
@@ -7,6 +7,7 @@ import { providerAuthForSelectedModel } from "../strategies/routing.js";
7
7
  import { scrubSecretValues } from "../telemetry/scrub.js";
8
8
  import { usageContextFor, } from "../telemetry/usage.js";
9
9
  import { awsRoleCredentials } from "./aws_assume_role.js";
10
+ import { copilotEndpoint } from "./github_copilot.js";
10
11
  import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
11
12
  import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
12
13
  import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
@@ -50,7 +51,10 @@ export function prepareProviderExecution(args) {
50
51
  ...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
51
52
  ...(supplied?.baseUrl || supplied?.headers
52
53
  ? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
53
- : {}),
54
+ // A Copilot token names its account's own API origin.
55
+ : provider === "github-copilot" && auth.type === "bearer"
56
+ ? { endpoint: copilotEndpoint(auth.apiKey) }
57
+ : {}),
54
58
  provider,
55
59
  providerKeySource,
56
60
  // Only resolved personal subscriptions are held at their usage limit;
@@ -58,7 +62,7 @@ export function prepareProviderExecution(args) {
58
62
  ...(providerKeySource === "subscription" && (!supplied || supplied.credentialId !== undefined) && args.credentials.attributed_user_id
59
63
  ? {
60
64
  subscriptionUserId: args.credentials.attributed_user_id,
61
- subscriptionCredentialId: supplied?.credentialId ?? args.credentials.subscription_credential_ids?.[provider],
65
+ subscriptionCredentialId: supplied?.credentialId,
62
66
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
63
67
  }
64
68
  : {}),
@@ -1,6 +1,6 @@
1
- import type { ProviderKeySource } from "../types.js";
1
+ import type { ProviderKeySource, SubscriptionKind } from "../types.js";
2
2
  import type { CapturedProviderResponse } from "./response_capture.js";
3
- export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
3
+ export type SubscriptionOAuthProvider = SubscriptionKind;
4
4
  export type SubscriptionUsageLimit = {
5
5
  oauthProvider: SubscriptionOAuthProvider;
6
6
  resetsAt: Date;
@@ -60,9 +60,10 @@ export declare function subscriptionOAuthProviderFor(provider: string, keySource
60
60
  /**
61
61
  * Recognize a personal subscription that has run out of quota. Claude Code
62
62
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
63
- * 429 with a structured `error.code` and `resets_at`. Meta documents no
64
- * usage-limit signature for Muse Code plans, so any 429 on one holds it until
65
- * the reset Meta gives, if any. OpenCode Go names its refusal
63
+ * 429 with a structured `error.code` and `resets_at`. Meta, GitHub Copilot,
64
+ * xAI, Kimi, and Vercel Token Pass document no usage-limit signature for their
65
+ * plans, so any 429 on one holds it until the reset it gives, if any. OpenCode
66
+ * Go names its refusal
66
67
  * `GoUsageLimitError`. The Codex WebSocket
67
68
  * transport bypasses fetch, so its usage-limit error only survives as message
68
69
  * text and is matched there without a reset time.
@@ -105,6 +105,9 @@ const SUBSCRIPTION_LABEL = {
105
105
  openai_codex: "ChatGPT",
106
106
  meta_muse: "Muse Code",
107
107
  opencode_go: "OpenCode Go",
108
+ github_copilot: "GitHub Copilot",
109
+ xai_grok: "Grok",
110
+ vercel_token_pass: "Vercel Token Pass",
108
111
  };
109
112
  // Providers whose plan page the accounts page links to for buying another.
110
113
  const BUYABLE_SUBSCRIPTIONS = new Set(["anthropic_claude_code", "openai_codex"]);
@@ -119,14 +122,21 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
119
122
  return "meta_muse";
120
123
  if (provider === "opencode-go")
121
124
  return "opencode_go";
125
+ if (provider === "github-copilot")
126
+ return "github_copilot";
127
+ if (provider === "xai")
128
+ return "xai_grok";
129
+ if (provider === "vercel-token-pass")
130
+ return "vercel_token_pass";
122
131
  return null;
123
132
  }
124
133
  /**
125
134
  * Recognize a personal subscription that has run out of quota. Claude Code
126
135
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
127
- * 429 with a structured `error.code` and `resets_at`. Meta documents no
128
- * usage-limit signature for Muse Code plans, so any 429 on one holds it until
129
- * the reset Meta gives, if any. OpenCode Go names its refusal
136
+ * 429 with a structured `error.code` and `resets_at`. Meta, GitHub Copilot,
137
+ * xAI, Kimi, and Vercel Token Pass document no usage-limit signature for their
138
+ * plans, so any 429 on one holds it until the reset it gives, if any. OpenCode
139
+ * Go names its refusal
130
140
  * `GoUsageLimitError`. The Codex WebSocket
131
141
  * transport bypasses fetch, so its usage-limit error only survives as message
132
142
  * text and is matched there without a reset time.
@@ -139,11 +149,12 @@ export function detectSubscriptionUsageLimit(args) {
139
149
  if (oauthProvider === "anthropic_claude_code") {
140
150
  return anthropicUsageLimit(args.captured, args.model, now);
141
151
  }
142
- if (oauthProvider === "meta_muse")
143
- return museUsageLimit(args.captured, now);
144
152
  if (oauthProvider === "opencode_go")
145
153
  return openCodeGoUsageLimit(args.captured, now);
146
- return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
154
+ if (oauthProvider === "openai_codex") {
155
+ return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
156
+ }
157
+ return planRateLimit(oauthProvider, args.captured, now);
147
158
  }
148
159
  // Claude Code plans also cap some model families on their own
149
160
  // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
@@ -215,13 +226,13 @@ function codexModelLimitExhausted(headers) {
215
226
  });
216
227
  return other && !plan;
217
228
  }
218
- function museUsageLimit(captured, now) {
229
+ function planRateLimit(oauthProvider, captured, now) {
219
230
  if (captured === undefined || captured.status !== 429)
220
231
  return null;
221
232
  return {
222
- oauthProvider: "meta_muse",
233
+ oauthProvider,
223
234
  resetsAt: laterReset(codexErrorBody(captured.bodyText)?.resets_at, captured.headers, now),
224
- reason: "Muse Code usage limit reached.",
235
+ reason: `${SUBSCRIPTION_LABEL[oauthProvider]} usage limit reached.`,
225
236
  };
226
237
  }
227
238
  // OpenCode Go refuses an exhausted plan with 429 and a `GoUsageLimitError`
@@ -4,7 +4,9 @@ import { buildRoutingContext } from "../context/routing_context.js";
4
4
  import { completeNonStreaming, executeNonStreaming, executeStreaming, prepareStreamingExecution, } from "../providers/execution.js";
5
5
  import { prepareProviderExecution, startProviderCompletion, startProviderStream, } from "../providers/provider_call.js";
6
6
  import { routeDecision } from "../strategies/route_decision.js";
7
- import { executionProviderForModel } from "../models/execution_provider.js";
7
+ import { credentialsServedBy, executionProviderForModel } from "../models/execution_provider.js";
8
+ import { gatewayPlatform } from "../platform/platform.js";
9
+ import { captureOperationalError } from "../observability/errors.js";
8
10
  import { trackBackgroundTelemetry } from "../telemetry/background.js";
9
11
  import { estimateBenchmarkReplay } from "../telemetry/benchmark_replay.js";
10
12
  import { buildCompletedPrefixHit } from "../telemetry/prefix_state.js";
@@ -39,6 +41,7 @@ export async function runPreparedRoutedCompletion(args) {
39
41
  interaction: prepared.interaction,
40
42
  primary: plan.primary,
41
43
  primaryRetries: plan.primaryRetries,
44
+ nextChoice: plan.nextChoice,
42
45
  reporter: prepared.reporter,
43
46
  protocol: prepared.protocol,
44
47
  startedCompletion: plan.startedCompletion,
@@ -51,6 +54,7 @@ export async function runPreparedRoutedCompletion(args) {
51
54
  interaction: prepared.interaction,
52
55
  primary: plan.primary,
53
56
  primaryRetries: plan.primaryRetries,
57
+ nextChoice: plan.nextChoice,
54
58
  reporter: prepared.reporter,
55
59
  startedStream: plan.startedStream,
56
60
  initialError: plan.initialStreamError,
@@ -83,6 +87,7 @@ export async function runPreparedRoutedInteraction(args) {
83
87
  interaction: args.prepared.interaction,
84
88
  primary: plan.primary,
85
89
  primaryRetries: plan.primaryRetries,
90
+ nextChoice: plan.nextChoice,
86
91
  reporter: args.prepared.reporter,
87
92
  protocol: args.prepared.protocol,
88
93
  startedCompletion: plan.startedCompletion,
@@ -259,6 +264,7 @@ async function prepareRuntimeExecution(args) {
259
264
  return {
260
265
  primary,
261
266
  primaryRetries: configuredPrimaryRetries(prepared.credentials.primary_retries),
267
+ nextChoice: (choice) => nextProviderChoice(prepared, choice),
262
268
  reportBarrier: selectionPromise,
263
269
  startedCompletion: speculative.transport === "completion" ? speculative.started : undefined,
264
270
  startedStream: speculative.transport === "stream" ? speculative.started : undefined,
@@ -271,6 +277,7 @@ function selectedExecutionPlan(prepared, selected) {
271
277
  return {
272
278
  primary: providerChoice(prepared, selected.decision),
273
279
  primaryRetries: configuredPrimaryRetries(prepared.credentials.primary_retries),
280
+ nextChoice: (choice) => nextProviderChoice(prepared, choice),
274
281
  };
275
282
  }
276
283
  async function startSpeculativeExecution(prepared, selectorBackend, clientSignal) {
@@ -431,10 +438,67 @@ function providerChoice(prepared, decision) {
431
438
  execution: providerExecution(prepared, decision),
432
439
  };
433
440
  }
434
- function providerExecution(prepared, decision) {
441
+ /**
442
+ * The same decision served by the model's next fallback after `choice`: a plan
443
+ * the platform still has a token for, or the router's API credential while
444
+ * the organization has credits. A fallback that cannot be prepared is
445
+ * skipped. Undefined when none is left.
446
+ */
447
+ async function nextProviderChoice(prepared, choice) {
448
+ const { credentials } = prepared;
449
+ const model = choice.decision.selectedModel;
450
+ const fallbacks = credentials.model_fallbacks?.[model] ?? [];
451
+ for (let index = (choice.fallback ?? -1) + 1; index < fallbacks.length; index += 1) {
452
+ const fallback = fallbacks[index];
453
+ if (!fallback.subscription && credentials.credit_exhausted === true)
454
+ continue;
455
+ const plan = fallback.subscription
456
+ ? await fallbackPlan(credentials, fallback, model, prepared.routing.conversationId)
457
+ : undefined;
458
+ if (fallback.subscription && plan === undefined)
459
+ continue;
460
+ try {
461
+ return {
462
+ decision: choice.decision,
463
+ fallback: index,
464
+ execution: providerExecution(prepared, choice.decision, credentialsServedBy(credentials, model, fallback.config, plan)),
465
+ };
466
+ }
467
+ catch (error) {
468
+ console.error("model fallback setup failed", scrubSecrets(error instanceof Error ? error.message : String(error)));
469
+ }
470
+ }
471
+ return undefined;
472
+ }
473
+ // The user's plan of the fallback's kind that serves this model now, if any.
474
+ async function fallbackPlan(credentials, fallback, model, conversationId) {
475
+ const platform = gatewayPlatform();
476
+ const userId = credentials.attributed_user_id;
477
+ // A strict router serves only plans the platform supplied up front.
478
+ if (platform.nextSubscription === undefined || !userId || credentials.strict === true)
479
+ return undefined;
480
+ try {
481
+ const next = await platform.nextSubscription({
482
+ userId,
483
+ provider: fallback.config.provider,
484
+ model,
485
+ conversationId,
486
+ ...(credentials.link_grant_id ? { linkGrantId: credentials.link_grant_id } : {}),
487
+ });
488
+ return next === undefined
489
+ ? undefined
490
+ : { apiKey: next.apiKey, subscription: fallback.subscription, credentialId: next.credentialId };
491
+ }
492
+ catch (error) {
493
+ console.error("fallback subscription lookup failed", error);
494
+ captureOperationalError(error, { code: "next_subscription_lookup_failed" });
495
+ return undefined;
496
+ }
497
+ }
498
+ function providerExecution(prepared, decision, credentials = prepared.credentials) {
435
499
  return prepareProviderExecution({
436
500
  decision,
437
- credentials: prepared.credentials,
501
+ credentials,
438
502
  billable: prepared.billable,
439
503
  routerId: prepared.routerId,
440
504
  pricing: prepared.routing.pricing,
@@ -492,6 +556,7 @@ function runtimeResult(result, prepared) {
492
556
  target,
493
557
  conversationId: prepared.routing.conversationId,
494
558
  leaseDepth: prepared.routing.leaseDepth,
559
+ provider: result.choice.execution.provider,
495
560
  providerBlockDepth: prepared.routing.providerBlockDepthFor(decision.selectedModel),
496
561
  fingerprints: prepared.routing.prefix.fingerprints,
497
562
  usage,
@@ -26,11 +26,12 @@ export type SelfHostedResolverDeps = {
26
26
  fetch: OAuthFetch;
27
27
  };
28
28
  /**
29
- * Resolve a configured router for one request. Each provider is served by a
30
- * connected personal subscription when the router allows it and one is
31
- * available, otherwise by the provider's API key; models whose provider has
32
- * neither are left out. A coding agent with its own model list on the router
33
- * is served that list.
29
+ * Resolve a configured router for one request. Each model is served by the
30
+ * connected personal subscriptions that serve it, when the router allows them,
31
+ * in plan order (see models/subscriptions.ts), then by its provider's API key:
32
+ * the first available serves and the rest fail over within the request.
33
+ * Models nothing can serve are left out. A coding agent with its own model
34
+ * list on the router is served that list.
34
35
  *
35
36
  * A Dari Link token is served apart from any router, on its grant's plans and
36
37
  * API keys alone: `dari/routing` chooses among every catalog model they
@@ -41,9 +42,10 @@ export declare function resolveSelfHostedRouter(deps: SelfHostedResolverDeps, re
41
42
  export declare function configuredProviderApiKey(deps: Pick<SelfHostedResolverDeps, "config" | "providerApiKey" | "env">, provider: string): Promise<string | undefined>;
42
43
  export declare function gatewayKeyIndex(keys: readonly string[], presented: string): number | null;
43
44
  /**
44
- * Providers a router lists that no credential can serve: no API key and no
45
- * connected subscription the router allows. Startup uses this, so it counts a
46
- * held subscription as connected (the request-time 424 reports holds) and
47
- * checks both harnesses, since startup does not know the client.
45
+ * Providers a router lists models of that no credential can serve: no API key
46
+ * and no connected subscription the router allows that serves them. Startup
47
+ * uses this, so it counts a held subscription as connected (the request-time
48
+ * 424 reports holds) and ignores which client a plan is limited to, since
49
+ * startup does not know the client.
48
50
  */
49
51
  export declare function providersWithoutCredentials(deps: Pick<SelfHostedResolverDeps, "subscriptions" | "providerApiKey" | "config" | "env">, router: RouterConfig): Promise<string[]>;