@mupt-ai/dari-gateway 1.0.339 → 1.0.341

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 (69) 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/budget.d.ts +18 -7
  5. package/dist/link/budget.js +58 -16
  6. package/dist/link/endpoints.js +64 -45
  7. package/dist/link/errors.js +4 -1
  8. package/dist/link/self_hosted.d.ts +3 -1
  9. package/dist/link/self_hosted.js +25 -9
  10. package/dist/link/service.d.ts +4 -4
  11. package/dist/link/service.js +41 -22
  12. package/dist/models/catalog.js +1 -0
  13. package/dist/models/execution_provider.d.ts +6 -1
  14. package/dist/models/execution_provider.js +12 -0
  15. package/dist/models/provider_defaults.js +9 -0
  16. package/dist/models/provider_models.json +217 -0
  17. package/dist/models/subscriptions.d.ts +5 -0
  18. package/dist/models/subscriptions.js +21 -2
  19. package/dist/platform/platform.d.ts +11 -7
  20. package/dist/providers/execution.d.ts +5 -0
  21. package/dist/providers/execution.js +12 -2
  22. package/dist/providers/github_copilot.d.ts +8 -0
  23. package/dist/providers/github_copilot.js +21 -0
  24. package/dist/providers/pi.js +3 -0
  25. package/dist/providers/provider_attempt_runner.d.ts +2 -0
  26. package/dist/providers/provider_attempt_runner.js +9 -0
  27. package/dist/providers/provider_call.js +6 -2
  28. package/dist/providers/subscription_limits.d.ts +6 -5
  29. package/dist/providers/subscription_limits.js +20 -9
  30. package/dist/runtime/routed_runtime.js +68 -3
  31. package/dist/self_host/resolve.d.ts +11 -9
  32. package/dist/self_host/resolve.js +249 -182
  33. package/dist/self_host/subscriptions/index.d.ts +6 -5
  34. package/dist/self_host/subscriptions/index.js +6 -5
  35. package/dist/self_host/subscriptions/oauth.d.ts +7 -3
  36. package/dist/self_host/subscriptions/oauth.js +195 -5
  37. package/dist/self_host/subscriptions/store.js +3 -0
  38. package/dist/telemetry/prefix_state.d.ts +1 -0
  39. package/dist/telemetry/prefix_state.js +1 -1
  40. package/dist/telemetry/report.js +2 -3
  41. package/dist/types.d.ts +6 -2
  42. package/package.json +2 -2
  43. package/src/index.ts +1 -1
  44. package/src/link/assets.ts +7 -0
  45. package/src/link/budget.ts +53 -18
  46. package/src/link/endpoints.ts +66 -45
  47. package/src/link/errors.ts +4 -1
  48. package/src/link/self_hosted.ts +26 -8
  49. package/src/link/service.ts +45 -23
  50. package/src/models/catalog.ts +1 -0
  51. package/src/models/execution_provider.ts +24 -1
  52. package/src/models/provider_defaults.ts +9 -0
  53. package/src/models/provider_models.json +217 -0
  54. package/src/models/subscriptions.ts +22 -2
  55. package/src/platform/platform.ts +13 -8
  56. package/src/providers/execution.ts +22 -2
  57. package/src/providers/github_copilot.ts +24 -0
  58. package/src/providers/pi.ts +2 -0
  59. package/src/providers/provider_attempt_runner.ts +15 -0
  60. package/src/providers/provider_call.ts +6 -2
  61. package/src/providers/subscription_limits.ts +20 -10
  62. package/src/runtime/routed_runtime.ts +79 -3
  63. package/src/self_host/resolve.ts +255 -187
  64. package/src/self_host/subscriptions/index.ts +7 -4
  65. package/src/self_host/subscriptions/oauth.ts +264 -8
  66. package/src/self_host/subscriptions/store.ts +3 -0
  67. package/src/telemetry/prefix_state.ts +4 -1
  68. package/src/telemetry/report.ts +2 -3
  69. package/src/types.ts +27 -3
@@ -1,22 +1,36 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
 
