@mupt-ai/dari-gateway 1.0.318 → 1.0.319

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.
@@ -420,6 +420,7 @@ export type SubscriptionHold = {
420
420
  export type NextSubscriptionRequest = {
421
421
  userId: string;
422
422
  provider: Provider;
423
+ model: string;
423
424
  conversationId: string;
424
425
  linkGrantId?: string;
425
426
  };
@@ -463,8 +463,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
463
463
  // Retrying an exhausted plan cannot succeed. The platform learns about it
464
464
  // before this request returns so the next resolve already serves the
465
465
  // user's next subscription, or the model's API credential when the router
466
- // allows subscription API fallback for it. A limit on one model holds only
467
- // that model, and the next resolve routes to the others.
466
+ // allows subscription API fallback for it. A model limit holds only that
467
+ // model on this plan; other plans may still serve it.
468
468
  const switched = execution.subscriptionUserId !== undefined
469
469
  && await holdSubscription({
470
470
  userId: execution.subscriptionUserId,
@@ -473,9 +473,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
473
473
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
474
474
  });
475
475
  // Nothing reached the client yet, so the same request is retried on the
476
- // next plan at once when the platform names it. The same plan still serves
477
- // after a model limit, so there is no next plan to retry on.
478
- const nextSubscription = switched && limit.model === undefined
476
+ // next plan with quota for this model, including model-specific limits.
477
+ const nextSubscription = switched
479
478
  ? await nextSubscriptionFor(execution)
480
479
  : undefined;
481
480
  return {
@@ -573,12 +572,15 @@ async function nextSubscriptionFor(execution) {
573
572
  if (platform.nextSubscription === undefined || execution.subscriptionUserId === undefined)
574
573
  return undefined;
575
574
  try {
576
- return await platform.nextSubscription({
575
+ const next = await platform.nextSubscription({
577
576
  userId: execution.subscriptionUserId,
578
577
  provider: execution.provider,
578
+ model: execution.model,
579
579
  conversationId: execution.conversationId,
580
580
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
581
581
  });
582
+ // Never retry a held credential, even if a stale lookup returns it.
583
+ return next?.credentialId === execution.subscriptionCredentialId ? undefined : next;
582
584
  }
583
585
  catch (error) {
584
586
  console.error("next subscription lookup failed", error);
@@ -55,10 +55,10 @@ export function prepareProviderExecution(args) {
55
55
  providerKeySource,
56
56
  // Only resolved personal subscriptions are held at their usage limit;
57
57
  // the platform manages the plans it supplies.
58
- ...(providerKeySource === "subscription" && !supplied && args.credentials.attributed_user_id
58
+ ...(providerKeySource === "subscription" && (!supplied || supplied.credentialId !== undefined) && args.credentials.attributed_user_id
59
59
  ? {
60
60
  subscriptionUserId: args.credentials.attributed_user_id,
61
- subscriptionCredentialId: args.credentials.subscription_credential_ids?.[provider],
61
+ subscriptionCredentialId: supplied?.credentialId ?? args.credentials.subscription_credential_ids?.[provider],
62
62
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
63
63
  }
64
64
  : {}),
@@ -196,7 +196,7 @@ async function withProviderCredentials(credentials, apiKey, clientHarness) {
196
196
  ...(clientHarness ? { clientHarness } : {}),
197
197
  }),
198
198
  ]));
199
- const provider_credentials = {};
199
+ const provider_credentials = { ...credentials.provider_credentials };
200
200
  const model_configs = { ...credentials.model_configs };
201
201
  for (const [model, credential] of resolved) {
202
202
  if (!credential?.apiKey.trim())
@@ -2,7 +2,7 @@ import { errorCode } from "../http/errors.js";
2
2
  import { selfHostedLink } from "../link/self_hosted.js";
3
3
  import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
4
4
  import { resolveSelfHostedRouter } from "./resolve.js";
5
- import { freshAccessToken } from "./subscriptions/index.js";
5
+ import { refreshedAccessToken } from "./subscriptions/access.js";
6
6
  /**
7
7
  * The self-hosted platform: routers from the config file, subscriptions,
8
8
  * Dari Link grants, prefix-cache state, and session pins in the gateway's
@@ -35,12 +35,12 @@ export function createSelfHostedPlatform(deps) {
35
35
  : deps.links.credentialIds(request.linkGrantId);
36
36
  const next = plan === null
37
37
  ? null
38
- : deps.subscriptions.selectCredential(plan, request.conversationId, new Date(), only);
38
+ : deps.subscriptions.selectCredential(plan, request.conversationId, new Date(), only, request.model);
39
39
  if (next === null)
40
40
  return undefined;
41
41
  return {
42
42
  credentialId: next.id,
43
- apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
43
+ apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
44
44
  };
45
45
  },
46
46
  async markSubscriptionUnavailable({ credentialId, limit, linkGrantId }) {
@@ -9,6 +9,7 @@ import { linkGrantUnavailableError, modelNotServed, plansExhausted, plansForAnot
9
9
  import { registeredModelPrice } from "../providers/pi.js";
10
10
  import { allRouterModels, routerModelsFor, } from "./config.js";
11
11
  import { linkTokenGrant } from "../link/service.js";
12
+ import { refreshedAccessToken } from "./subscriptions/access.js";
12
13
  import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
13
14
  // A self-hosted gateway is one tenant; these stand in for the hosted
14
15
  // organization and the user a personal subscription belongs to.
@@ -83,22 +84,39 @@ export async function resolveSelfHostedRouter(deps, request) {
83
84
  const apiKey = await configuredProviderApiKey(deps, provider);
84
85
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
85
86
  }
86
- // A model at its own limit on the serving plan leaves routing until it resets.
87
+ // A model-specific hold tries the pool's other plans before removing the
88
+ // model. Its provider's active plan and conversation pin stay unchanged.
89
+ const modelCredentials = {};
87
90
  const linkUnavailable = grant === null
88
91
  ? {}
89
92
  : grantUnavailable(granted, credentials, request.clientHarness, now);
90
- const models = listed.filter((model) => {
93
+ const models = [];
94
+ for (const model of listed) {
91
95
  const credential = credentials.get(providerForModel(model.id));
92
96
  if (credential == null)
93
- return false;
97
+ continue;
94
98
  const plan = credential.subscription;
95
99
  const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
96
- if (plan === undefined || hold === undefined)
97
- return true;
100
+ if (plan === undefined || hold === undefined) {
101
+ models.push(model);
102
+ continue;
103
+ }
104
+ const alternate = deps.subscriptions.selectCredential(plan.provider, undefined, now, servable, model.id);
105
+ if (alternate !== null) {
106
+ modelCredentials[model.id] = {
107
+ apiKey: request.provisional === true
108
+ ? alternate.accessToken
109
+ // A model-only failover must not move the provider-wide rotation anchor.
110
+ : await refreshedAccessToken(deps.subscriptions, alternate, { fetch: deps.fetch }),
111
+ subscription: alternate.provider,
112
+ credentialId: alternate.id,
113
+ };
114
+ models.push(model);
115
+ continue;
116
+ }
98
117
  exhausted.add(plan.provider);
99
118
  linkUnavailable[model.id] = plansExhausted([plan.provider], hold.until);
100
- return false;
101
- });
119
+ }
102
120
  // A grant with a gateway key serves the gateway's models by name, listed or not.
103
121
  const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
104
122
  if (models.length === 0 && !gatewayKeyed) {
@@ -124,6 +142,7 @@ export async function resolveSelfHostedRouter(deps, request) {
124
142
  provider_keys: {},
125
143
  provider_key_sources: {},
126
144
  subscription_credential_ids: {},
145
+ provider_credentials: modelCredentials,
127
146
  link_grant_id: grant?.id ?? null,
128
147
  ...(grant === null
129
148
  ? {}
@@ -100,7 +100,7 @@ export declare class SubscriptionStore {
100
100
  * is among the gateway owner's, or with `only` among those subscription ids,
101
101
  * as for a Dari Link grant.
102
102
  */
103
- selectCredential(provider: SubscriptionProvider, conversationId: string | undefined, now?: Date, only?: ReadonlySet<string>): SubscriptionCredential | null;
103
+ selectCredential(provider: SubscriptionProvider, conversationId: string | undefined, now?: Date, only?: ReadonlySet<string>, model?: string): SubscriptionCredential | null;
104
104
  /** Record the usage a response reported for a subscription. */
105
105
  recordUsage(id: string, usage: SubscriptionUsage, now?: Date): void;
106
106
  private pinnedCredential;
@@ -175,9 +175,10 @@ export class SubscriptionStore {
175
175
  * is among the gateway owner's, or with `only` among those subscription ids,
176
176
  * as for a Dari Link grant.
177
177
  */
178
- selectCredential(provider, conversationId, now = new Date(), only) {
178
+ selectCredential(provider, conversationId, now = new Date(), only, model) {
179
179
  const all = only === undefined ? this.list(provider) : this.withIds(only, provider);
180
- const available = all.filter((credential) => !isHeld(credential, now));
180
+ const available = all.filter((credential) => !isHeld(credential, now)
181
+ && (model === undefined || !activeModelHolds(credential, now).some((hold) => hold.model === model)));
181
182
  if (available.length === 0)
182
183
  return null;
183
184
  const order = rotationFrom(all, lastUsed(all));
@@ -191,7 +192,7 @@ export class SubscriptionStore {
191
192
  ? [...withHeadroom].sort(soonestResetFirst(now, order))[0]
192
193
  : [...available].sort(leastUsedFirst(now, order))[0];
193
194
  }
194
- if (conversationId !== undefined)
195
+ if (conversationId !== undefined && model === undefined)
195
196
  this.pinConversation(conversationId, provider, chosen.id, now);
196
197
  return chosen;
197
198
  }
package/dist/types.d.ts CHANGED
@@ -24,6 +24,7 @@ export type ProviderCredential = {
24
24
  baseUrl?: string;
25
25
  headers?: Record<string, string>;
26
26
  subscription?: SubscriptionKind;
27
+ credentialId?: string;
27
28
  };
28
29
  export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
29
30
  export type AwsProviderAuth = AwsSigV4ProviderAuth | AwsAssumeRoleProviderAuth;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.318",
3
+ "version": "1.0.319",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.318",
55
+ "@mupt-ai/dari-router": "1.0.319",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -471,6 +471,7 @@ export type SubscriptionHold = {
471
471
  export type NextSubscriptionRequest = {
472
472
  userId: string;
473
473
  provider: Provider;
474
+ model: string;
474
475
  conversationId: string;
475
476
  // The Dari Link grant the request ran under: the next plan must be one of
476
477
  // its subscriptions.
@@ -764,8 +764,8 @@ async function providerFailedAttempt(
764
764
  // Retrying an exhausted plan cannot succeed. The platform learns about it
765
765
  // before this request returns so the next resolve already serves the
766
766
  // user's next subscription, or the model's API credential when the router
767
- // allows subscription API fallback for it. A limit on one model holds only
768
- // that model, and the next resolve routes to the others.
767
+ // allows subscription API fallback for it. A model limit holds only that
768
+ // model on this plan; other plans may still serve it.
769
769
  const switched = execution.subscriptionUserId !== undefined
770
770
  && await holdSubscription({
771
771
  userId: execution.subscriptionUserId,
@@ -774,9 +774,8 @@ async function providerFailedAttempt(
774
774
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
775
775
  });
776
776
  // Nothing reached the client yet, so the same request is retried on the
777
- // next plan at once when the platform names it. The same plan still serves
778
- // after a model limit, so there is no next plan to retry on.
779
- const nextSubscription = switched && limit.model === undefined
777
+ // next plan with quota for this model, including model-specific limits.
778
+ const nextSubscription = switched
780
779
  ? await nextSubscriptionFor(execution)
781
780
  : undefined;
782
781
  return {
@@ -890,12 +889,15 @@ async function nextSubscriptionFor(execution: ProviderExecution): Promise<NextSu
890
889
  const platform = gatewayPlatform();
891
890
  if (platform.nextSubscription === undefined || execution.subscriptionUserId === undefined) return undefined;
892
891
  try {
893
- return await platform.nextSubscription({
892
+ const next = await platform.nextSubscription({
894
893
  userId: execution.subscriptionUserId,
895
894
  provider: execution.provider,
895
+ model: execution.model,
896
896
  conversationId: execution.conversationId,
897
897
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
898
898
  });
899
+ // Never retry a held credential, even if a stale lookup returns it.
900
+ return next?.credentialId === execution.subscriptionCredentialId ? undefined : next;
899
901
  } catch (error) {
900
902
  console.error("next subscription lookup failed", error);
901
903
  captureOperationalError(error, { code: "next_subscription_lookup_failed" });
@@ -171,10 +171,10 @@ export function prepareProviderExecution(args: {
171
171
  providerKeySource,
172
172
  // Only resolved personal subscriptions are held at their usage limit;
173
173
  // the platform manages the plans it supplies.
174
- ...(providerKeySource === "subscription" && !supplied && args.credentials.attributed_user_id
174
+ ...(providerKeySource === "subscription" && (!supplied || supplied.credentialId !== undefined) && args.credentials.attributed_user_id
175
175
  ? {
176
176
  subscriptionUserId: args.credentials.attributed_user_id,
177
- subscriptionCredentialId: args.credentials.subscription_credential_ids?.[provider],
177
+ subscriptionCredentialId: supplied?.credentialId ?? args.credentials.subscription_credential_ids?.[provider],
178
178
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
179
179
  }
180
180
  : {}),
@@ -267,7 +267,7 @@ async function withProviderCredentials(
267
267
  }),
268
268
  ] as const),
269
269
  );
270
- const provider_credentials: Record<string, ProviderCredential> = {};
270
+ const provider_credentials: Record<string, ProviderCredential> = { ...credentials.provider_credentials };
271
271
  const model_configs = { ...credentials.model_configs };
272
272
  for (const [model, credential] of resolved) {
273
273
  if (!credential?.apiKey.trim()) continue;
@@ -5,7 +5,8 @@ import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.j
5
5
  import type { PrefixStore } from "./prefix_store.js";
6
6
  import type { SessionPinStore } from "./session_pin_store.js";
7
7
  import { resolveSelfHostedRouter, type SelfHostedResolverDeps } from "./resolve.js";
8
- import { freshAccessToken, type SubscriptionStore } from "./subscriptions/index.js";
8
+ import { type SubscriptionStore } from "./subscriptions/index.js";
9
+ import { refreshedAccessToken } from "./subscriptions/access.js";
9
10
 
10
11
  /**
11
12
  * The self-hosted platform: routers from the config file, subscriptions,
@@ -43,11 +44,11 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
43
44
  : deps.links.credentialIds(request.linkGrantId);
44
45
  const next = plan === null
45
46
  ? null
46
- : deps.subscriptions.selectCredential(plan, request.conversationId, new Date(), only);
47
+ : deps.subscriptions.selectCredential(plan, request.conversationId, new Date(), only, request.model);
47
48
  if (next === null) return undefined;
48
49
  return {
49
50
  credentialId: next.id,
50
- apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
51
+ apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
51
52
  };
52
53
  },
53
54
  async markSubscriptionUnavailable({ credentialId, limit, linkGrantId }) {
@@ -20,7 +20,7 @@ import {
20
20
  plansForAnotherClient,
21
21
  } from "../link/errors.js";
22
22
  import { registeredModelPrice } from "../providers/pi.js";
23
- import type { LinkUnavailable, ProviderKeySource, ResolvedRouter } from "../types.js";
23
+ import type { LinkUnavailable, ProviderCredential as SuppliedProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
24
24
  import {
25
25
  allRouterModels,
26
26
  routerModelsFor,
@@ -32,6 +32,7 @@ import type { ActiveLinkGrant } from "../link/grants.js";
32
32
  import type { SqliteLinkStore } from "../link/sqlite_store.js";
33
33
  import { linkTokenGrant } from "../link/service.js";
34
34
  import type { RouterModelStore } from "./router_models.js";
35
+ import { refreshedAccessToken } from "./subscriptions/access.js";
35
36
  import {
36
37
  activeModelHolds,
37
38
  freshAccessToken,
@@ -148,20 +149,39 @@ export async function resolveSelfHostedRouter(
148
149
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
149
150
  }
150
151
 
151
- // A model at its own limit on the serving plan leaves routing until it resets.
152
+ // A model-specific hold tries the pool's other plans before removing the
153
+ // model. Its provider's active plan and conversation pin stay unchanged.
154
+ const modelCredentials: Record<string, SuppliedProviderCredential> = {};
152
155
  const linkUnavailable = grant === null
153
156
  ? {}
154
157
  : grantUnavailable(granted, credentials, request.clientHarness, now);
155
- const models = listed.filter((model) => {
158
+ const models = [];
159
+ for (const model of listed) {
156
160
  const credential = credentials.get(providerForModel(model.id));
157
- if (credential == null) return false;
161
+ if (credential == null) continue;
158
162
  const plan = credential.subscription;
159
163
  const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
160
- if (plan === undefined || hold === undefined) return true;
164
+ if (plan === undefined || hold === undefined) {
165
+ models.push(model);
166
+ continue;
167
+ }
168
+ const alternate = deps.subscriptions.selectCredential(plan.provider, undefined, now, servable, model.id);
169
+ if (alternate !== null) {
170
+ modelCredentials[model.id] = {
171
+ apiKey: request.provisional === true
172
+ ? alternate.accessToken
173
+ // A model-only failover must not move the provider-wide rotation anchor.
174
+ : await refreshedAccessToken(deps.subscriptions, alternate, { fetch: deps.fetch }),
175
+ subscription: alternate.provider,
176
+ credentialId: alternate.id,
177
+ };
178
+ models.push(model);
179
+ continue;
180
+ }
161
181
  exhausted.add(plan.provider);
162
182
  linkUnavailable[model.id] = plansExhausted([plan.provider], hold.until);
163
- return false;
164
- });
183
+ }
184
+
165
185
  // A grant with a gateway key serves the gateway's models by name, listed or not.
166
186
  const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
167
187
  if (models.length === 0 && !gatewayKeyed) {
@@ -188,6 +208,7 @@ export async function resolveSelfHostedRouter(
188
208
  provider_keys: {},
189
209
  provider_key_sources: {},
190
210
  subscription_credential_ids: {},
211
+ provider_credentials: modelCredentials,
191
212
  link_grant_id: grant?.id ?? null,
192
213
  ...(grant === null
193
214
  ? {}
@@ -304,9 +304,11 @@ export class SubscriptionStore {
304
304
  conversationId: string | undefined,
305
305
  now = new Date(),
306
306
  only?: ReadonlySet<string>,
307
+ model?: string,
307
308
  ): SubscriptionCredential | null {
308
309
  const all = only === undefined ? this.list(provider) : this.withIds(only, provider);
309
- const available = all.filter((credential) => !isHeld(credential, now));
310
+ const available = all.filter((credential) => !isHeld(credential, now)
311
+ && (model === undefined || !activeModelHolds(credential, now).some((hold) => hold.model === model)));
310
312
  if (available.length === 0) return null;
311
313
  const order = rotationFrom(all, lastUsed(all));
312
314
  const withHeadroom = available.filter((credential) => hasHeadroom(credential, now));
@@ -320,7 +322,7 @@ export class SubscriptionStore {
320
322
  ? [...withHeadroom].sort(soonestResetFirst(now, order))[0]!
321
323
  : [...available].sort(leastUsedFirst(now, order))[0]!;
322
324
  }
323
- if (conversationId !== undefined) this.pinConversation(conversationId, provider, chosen.id, now);
325
+ if (conversationId !== undefined && model === undefined) this.pinConversation(conversationId, provider, chosen.id, now);
324
326
  return chosen;
325
327
  }
326
328
 
package/src/types.ts CHANGED
@@ -63,6 +63,8 @@ export type ProviderCredential = {
63
63
  baseUrl?: string;
64
64
  headers?: Record<string, string>;
65
65
  subscription?: SubscriptionKind;
66
+ // A resolved personal plan: quota holds and usage belong to this credential.
67
+ credentialId?: string;
66
68
  };
67
69
 
68
70
  export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
@@ -142,7 +144,7 @@ export type ResolvedRouter = {
142
144
  provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
143
145
  provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
144
146
  // Model -> the platform-supplied credential that replaces the provider key
145
- // above for this request. Filled from resolveProviderCredential.
147
+ // above for this request. Supplied by resolveRouter or resolveProviderCredential.
146
148
  provider_credentials?: Record<string, ProviderCredential>;
147
149
  // Execution provider -> the user's subscription credential serving it.
148
150
  subscription_credential_ids?: Partial<Record<Provider, string>>;