@mupt-ai/dari-gateway 1.0.356 → 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 (40) hide show
  1. package/README.md +4 -3
  2. package/dist/models/execution_provider.d.ts +2 -3
  3. package/dist/models/execution_provider.js +7 -6
  4. package/dist/models/sources.d.ts +37 -0
  5. package/dist/models/sources.js +88 -0
  6. package/dist/platform/platform.d.ts +4 -1
  7. package/dist/providers/execution.js +9 -3
  8. package/dist/providers/provider_call.d.ts +3 -0
  9. package/dist/providers/provider_call.js +3 -5
  10. package/dist/runtime/routed_runtime.js +12 -5
  11. package/dist/self_host/config.d.ts +11 -5
  12. package/dist/self_host/config.js +22 -6
  13. package/dist/self_host/connected.js +1 -1
  14. package/dist/self_host/platform.js +2 -2
  15. package/dist/self_host/resolve.js +41 -24
  16. package/dist/self_host/subscriptions/http.js +1 -9
  17. package/dist/self_host/subscriptions/resets.d.ts +11 -5
  18. package/dist/self_host/subscriptions/resets.js +23 -17
  19. package/dist/self_host/subscriptions/store.d.ts +0 -3
  20. package/dist/self_host/subscriptions/store.js +1 -14
  21. package/dist/strategies/routing.js +1 -3
  22. package/dist/telemetry/report.js +3 -3
  23. package/dist/types.d.ts +6 -0
  24. package/package.json +2 -2
  25. package/src/models/execution_provider.ts +5 -5
  26. package/src/models/sources.ts +114 -0
  27. package/src/platform/platform.ts +6 -1
  28. package/src/providers/execution.ts +9 -3
  29. package/src/providers/provider_call.ts +7 -10
  30. package/src/runtime/routed_runtime.ts +10 -4
  31. package/src/self_host/config.ts +34 -11
  32. package/src/self_host/connected.ts +1 -1
  33. package/src/self_host/platform.ts +2 -2
  34. package/src/self_host/resolve.ts +36 -20
  35. package/src/self_host/subscriptions/http.ts +1 -8
  36. package/src/self_host/subscriptions/resets.ts +27 -19
  37. package/src/self_host/subscriptions/store.ts +1 -18
  38. package/src/strategies/routing.ts +1 -3
  39. package/src/telemetry/report.ts +3 -3
  40. package/src/types.ts +14 -0
@@ -6,6 +6,7 @@ import {
6
6
  } from "@mupt-ai/dari-router/policy-engine";
7
7
 
8
8
  import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
9
+ import { checkSources, DEFAULT_RESET_MIN_HOURS, type Source } from "../models/sources.js";
9
10
  import { otherModelProviders, providerModel } from "../models/canonical.js";
10
11
  import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } from "../types.js";
11
12
 
@@ -22,7 +23,9 @@ import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } f
22
23
  * agentModels: # optional: a coding agent's own list
23
24
  * codex:
24
25
  * - openai/gpt-6.2-sol
25
- * subscriptions: true # serve with connected Claude Code / ChatGPT plans
26
+ * - id: anthropic/claude-opus-5-5
27
+ * sources: [plan, reset, key] # optional; default [plan, key]
28
+ * resetMinHours: 24 # spend a banked reset only when a plan is out this long
26
29
  * sessionPinning: false # route each session and subagent once, then keep its model
27
30
  * roleModels: # optional: serve an agent role one model, without routing
28
31
  * main: anthropic/claude-fable-5-2