3
+ import { COPILOT_HEADERS } from "../../providers/github_copilot.js";
4
+
3
5
  /**
4
6
  * OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
5
7
  * pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
6
8
  * the gateway polls for approval), Muse Code (Meta's device code, then the
7
- * subscription's Model API key minted from the sign-in token), and OpenCode Go
9
+ * subscription's Model API key minted from the sign-in token), OpenCode Go
8
10
  * (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
9
- * the workspace that holds the plan).
11
+ * the workspace that holds the plan), GitHub Copilot, and Grok
12
+ * (each vendor's device sign-in, as its own coding agent runs it), and Vercel
13
+ * Token Pass (no protocol: the plan is a Token Pass key the user pastes).
10
14
  * Every network call goes through the injected `fetch`.
11
15
  */
12
16
 
13
- export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
17
+ export type SubscriptionProvider =
18
+ | "anthropic_claude_code"
19
+ | "openai_codex"
20
+ | "meta_muse"
21
+ | "opencode_go"
22
+ | "github_copilot"
23
+ | "xai_grok"
24
+ | "vercel_token_pass";
14
25
 
15
26
  export const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[] = [
16
27
  "anthropic_claude_code",
17
28
  "openai_codex",
18
29
  "meta_muse",
19
30
  "opencode_go",
31
+ "github_copilot",
32
+ "xai_grok",
33
+ "vercel_token_pass",
20
34
  ];
21
35
 
22
36
  const OPENCODE_CONSOLE_URL = "https://opencode.ai/console";
@@ -108,11 +122,97 @@ const MUSE_SIGN_IN_REFRESH_PREFIX = "refresh:";
108
122
  export const META_APPROVAL_PENDING =
109
123
  "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
110
124
 
