@mupt-ai/dari-gateway 1.0.338 → 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.
- package/README.md +9 -7
- package/dist/index.d.ts +1 -1
- package/dist/ingress/codex.js +11 -5
- package/dist/ingress/codex_models.d.ts +2 -1
- package/dist/ingress/codex_models.js +60 -26
- package/dist/ingress/models.js +9 -4
- package/dist/link/assets.js +7 -0
- package/dist/link/endpoints.js +26 -6
- package/dist/link/errors.js +3 -0
- package/dist/link/self_hosted.js +8 -2
- package/dist/models/catalog.js +1 -0
- package/dist/models/execution_provider.d.ts +6 -1
- package/dist/models/execution_provider.js +12 -0
- package/dist/models/provider_defaults.js +9 -0
- package/dist/models/provider_models.json +217 -0
- package/dist/models/subscriptions.d.ts +5 -0
- package/dist/models/subscriptions.js +21 -2
- package/dist/providers/execution.d.ts +5 -0
- package/dist/providers/execution.js +12 -2
- package/dist/providers/github_copilot.d.ts +8 -0
- package/dist/providers/github_copilot.js +21 -0
- package/dist/providers/pi.js +3 -0
- package/dist/providers/provider_attempt_runner.d.ts +2 -0
- package/dist/providers/provider_attempt_runner.js +9 -0
- package/dist/providers/provider_call.js +6 -2
- package/dist/providers/subscription_limits.d.ts +6 -5
- package/dist/providers/subscription_limits.js +20 -9
- package/dist/runtime/model_menu_hint.d.ts +2 -0
- package/dist/runtime/model_menu_hint.js +13 -0
- package/dist/runtime/routed_completion.d.ts +2 -1
- package/dist/runtime/routed_completion.js +6 -2
- package/dist/runtime/routed_runtime.js +68 -3
- package/dist/self_host/resolve.d.ts +11 -9
- package/dist/self_host/resolve.js +247 -181
- package/dist/self_host/subscriptions/index.d.ts +6 -5
- package/dist/self_host/subscriptions/index.js +6 -5
- package/dist/self_host/subscriptions/oauth.d.ts +7 -3
- package/dist/self_host/subscriptions/oauth.js +195 -5
- package/dist/self_host/subscriptions/store.js +3 -0
- package/dist/telemetry/prefix_state.d.ts +1 -0
- package/dist/telemetry/prefix_state.js +1 -1
- package/dist/telemetry/report.js +2 -3
- package/dist/types.d.ts +6 -2
- package/package.json +2 -2
- package/src/index.ts +1 -1
- package/src/ingress/codex.ts +11 -5
- package/src/ingress/codex_models.ts +71 -27
- package/src/ingress/models.ts +9 -4
- package/src/link/assets.ts +7 -0
- package/src/link/endpoints.ts +27 -7
- package/src/link/errors.ts +3 -0
- package/src/link/self_hosted.ts +9 -1
- package/src/models/catalog.ts +1 -0
- package/src/models/execution_provider.ts +24 -1
- package/src/models/provider_defaults.ts +9 -0
- package/src/models/provider_models.json +217 -0
- package/src/models/subscriptions.ts +22 -2
- package/src/providers/execution.ts +22 -2
- package/src/providers/github_copilot.ts +24 -0
- package/src/providers/pi.ts +2 -0
- package/src/providers/provider_attempt_runner.ts +15 -0
- package/src/providers/provider_call.ts +6 -2
- package/src/providers/subscription_limits.ts +20 -10
- package/src/runtime/model_menu_hint.ts +20 -0
- package/src/runtime/routed_completion.ts +9 -3
- package/src/runtime/routed_runtime.ts +79 -3
- package/src/self_host/resolve.ts +253 -186
- package/src/self_host/subscriptions/index.ts +7 -4
- package/src/self_host/subscriptions/oauth.ts +264 -8
- package/src/self_host/subscriptions/store.ts +3 -0
- package/src/telemetry/prefix_state.ts +4 -1
- package/src/telemetry/report.ts +2 -3
- package/src/types.ts +27 -3
|
@@ -10,6 +10,9 @@ export type ProviderAttemptFailure =
|
|
|
10
10
|
// The plan that replaced an exhausted one; the same request is retried
|
|
11
11
|
// on it at once.
|
|
12
12
|
nextSubscription?: NextSubscription;
|
|
13
|
+
// Neither this credential nor a retry on it can serve: the same request
|
|
14
|
+
// moves to the model's next candidate (another plan, or the API key).
|
|
15
|
+
failover?: true;
|
|
13
16
|
}
|
|
14
17
|
| {
|
|
15
18
|
kind: "customer_canceled";
|
|
@@ -51,6 +54,9 @@ type RunProviderAttemptPlanArgs<TChoice, TValue, TInitial> = {
|
|
|
51
54
|
// The choice served by another of the user's plans; without it a failure
|
|
52
55
|
// naming one is not retried on it.
|
|
53
56
|
onSubscription?: (choice: TChoice, next: NextSubscription) => TChoice;
|
|
57
|
+
// The same model served by its next candidate, or undefined when none is
|
|
58
|
+
// left; without it a failure asking for failover stands.
|
|
59
|
+
nextChoice?: (choice: TChoice) => Promise<TChoice | undefined>;
|
|
54
60
|
};
|
|
55
61
|
|
|
56
62
|
type ChoiceResult<TChoice, TValue> = ProviderAttemptPlanResult<TChoice, TValue>;
|
|
@@ -130,6 +136,15 @@ async function runChoice<TChoice, TValue, TInitial>(
|
|
|
130
136
|
maxAttempts += 1;
|
|
131
137
|
continue;
|
|
132
138
|
}
|
|
139
|
+
if (result.kind === "provider_failed" && result.failover === true && args.nextChoice) {
|
|
140
|
+
const next = await args.nextChoice(choice);
|
|
141
|
+
if (next !== undefined) {
|
|
142
|
+
// The next candidate gets the router's full retry budget.
|
|
143
|
+
choice = next;
|
|
144
|
+
maxAttempts = attempt + args.retries + 1;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
133
148
|
if (!result.retryable) break;
|
|
134
149
|
}
|
|
135
150
|
|
|
@@ -36,6 +36,7 @@ import type {
|
|
|
36
36
|
ServedDecision,
|
|
37
37
|
} from "../types.js";
|
|
38
38
|
import { awsRoleCredentials } from "./aws_assume_role.js";
|
|
39
|
+
import { copilotEndpoint } from "./github_copilot.js";
|
|
39
40
|
import {
|
|
40
41
|
attachProviderResponseCapture,
|
|
41
42
|
createProviderResponseCapture,
|
|
@@ -166,7 +167,10 @@ export function prepareProviderExecution(args: {
|
|
|
166
167
|
...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
167
168
|
...(supplied?.baseUrl || supplied?.headers
|
|
168
169
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
169
|
-
|
|
170
|
+
// A Copilot token names its account's own API origin.
|
|
171
|
+
: provider === "github-copilot" && auth.type === "bearer"
|
|
172
|
+
? { endpoint: copilotEndpoint(auth.apiKey) }
|
|
173
|
+
: {}),
|
|
170
174
|
provider,
|
|
171
175
|
providerKeySource,
|
|
172
176
|
// Only resolved personal subscriptions are held at their usage limit;
|
|
@@ -174,7 +178,7 @@ export function prepareProviderExecution(args: {
|
|
|
174
178
|
...(providerKeySource === "subscription" && (!supplied || supplied.credentialId !== undefined) && args.credentials.attributed_user_id
|
|
175
179
|
? {
|
|
176
180
|
subscriptionUserId: args.credentials.attributed_user_id,
|
|
177
|
-
subscriptionCredentialId: supplied?.credentialId
|
|
181
|
+
subscriptionCredentialId: supplied?.credentialId,
|
|
178
182
|
...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
|
|
179
183
|
}
|
|
180
184
|
: {}),
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
|
|
3
3
|
import { providerFailureMessage } from "../runtime/provider_stream_outcome.js";
|
|
4
|
-
import type { ProviderKeySource } from "../types.js";
|
|
4
|
+
import type { ProviderKeySource, SubscriptionKind } from "../types.js";
|
|
5
5
|
import type { CapturedProviderResponse } from "./response_capture.js";
|
|
6
6
|
|
|
7
|
-
export type SubscriptionOAuthProvider =
|
|
7
|
+
export type SubscriptionOAuthProvider = SubscriptionKind;
|
|
8
8
|
|
|
9
9
|
export type SubscriptionUsageLimit = {
|
|
10
10
|
oauthProvider: SubscriptionOAuthProvider;
|
|
@@ -168,6 +168,9 @@ const SUBSCRIPTION_LABEL: Record<SubscriptionOAuthProvider, string> = {
|
|
|
168
168
|
openai_codex: "ChatGPT",
|
|
169
169
|
meta_muse: "Muse Code",
|
|
170
170
|
opencode_go: "OpenCode Go",
|
|
171
|
+
github_copilot: "GitHub Copilot",
|
|
172
|
+
xai_grok: "Grok",
|
|
173
|
+
vercel_token_pass: "Vercel Token Pass",
|
|
171
174
|
};
|
|
172
175
|
|
|
173
176
|
// Providers whose plan page the accounts page links to for buying another.
|
|
@@ -182,15 +185,19 @@ export function subscriptionOAuthProviderFor(
|
|
|
182
185
|
if (provider === "openai" || provider === "openai-codex") return "openai_codex";
|
|
183
186
|
if (provider === "meta") return "meta_muse";
|
|
184
187
|
if (provider === "opencode-go") return "opencode_go";
|
|
188
|
+
if (provider === "github-copilot") return "github_copilot";
|
|
189
|
+
if (provider === "xai") return "xai_grok";
|
|
190
|
+
if (provider === "vercel-token-pass") return "vercel_token_pass";
|
|
185
191
|
return null;
|
|
186
192
|
}
|
|
187
193
|
|
|
188
194
|
/**
|
|
189
195
|
* Recognize a personal subscription that has run out of quota. Claude Code
|
|
190
196
|
* answers 429 with the unified rate-limit headers; the ChatGPT backend answers
|
|
191
|
-
* 429 with a structured `error.code` and `resets_at`. Meta
|
|
192
|
-
*
|
|
193
|
-
* the reset
|
|
197
|
+
* 429 with a structured `error.code` and `resets_at`. Meta, GitHub Copilot,
|
|
198
|
+
* xAI, Kimi, and Vercel Token Pass document no usage-limit signature for their
|
|
199
|
+
* plans, so any 429 on one holds it until the reset it gives, if any. OpenCode
|
|
200
|
+
* Go names its refusal
|
|
194
201
|
* `GoUsageLimitError`. The Codex WebSocket
|
|
195
202
|
* transport bypasses fetch, so its usage-limit error only survives as message
|
|
196
203
|
* text and is matched there without a reset time.
|
|
@@ -210,9 +217,11 @@ export function detectSubscriptionUsageLimit(args: {
|
|
|
210
217
|
if (oauthProvider === "anthropic_claude_code") {
|
|
211
218
|
return anthropicUsageLimit(args.captured, args.model, now);
|
|
212
219
|
}
|
|
213
|
-
if (oauthProvider === "meta_muse") return museUsageLimit(args.captured, now);
|
|
214
220
|
if (oauthProvider === "opencode_go") return openCodeGoUsageLimit(args.captured, now);
|
|
215
|
-
|
|
221
|
+
if (oauthProvider === "openai_codex") {
|
|
222
|
+
return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
|
|
223
|
+
}
|
|
224
|
+
return planRateLimit(oauthProvider, args.captured, now);
|
|
216
225
|
}
|
|
217
226
|
|
|
218
227
|
// Claude Code plans also cap some model families on their own
|
|
@@ -294,15 +303,16 @@ function codexModelLimitExhausted(headers: Headers): boolean {
|
|
|
294
303
|
return other && !plan;
|
|
295
304
|
}
|
|
296
305
|
|
|
297
|
-
function
|
|
306
|
+
function planRateLimit(
|
|
307
|
+
oauthProvider: SubscriptionOAuthProvider,
|
|
298
308
|
captured: CapturedProviderResponse | undefined,
|
|
299
309
|
now: Date,
|
|
300
310
|
): SubscriptionUsageLimit | null {
|
|
301
311
|
if (captured === undefined || captured.status !== 429) return null;
|
|
302
312
|
return {
|
|
303
|
-
oauthProvider
|
|
313
|
+
oauthProvider,
|
|
304
314
|
resetsAt: laterReset(codexErrorBody(captured.bodyText)?.resets_at, captured.headers, now),
|
|
305
|
-
reason:
|
|
315
|
+
reason: `${SUBSCRIPTION_LABEL[oauthProvider]} usage limit reached.`,
|
|
306
316
|
};
|
|
307
317
|
}
|
|
308
318
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
|
|
2
|
+
import type { ClientHarness } from "../types.js";
|
|
3
|
+
|
|
4
|
+
/* Codex fills its /model menu from the router's model list and keeps the
|
|
5
|
+
copy it read: one read before the router's models changed still offers a
|
|
6
|
+
model the router no longer serves. Codex shows the user this error's
|
|
7
|
+
message, so for Codex the message says how to bring the menu up to date. */
|
|
8
|
+
export function withModelMenuHint(error: unknown, clientHarness: ClientHarness | undefined): unknown {
|
|
9
|
+
if (clientHarness !== "codex") return error;
|
|
10
|
+
const { status, message, code, param } = normalizeError(error);
|
|
11
|
+
if (code !== "model_not_enabled") return error;
|
|
12
|
+
return new HttpError(
|
|
13
|
+
status,
|
|
14
|
+
`${message} Codex's /model list may be out of date: run \`dari setup codex --refresh\`.`,
|
|
15
|
+
code,
|
|
16
|
+
param,
|
|
17
|
+
errorResponseHeaders(error),
|
|
18
|
+
error instanceof HttpError ? error.body : undefined,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
@@ -4,10 +4,11 @@ import { isBackgroundRequest, type InteractionRequest } from "../interaction/typ
|
|
|
4
4
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
5
5
|
import { captureRequestError } from "../observability/errors.js";
|
|
6
6
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
7
|
-
import type { ClientHarness } from "../types.js";
|
|
7
|
+
import type { ClientHarness, ResolvedRouter } from "../types.js";
|
|
8
8
|
import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
|
|
9
9
|
import type { HarnessConversationIdentity } from "./harness_identity/index.js";
|
|
10
10
|
import { CustomerDisconnectedError } from "./customer_disconnect.js";
|
|
11
|
+
import { withModelMenuHint } from "./model_menu_hint.js";
|
|
11
12
|
import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
|
|
12
13
|
import type { RoutedProtocol } from "./routed_protocol.js";
|
|
13
14
|
import { runPreparedRoutedCompletion } from "./routed_runtime.js";
|
|
@@ -23,6 +24,8 @@ export async function handleRoutedCompletion(args: {
|
|
|
23
24
|
selectorBackend: SelectorBackend;
|
|
24
25
|
clientHarness?: ClientHarness;
|
|
25
26
|
harnessConversationIdentity?: HarnessConversationIdentity;
|
|
27
|
+
// Headers the client reads from a successful response, from its router.
|
|
28
|
+
responseHeaders?: (router: ResolvedRouter) => Record<string, string>;
|
|
26
29
|
}): Promise<Response> {
|
|
27
30
|
const requestId = randomUUID();
|
|
28
31
|
const clientRequestId = normalizedClientRequestId(args.request.headers.get("x-request-id"));
|
|
@@ -42,7 +45,7 @@ export async function handleRoutedCompletion(args: {
|
|
|
42
45
|
harnessConversationIdentity: args.harnessConversationIdentity,
|
|
43
46
|
}).catch((error: unknown) => ({ error }));
|
|
44
47
|
if ("error" in prepared) {
|
|
45
|
-
const response = args.errorResponse(prepared.error);
|
|
48
|
+
const response = args.errorResponse(withModelMenuHint(prepared.error, args.clientHarness));
|
|
46
49
|
captureRequestError(prepared.error, {
|
|
47
50
|
request: args.request,
|
|
48
51
|
routerId: args.routerId,
|
|
@@ -68,11 +71,14 @@ export async function handleRoutedCompletion(args: {
|
|
|
68
71
|
selectorBackend: args.selectorBackend,
|
|
69
72
|
clientSignal: args.request.signal,
|
|
70
73
|
});
|
|
74
|
+
for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
|
|
75
|
+
response.headers.set(name, value);
|
|
76
|
+
}
|
|
71
77
|
return responseWithRequestId(response, requestId);
|
|
72
78
|
} catch (error) {
|
|
73
79
|
const terminal = prepared.reporter.freezeFailure(error);
|
|
74
80
|
terminal.report();
|
|
75
|
-
let response = args.errorResponse(error);
|
|
81
|
+
let response = args.errorResponse(withModelMenuHint(error, args.clientHarness));
|
|
76
82
|
// Provider retries may already have consumed tokens before the HTTP error.
|
|
77
83
|
// Return the same model-only cost as successful OpenAI-compatible responses.
|
|
78
84
|
if (args.payload.sourceProtocol === "openai_chat") {
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
executeStreaming,
|
|
17
17
|
prepareStreamingExecution,
|
|
18
18
|
type CompletedNonStreamingExecution,
|
|
19
|
+
type NextProviderChoice,
|
|
19
20
|
type ProviderChoice,
|
|
20
21
|
} from "../providers/execution.js";
|
|
21
22
|
import {
|
|
@@ -29,12 +30,14 @@ import {
|
|
|
29
30
|
} from "../providers/provider_call.js";
|
|
30
31
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
31
32
|
import { routeDecision, type RoutedDecision } from "../strategies/route_decision.js";
|
|
32
|
-
import { executionProviderForModel } from "../models/execution_provider.js";
|
|
33
|
+
import { credentialsServedBy, executionProviderForModel } from "../models/execution_provider.js";
|
|
34
|
+
import { gatewayPlatform } from "../platform/platform.js";
|
|
35
|
+
import { captureOperationalError } from "../observability/errors.js";
|
|
33
36
|
import { trackBackgroundTelemetry } from "../telemetry/background.js";
|
|
34
37
|
import { estimateBenchmarkReplay } from "../telemetry/benchmark_replay.js";
|
|
35
38
|
import { buildCompletedPrefixHit } from "../telemetry/prefix_state.js";
|
|
36
39
|
import { scrubSecrets } from "../telemetry/scrub.js";
|
|
37
|
-
import type { ResolvedRouter } from "../types.js";
|
|
40
|
+
import type { ModelFallback, ProviderCredential, ResolvedRouter } from "../types.js";
|
|
38
41
|
import type { PreparedRoutedCompletion } from "./prepare_routed_completion.js";
|
|
39
42
|
import { auxiliaryDecision } from "./claude_code/auxiliary_routing.js";
|
|
40
43
|
import { explicitModelDecision, strictModelDecision } from "./explicit_model.js";
|
|
@@ -70,6 +73,7 @@ type SpeculativeExecution = {
|
|
|
70
73
|
type RuntimeExecutionPlan = {
|
|
71
74
|
primary: ProviderChoice;
|
|
72
75
|
primaryRetries: number;
|
|
76
|
+
nextChoice: NextProviderChoice;
|
|
73
77
|
reportBarrier?: Promise<unknown>;
|
|
74
78
|
startedCompletion?: StartedCompletion;
|
|
75
79
|
startedStream?: StartedStream;
|
|
@@ -137,6 +141,7 @@ export async function runPreparedRoutedCompletion(args: {
|
|
|
137
141
|
interaction: prepared.interaction,
|
|
138
142
|
primary: plan.primary,
|
|
139
143
|
primaryRetries: plan.primaryRetries,
|
|
144
|
+
nextChoice: plan.nextChoice,
|
|
140
145
|
reporter: prepared.reporter,
|
|
141
146
|
protocol: prepared.protocol,
|
|
142
147
|
startedCompletion: plan.startedCompletion,
|
|
@@ -149,6 +154,7 @@ export async function runPreparedRoutedCompletion(args: {
|
|
|
149
154
|
interaction: prepared.interaction,
|
|
150
155
|
primary: plan.primary,
|
|
151
156
|
primaryRetries: plan.primaryRetries,
|
|
157
|
+
nextChoice: plan.nextChoice,
|
|
152
158
|
reporter: prepared.reporter,
|
|
153
159
|
startedStream: plan.startedStream,
|
|
154
160
|
initialError: plan.initialStreamError,
|
|
@@ -189,6 +195,7 @@ export async function runPreparedRoutedInteraction(args: {
|
|
|
189
195
|
interaction: args.prepared.interaction,
|
|
190
196
|
primary: plan.primary,
|
|
191
197
|
primaryRetries: plan.primaryRetries,
|
|
198
|
+
nextChoice: plan.nextChoice,
|
|
192
199
|
reporter: args.prepared.reporter,
|
|
193
200
|
protocol: args.prepared.protocol,
|
|
194
201
|
startedCompletion: plan.startedCompletion,
|
|
@@ -399,6 +406,7 @@ async function prepareRuntimeExecution(args: {
|
|
|
399
406
|
primaryRetries: configuredPrimaryRetries(
|
|
400
407
|
prepared.credentials.primary_retries,
|
|
401
408
|
),
|
|
409
|
+
nextChoice: (choice) => nextProviderChoice(prepared, choice),
|
|
402
410
|
reportBarrier: selectionPromise,
|
|
403
411
|
startedCompletion:
|
|
404
412
|
speculative.transport === "completion" ? speculative.started : undefined,
|
|
@@ -420,6 +428,7 @@ function selectedExecutionPlan(
|
|
|
420
428
|
primaryRetries: configuredPrimaryRetries(
|
|
421
429
|
prepared.credentials.primary_retries,
|
|
422
430
|
),
|
|
431
|
+
nextChoice: (choice) => nextProviderChoice(prepared, choice),
|
|
423
432
|
};
|
|
424
433
|
}
|
|
425
434
|
|
|
@@ -606,13 +615,79 @@ function providerChoice(
|
|
|
606
615
|
};
|
|
607
616
|
}
|
|
608
617
|
|
|
618
|
+
/**
|
|
619
|
+
* The same decision served by the model's next fallback after `choice`: a plan
|
|
620
|
+
* the platform still has a token for, or the router's API credential while
|
|
621
|
+
* the organization has credits. A fallback that cannot be prepared is
|
|
622
|
+
* skipped. Undefined when none is left.
|
|
623
|
+
*/
|
|
624
|
+
async function nextProviderChoice(
|
|
625
|
+
prepared: PreparedRoutedCompletion,
|
|
626
|
+
choice: ProviderChoice,
|
|
627
|
+
): Promise<ProviderChoice | undefined> {
|
|
628
|
+
const { credentials } = prepared;
|
|
629
|
+
const model = choice.decision.selectedModel;
|
|
630
|
+
const fallbacks = credentials.model_fallbacks?.[model] ?? [];
|
|
631
|
+
for (let index = (choice.fallback ?? -1) + 1; index < fallbacks.length; index += 1) {
|
|
632
|
+
const fallback = fallbacks[index]!;
|
|
633
|
+
if (!fallback.subscription && credentials.credit_exhausted === true) continue;
|
|
634
|
+
const plan = fallback.subscription
|
|
635
|
+
? await fallbackPlan(credentials, fallback, model, prepared.routing.conversationId)
|
|
636
|
+
: undefined;
|
|
637
|
+
if (fallback.subscription && plan === undefined) continue;
|
|
638
|
+
try {
|
|
639
|
+
return {
|
|
640
|
+
decision: choice.decision,
|
|
641
|
+
fallback: index,
|
|
642
|
+
execution: providerExecution(prepared, choice.decision, credentialsServedBy(credentials, model, fallback.config, plan)),
|
|
643
|
+
};
|
|
644
|
+
} catch (error) {
|
|
645
|
+
console.error(
|
|
646
|
+
"model fallback setup failed",
|
|
647
|
+
scrubSecrets(error instanceof Error ? error.message : String(error)),
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return undefined;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// The user's plan of the fallback's kind that serves this model now, if any.
|
|
655
|
+
async function fallbackPlan(
|
|
656
|
+
credentials: ResolvedRouter,
|
|
657
|
+
fallback: ModelFallback,
|
|
658
|
+
model: string,
|
|
659
|
+
conversationId: string,
|
|
660
|
+
): Promise<ProviderCredential | undefined> {
|
|
661
|
+
const platform = gatewayPlatform();
|
|
662
|
+
const userId = credentials.attributed_user_id;
|
|
663
|
+
// A strict router serves only plans the platform supplied up front.
|
|
664
|
+
if (platform.nextSubscription === undefined || !userId || credentials.strict === true) return undefined;
|
|
665
|
+
try {
|
|
666
|
+
const next = await platform.nextSubscription({
|
|
667
|
+
userId,
|
|
668
|
+
provider: fallback.config.provider,
|
|
669
|
+
model,
|
|
670
|
+
conversationId,
|
|
671
|
+
...(credentials.link_grant_id ? { linkGrantId: credentials.link_grant_id } : {}),
|
|
672
|
+
});
|
|
673
|
+
return next === undefined
|
|
674
|
+
? undefined
|
|
675
|
+
: { apiKey: next.apiKey, subscription: fallback.subscription!, credentialId: next.credentialId };
|
|
676
|
+
} catch (error) {
|
|
677
|
+
console.error("fallback subscription lookup failed", error);
|
|
678
|
+
captureOperationalError(error, { code: "next_subscription_lookup_failed" });
|
|
679
|
+
return undefined;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
609
683
|
function providerExecution(
|
|
610
684
|
prepared: PreparedRoutedCompletion,
|
|
611
685
|
decision: RoutingDecision,
|
|
686
|
+
credentials: ResolvedRouter = prepared.credentials,
|
|
612
687
|
): ProviderExecution {
|
|
613
688
|
return prepareProviderExecution({
|
|
614
689
|
decision,
|
|
615
|
-
credentials
|
|
690
|
+
credentials,
|
|
616
691
|
billable: prepared.billable,
|
|
617
692
|
routerId: prepared.routerId,
|
|
618
693
|
pricing: prepared.routing.pricing,
|
|
@@ -674,6 +749,7 @@ function runtimeResult(
|
|
|
674
749
|
target,
|
|
675
750
|
conversationId: prepared.routing.conversationId,
|
|
676
751
|
leaseDepth: prepared.routing.leaseDepth,
|
|
752
|
+
provider: result.choice.execution.provider,
|
|
677
753
|
providerBlockDepth:
|
|
678
754
|
prepared.routing.providerBlockDepthFor(decision.selectedModel),
|
|
679
755
|
fingerprints: prepared.routing.prefix.fingerprints,
|