@mupt-ai/dari-gateway 1.0.355 → 1.0.357

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 (47) hide show
  1. package/README.md +4 -3
  2. package/dist/ingress/models.js +8 -1
  3. package/dist/link/self_hosted.js +1 -0
  4. package/dist/models/execution_provider.d.ts +2 -3
  5. package/dist/models/execution_provider.js +7 -6
  6. package/dist/models/sources.d.ts +37 -0
  7. package/dist/models/sources.js +88 -0
  8. package/dist/platform/platform.d.ts +5 -1
  9. package/dist/platform/routing_contract.d.ts +1 -0
  10. package/dist/platform/routing_contract.js +3 -0
  11. package/dist/providers/execution.js +9 -3
  12. package/dist/providers/provider_call.d.ts +3 -0
  13. package/dist/providers/provider_call.js +3 -5
  14. package/dist/runtime/routed_runtime.js +12 -5
  15. package/dist/self_host/config.d.ts +11 -5
  16. package/dist/self_host/config.js +22 -6
  17. package/dist/self_host/connected.js +6 -3
  18. package/dist/self_host/platform.js +2 -2
  19. package/dist/self_host/resolve.js +41 -24
  20. package/dist/self_host/subscriptions/http.js +8 -10
  21. package/dist/self_host/subscriptions/resets.d.ts +11 -5
  22. package/dist/self_host/subscriptions/resets.js +23 -17
  23. package/dist/self_host/subscriptions/store.d.ts +1 -3
  24. package/dist/self_host/subscriptions/store.js +7 -17
  25. package/dist/strategies/routing.js +1 -3
  26. package/dist/telemetry/report.js +3 -3
  27. package/dist/types.d.ts +6 -0
  28. package/package.json +2 -2
  29. package/src/ingress/models.ts +8 -1
  30. package/src/link/self_hosted.ts +1 -0
  31. package/src/models/execution_provider.ts +5 -5
  32. package/src/models/sources.ts +114 -0
  33. package/src/platform/platform.ts +10 -1
  34. package/src/platform/routing_contract.ts +4 -0
  35. package/src/providers/execution.ts +9 -3
  36. package/src/providers/provider_call.ts +7 -10
  37. package/src/runtime/routed_runtime.ts +10 -4
  38. package/src/self_host/config.ts +34 -11
  39. package/src/self_host/connected.ts +6 -3
  40. package/src/self_host/platform.ts +2 -2
  41. package/src/self_host/resolve.ts +36 -20
  42. package/src/self_host/subscriptions/http.ts +9 -9
  43. package/src/self_host/subscriptions/resets.ts +27 -19
  44. package/src/self_host/subscriptions/store.ts +11 -21
  45. package/src/strategies/routing.ts +1 -3
  46. package/src/telemetry/report.ts +3 -3
  47. package/src/types.ts +14 -0
@@ -5,6 +5,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
5
5
  import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
6
6
  import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
7
7
  import { gatewayFor } from "../models/gateways.js";
8
+ import { candidatesFor, DEFAULT_RESET_MIN_HOURS, SELF_HOSTED_DEFAULT_SOURCES } from "../models/sources.js";
8
9
  import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
9
10
  import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
10
11
  import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