@@ -78,7 +81,8 @@ export type RouterConfig = {
78
81
  // A coding agent's own models, served to it in place of `models`.
79
82
  agentModels: Partial<Record<ClientHarness, RouterModelConfig[]>>;
80
83
  retries: number;
81
- subscriptions: boolean;
84
+ // Spend a banked reset only when the plan would otherwise stay out this long.
85
+ resetMinHours: number;
82
86
  sessionPinning: boolean;
83
87
  nativeCompaction: boolean;
84
88
  zdr: boolean;
@@ -98,6 +102,9 @@ export type RouterModelConfig = {
98
102
  // The provider that serves the model when not the one its id names, such as
99
103
  // `opencode-go` for `deepseek-ai/DeepSeek-V4.1-Flash-1017`.
100
104
  provider?: string;
105
+ // Where the model is served from, in order (models/sources.ts); absent
106
+ // means SELF_HOSTED_DEFAULT_SOURCES.
107
+ sources?: Source[];
101
108
  };
102
109
 
103
110
  /** The provider that serves a router's model, whose credential it needs. */
@@ -226,7 +233,7 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
226
233
  roleModel(field, model, [models, ...Object.values(agentModels)].flat())),
227
234
  rolePrompts: parseRoleMap(`routers.${id}.rolePrompts`, raw.rolePrompts, rolePrompt),
228
235
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
229
- subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
236
+ resetMinHours: optionalResetMinHours(raw.resetMinHours, `routers.${id}.resetMinHours`),
230
237
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
231
238
  nativeCompaction: optionalBoolean(raw.nativeCompaction, `routers.${id}.nativeCompaction`) ?? false,
232
239
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
@@ -306,6 +313,11 @@ function parseModel(routerId: string, raw: unknown): RouterModelConfig {
306
313
  );
307
314
  }
308
315
  const model: RouterModelConfig = { id: entry.id };
