@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.
Files changed (73) hide show
  1. package/README.md +9 -7
  2. package/dist/index.d.ts +1 -1
  3. package/dist/ingress/codex.js +11 -5
  4. package/dist/ingress/codex_models.d.ts +2 -1
  5. package/dist/ingress/codex_models.js +60 -26
  6. package/dist/ingress/models.js +9 -4
  7. package/dist/link/assets.js +7 -0
  8. package/dist/link/endpoints.js +26 -6
  9. package/dist/link/errors.js +3 -0
  10. package/dist/link/self_hosted.js +8 -2
  11. package/dist/models/catalog.js +1 -0
  12. package/dist/models/execution_provider.d.ts +6 -1
  13. package/dist/models/execution_provider.js +12 -0
  14. package/dist/models/provider_defaults.js +9 -0
  15. package/dist/models/provider_models.json +217 -0
  16. package/dist/models/subscriptions.d.ts +5 -0
  17. package/dist/models/subscriptions.js +21 -2
  18. package/dist/providers/execution.d.ts +5 -0
  19. package/dist/providers/execution.js +12 -2
  20. package/dist/providers/github_copilot.d.ts +8 -0
  21. package/dist/providers/github_copilot.js +21 -0
  22. package/dist/providers/pi.js +3 -0
  23. package/dist/providers/provider_attempt_runner.d.ts +2 -0
  24. package/dist/providers/provider_attempt_runner.js +9 -0
  25. package/dist/providers/provider_call.js +6 -2
  26. package/dist/providers/subscription_limits.d.ts +6 -5
  27. package/dist/providers/subscription_limits.js +20 -9
  28. package/dist/runtime/model_menu_hint.d.ts +2 -0
  29. package/dist/runtime/model_menu_hint.js +13 -0
  30. package/dist/runtime/routed_completion.d.ts +2 -1
  31. package/dist/runtime/routed_completion.js +6 -2
  32. package/dist/runtime/routed_runtime.js +68 -3
  33. package/dist/self_host/resolve.d.ts +11 -9
  34. package/dist/self_host/resolve.js +247 -181
  35. package/dist/self_host/subscriptions/index.d.ts +6 -5
  36. package/dist/self_host/subscriptions/index.js +6 -5
  37. package/dist/self_host/subscriptions/oauth.d.ts +7 -3
  38. package/dist/self_host/subscriptions/oauth.js +195 -5
  39. package/dist/self_host/subscriptions/store.js +3 -0
  40. package/dist/telemetry/prefix_state.d.ts +1 -0
  41. package/dist/telemetry/prefix_state.js +1 -1
  42. package/dist/telemetry/report.js +2 -3
  43. package/dist/types.d.ts +6 -2
  44. package/package.json +2 -2
  45. package/src/index.ts +1 -1
  46. package/src/ingress/codex.ts +11 -5
  47. package/src/ingress/codex_models.ts +71 -27
  48. package/src/ingress/models.ts +9 -4
  49. package/src/link/assets.ts +7 -0
  50. package/src/link/endpoints.ts +27 -7
  51. package/src/link/errors.ts +3 -0
  52. package/src/link/self_hosted.ts +9 -1
  53. package/src/models/catalog.ts +1 -0
  54. package/src/models/execution_provider.ts +24 -1
  55. package/src/models/provider_defaults.ts +9 -0
  56. package/src/models/provider_models.json +217 -0
  57. package/src/models/subscriptions.ts +22 -2
  58. package/src/providers/execution.ts +22 -2
  59. package/src/providers/github_copilot.ts +24 -0
  60. package/src/providers/pi.ts +2 -0
  61. package/src/providers/provider_attempt_runner.ts +15 -0
  62. package/src/providers/provider_call.ts +6 -2
  63. package/src/providers/subscription_limits.ts +20 -10
  64. package/src/runtime/model_menu_hint.ts +20 -0
  65. package/src/runtime/routed_completion.ts +9 -3
  66. package/src/runtime/routed_runtime.ts +79 -3
  67. package/src/self_host/resolve.ts +253 -186
  68. package/src/self_host/subscriptions/index.ts +7 -4
  69. package/src/self_host/subscriptions/oauth.ts +264 -8
  70. package/src/self_host/subscriptions/store.ts +3 -0
  71. package/src/telemetry/prefix_state.ts +4 -1
  72. package/src/telemetry/report.ts +2 -3
  73. package/src/types.ts +27 -3
@@ -3,6 +3,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
3
3
  import { explicitModelId } from "../protocol/input/router_model.js";
4
4
  import { captureRequestError } from "../observability/errors.js";
5
5
  import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
6
+ import { withModelMenuHint } from "./model_menu_hint.js";
6
7
  import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
7
8
  import { runPreparedRoutedCompletion } from "./routed_runtime.js";
8
9
  export async function handleRoutedCompletion(args) {
@@ -24,7 +25,7 @@ export async function handleRoutedCompletion(args) {
24
25
  harnessConversationIdentity: args.harnessConversationIdentity,
25
26
  }).catch((error) => ({ error }));
26
27
  if ("error" in prepared) {
27
- const response = args.errorResponse(prepared.error);
28
+ const response = args.errorResponse(withModelMenuHint(prepared.error, args.clientHarness));
28
29
  captureRequestError(prepared.error, {
29
30
  request: args.request,
30
31
  routerId: args.routerId,
@@ -48,12 +49,15 @@ export async function handleRoutedCompletion(args) {
48
49
  selectorBackend: args.selectorBackend,
49
50
  clientSignal: args.request.signal,
50
51
  });
52
+ for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
53
+ response.headers.set(name, value);
54
+ }
51
55
  return responseWithRequestId(response, requestId);
52
56
  }
53
57
  catch (error) {
54
58
  const terminal = prepared.reporter.freezeFailure(error);
55
59
  terminal.report();
56
- let response = args.errorResponse(error);
60
+ let response = args.errorResponse(withModelMenuHint(error, args.clientHarness));
57
61
  // Provider retries may already have consumed tokens before the HTTP error.
58
62
  // Return the same model-only cost as successful OpenAI-compatible responses.
59
63
  if (args.payload.sourceProtocol === "openai_chat") {
@@ -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[]>;