125
+ // Device sign-ins the gateway polls in one shape: start at `deviceCodeUrl`,
126
+ // then ask `tokenUrl` whether the user approved.
127
+ type DeviceSignIn = {
128
+ // Whose sign-in it is, as messages name it.
129
+ vendor: string;
130
+ clientId: string;
131
+ deviceCodeUrl: string;
132
+ tokenUrl: string;
133
+ scope?: string;
134
+ headers?: Record<string, string>;
135
+ };
136
+
137
+ // GitHub Copilot's sign-in, as VS Code's Copilot Chat runs it, for github.com
138
+ // accounts. The GitHub token it grants is the refresh token: it mints the
139
+ // short-lived Copilot token that serves requests.
140
+ const GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
141
+ const COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token";
142
+ const GITHUB_USER_URL = "https://api.github.com/user";
143
+ // Copilot tokens live about half an hour; mint the next one before then.
144
+ const COPILOT_TOKEN_SKEW_MS = 5 * 60_000;
145
+
146
+ // SuperGrok and X Premium sign in as xAI's Grok CLI does.
147
+ const XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
148
+
149
+ const DEVICE_SIGN_INS = {
150
+ github_copilot: {
151
+ vendor: "GitHub",
152
+ clientId: GITHUB_COPILOT_CLIENT_ID,
153
+ deviceCodeUrl: "https://github.com/login/device/code",
154
+ tokenUrl: "https://github.com/login/oauth/access_token",
155
+ scope: "read:user",
156
+ headers: { "User-Agent": COPILOT_HEADERS["User-Agent"]! },
157
+ },
158
+ xai_grok: {
159
+ vendor: "xAI",
160
+ clientId: XAI_CLIENT_ID,
161
+ deviceCodeUrl: "https://auth.x.ai/oauth2/device/code",
162
+ tokenUrl: "https://auth.x.ai/oauth2/token",
163
+ scope: "openid profile email offline_access grok-cli:access api:access",
164
+ },
165
+ } as const satisfies Record<string, DeviceSignIn>;
166
+
167
+ type DeviceProvider = keyof typeof DEVICE_SIGN_INS;
168
+
169
+ function isDeviceProvider(provider: SubscriptionProvider): provider is DeviceProvider {
170
+ return provider in DEVICE_SIGN_INS;
171
+ }
172
+
173
+ export const GITHUB_APPROVAL_PENDING = approvalPending("GitHub");
174
+ export const XAI_APPROVAL_PENDING = approvalPending("xAI");
175
+
176
+ function approvalPending(vendor: string): string {
177
+ return `${vendor} approval is still pending. Enter the code at ${vendor}, finish approval, then try again.`;
178
+ }
179
+
180
+ // Device-flow access tokens that state no lifetime last an hour.
181
+ const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
182
+
183
+ // A Token Pass is an AI Gateway key restricted to Token Pass, created on
184
+ // Vercel's Token Pass page (or with `vercel token-pass`) and pasted back.
185
+ const VERCEL_TOKEN_PASS_URL = "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Ftoken-pass";
186
+ // A Token Pass key carries no expiry; this only keeps refresh idle.
187
+ const VERCEL_KEY_LIFETIME_MS = 3650 * 24 * 60 * 60_000;
188
+
111
189
  export async function startOAuth(
112
190
  provider: SubscriptionProvider,
113
191
  options: OAuthOptions,
114
192
  ): Promise<OAuthAuthorization> {
115
193
  const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
194
+ if (provider === "vercel_token_pass") {
195
+ return { authorizationUrl: VERCEL_TOKEN_PASS_URL, expiresAt, userCode: null, flow: {} };
196
+ }
197
+ if (isDeviceProvider(provider)) {
198
+ const signIn: DeviceSignIn = DEVICE_SIGN_INS[provider];
199
+ const device = await postForm(
200
+ options.fetch,
201
+ signIn.deviceCodeUrl,
202
+ { client_id: signIn.clientId, ...(signIn.scope === undefined ? {} : { scope: signIn.scope }) },
203
+ `${signIn.vendor} device code request`,
204
+ signIn.headers,
205
+ );
206
+ const complete = device.verification_uri_complete;
207
+ return {
208
+ authorizationUrl: typeof complete === "string" && complete.startsWith("https://")
209
+ ? complete
210
+ : requiredString(device, "verification_uri"),
211
+ expiresAt,
212
+ userCode: requiredString(device, "user_code"),
213
+ flow: { device_code: requiredString(device, "device_code") },
214
+ };
215
+ }
116
216
  if (provider === "opencode_go") {
117
217
  const device = await postJson(
118
218
  options.fetch,
@@ -193,6 +293,24 @@ export async function completeOAuth(
193
293
  options: OAuthOptions,
194
294
  ): Promise<OAuthTokens> {
195
295
  const now = options.now ?? new Date();
296
+ if (provider === "vercel_token_pass") return vercelTokenPassTokens(authorizationResponse, now);
297
+ if (isDeviceProvider(provider)) {
298
+ const token = await deviceApproval(provider, requiredString(flow, "device_code"), options.fetch);
299
+ if (provider === "github_copilot") {
300
+ const githubToken = requiredString(token, "access_token");
301
+ const tokens = await copilotTokens(githubToken, options.fetch, now).catch((error: unknown) => {
302
+ // GitHub mints no Copilot token for an account without a plan.
303
+ if (error instanceof SubscriptionOAuthProviderError && [401, 403, 404].includes(error.status ?? 0)) {
304
+ throw new SubscriptionOAuthInputError(
305
+ "This GitHub account has no active Copilot plan. Subscribe at https://github.com/features/copilot/plans, then connect again.",
306
+ );
307
+ }
308
+ throw error;
309
+ });
310
+ return { ...tokens, accountEmail: await githubAccount(options.fetch, githubToken) };
311
+ }
312
+ return deviceTokens(provider, token, now, null);
313
+ }
196
314
  if (provider === "opencode_go") {
197
315
  let token: Record<string, unknown>;
198
316
  try {
@@ -315,6 +433,19 @@ export async function refreshOAuth(
315
433
  options: OAuthOptions,
316
434
  ): Promise<OAuthTokens> {
317
435
  const now = options.now ?? new Date();
436
+ if (credential.provider === "vercel_token_pass") return vercelTokenPassTokens(credential.refreshToken, now);
437
+ if (credential.provider === "github_copilot") return await copilotTokens(credential.refreshToken, options.fetch, now);
438
+ if (isDeviceProvider(credential.provider)) {
439
+ const signIn: DeviceSignIn = DEVICE_SIGN_INS[credential.provider];
440
+ const token = await postForm(
441
+ options.fetch,
442
+ signIn.tokenUrl,
443
+ { grant_type: "refresh_token", client_id: signIn.clientId, refresh_token: credential.refreshToken },
444
+ `${signIn.vendor} sign-in refresh`,
445
+ signIn.headers,
446
+ );
447
+ return deviceTokens(credential.provider, token, now, credential.refreshToken);
448
+ }
318
449
  if (credential.provider === "opencode_go") {
319
450
  const token = await postJson(
320
451
  options.fetch,
@@ -533,14 +664,16 @@ function postForm(
533
664
  url: string,
534
665
  payload: Record<string, string>,
535
666
  operation: string,
667
+ headers: Record<string, string> = {},
536
668
  ): Promise<Record<string, unknown>> {
537
- return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation);
669
+ return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation, headers);
538
670
  }
539
671
 
672
+ // A null body is a GET.
540
673
  async function requestJson(
541
674
  fetch: OAuthFetch,
542
675
  url: string,
543
- body: string,
676
+ body: string | null,
544
677
  contentType: string,
545
678
  operation: string,
546
679
  headers: Record<string, string> = {},
@@ -548,9 +681,14 @@ async function requestJson(
548
681
  let response: Response;
549
682
  try {
550
683
  response = await fetch(url, {
551
- method: "POST",
552
- headers: { Accept: "application/json", "Content-Type": contentType, "User-Agent": "Dari/1.0", ...headers },
553
- body,
684
+ method: body === null ? "GET" : "POST",
685
+ headers: {
686
+ Accept: "application/json",
687
+ ...(body === null ? {} : { "Content-Type": contentType }),
688
+ "User-Agent": "Dari/1.0",
689
+ ...headers,
690
+ },
691
+ ...(body === null ? {} : { body }),
554
692
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
555
693
  });
556
694
  } catch {
@@ -623,3 +761,121 @@ async function opencodeEmail(fetch: OAuthFetch, accessToken: string): Promise<st
623
761
  return null;
624
762
  }
625
763
  }
764
+
765
+ // Ask a device sign-in whether the user approved its code. GitHub answers an
766
+ // unfinished sign-in with HTTP 200 and an `error`; the others with HTTP 400.
767
+ async function deviceApproval(
768
+ provider: DeviceProvider,
769
+ deviceCode: string,
770
+ fetch: OAuthFetch,
771
+ ): Promise<Record<string, unknown>> {
772
+ const signIn: DeviceSignIn = DEVICE_SIGN_INS[provider];
773
+ let token: Record<string, unknown>;
774
+ let errorCode: string | undefined;
775
+ try {
776
+ token = await postForm(
777
+ fetch,
778
+ signIn.tokenUrl,
779
+ {
780
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
781
+ device_code: deviceCode,
782
+ client_id: signIn.clientId,
783
+ },
784
+ `${signIn.vendor} device approval check`,
785
+ signIn.headers,
786
+ );
787
+ errorCode = typeof token.error === "string" ? token.error : undefined;
788
+ } catch (error) {
789
+ if (!(error instanceof SubscriptionOAuthProviderError) || error.errorCode === undefined) throw error;
790
+ token = {};
791
+ errorCode = error.errorCode;
792
+ }
793
+ if (errorCode === undefined) return token;
794
+ if (errorCode === "authorization_pending" || errorCode === "slow_down") {
795
+ throw new SubscriptionOAuthInputError(approvalPending(signIn.vendor));
796
+ }
797
+ if (errorCode === "access_denied" || errorCode === "authorization_denied") {
798
+ throw new SubscriptionOAuthInputError(`The sign-in was declined on ${signIn.vendor}. Start again to retry.`);
799
+ }
800
+ if (errorCode === "expired_token") {
801
+ throw new SubscriptionOAuthInputError(`The ${signIn.vendor} sign-in code expired. Start again.`);
802
+ }
803
+ throw new SubscriptionOAuthProviderError(`${signIn.vendor} device approval check failed.`, undefined, errorCode);
804
+ }
805
+
806
+ // Grok tokens. A refresh that rotates no refresh token keeps the
807
+ // stored one; Grok's ID token names the account.
808
+ function deviceTokens(
809
+ provider: "xai_grok",
810
+ payload: Record<string, unknown>,
811
+ now: Date,
812
+ fallbackRefreshToken: string | null,
813
+ ): OAuthTokens {
814
+ const idToken = typeof payload.id_token === "string" ? payload.id_token : null;
815
+ const email = idToken === null ? undefined : jwtPayload(idToken)?.email;
816
+ const lifetime = payload.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveInt(payload.expires_in);
817
+ return {
818
+ provider,
819
+ accessToken: requiredString(payload, "access_token"),
820
+ refreshToken: refreshTokenFrom(payload, fallbackRefreshToken),
821
+ expiresAt: new Date(now.getTime() + lifetime * 1000),
822
+ accountId: null,
823
+ accountEmail: typeof email === "string" && email ? email : null,
824
+ };
825
+ }
826
+
827
+ // Mints the Copilot token that serves requests from the GitHub token.
828
+ async function copilotTokens(githubToken: string, fetch: OAuthFetch, now: Date): Promise<OAuthTokens> {
829
+ const minted = await requestJson(
830
+ fetch,
831
+ COPILOT_TOKEN_URL,
832
+ null,
833
+ "",
834
+ "GitHub Copilot token request",
835
+ { ...COPILOT_HEADERS, Authorization: `Bearer ${githubToken}` },
836
+ );
837
+ const expiresAt = minted.expires_at;
838
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) {
839
+ throw new SubscriptionOAuthProviderError(INCOMPLETE);
840
+ }
841
+ return {
842
+ provider: "github_copilot",
843
+ accessToken: requiredString(minted, "token"),
844
+ refreshToken: githubToken,
845
+ expiresAt: new Date(Math.max(now.getTime(), expiresAt * 1000 - COPILOT_TOKEN_SKEW_MS)),
846
+ accountId: null,
847
+ accountEmail: null,
848
+ };
849
+ }
850
+
851
+ // The signed-in GitHub account's email, else its login; best effort.
852
+ async function githubAccount(fetch: OAuthFetch, githubToken: string): Promise<string | null> {
853
+ try {
854
+ const user = await requestJson(fetch, GITHUB_USER_URL, null, "", "GitHub account lookup", {
855
+ Authorization: `Bearer ${githubToken}`,
856
+ });
857
+ for (const field of ["email", "login"]) {
858
+ const value = user[field];
859
+ if (typeof value === "string" && value) return value;
860
+ }
861
+ return null;
862
+ } catch {
863
+ return null;
864
+ }
865
+ }
866
+
867
+ // The pasted key is both tokens; refreshing hands the same key back.
868
+ function vercelTokenPassTokens(key: string, now: Date): OAuthTokens {
869
+ const apiKey = key.trim();
870
+ if (!apiKey || /\s/.test(apiKey)) {
871
+ throw new SubscriptionOAuthInputError("Paste the Token Pass key you created at Vercel.");
872
+ }
873
+ return {
874
+ provider: "vercel_token_pass",
875
+ accessToken: apiKey,
876
+ refreshToken: apiKey,
877
+ expiresAt: new Date(now.getTime() + VERCEL_KEY_LIFETIME_MS),
878
+ accountId: null,
879
+ accountEmail: null,
880
+ };
881
+ }
@@ -87,6 +87,9 @@ const BASE_NAMES: Record<SubscriptionProvider, string> = {
87
87
  openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
88
88
  meta_muse: "META_MUSE_OAUTH_TOKEN",
89
89
  opencode_go: "OPENCODE_GO_OAUTH_TOKEN",
90
+ github_copilot: "GITHUB_COPILOT_OAUTH_TOKEN",
91
+ xai_grok: "XAI_GROK_OAUTH_TOKEN",
92
+ vercel_token_pass: "VERCEL_TOKEN_PASS_API_KEY",
90
93
  };
91
94
 
92
95
  type CredentialRow = {
@@ -33,6 +33,9 @@ export function buildCompletedPrefixHit(args: {
33
33
  chain: string[];
34
34
  looseChain: readonly string[];
35
35
  target: ProviderIdentity;
36
+ // The provider that served the turn, whose cache now holds its prefix; a
37
+ // fallback may serve a model on another provider than its target's.
38
+ provider: string;
36
39
  conversationId: string;
37
40
  leaseDepth: number;
38
41
  providerBlockDepth: number;
@@ -57,7 +60,7 @@ export function buildCompletedPrefixHit(args: {
57
60
  loose_hash: looseOutputHash(args.looseChain, args.output, args.request.sourceProtocol),
58
61
  conversation_id: args.conversationId,
59
62
  model: args.model,
60
- provider: args.target.provider,
63
+ provider: args.provider,
61
64
  next_model: args.nextModel,
62
65
  next_reasoning_effort: args.nextReasoningEffort,
63
66
  message_depth: args.chain.length + outputExtension.length,
@@ -468,6 +468,7 @@ export class RequestReporter {
468
468
  chain: selectedChain,
469
469
  looseChain: a.looseChain,
470
470
  target: selectedTarget,
471
+ provider: selectedProvider ?? selectedTarget.provider,
471
472
  conversationId: a.conversationId,
472
473
  leaseDepth: a.leaseDepth,
473
474
  providerBlockDepth:
@@ -518,9 +519,7 @@ export class RequestReporter {
518
519
  thinking: outcome.providerExecution?.thinkingLevel ?? reasoningBucket,
519
520
  costUsd: costSource === null || !isRecord(usage?.cost) ? null : finiteNumber(usage.cost.total),
520
521
  credentialId: keySource === "subscription"
521
- ? outcome.providerExecution?.subscriptionCredentialId ?? (selectedProvider
522
- ? a.credentials.subscription_credential_ids?.[selectedProvider] ?? null
523
- : null)
522
+ ? outcome.providerExecution?.subscriptionCredentialId ?? null
524
523
  : selectedProvider ? a.credentials.link_key_credential_ids?.[selectedProvider] ?? null : null,
525
524
  }
526
525
  : undefined;
package/src/types.ts CHANGED
@@ -52,7 +52,19 @@ export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
52
52
  // - "meta_muse": a Meta (Muse) sign-in; the token is the Model API key the
53
53
  // sign-in mints (Pi's Meta OAuth `access`).
54
54
  // - "opencode_go": an OpenCode Go plan; the token is the plan's API key.
55
- export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go";
55
+ // - "github_copilot": a GitHub Copilot plan; the token is the short-lived
56
+ // Copilot token, which names the account's own API origin.
57
+ // - "xai_grok": a SuperGrok or X Premium sign-in; the token is its OAuth
58
+ // access token.
59
+ // - "vercel_token_pass": a Vercel Token Pass; the token is its AI Gateway key.
60
+ export type SubscriptionKind =
61
+ | "openai_codex"
62
+ | "anthropic_claude_code"
63
+ | "meta_muse"
64
+ | "opencode_go"
65
+ | "github_copilot"
66
+ | "xai_grok"
67
+ | "vercel_token_pass";
56
68
 
57
69
  // A bearer credential an embedding platform supplies for one request through
58
70
  // GatewayPlatform.resolveProviderCredential, optionally with its own endpoint.
@@ -122,6 +134,15 @@ export type ResolvedRouterModelConfig = {
122
134
  zdr?: boolean;
123
135
  };
124
136
 
137
+ // Another way to serve a model when the one before it fails within a request:
138
+ // one of the user's plans, whose token the gateway fetches through
139
+ // GatewayPlatform.nextSubscription, or without `subscription` the router's
140
+ // API credential for `config.provider` (provider_keys / provider_auth).
141
+ export type ModelFallback = {
142
+ config: ResolvedRouterModelConfig;
143
+ subscription?: SubscriptionKind | null;
144
+ };
145
+
125
146
  /** Why a Dari Link grant cannot serve one provider's models now. */
126
147
  export type LinkUnavailable = {
127
148
  code: "subscription_exhausted" | "subscription_client_mismatch" | "grant_budget_exhausted";
@@ -146,8 +167,11 @@ export type ResolvedRouter = {
146
167
  // Model -> the platform-supplied credential that replaces the provider key
147
168
  // above for this request. Supplied by resolveRouter or resolveProviderCredential.
148
169
  provider_credentials?: Record<string, ProviderCredential>;
149
- // Execution provider -> the user's subscription credential serving it.
150
- subscription_credential_ids?: Partial<Record<Provider, string>>;
170
+ // Model -> what serves it, in order, when the first candidate
171
+ // (model_configs + provider_credentials) fails in a way another plan or the
172
+ // API key may not: a usage limit with no plan of the same kind left, or a
173
+ // plan's token refused (401/403). Absent: no in-request failover.
174
+ model_fallbacks?: Record<string, ModelFallback[]>;
151
175
  // A Dari Link grant's request: provider or gateway -> the granted API key
152
176
  // serving it, whose monthly spend the request counts toward.
153
177
  link_key_credential_ids?: Partial<Record<Provider, string>>;