@@ -53,8 +54,6 @@ export async function resolveSelfHostedRouter(deps, request) {
53
54
  const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
54
55
  const now = new Date();
55
56
  const servable = grant === null ? undefined : new Set(grant.credentialIds);
56
- // A grant uses the subscriptions its user chose, whatever the router allows.
57
- const plansServe = router?.subscriptions === true || grant !== null;
58
57
  // The plan of each kind that serves this conversation, chosen once.
59
58
  const conversationPlans = new Map();
60
59
  const conversationPlan = (kind) => {
@@ -119,6 +118,8 @@ export async function resolveSelfHostedRouter(deps, request) {
119
118
  model_thinking_levels: thinkingLevels(listed),
120
119
  model_prices: {},
121
120
  model_configs: {},
121
+ model_sources: {},
122
+ reset_min_hours: router?.resetMinHours ?? DEFAULT_RESET_MIN_HOURS,
122
123
  };
123
124
  // Each model is served by the user's plans that serve it, in order, then by
124
125
  // its provider's API key; the first serves and the rest are its fallbacks.
@@ -131,31 +132,45 @@ export async function resolveSelfHostedRouter(deps, request) {
131
132
  const models = [];
132
133
  for (const model of listed) {
133
134
  const base = modelProvider(model);
134
- const candidates = [];
135
135
  const heldKinds = [];
136
136
  const modelHolds = [];
137
- for (const kind of plansServe ? modelSubscriptions(model.id) : []) {
137
+ // A grant serves its plans, then its keys; a router model its own list.
138
+ let sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
139
+ if (grant !== null)
140
+ sources = SELF_HOSTED_DEFAULT_SOURCES;
141
+ const plans = [];
142
+ for (const kind of modelSubscriptions(model.id)) {
138
143
  const client = subscriptionClient(kind);
139
- if (client !== undefined && client !== request.clientHarness)
140
- continue;
141
- const plan = planFor(kind, model.id);
142
- if (plan !== null) {
143
- candidates.push({ provider: subscriptionModelProvider(kind), plan });
144
- continue;
145
- }
146
- const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
147
- if (connected.length === 0)
148
- continue;
149
- heldKinds.push(kind);
150
- for (const credential of connected) {
151
- for (const hold of activeModelHolds(credential, now))
152
- if (hold.model === model.id)
153
- modelHolds.push(hold.until);
154
- }
144
+ plans.push({
145
+ servesClient: client === undefined || client === request.clientHarness,
146
+ candidate: async () => {
147
+ const plan = planFor(kind, model.id);
148
+ if (plan !== null)
149
+ return { provider: subscriptionModelProvider(kind), plan };
150
+ // Held at its limit: remember why, for the error when nothing serves.
151
+ const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
152
+ if (connected.length > 0)
153
+ heldKinds.push(kind);
154
+ for (const credential of connected) {
155
+ for (const hold of activeModelHolds(credential, now)) {
156
+ if (hold.model === model.id)
157
+ modelHolds.push(hold.until);
158
+ }
159
+ }
160
+ return null;
161
+ },
162
+ });
155
163
  }
156
- const key = await apiKey(base);
157
- if (key !== undefined)
158
- candidates.push({ provider: base, key });
164
+ const candidates = await candidatesFor(sources, plans, {
165
+ key: async () => {
166
+ const key = await apiKey(base);
167
+ if (key === undefined)
168
+ return null;
169
+ return { provider: base, key };
170
+ },
171
+ // A self-hosted gateway has no managed keys.
172
+ managed: async () => null,
173
+ });
159
174
  if (candidates.length === 0) {
160
175
  for (const kind of heldKinds)
161
176
  exhausted.add(kind);
@@ -170,6 +185,7 @@ export async function resolveSelfHostedRouter(deps, request) {
170
185
  continue;
171
186
  }
172
187
  models.push(model);
188
+ resolved.model_sources[model.id] = [...sources];
173
189
  const [first, ...rest] = candidates;
174
190
  const firstConfig = candidateConfig(deps, model.id, first);
175
191
  const price = priceFor(model.id, first.provider);
@@ -379,7 +395,8 @@ export async function providersWithoutCredentials(deps, router) {
379
395
  const provider = modelProvider(model);
380
396
  if (missing.has(provider))
381
397
  continue;
382
- const plans = router.subscriptions ? modelSubscriptions(model.id) : [];
398
+ const sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
399
+ const plans = sources.includes("plan") ? modelSubscriptions(model.id) : [];
383
400
  if (plans.some((plan) => deps.subscriptions.list(plan).length > 0))
384
401
  continue;
385
402
  if (await configuredProviderApiKey(deps, provider) === undefined)
@@ -12,7 +12,7 @@ import { refreshStaleUsage } from "./usage.js";
12
12
  const BASE = "/v1/organizations/current/credentials";
13
13
  // Subscription names are env-var-style, which keeps other credential routes
14
14
  // such as `provider-credentials/...` out of these matches.
15
- const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
15
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
16
16
  class HttpError extends Error {
17
17
  status;
18
18
  constructor(status, message) {
@@ -81,13 +81,6 @@ export async function handleSubscriptionRequest(request, deps) {
81
81
  if (action === "/mark-available" && request.method === "POST") {
82
82
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
83
83
  }
84
- if (action === "/auto-reset" && request.method === "PUT") {
85
- const body = await readBody(request);
86
- if (typeof body.enabled !== "boolean")
87
- throw new HttpError(400, "enabled must be true or false.");
88
- const credential = resettable(found(deps.store.getByName(name), name));
89
- return json(200, summary(deps.store, found(deps.store.setAutoRedeemResets(credential.name, body.enabled, now), name), now));
90
- }
91
84
  if (action === "/resets" && request.method === "GET") {
92
85
  const credential = resettable(found(deps.store.getByName(name), name));
93
86
  const resets = await fromProvider(() => listResets({ ...deps, now }, credential));
@@ -146,6 +139,11 @@ async function startSession(deps, body, now) {
146
139
  const isPrivate = body.private ?? reconnecting?.private ?? false;
147
140
  if (typeof isPrivate !== "boolean")
148
141
  throw new HttpError(400, "private must be true or false.");
142
+ // `dari accounts subscription move` names the hosted plan it moves here.
143
+ const movingFrom = body.moving_from ?? null;
144
+ if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
145
+ throw new HttpError(400, "moving_from must be a non-empty string.");
146
+ }
149
147
  const authorization = await startOAuth(provider, { fetch: deps.fetch, now });
150
148
  const session = deps.store.createSession({
151
149
  provider: provider,
@@ -153,6 +151,7 @@ async function startSession(deps, body, now) {
153
151
  credentialName,
154
152
  owner: null,
155
153
  private: isPrivate,
154
+ movingFrom,
156
155
  expiresAt: authorization.expiresAt,
157
156
  }, now);
158
157
  return {
@@ -189,7 +188,7 @@ async function completeSession(deps, body, now) {
189
188
  let elsewhere = [];
190
189
  if (deps.hostedAccounts !== undefined && !reconnectsSameAccount) {
191
190
  try {
192
- elsewhere = await deps.hostedAccounts();
191
+ elsewhere = (await deps.hostedAccounts()).filter((account) => !(account.place === "dari" && account.name === session.movingFrom));
193
192
  }
194
193
  catch (error) {
195
194
  // The provider code is spent: keep the sign-in, checked against this
@@ -294,7 +293,6 @@ function credentialBody(credential, active, now) {
294
293
  // The share of its tightest window the plan last reported used, and
295
294
  // every window as shown; null when it reports none and is not held.
296
295
  usage: usageBody(credential, now),
297
- auto_redeem_resets: credential.autoRedeemResets,
298
296
  };
299
297
  }
300
298
  function resettable(credential) {
@@ -1,13 +1,19 @@
1
1
  import { type BankedReset } from "../../providers/subscription_resets.js";
2
+ import { type Source } from "../../models/sources.js";
2
3
  import type { OAuthFetch } from "./oauth.js";
3
4
  import { type SubscriptionCredential, type SubscriptionStore } from "./store.js";
4
5
  /**
5
6
  * Banked limit resets of the gateway owner's ChatGPT and Claude Code plans, as
6
7
  * hosted Dari spends them (dari-routing-backend subscription_recovery.ts and
7
8
  * the control plane's subscription_resets.py): listed and spent on request,
8
- * and, for a plan whose owner turned it on, spent once every plan of its
9
- * provider is held.
9
+ * and spent once every plan of its provider is held when the model's sources
10
+ * say so (models/sources.ts shouldSpendReset).
10
11
  */
12
+ /** The held model's sources and its router's reset threshold. */
13
+ export type ResetPolicy = {
14
+ sources: readonly Source[];
15
+ resetMinHours: number;
16
+ };
11
17
  /** Where the gateway reaches Claude and ChatGPT: the config's endpoints, or the providers'. */
12
18
  export type ProviderBaseUrls = {
13
19
  claude?: string;
@@ -35,7 +41,7 @@ export declare function useReset(deps: ResetDeps, credential: SubscriptionCreden
35
41
  * After a usage-limit hold on one of the owner's plans: correct a ChatGPT
36
42
  * plan's hold from Codex's report, and once every plan of the provider is
37
43
  * held, release one the provider already serves again or spend one banked
38
- * reset on the plan that would stay out longest, among those with
39
- * auto-reset on. Returns whether a plan of the provider serves now.
44
+ * reset on the plan that would stay out longest, when the policy says so.
45
+ * Returns whether a plan of the provider serves now.
40
46
  */
41
- export declare function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential): Promise<boolean>;
47
+ export declare function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy): Promise<boolean>;
@@ -1,5 +1,6 @@
1
1
  import { claimClaudeReset, claudeOrganizationUuid, claudeResetsFromReport, claudeUsageFromReport, claudeUsageReport, codexResets, codexUsage, consumeCodexReset, nextClaudeGrant, uuidv5, } from "../../providers/subscription_resets.js";
2
2
  import { codexUsageFromReport, fetchCodexUsageReport } from "../../providers/codex_usage.js";
3
+ import { shouldSpendReset } from "../../models/sources.js";
3
4
  import { refreshedAccessToken } from "./access.js";
4
5
  import { isHeld } from "./store.js";
5
6
  export function providerBaseUrls(providers) {
@@ -63,40 +64,44 @@ export async function useReset(deps, credential, resetId) {
63
64
  * After a usage-limit hold on one of the owner's plans: correct a ChatGPT
64
65
  * plan's hold from Codex's report, and once every plan of the provider is
65
66
  * held, release one the provider already serves again or spend one banked
66
- * reset on the plan that would stay out longest, among those with
67
- * auto-reset on. Returns whether a plan of the provider serves now.
67
+ * reset on the plan that would stay out longest, when the policy says so.
68
+ * Returns whether a plan of the provider serves now.
68
69
  */
69
- export async function recoverHeldPlans(deps, held) {
70
+ export async function recoverHeldPlans(deps, held, policy) {
70
71
  const now = deps.now ?? new Date();
71
72
  const serving = () => deps.store.activeCredential(held.provider, now) !== null;
72
73
  try {
73
74
  if (held.provider === "openai_codex")
74
- await recoverCodex(deps, held, now, serving);
75
+ await recoverCodex(deps, held, policy, now, serving);
75
76
  else if (held.provider === "anthropic_claude_code" && !serving())
76
- await recoverClaude(deps, now);
77
+ await recoverClaude(deps, policy, now);
77
78
  }
78
79
  catch (error) {
79
80
  console.error("subscription recovery failed", error instanceof Error ? error.message : String(error));
80
81
  }
81
82
  return serving();
82
83
  }
83
- async function recoverClaude(deps, now) {
84
+ async function recoverClaude(deps, policy, now) {
84
85
  const candidates = deps.store.list("anthropic_claude_code")
85
- .filter((plan) => plan.autoRedeemResets && isHeld(plan, now))
86
+ .filter((plan) => isHeld(plan, now))
86
87
  .sort((a, b) => b.unavailableUntil.getTime() - a.unavailableUntil.getTime());
87
88
  for (const plan of candidates) {
88
- const outcome = await claimOnHold(deps, plan, now);
89
+ const outcome = await claimOnHold(deps, plan, policy, now);
89
90
  // At most one reset per outage.
90
91
  if (outcome !== "skipped")
91
92
  return;
92
93
  }
93
94
  }
94
- async function claimOnHold(deps, plan, now) {
95
+ async function claimOnHold(deps, plan, policy, now) {
95
96
  let token;
96
97
  let grant = null;
97
98
  try {
98
99
  token = await refreshedAccessToken(deps.store, plan, deps);
99
- const grantId = nextClaudeGrant(await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude));
100
+ const report = await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude);
101
+ const resets = claudeResetsFromReport(report);
102
+ if (!shouldSpendReset({ ...policy, returnsAt: plan.unavailableUntil, resets, now }))
103
+ return "skipped";
104
+ const grantId = nextClaudeGrant(report);
100
105
  const organizationUuid = grantId === null ? null : await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
101
106
  if (grantId !== null && organizationUuid !== null)
102
107
  grant = { grantId, organizationUuid };
@@ -127,7 +132,7 @@ async function claimOnHold(deps, plan, now) {
127
132
  // Claude declined without spending a reset; another plan may claim one.
128
133
  return ["not_limited", "ineligible", "cooldown"].includes(result) ? "skipped" : "spent";
129
134
  }
130
- async function recoverCodex(deps, held, now, serving) {
135
+ async function recoverCodex(deps, held, policy, now, serving) {
131
136
  const usages = new Map();
132
137
  const usageOf = async (plan) => {
133
138
  if (!usages.has(plan.id)) {
@@ -160,31 +165,32 @@ async function recoverCodex(deps, held, now, serving) {
160
165
  return;
161
166
  }
162
167
  const back = naturalRecovery(usage, now);
163
- if (plan.autoRedeemResets && back !== null && usage.availableResets > 0)
168
+ if (back !== null && usage.availableResets > 0)
164
169
  candidates.push({ plan, recovery: back });
165
170
  }
166
171
  // The plan that would stay out longest gains the most from a reset.
167
172
  candidates.sort((a, b) => b.recovery.getTime() - a.recovery.getTime());
168
173
  for (const { plan, recovery: back } of candidates) {
169
- const outcome = await redeemOnHold(deps, plan, back, now);
174
+ const outcome = await redeemOnHold(deps, plan, back, policy, now);
170
175
  // At most one credit per outage, even when Codex has not caught up.
171
176
  if (outcome !== "skipped")
172
177
  return;
173
178
  }
174
179
  }
175
- async function redeemOnHold(deps, plan, recovery, now) {
180
+ async function redeemOnHold(deps, plan, recovery, policy, now) {
176
181
  let access;
177
- let creditId;
182
+ let resets;
178
183
  try {
179
184
  access = codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps));
180
- creditId = (await codexResets(deps.fetch, access))[0]?.id;
185
+ resets = await codexResets(deps.fetch, access);
181
186
  }
182
187
  catch (error) {
183
188
  console.error("codex reset credit read failed", error instanceof Error ? error.message : String(error));
184
189
  return "skipped";
185
190
  }
186
- if (creditId === undefined)
191
+ if (!shouldSpendReset({ ...policy, returnsAt: recovery, resets, now }))
187
192
  return "skipped";
193
+ const creditId = resets[0].id;
188
194
  let code;
189
195
  try {
190
196
  // One outage is one exhausted window, so its reset names it.
@@ -38,7 +38,6 @@ export type SubscriptionCredential = {
38
38
  accountId: string | null;
39
39
  owner: string | null;
40
40
  private: boolean;
41
- autoRedeemResets: boolean;
42
41
  accessToken: string;
43
42
  refreshToken: string;
44
43
  expiresAt: Date;
@@ -65,6 +64,7 @@ export type PendingOAuthSession = {
65
64
  credentialName: string | null;
66
65
  owner: string | null;
67
66
  private: boolean;
67
+ movingFrom: string | null;
68
68
  expiresAt: Date;
69
69
  };
70
70
  /** The parts of a plan that say which provider account it is. */
@@ -169,8 +169,6 @@ export declare class SubscriptionStore {
169
169
  rename(name: string, label: string | null, now?: Date): SubscriptionCredential | null;
170
170
  /** Make the gateway owner's subscription private, or not. Null when it is not connected. */
171
171
  setPrivate(name: string, isPrivate: boolean, now?: Date): SubscriptionCredential | null;
172
- /** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
173
- setAutoRedeemResets(name: string, enabled: boolean, now?: Date): SubscriptionCredential | null;
174
172
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
175
173
  disconnect(name: string, owner?: string | null): SubscriptionCredential | null;
176
174
  /**
@@ -62,7 +62,7 @@ const ADDED_COLUMNS = {
62
62
  model_holds: "TEXT",
63
63
  owner: "TEXT",
64
64
  private: "INTEGER",
65
- auto_redeem_resets: "INTEGER",
65
+ auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
66
66
  };
67
67
  export class SubscriptionStore {
68
68
  db;
@@ -127,10 +127,11 @@ export class SubscriptionStore {
127
127
  credential_name TEXT,
128
128
  owner TEXT,
129
129
  private INTEGER,
130
+ moving_from TEXT,
130
131
  expires_at INTEGER NOT NULL
131
132
  )`);
132
133
  const sessionColumns = new Set(db.query("PRAGMA table_info(subscription_oauth_sessions)").all().map((column) => column.name));
133
- for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"]]) {
134
+ for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"], ["moving_from", "TEXT"]]) {
134
135
  if (!sessionColumns.has(column))
135
136
  db.run(`ALTER TABLE subscription_oauth_sessions ADD COLUMN ${column} ${type}`);
136
137
  }
@@ -428,18 +429,6 @@ export class SubscriptionStore {
428
429
  this.onChange?.("plans");
429
430
  return this.get(credential.id);
430
431
  }
431
- /** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
432
- setAutoRedeemResets(name, enabled, now = new Date()) {
433
- const credential = this.getByName(name);
434
- if (credential === null)
435
- return null;
436
- this.db.run("UPDATE subscription_credentials SET auto_redeem_resets = ?, updated_at = ? WHERE id = ?", [
437
- enabled ? 1 : 0,
438
- now.getTime(),
439
- credential.id,
440
- ]);
441
- return this.get(credential.id);
442
- }
443
432
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
444
433
  disconnect(name, owner = null) {
445
434
  const credential = this.getByName(name, owner);
@@ -500,14 +489,15 @@ export class SubscriptionStore {
500
489
  createSession(session, now = new Date()) {
501
490
  const token = randomBytes(32).toString("base64url");
502
491
  this.db.run("DELETE FROM subscription_oauth_sessions WHERE expires_at <= ?", [now.getTime()]);
503
- this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, expires_at)
504
- VALUES (?, ?, ?, ?, ?, ?, ?)`, [
492
+ this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, moving_from, expires_at)
493
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
505
494
  token,
506
495
  session.provider,
507
496
  this.seal(JSON.stringify(session.flow), flowPlace(token)),
508
497
  session.credentialName,
509
498
  session.owner,
510
499
  session.private ? 1 : 0,
500
+ session.movingFrom,
511
501
  session.expiresAt.getTime(),
512
502
  ]);
513
503
  return { token, ...session };
@@ -526,6 +516,7 @@ export class SubscriptionStore {
526
516
  credentialName: row.credential_name,
527
517
  owner: row.owner,
528
518
  private: row.private === 1,
519
+ movingFrom: row.moving_from,
529
520
  expiresAt: new Date(row.expires_at),
530
521
  };
531
522
  }
@@ -626,7 +617,6 @@ function credentialFromRow(row) {
626
617
  accountId: row.account_id,
627
618
  owner: row.owner,
628
619
  private: row.private === 1,
629
- autoRedeemResets: row.auto_redeem_resets === 1,
630
620
  accessToken: row.access_token,
631
621
  refreshToken: row.refresh_token,
632
622
  expiresAt: new Date(row.expires_at),
@@ -168,9 +168,7 @@ export function providerAuthForSelectedModel(args) {
168
168
  }
169
169
  if (key)
170
170
  return { type: "bearer", apiKey: key };
171
- const source = args.credentials.provider_key_sources?.[provider] ?? "user";
172
- const prefix = source === "managed" ? "Dari-managed" : "stored";
173
- throw new HttpError(401, `No ${prefix} ${providerLabel(provider)} provider credential is configured for this router.`, "missing_provider_key");
171
+ throw new HttpError(401, `No stored ${providerLabel(provider)} provider credential is configured for this router.`, "missing_provider_key");
174
172
  }
175
173
  function isAwsAssumeRoleProviderAuth(value) {
176
174
  return (isRecord(value)
@@ -6,7 +6,7 @@
6
6
  import { linkRequestRecorded, linkRequestStarted } from "../link/in_flight.js";
7
7
  import { selectPrefixHit, } from "@mupt-ai/dari-router/policy-engine";
8
8
  import { errorCode } from "../http/errors.js";
9
- import { executionProviderForModel } from "../models/execution_provider.js";
9
+ import { executionProviderForModel, keySourceForModel } from "../models/execution_provider.js";
10
10
  import { isBackgroundRequest, } from "../interaction/types.js";
11
11
  import { captureOperationalError } from "../observability/errors.js";
12
12
  import { gatewayPlatform } from "../platform/platform.js";
@@ -229,8 +229,8 @@ export class RequestReporter {
229
229
  const selectedProvider = outcome.providerExecution?.provider ?? (selectedModel
230
230
  ? executionProviderForModel(a.credentials, selectedModel)
231
231
  : null);
232
- const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel && selectedProvider
233
- ? (a.credentials.provider_key_sources?.[selectedProvider] ?? "user")
232
+ const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
233
+ ? keySourceForModel(a.credentials, selectedModel)
234
234
  : null);
235
235
  const selectedEstimate = a.costEstimates.find((item) => item.model === selectedModel &&
236
236
  item.reasoning_effort === reasoningBucket);
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Source } from "./models/sources.js";
1
2
  import type { CustomRouterConfig, Provider, ReasoningEffort, RouterEval, RouterEvalScore, RouterModelPrice, RouterPrefixHit, RoutingDecision, RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
2
3
  export type ProviderKeySource = "user" | "managed" | "subscription";
3
4
  export type BearerProviderAuth = {
@@ -25,6 +26,7 @@ export type ProviderCredential = {
25
26
  headers?: Record<string, string>;
26
27
  subscription?: SubscriptionKind;
27
28
  credentialId?: string;
29
+ managed?: true;
28
30
  };
29
31
  export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
30
32
  export type AwsProviderAuth = AwsSigV4ProviderAuth | AwsAssumeRoleProviderAuth;
@@ -67,6 +69,7 @@ export type ResolvedRouterModelConfig = {
67
69
  export type ModelFallback = {
68
70
  config: ResolvedRouterModelConfig;
69
71
  subscription?: SubscriptionKind | null;
72
+ managed?: true;
70
73
  };
71
74
  /** Why a Dari Link grant cannot serve one provider's models now. */
72
75
  export type LinkUnavailable = {
@@ -86,6 +89,7 @@ export type ResolvedRouter = {
86
89
  provider_keys: Partial<Record<Provider, string>>;
87
90
  provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
88
91
  provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
92
+ managed_keys?: Partial<Record<Provider, string>>;
89
93
  provider_credentials?: Record<string, ProviderCredential>;
90
94
  model_fallbacks?: Record<string, ModelFallback[]>;
91
95
  link_key_credential_ids?: Partial<Record<Provider, string>>;
@@ -107,6 +111,8 @@ export type ResolvedRouter = {
107
111
  session_pinning?: boolean;
108
112
  native_compaction?: boolean;
109
113
  primary_retries?: number;
114
+ model_sources?: Record<string, Source[]>;
115
+ reset_min_hours?: number;
110
116
  strict?: boolean;
111
117
  strict_providers?: string[];
112
118
  evals?: RouterEval[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.355",
3
+ "version": "1.0.357",
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.355",
55
+ "@mupt-ai/dari-router": "1.0.357",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -19,6 +19,7 @@ import { anthropicModelsResponse } from "./anthropic_models.js";
19
19
  import { namedClientHarness } from "./client_harness.js";
20
20
  import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
21
21
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
22
+ import { GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
22
23
 
23
24
  export async function handleModels(request: Request, routerId: string): Promise<Response> {
24
25
  // Anthropic SDK clients always send anthropic-version, and API-key probes
@@ -39,9 +40,15 @@ export async function handleModels(request: Request, routerId: string): Promise<
39
40
  // names its own version in the query, as only Codex does.
40
41
  const codexDirect = !anthropicClient && query.has("client_version");
41
42
  const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
43
+ const gatewayId = request.headers.get(GATEWAY_ID_HEADER)?.trim();
42
44
  let router;
43
45
  try {
44
- router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
46
+ router = await resolveRouter({
47
+ routerId,
48
+ apiKey,
49
+ ...(clientHarness ? { clientHarness } : {}),
50
+ ...(gatewayId ? { gatewayId } : {}),
51
+ });
45
52
  } catch (error) {
46
53
  // A Dari Link grant that can serve this client nothing now lists no
47
54
  // models; a child token still lists its one model.
@@ -121,6 +121,7 @@ export function selfHostedLink(
121
121
  credentialName: null,
122
122
  owner: newSubject(),
123
123
  private: false,
124
+ movingFrom: null,
124
125
  expiresAt: authorization.expiresAt,
125
126
  });
126
127
  return { session: session.token, authorizationUrl: authorization.authorizationUrl, userCode: authorization.userCode };
@@ -16,17 +16,17 @@ export function executionProviderForModel(
16
16
  }
17
17
 
18
18
  /**
19
- * The key that serves a model on a resolved router: a platform-supplied
20
- * credential first, then the resolved provider key. Missing declarations are
21
- * user-owned so unknown platform data cannot trigger managed-key billing.
19
+ * Who pays for the key that serves a model: a supplied plan, Dari's managed
20
+ * key (billed to credits), or otherwise the router's own saved key.
22
21
  */
23
22
  export function keySourceForModel(
24
23
  credentials: ResolvedRouter,
25
24
  model: string,
26
25
  ): ProviderKeySource {
27
26
  const supplied = credentials.provider_credentials?.[model];
28
- if (supplied) return supplied.subscription ? "subscription" : "user";
29
- return credentials.provider_key_sources?.[executionProviderForModel(credentials, model)] ?? "user";
27
+ if (supplied?.subscription) return "subscription";
28
+ if (supplied?.managed) return "managed";
29
+ return "user";
30
30
  }
31
31
 
32
32
  /**