316
+ if (entry.sources != null) {
317
+ const checked = checkSources(entry.sources);
318
+ if ("error" in checked) throw new Error(`Model ${entry.id} on router "${routerId}": ${checked.error}`);
319
+ model.sources = checked.sources;
320
+ }
309
321
  if (entry.thinking != null) {
310
322
  if (
311
323
  !Array.isArray(entry.thinking) ||
@@ -337,6 +349,14 @@ function optionalBoolean(value: unknown, field: string): boolean | undefined {
337
349
  return value;
338
350
  }
339
351
 
352
+ function optionalResetMinHours(value: unknown, field: string): number {
353
+ if (value === undefined) return DEFAULT_RESET_MIN_HOURS;
354
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
355
+ throw new Error(`${field} must be a number of hours, 0 or more.`);
356
+ }
357
+ return value;
358
+ }
359
+
340
360
  function optionalRetries(value: unknown, field: string): number | undefined {
341
361
  if (value === undefined) return undefined;
342
362
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 5) {
@@ -351,8 +371,10 @@ function optionalRetries(value: unknown, field: string): number | undefined {
351
371
  *
352
372
  * ```yaml
353
373
  * name: Opus 5.5 + DeepSeek Subagents
374
+ * reset_min_hours: 24
354
375
  * models:
355
- * - anthropic/claude-opus-5-5
376
+ * - id: anthropic/claude-opus-5-5
377
+ * sources: [plan, reset, key] # default [plan, key]
356
378
  * - id: deepseek-ai/DeepSeek-V4.1-Flash-1017
357
379
  * thinking: [high]
358
380
  * provider: opencode-go # served by this provider, not the one its id names
@@ -365,15 +387,15 @@ function optionalRetries(value: unknown, field: string): number | undefined {
365
387
  * agents: { codex: [openai/gpt-6.1-sol] }
366
388
  * ```
367
389
  *
368
- * The gateway pays with connected subscriptions when `payment.allow` lists
369
- * `subscription`, and otherwise with provider API keys; it has no credits.
390
+ * Each model's `sources` decide whether connected plans or provider API keys
391
+ * serve it; the gateway has no credits. `payment` is checked and left unused.
370
392
  * `hosted` settings and a model's `fast` apply only on hosted Dari, and are
371
393
  * accepted and left unused; `routing.rules` runs only there and is refused.
372
394
  */
373
395
  export type RouterSpec = { name: string; router: RouterConfig };
374
396
 
375
- const SPEC_FIELDS = ["name", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
376
- const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast"];
397
+ const SPEC_FIELDS = ["name", "reset_min_hours", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
398
+ const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast", "sources"];
377
399
  const PAYMENT_KINDS = ["subscription", "key", "credits"];
378
400
  const SPEC_NAME_MAX_LENGTH = 120;
379
401
 
@@ -427,7 +449,7 @@ export function parseRouterSpec(id: string, raw: unknown): RouterSpec {
427
449
  roleModel(`${field}.model`, model, [models, ...Object.values(agentModels)].flat())),
428
450
  rolePrompts: parseRoleMap("roles", roleValues("prompt"), (field, prompt) => rolePrompt(`${field}.prompt`, prompt)),
429
451
  retries: optionalRetries(routing.retries ?? undefined, "routing.retries") ?? 1,
430
- subscriptions: allow.includes("subscription"),
452
+ resetMinHours: optionalResetMinHours(spec.reset_min_hours ?? undefined, "reset_min_hours"),
431
453
  sessionPinning: optionalBoolean(routing.session_pinning ?? undefined, "routing.session_pinning") ?? false,
432
454
  nativeCompaction: optionalBoolean(spec.native_compaction ?? undefined, "native_compaction") ?? false,
433
455
  zdr: false,
@@ -446,11 +468,12 @@ export function routerSpecFor(name: string, router: RouterConfig): Record<string
446
468
  const agents = Object.entries(router.agentModels);
447
469
  return {
448
470
  name,
471
+ reset_min_hours: router.resetMinHours,
449
472
  models: router.models.map(specModel),
450
473
  ...(Object.keys(roles).length > 0 ? { roles } : {}),
451
474
  routing: { session_pinning: router.sessionPinning, retries: router.retries },
452
475
  // The gateway pays with plans and API keys; it has no credits.
453
- payment: { allow: router.subscriptions ? ["subscription", "key"] : ["key"] },
476
+ payment: { allow: ["subscription", "key"] },
454
477
  native_compaction: router.nativeCompaction,
455
478
  ...(agents.length > 0
456
479
  ? { agents: Object.fromEntries(agents.map(([agent, models]) => [agent, models!.map(specModel)])) }
@@ -465,7 +488,7 @@ export function routerSpecYaml(spec: unknown): string {
465
488
  }
466
489
 
467
490
  function specModel(model: RouterModelConfig): string | Record<string, unknown> {
468
- return model.thinking === undefined && model.provider === undefined ? model.id : { ...model };
491
+ return model.thinking === undefined && model.provider === undefined && model.sources === undefined ? model.id : { ...model };
469
492
  }
470
493
 
471
494
  // A spec section as a map, refusing fields the spec does not have; absent is empty.
@@ -137,7 +137,7 @@ async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetc
137
137
  if (models.length === 0) throw new Error("it lists no models");
138
138
  return parseGatewayConfig({
139
139
  routers: {
140
- [routerId]: { models, subscriptions: true, nativeCompaction: catalog.remote_compaction === "v2" },
140
+ [routerId]: { models, nativeCompaction: catalog.remote_compaction === "v2" },
141
141
  },
142
142
  }).routers[routerId]!;
143
143
  }
@@ -63,7 +63,7 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
63
63
  apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
64
64
  };
65
65
  },
66
- async markSubscriptionUnavailable({ credentialId, limit, linkGrantId }) {
66
+ async markSubscriptionUnavailable({ credentialId, limit, linkGrantId, sources, resetMinHours }) {
67
67
  if (credentialId === undefined) return false;
68
68
  if (limit.model !== undefined) {
69
69
  return deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
@@ -79,7 +79,7 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
79
79
  store: deps.subscriptions,
80
80
  fetch: deps.fetch,
81
81
  baseUrls: providerBaseUrls(deps.config.providers),
82
- }, held);
82
+ }, held, { sources, resetMinHours });
83
83
  }
84
84
  // A grant's retry may use only its own subscriptions.
85
85
  const provider = deps.subscriptions.get(credentialId)?.provider;
@@ -19,6 +19,7 @@ import {
19
19
  } from "../models/subscriptions.js";
20
20
  import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
21
21
  import { gatewayFor } from "../models/gateways.js";
22
+ import { candidatesFor, DEFAULT_RESET_MIN_HOURS, SELF_HOSTED_DEFAULT_SOURCES, type PlanOption, type Source } from "../models/sources.js";
22
23
  import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
23
24
  import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
24
25
  import type {
@@ -124,9 +125,6 @@ export async function resolveSelfHostedRouter(
124
125
  const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
125
126
  const now = new Date();
126
127
  const servable = grant === null ? undefined : new Set(grant.credentialIds);
127
- // A grant uses the subscriptions its user chose, whatever the router allows.
128
- const plansServe = router?.subscriptions === true || grant !== null;
129
-
130
128
  // The plan of each kind that serves this conversation, chosen once.
131
129
  const conversationPlans = new Map<SubscriptionProvider, SubscriptionCredential | null>();
132
130
  const conversationPlan = (kind: SubscriptionProvider) => {
@@ -188,6 +186,8 @@ export async function resolveSelfHostedRouter(
188
186
  model_thinking_levels: thinkingLevels(listed),
189
187
  model_prices: {},
190
188
  model_configs: {},
189
+ model_sources: {},
190
+ reset_min_hours: router?.resetMinHours ?? DEFAULT_RESET_MIN_HOURS,
191
191
  };
192
192
 
193
193
  // Each model is served by the user's plans that serve it, in order, then by
@@ -201,26 +201,40 @@ export async function resolveSelfHostedRouter(
201
201
  const models: RouterModelConfig[] = [];
202
202
  for (const model of listed) {
203
203
  const base = modelProvider(model);
204
- const candidates: Candidate[] = [];
205
204
  const heldKinds: SubscriptionProvider[] = [];
206
205
  const modelHolds: Date[] = [];
207
- for (const kind of plansServe ? modelSubscriptions(model.id) : []) {
206
+ // A grant serves its plans, then its keys; a router model its own list.
207
+ let sources: readonly Source[] = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
208
+ if (grant !== null) sources = SELF_HOSTED_DEFAULT_SOURCES;
209
+ const plans: PlanOption<Candidate>[] = [];
210
+ for (const kind of modelSubscriptions(model.id)) {
208
211
  const client = subscriptionClient(kind);
209
- if (client !== undefined && client !== request.clientHarness) continue;
210
- const plan = planFor(kind, model.id);
211
- if (plan !== null) {
212
- candidates.push({ provider: subscriptionModelProvider(kind), plan });
213
- continue;
214
- }
215
- const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
216
- if (connected.length === 0) continue;
217
- heldKinds.push(kind);
218
- for (const credential of connected) {
219
- for (const hold of activeModelHolds(credential, now)) if (hold.model === model.id) modelHolds.push(hold.until);
220
- }
212
+ plans.push({
213
+ servesClient: client === undefined || client === request.clientHarness,
214
+ candidate: async () => {
215
+ const plan = planFor(kind, model.id);
216
+ if (plan !== null) return { provider: subscriptionModelProvider(kind), plan };
217
+ // Held at its limit: remember why, for the error when nothing serves.
218
+ const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
219
+ if (connected.length > 0) heldKinds.push(kind);
220
+ for (const credential of connected) {
221
+ for (const hold of activeModelHolds(credential, now)) {
222
+ if (hold.model === model.id) modelHolds.push(hold.until);
223
+ }
224
+ }
225
+ return null;
226
+ },
227
+ });
221
228
  }
222
- const key = await apiKey(base);
223
- if (key !== undefined) candidates.push({ provider: base, key });
229
+ const candidates = await candidatesFor(sources, plans, {
230
+ key: async () => {
231
+ const key = await apiKey(base);
232
+ if (key === undefined) return null;
233
+ return { provider: base, key };
234
+ },
235
+ // A self-hosted gateway has no managed keys.
236
+ managed: async () => null,
237
+ });
224
238
 
225
239
  if (candidates.length === 0) {
226
240
  for (const kind of heldKinds) exhausted.add(kind);
@@ -233,6 +247,7 @@ export async function resolveSelfHostedRouter(
233
247
  continue;
234
248
  }
235
249
  models.push(model);
250
+ resolved.model_sources![model.id] = [...sources];
236
251
  const [first, ...rest] = candidates;
237
252
  const firstConfig = candidateConfig(deps, model.id, first!);
238
253
  const price = priceFor(model.id, first!.provider);
@@ -461,7 +476,8 @@ export async function providersWithoutCredentials(
461
476
  for (const model of allRouterModels(router)) {
462
477
  const provider = modelProvider(model);
463
478
  if (missing.has(provider)) continue;
464
- const plans = router.subscriptions ? modelSubscriptions(model.id) : [];
479
+ const sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
480
+ const plans = sources.includes("plan") ? modelSubscriptions(model.id) : [];
465
481
  if (plans.some((plan) => deps.subscriptions.list(plan).length > 0)) continue;
466
482
  if (await configuredProviderApiKey(deps, provider) === undefined) missing.add(provider);
467
483
  }
@@ -43,7 +43,7 @@ export type SubscriptionHttpDeps = {
43
43
  const BASE = "/v1/organizations/current/credentials";
44
44
  // Subscription names are env-var-style, which keeps other credential routes
45
45
  // such as `provider-credentials/...` out of these matches.
46
- const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
46
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
47
47
 
48
48
  class HttpError extends Error {
49
49
  constructor(readonly status: number, message: string) {
@@ -108,12 +108,6 @@ export async function handleSubscriptionRequest(
108
108
  if (action === "/mark-available" && request.method === "POST") {
109
109
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
110
110
  }
111
- if (action === "/auto-reset" && request.method === "PUT") {
112
- const body = await readBody(request);
113
- if (typeof body.enabled !== "boolean") throw new HttpError(400, "enabled must be true or false.");
114
- const credential = resettable(found(deps.store.getByName(name), name));
115
- return json(200, summary(deps.store, found(deps.store.setAutoRedeemResets(credential.name, body.enabled, now), name), now));
116
- }
117
111
  if (action === "/resets" && request.method === "GET") {
118
112
  const credential = resettable(found(deps.store.getByName(name), name));
119
113
  const resets = await fromProvider(() => listResets({ ...deps, now }, credential));
@@ -331,7 +325,6 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
331
325
  // The share of its tightest window the plan last reported used, and
332
326
  // every window as shown; null when it reports none and is not held.
333
327
  usage: usageBody(credential, now),
334
- auto_redeem_resets: credential.autoRedeemResets,
335
328
  };
336
329
  }
337
330
 
@@ -14,6 +14,7 @@ import {
14
14
  type CodexUsage,
15
15
  } from "../../providers/subscription_resets.js";
16
16
  import { codexUsageFromReport, fetchCodexUsageReport } from "../../providers/codex_usage.js";
17
+ import { shouldSpendReset, type Source } from "../../models/sources.js";
17
18
  import { refreshedAccessToken } from "./access.js";
18
19
  import type { OAuthFetch, SubscriptionProvider } from "./oauth.js";
19
20
  import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./store.js";
@@ -22,10 +23,13 @@ import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./s
22
23
  * Banked limit resets of the gateway owner's ChatGPT and Claude Code plans, as
23
24
  * hosted Dari spends them (dari-routing-backend subscription_recovery.ts and
24
25
  * the control plane's subscription_resets.py): listed and spent on request,
25
- * and, for a plan whose owner turned it on, spent once every plan of its
26
- * provider is held.
26
+ * and spent once every plan of its provider is held when the model's sources
27
+ * say so (models/sources.ts shouldSpendReset).
27
28
  */
28
29
 
30
+ /** The held model's sources and its router's reset threshold. */
31
+ export type ResetPolicy = { sources: readonly Source[]; resetMinHours: number };
32
+
29
33
  /** Where the gateway reaches Claude and ChatGPT: the config's endpoints, or the providers'. */
30
34
  export type ProviderBaseUrls = { claude?: string; codex?: string };
31
35
 
@@ -97,38 +101,41 @@ export async function useReset(deps: ResetDeps, credential: SubscriptionCredenti
97
101
  * After a usage-limit hold on one of the owner's plans: correct a ChatGPT
98
102
  * plan's hold from Codex's report, and once every plan of the provider is
99
103
  * held, release one the provider already serves again or spend one banked
100
- * reset on the plan that would stay out longest, among those with
101
- * auto-reset on. Returns whether a plan of the provider serves now.
104
+ * reset on the plan that would stay out longest, when the policy says so.
105
+ * Returns whether a plan of the provider serves now.
102
106
  */
103
- export async function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential): Promise<boolean> {
107
+ export async function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy): Promise<boolean> {
104
108
  const now = deps.now ?? new Date();
105
109
  const serving = () => deps.store.activeCredential(held.provider, now) !== null;
106
110
  try {
107
- if (held.provider === "openai_codex") await recoverCodex(deps, held, now, serving);
108
- else if (held.provider === "anthropic_claude_code" && !serving()) await recoverClaude(deps, now);
111
+ if (held.provider === "openai_codex") await recoverCodex(deps, held, policy, now, serving);
112
+ else if (held.provider === "anthropic_claude_code" && !serving()) await recoverClaude(deps, policy, now);
109
113
  } catch (error) {
110
114
  console.error("subscription recovery failed", error instanceof Error ? error.message : String(error));
111
115
  }
112
116
  return serving();
113
117
  }
114
118
 
115
- async function recoverClaude(deps: ResetDeps, now: Date): Promise<void> {
119
+ async function recoverClaude(deps: ResetDeps, policy: ResetPolicy, now: Date): Promise<void> {
116
120
  const candidates = deps.store.list("anthropic_claude_code")
117
- .filter((plan) => plan.autoRedeemResets && isHeld(plan, now))
121
+ .filter((plan) => isHeld(plan, now))
118
122
  .sort((a, b) => b.unavailableUntil!.getTime() - a.unavailableUntil!.getTime());
119
123
  for (const plan of candidates) {
120
- const outcome = await claimOnHold(deps, plan, now);
124
+ const outcome = await claimOnHold(deps, plan, policy, now);
121
125
  // At most one reset per outage.
122
126
  if (outcome !== "skipped") return;
123
127
  }
124
128
  }
125
129
 
126
- async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, now: Date): Promise<"skipped" | "spent" | "restored"> {
130
+ async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, policy: ResetPolicy, now: Date): Promise<"skipped" | "spent" | "restored"> {
127
131
  let token: string;
128
132
  let grant: { grantId: string; organizationUuid: string } | null = null;
129
133
  try {
130
134
  token = await refreshedAccessToken(deps.store, plan, deps);
131
- const grantId = nextClaudeGrant(await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude));
135
+ const report = await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude);
136
+ const resets = claudeResetsFromReport(report);
137
+ if (!shouldSpendReset({ ...policy, returnsAt: plan.unavailableUntil!, resets, now })) return "skipped";
138
+ const grantId = nextClaudeGrant(report);
132
139
  const organizationUuid = grantId === null ? null : await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
133
140
  if (grantId !== null && organizationUuid !== null) grant = { grantId, organizationUuid };
134
141
  } catch (error) {
@@ -156,7 +163,7 @@ async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, now: D
156
163
  return ["not_limited", "ineligible", "cooldown"].includes(result) ? "skipped" : "spent";
157
164
  }
158
165
 
159
- async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, now: Date, serving: () => boolean): Promise<void> {
166
+ async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy, now: Date, serving: () => boolean): Promise<void> {
160
167
  const usages = new Map<string, CodexUsage | null>();
161
168
  const usageOf = async (plan: SubscriptionCredential) => {
162
169
  if (!usages.has(plan.id)) {
@@ -185,28 +192,29 @@ async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, now:
185
192
  return;
186
193
  }
187
194
  const back = naturalRecovery(usage, now);
188
- if (plan.autoRedeemResets && back !== null && usage.availableResets > 0) candidates.push({ plan, recovery: back });
195
+ if (back !== null && usage.availableResets > 0) candidates.push({ plan, recovery: back });
189
196
  }
190
197
  // The plan that would stay out longest gains the most from a reset.
191
198
  candidates.sort((a, b) => b.recovery.getTime() - a.recovery.getTime());
192
199
  for (const { plan, recovery: back } of candidates) {
193
- const outcome = await redeemOnHold(deps, plan, back, now);
200
+ const outcome = await redeemOnHold(deps, plan, back, policy, now);
194
201
  // At most one credit per outage, even when Codex has not caught up.
195
202
  if (outcome !== "skipped") return;
196
203
  }
197
204
  }
198
205
 
199
- async function redeemOnHold(deps: ResetDeps, plan: SubscriptionCredential, recovery: Date, now: Date): Promise<"skipped" | "spent" | "restored"> {
206
+ async function redeemOnHold(deps: ResetDeps, plan: SubscriptionCredential, recovery: Date, policy: ResetPolicy, now: Date): Promise<"skipped" | "spent" | "restored"> {
200
207
  let access: CodexAccess;
201
- let creditId: string | undefined;
208
+ let resets: BankedReset[];
202
209
  try {
203
210
  access = codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps));
204
- creditId = (await codexResets(deps.fetch, access))[0]?.id;
211
+ resets = await codexResets(deps.fetch, access);
205
212
  } catch (error) {
206
213
  console.error("codex reset credit read failed", error instanceof Error ? error.message : String(error));
207
214
  return "skipped";
208
215
  }
209
- if (creditId === undefined) return "skipped";
216
+ if (!shouldSpendReset({ ...policy, returnsAt: recovery, resets, now })) return "skipped";
217
+ const creditId = resets[0]!.id;
210
218
  let code: string;
211
219
  try {
212
220
  // One outage is one exhausted window, so its reset names it.
@@ -53,9 +53,6 @@ export type SubscriptionCredential = {
53
53
  // Kept off hosted Dari: a gateway connected to it neither serves nor
54
54
  // reports the plan.
55
55
  private: boolean;
56
- // Whether routing may spend the plan's banked limit resets once every plan
57
- // of its provider is held (ChatGPT and Claude Code).
58
- autoRedeemResets: boolean;
59
56
  accessToken: string;
60
57
  refreshToken: string;
61
58
  expiresAt: Date;
@@ -168,7 +165,6 @@ type CredentialRow = {
168
165
  account_id: string | null;
169
166
  owner: string | null;
170
167
  private: number | null;
171
- auto_redeem_resets: number | null;
172
168
  access_token: string;
173
169
  refresh_token: string;
174
170
  expires_at: number;
@@ -195,7 +191,7 @@ const ADDED_COLUMNS = {
195
191
  model_holds: "TEXT",
196
192
  owner: "TEXT",
197
193
  private: "INTEGER",
198
- auto_redeem_resets: "INTEGER",
194
+ auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
199
195
  } as const;
200
196
 
201
197
  type SessionRow = {
@@ -634,18 +630,6 @@ export class SubscriptionStore {
634
630
  return this.get(credential.id);
635
631
  }
636
632
 
637
- /** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
638
- setAutoRedeemResets(name: string, enabled: boolean, now = new Date()): SubscriptionCredential | null {
639
- const credential = this.getByName(name);
640
- if (credential === null) return null;
641
- this.db.run("UPDATE subscription_credentials SET auto_redeem_resets = ?, updated_at = ? WHERE id = ?", [
642
- enabled ? 1 : 0,
643
- now.getTime(),
644
- credential.id,
645
- ]);
646
- return this.get(credential.id);
647
- }
648
-
649
633
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
650
634
  disconnect(name: string, owner: string | null = null): SubscriptionCredential | null {
651
635
  const credential = this.getByName(name, owner);
@@ -859,7 +843,6 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
859
843
  accountId: row.account_id,
860
844
  owner: row.owner,
861
845
  private: row.private === 1,
862
- autoRedeemResets: row.auto_redeem_resets === 1,
863
846
  accessToken: row.access_token,
864
847
  refreshToken: row.refresh_token,
865
848
  expiresAt: new Date(row.expires_at),
@@ -313,11 +313,9 @@ export function providerAuthForSelectedModel(args: {
313
313
  return structured;
314
314
  }
315
315
  if (key) return { type: "bearer", apiKey: key };
316
- const source = args.credentials.provider_key_sources?.[provider] ?? "user";
317
- const prefix = source === "managed" ? "Dari-managed" : "stored";
318
316
  throw new HttpError(
319
317
  401,
320
- `No ${prefix} ${providerLabel(provider)} provider credential is configured for this router.`,
318
+ `No stored ${providerLabel(provider)} provider credential is configured for this router.`,
321
319
  "missing_provider_key",
322
320
  );
323
321
  }
@@ -18,7 +18,7 @@ import {
18
18
  } from "@mupt-ai/dari-router/policy-engine";
19
19
  import type { ImageCapabilityPrunedModel } from "../context/routing_context.js";
20
20
  import { HttpError, errorCode } from "../http/errors.js";
21
- import { executionProviderForModel } from "../models/execution_provider.js";
21
+ import { executionProviderForModel, keySourceForModel } from "../models/execution_provider.js";
22
22
  import {
23
23
  isBackgroundRequest,
24
24
  type InteractionOutput,
@@ -396,8 +396,8 @@ export class RequestReporter {
396
396
  const selectedProvider = outcome.providerExecution?.provider ?? (selectedModel
397
397
  ? executionProviderForModel(a.credentials, selectedModel)
398
398
  : null);
399
- const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel && selectedProvider
400
- ? (a.credentials.provider_key_sources?.[selectedProvider] ?? "user")
399
+ const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
400
+ ? keySourceForModel(a.credentials, selectedModel)
401
401
  : null);
402
402
  const selectedEstimate = a.costEstimates.find(
403
403
  (item) =>
package/src/types.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Source } from "./models/sources.js";
1
2
  import type {
2
3
  CustomRouterConfig,
3
4
  Provider,
@@ -74,6 +75,8 @@ export type ProviderCredential = {
74
75
  subscription?: SubscriptionKind;
75
76
  // A resolved personal plan: quota holds and usage belong to this credential.
76
77
  credentialId?: string;
78
+ // Dari's managed key: billed to the organization's credits.
79
+ managed?: true;
77
80
  };
78
81
 
79
82
  export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
@@ -138,6 +141,8 @@ export type ResolvedRouterModelConfig = {
138
141
  export type ModelFallback = {
139
142
  config: ResolvedRouterModelConfig;
140
143
  subscription?: SubscriptionKind | null;
144
+ // Served by Dari's managed key for config.provider (managed_keys).
145
+ managed?: true;
141
146
  };
142
147
 
143
148
  /** Why a Dari Link grant cannot serve one provider's models now. */
@@ -160,7 +165,11 @@ export type ResolvedRouter = {
160
165
  enabled_models: string[];
161
166
  provider_keys: Partial<Record<Provider, string>>;
162
167
  provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
168
+ // Describes only the router's saved keys above ("user"); a managed key is
169
+ // supplied per model (provider_credentials, managed_keys).
163
170
  provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
171
+ // Dari's managed key per provider, for managed fallbacks.
172
+ managed_keys?: Partial<Record<Provider, string>>;
164
173
  // Model -> the platform-supplied credential that replaces the provider key
165
174
  // above for this request. Supplied by resolveRouter or resolveProviderCredential.
166
175
  provider_credentials?: Record<string, ProviderCredential>;
@@ -202,6 +211,11 @@ export type ResolvedRouter = {
202
211
  // support it.
203
212
  native_compaction?: boolean;
204
213
  primary_retries?: number;
214
+ // Each enabled model's sources (models/sources.ts), and how long a plan must
215
+ // otherwise stay out before a banked reset is spent on it. A model with no
216
+ // entry never spends one.
217
+ model_sources?: Record<string, Source[]>;
218
+ reset_min_hours?: number;
205
219
  // Serve only the requested `dari/model/<id>` at the requested thinking
206
220
  // level: no selector, lease, or personal subscription the platform did not
207
221
  // supply through resolveProviderCredential, and an error for anything