@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
package/README.md CHANGED
@@ -112,20 +112,21 @@ A router spec is a whole router as one YAML file with no credentials, the same f
112
112
  ```yaml
113
113
  name: Opus 5.5 + DeepSeek Subagents
114
114
  models:
115
- - anthropic/claude-opus-5-5
115
+ - id: anthropic/claude-opus-5-5
116
+ sources: [plan, reset, api] # where it is served from, in order
116
117
  - id: deepseek-ai/DeepSeek-V4.1-Flash-1017
117
118
  thinking: [high]
118
119
  provider: opencode-go # served by this provider, not the one its id names
120
+ reset_min_hours: 24 # spend a banked reset only when a plan would be out this long
119
121
  roles:
120
122
  main: { model: anthropic/claude-opus-5-5 }
121
123
  subagent: { model: deepseek-ai/DeepSeek-V4.1-Flash-1017, prompt: Be brief. }
122
124
  routing: { session_pinning: false, retries: 1 }
123
- payment: { allow: [subscription, key] } # without subscription, only API keys pay
124
125
  native_compaction: false
125
126
  agents: { codex: [openai/gpt-6.1-sol] }
126
127
  ```
127
128
 
128
- The gateway pays with connected subscriptions when `payment.allow` lists `subscription`, then with provider API keys; it has no Dari credits. On hosted Dari the same setting is the router's `subscription_providers`: it can name any provider whose models some plan serves, such as `fireworks` or `google`, and those models try the user's plans first. `hosted` settings and a model's `fast` apply only on hosted Dari and are ignored here; `routing.rules` runs only on hosted Dari and is refused. A model's `provider` must be one that serves it, such as `opencode-go` or `fireworks` for the DeepSeek, Kimi, and GLM models; the plan-only provider `vercel-token-pass` serves through a connected subscription.
129
+ Each model lists its `sources`, tried in order: `plan` (connected subscriptions), `reset` (when those plans are out, spend a banked reset, but only if the plan would otherwise be out at least `reset_min_hours`, or the reset would expire first; only right after `plan`), and `api` (the provider's API key). A model without `sources` uses `[plan, api]` here; on hosted Dari a model without them uses `[plan]`. The gateway has no Dari credits. `hosted` settings and a model's `fast` apply only on hosted Dari and are ignored here; `routing.rules` runs only on hosted Dari and is refused. A model's `provider` must be one that serves it, such as `opencode-go` or `fireworks` for the DeepSeek, Kimi, and GLM models; the plan-only provider `vercel-token-pass` serves through a connected subscription.
129
130
 
130
131
  With any gateway key:
131
132
 
@@ -18,6 +18,7 @@ import { anthropicModelsResponse } from "./anthropic_models.js";
18
18
  import { namedClientHarness } from "./client_harness.js";
19
19
  import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
20
20
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
21
+ import { GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
21
22
  export async function handleModels(request, routerId) {
22
23
  // Anthropic SDK clients always send anthropic-version, and API-key probes
23
24
  // authenticate via x-api-key instead of a bearer Authorization header.
@@ -36,9 +37,15 @@ export async function handleModels(request, routerId) {
36
37
  // names its own version in the query, as only Codex does.
37
38
  const codexDirect = !anthropicClient && query.has("client_version");
38
39
  const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
40
+ const gatewayId = request.headers.get(GATEWAY_ID_HEADER)?.trim();
39
41
  let router;
40
42
  try {
41
- router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
43
+ router = await resolveRouter({
44
+ routerId,
45
+ apiKey,
46
+ ...(clientHarness ? { clientHarness } : {}),
47
+ ...(gatewayId ? { gatewayId } : {}),
48
+ });
42
49
  }
43
50
  catch (error) {
44
51
  // A Dari Link grant that can serve this client nothing now lists no
@@ -99,6 +99,7 @@ export function selfHostedLink(deps) {
99
99
  credentialName: null,
100
100
  owner: newSubject(),
101
101
  private: false,
102
+ movingFrom: null,
102
103
  expiresAt: authorization.expiresAt,
103
104
  });
104
105
  return { session: session.token, authorizationUrl: authorization.authorizationUrl, userCode: authorization.userCode };
@@ -2,9 +2,8 @@ import type { ProviderCredential, ProviderKeySource, ResolvedRouter, ResolvedRou
2
2
  /** Actual serving provider for a canonical model on a resolved managed router. */
3
3
  export declare function executionProviderForModel(credentials: ResolvedRouter, model: string): string;
4
4
  /**
5
- * The key that serves a model on a resolved router: a platform-supplied
6
- * credential first, then the resolved provider key. Missing declarations are
7
- * user-owned so unknown platform data cannot trigger managed-key billing.
5
+ * Who pays for the key that serves a model: a supplied plan, Dari's managed
6
+ * key (billed to credits), or otherwise the router's own saved key.
8
7
  */
9
8
  export declare function keySourceForModel(credentials: ResolvedRouter, model: string): ProviderKeySource;
10
9
  /**
@@ -5,15 +5,16 @@ export function executionProviderForModel(credentials, model) {
5
5
  return configured || providerForModel(model);
6
6
  }
7
7
  /**
8
- * The key that serves a model on a resolved router: a platform-supplied
9
- * credential first, then the resolved provider key. Missing declarations are
10
- * user-owned so unknown platform data cannot trigger managed-key billing.
8
+ * Who pays for the key that serves a model: a supplied plan, Dari's managed
9
+ * key (billed to credits), or otherwise the router's own saved key.
11
10
  */
12
11
  export function keySourceForModel(credentials, model) {
13
12
  const supplied = credentials.provider_credentials?.[model];
14
- if (supplied)
15
- return supplied.subscription ? "subscription" : "user";
16
- return credentials.provider_key_sources?.[executionProviderForModel(credentials, model)] ?? "user";
13
+ if (supplied?.subscription)
14
+ return "subscription";
15
+ if (supplied?.managed)
16
+ return "managed";
17
+ return "user";
17
18
  }
18
19
  /**
19
20
  * The router as one of a model's fallbacks serves it: the fallback's config,
@@ -0,0 +1,37 @@
1
+ export type Source = "plan" | "reset" | "key" | "managed";
2
+ export declare const SOURCES: readonly Source[];
3
+ export declare const HOSTED_DEFAULT_SOURCES: readonly Source[];
4
+ export declare const SELF_HOSTED_DEFAULT_SOURCES: readonly Source[];
5
+ export declare const DEFAULT_RESET_MIN_HOURS = 24;
6
+ /** The list as given, or why it is not a valid list of sources. */
7
+ export declare function checkSources(list: unknown): {
8
+ sources: Source[];
9
+ } | {
10
+ error: string;
11
+ };
12
+ /** One plan that offers the model, and how to serve with it. */
13
+ export type PlanOption<Candidate> = {
14
+ servesClient: boolean;
15
+ candidate: () => Promise<Candidate | null>;
16
+ };
17
+ /**
18
+ * The ways to serve one model, in its sources' order. The first serves the
19
+ * request; the rest are its fallbacks.
20
+ */
21
+ export declare function candidatesFor<Candidate>(sources: readonly Source[], plans: readonly PlanOption<Candidate>[], keys: {
22
+ key: () => Promise<Candidate | null>;
23
+ managed: () => Promise<Candidate | null>;
24
+ }): Promise<Candidate[]>;
25
+ /**
26
+ * A plan just hit its limit and no other plan of its kind can serve. Whether
27
+ * to spend one of its banked resets to bring it back now.
28
+ */
29
+ export declare function shouldSpendReset(args: {
30
+ sources: readonly Source[];
31
+ resetMinHours: number;
32
+ returnsAt: Date;
33
+ resets: ReadonlyArray<{
34
+ expiresAt: Date | null;
35
+ }>;
36
+ now: Date;
37
+ }): boolean;
@@ -0,0 +1,88 @@
1
+ // How a router serves one model: the whole policy lives in this file.
2
+ //
3
+ // Each model on a router lists its sources, tried in order:
4
+ // "plan" the user's subscriptions that serve the model
5
+ // "reset" when those plans are all at their limit, spend a banked reset
6
+ // to bring one back (only right after "plan")
7
+ // "key" the router's saved key for the model's provider (the user's own)
8
+ // "managed" Dari's key for the provider, billed to the organization's credits
9
+ //
10
+ // Hosted Dari and the self-hosted gateway both call these functions.
11
+ export const SOURCES = ["plan", "reset", "key", "managed"];
12
+ // A model added to a hosted router without a list: its plans only, so
13
+ // nothing is ever billed unless the router says so.
14
+ export const HOSTED_DEFAULT_SOURCES = ["plan"];
15
+ // A model on a self-hosted gateway's router without a list: its plans, then
16
+ // the provider key the gateway was given. A self-hosted gateway has no
17
+ // managed keys.
18
+ export const SELF_HOSTED_DEFAULT_SOURCES = ["plan", "key"];
19
+ // Spend a banked reset only when the plan would otherwise stay out this long.
20
+ export const DEFAULT_RESET_MIN_HOURS = 24;
21
+ /** The list as given, or why it is not a valid list of sources. */
22
+ export function checkSources(list) {
23
+ if (!Array.isArray(list))
24
+ return { error: "Sources must be a list of plan, reset, key, and managed." };
25
+ const sources = [];
26
+ for (const item of list) {
27
+ if (!SOURCES.includes(item))
28
+ return { error: `Unknown source ${JSON.stringify(item)}; use plan, reset, key, or managed.` };
29
+ if (sources.includes(item))
30
+ return { error: `Source ${item} is listed twice.` };
31
+ sources.push(item);
32
+ }
33
+ const reset = sources.indexOf("reset");
34
+ if (reset !== -1 && sources[reset - 1] !== "plan")
35
+ return { error: "Source reset must come right after plan." };
36
+ return { sources };
37
+ }
38
+ /**
39
+ * The ways to serve one model, in its sources' order. The first serves the
40
+ * request; the rest are its fallbacks.
41
+ */
42
+ export async function candidatesFor(sources, plans, keys) {
43
+ const candidates = [];
44
+ for (const source of sources) {
45
+ if (source === "plan") {
46
+ for (const plan of plans) {
47
+ if (!plan.servesClient)
48
+ continue;
49
+ const candidate = await plan.candidate();
50
+ if (candidate !== null)
51
+ candidates.push(candidate);
52
+ }
53
+ }
54
+ if (source === "key") {
55
+ const candidate = await keys.key();
56
+ if (candidate !== null)
57
+ candidates.push(candidate);
58
+ }
59
+ if (source === "managed") {
60
+ const candidate = await keys.managed();
61
+ if (candidate !== null)
62
+ candidates.push(candidate);
63
+ }
64
+ // "reset" adds no candidate here: it decides what happens when a plan
65
+ // runs out mid-request (shouldSpendReset).
66
+ }
67
+ return candidates;
68
+ }
69
+ /**
70
+ * A plan just hit its limit and no other plan of its kind can serve. Whether
71
+ * to spend one of its banked resets to bring it back now.
72
+ */
73
+ export function shouldSpendReset(args) {
74
+ if (!args.sources.includes("reset"))
75
+ return false;
76
+ if (args.resets.length === 0)
77
+ return false;
78
+ // A long wait is worth a reset.
79
+ const waitHours = (args.returnsAt.getTime() - args.now.getTime()) / 3_600_000;
80
+ if (waitHours >= args.resetMinHours)
81
+ return true;
82
+ // A reset that would expire before the plan comes back is lost anyway.
83
+ for (const reset of args.resets) {
84
+ if (reset.expiresAt !== null && reset.expiresAt < args.returnsAt)
85
+ return true;
86
+ }
87
+ return false;
88
+ }
@@ -1,3 +1,4 @@
1
+ import type { Source } from "../models/sources.js";
1
2
  import type { ActivityPlatform } from "../activity/http.js";
2
3
  import type { Provider, ReasoningEffort, RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
3
4
  import type { HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
@@ -67,7 +68,7 @@ export type GatewayPlatform = {
67
68
  nextSubscription?(request: NextSubscriptionRequest): Promise<NextSubscription | undefined>;
68
69
  /**
69
70
  * Account one call served on a platform-managed provider key. Only reached
70
- * when `resolveRouter` reports a "managed" key source.
71
+ * for a model whose supplied credential is `managed`.
71
72
  */
72
73
  recordUsage(usage: Record<string, unknown>): Promise<void>;
73
74
  /** Receive the finished request's log row. Must not throw. */
@@ -493,6 +494,7 @@ export type ResolveRouterRequest = {
493
494
  conversationId?: string;
494
495
  includePublicEvalCatalog?: boolean;
495
496
  clientHarness?: ClientHarness;
497
+ gatewayId?: string;
496
498
  provisional?: boolean;
497
499
  };
498
500
  export type ProviderCredentialRequest = {
@@ -536,6 +538,8 @@ export type SubscriptionHold = {
536
538
  credentialId: string | undefined;
537
539
  limit: SubscriptionUsageLimit;
538
540
  linkGrantId?: string;
541
+ sources: Source[];
542
+ resetMinHours: number;
539
543
  };
540
544
  export type NextSubscriptionRequest = {
541
545
  userId: string;
@@ -1,2 +1,3 @@
1
1
  export declare const DEFAULT_ROUTER_ALIAS = "default";
2
2
  export declare const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
3
+ export declare const GATEWAY_ID_HEADER = "x-dari-gateway-id";
@@ -3,3 +3,6 @@
3
3
  export const DEFAULT_ROUTER_ALIAS = "default";
4
4
  // The most prefix hashes one router resolution looks up.
5
5
  export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
6
+ // Names the gateway connected to hosted Dari that sent a request, so a model
7
+ // list counts the plans that gateway keeps on its computer.
8
+ export const GATEWAY_ID_HEADER = "x-dari-gateway-id";
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_RESET_MIN_HOURS } from "../models/sources.js";
1
2
  import { HttpError } from "../http/errors.js";
2
3
  import { linkUnavailableError, plansExhausted } from "../link/errors.js";
3
4
  import { piMessageToInteractionOutput } from "./pi_output.js";
@@ -454,9 +455,12 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
454
455
  logUnclassifiedRefusal(execution, responseCapture);
455
456
  // The customer's own key was refused: theirs to fix, not a gateway fault.
456
457
  const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
457
- // A plan whose token is refused cannot serve; the model's next candidate
458
- // may. The plan is not held: a refused token is not a usage limit.
458
+ // A plan or saved key that is refused cannot serve; the model's next
459
+ // candidate (such as Dari's managed key) may. A refused token is not a
460
+ // usage limit, so nothing is held.
459
461
  const planRefused = execution.providerKeySource === "subscription" && (status === 401 || status === 403);
462
+ // The user's own key ran out (rate limit or quota): Dari's key may serve.
463
+ const keyLimited = execution.providerKeySource === "user" && status === 429;
460
464
  return {
461
465
  kind: "provider_failed",
462
466
  message: rejected
@@ -464,7 +468,7 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
464
468
  : message,
465
469
  latencyMs,
466
470
  retryable: !isPromptPolicyRejection(message),
467
- ...(planRefused ? { failover: true } : {}),
471
+ ...(planRefused || rejected || keyLimited ? { failover: true } : {}),
468
472
  };
469
473
  }
470
474
  const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
@@ -481,6 +485,8 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
481
485
  userId: execution.subscriptionUserId,
482
486
  credentialId: execution.subscriptionCredentialId,
483
487
  limit,
488
+ sources: execution.subscriptionSources ?? [],
489
+ resetMinHours: execution.subscriptionResetMinHours ?? DEFAULT_RESET_MIN_HOURS,
484
490
  ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
485
491
  });
486
492
  // Nothing reached the client yet, so the same request is retried on the
@@ -1,3 +1,4 @@
1
+ import { type Source } from "../models/sources.js";
1
2
  import { type CandidateCostEstimate, type ModelPricing, type PricingLookup, type Provider, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
3
  import type { RequestTags } from "../platform/platform.js";
3
4
  import type { InteractionRequest, ProviderIdentity } from "../interaction/types.js";
@@ -27,6 +28,8 @@ export type ProviderExecution = ProviderCallConfig & {
27
28
  subscriptionUserId?: string;
28
29
  subscriptionCredentialId?: string;
29
30
  subscriptionLinkGrantId?: string;
31
+ subscriptionSources?: Source[];
32
+ subscriptionResetMinHours?: number;
30
33
  thinkingLevel: string;
31
34
  usageContext: RoutingUsageContext | undefined;
32
35
  headers: Record<string, string>;
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_RESET_MIN_HOURS } from "../models/sources.js";
1
2
  import { isRecord, } from "@mupt-ai/dari-router/policy-engine";
2
3
  import { executionProviderForModel, keySourceForModel } from "../models/execution_provider.js";
3
4
  import { HttpError } from "../http/errors.js";
@@ -23,11 +24,6 @@ export function prepareProviderExecution(args) {
23
24
  const thinkingLevel = args.clientThinking ?? args.decision.reasoningEffort;
24
25
  const supplied = args.credentials.provider_credentials?.[model];
25
26
  const providerKeySource = keySourceForModel(args.credentials, model);
26
- // A strict router serves a plan only when the platform supplied it for this
27
- // request, never a pooled or personal one it resolved.
28
- if (args.credentials.strict === true && providerKeySource === "subscription" && !supplied) {
29
- throw new HttpError(400, `Strict routers do not serve '${model}' from a personal subscription.`, "strict_subscription_refused", "model");
30
- }
31
27
  const auth = supplied
32
28
  ? { type: "bearer", apiKey: supplied.apiKey.trim() }
33
29
  : providerAuthForSelectedModel({ selectedModel: model, credentials: args.credentials });
@@ -59,6 +55,8 @@ export function prepareProviderExecution(args) {
59
55
  ? {
60
56
  subscriptionUserId: args.credentials.attributed_user_id,
61
57
  subscriptionCredentialId: supplied?.credentialId,
58
+ subscriptionSources: args.credentials.model_sources?.[model] ?? [],
59
+ subscriptionResetMinHours: args.credentials.reset_min_hours ?? DEFAULT_RESET_MIN_HOURS,
62
60
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
63
61
  }
64
62
  : {}),
@@ -452,11 +452,18 @@ async function nextProviderChoice(prepared, choice) {
452
452
  const fallback = fallbacks[index];
453
453
  if (!fallback.subscription && credentials.credit_exhausted === true)
454
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;
455
+ let plan;
456
+ if (fallback.subscription) {
457
+ plan = await fallbackPlan(credentials, fallback, model, prepared.routing.conversationId);
458
+ if (plan === undefined)
459
+ continue;
460
+ }
461
+ if (fallback.managed) {
462
+ const key = credentials.managed_keys?.[fallback.config.provider];
463
+ if (!key)
464
+ continue;
465
+ plan = { apiKey: key, managed: true };
466
+ }
460
467
  try {
461
468
  return {
462
469
  decision: choice.decision,
@@ -1,4 +1,5 @@
1
1
  import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
+ import { type Source } from "../models/sources.js";
2
3
  import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../types.js";
3
4
  /**
4
5
  * The self-hosted gateway's configuration file (YAML or JSON):
@@ -13,7 +14,9 @@ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../type
13
14
  * agentModels: # optional: a coding agent's own list
14
15
  * codex:
15
16
  * - openai/gpt-6.2-sol
16
- * subscriptions: true # serve with connected Claude Code / ChatGPT plans
17
+ * - id: anthropic/claude-opus-5-5
18
+ * sources: [plan, reset, key] # optional; default [plan, key]
19
+ * resetMinHours: 24 # spend a banked reset only when a plan is out this long
17
20
  * sessionPinning: false # route each session and subagent once, then keep its model
18
21
  * roleModels: # optional: serve an agent role one model, without routing
19
22
  * main: anthropic/claude-fable-5-2
@@ -56,7 +59,7 @@ export type RouterConfig = {
56
59
  models: RouterModelConfig[];
57
60
  agentModels: Partial<Record<ClientHarness, RouterModelConfig[]>>;
58
61
  retries: number;
59
- subscriptions: boolean;
62
+ resetMinHours: number;
60
63
  sessionPinning: boolean;
61
64
  nativeCompaction: boolean;
62
65
  zdr: boolean;
@@ -67,6 +70,7 @@ export type RouterModelConfig = {
67
70
  id: string;
68
71
  thinking?: ReasoningEffort[];
69
72
  provider?: string;
73
+ sources?: Source[];
70
74
  };
71
75
  /** The provider that serves a router's model, whose credential it needs. */
72
76
  export declare function modelProvider(model: RouterModelConfig): string;
@@ -92,8 +96,10 @@ export declare function parseRouterModels(routerId: string, field: string, raw:
92
96
  *
93
97
  * ```yaml
94
98
  * name: Opus 5.5 + DeepSeek Subagents
99
+ * reset_min_hours: 24
95
100
  * models:
96
- * - anthropic/claude-opus-5-5
101
+ * - id: anthropic/claude-opus-5-5
102
+ * sources: [plan, reset, key] # default [plan, key]
97
103
  * - id: deepseek-ai/DeepSeek-V4.1-Flash-1017
98
104
  * thinking: [high]
99
105
  * provider: opencode-go # served by this provider, not the one its id names
@@ -106,8 +112,8 @@ export declare function parseRouterModels(routerId: string, field: string, raw:
106
112
  * agents: { codex: [openai/gpt-6.1-sol] }
107
113
  * ```
108
114
  *
109
- * The gateway pays with connected subscriptions when `payment.allow` lists
110
- * `subscription`, and otherwise with provider API keys; it has no credits.
115
+ * Each model's `sources` decide whether connected plans or provider API keys
116
+ * serve it; the gateway has no credits. `payment` is checked and left unused.
111
117
  * `hosted` settings and a model's `fast` apply only on hosted Dari, and are
112
118
  * accepted and left unused; `routing.rules` runs only there and is refused.
113
119
  */
@@ -1,5 +1,6 @@
1
1
  import { isReasoningEffort, isRecord, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
3
+ import { checkSources, DEFAULT_RESET_MIN_HOURS } from "../models/sources.js";
3
4
  import { otherModelProviders, providerModel } from "../models/canonical.js";
4
5
  const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
5
6
  /** The provider that serves a router's model, whose credential it needs. */
@@ -119,7 +120,7 @@ function parseRouter(id, raw) {
119
120
  roleModels: parseRoleMap(`routers.${id}.roleModels`, raw.roleModels, (field, model) => roleModel(field, model, [models, ...Object.values(agentModels)].flat())),
120
121
  rolePrompts: parseRoleMap(`routers.${id}.rolePrompts`, raw.rolePrompts, rolePrompt),
121
122
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
122
- subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
123
+ resetMinHours: optionalResetMinHours(raw.resetMinHours, `routers.${id}.resetMinHours`),
123
124
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
124
125
  nativeCompaction: optionalBoolean(raw.nativeCompaction, `routers.${id}.nativeCompaction`) ?? false,
125
126
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
@@ -189,6 +190,12 @@ function parseModel(routerId, raw) {
189
190
  throw new Error(`Router "${routerId}" has an invalid model; use a canonical "provider/model" id.`);
190
191
  }
191
192
  const model = { id: entry.id };
193
+ if (entry.sources != null) {
194
+ const checked = checkSources(entry.sources);
195
+ if ("error" in checked)
196
+ throw new Error(`Model ${entry.id} on router "${routerId}": ${checked.error}`);
197
+ model.sources = checked.sources;
198
+ }
192
199
  if (entry.thinking != null) {
193
200
  if (!Array.isArray(entry.thinking) ||
194
201
  entry.thinking.length === 0 ||
@@ -214,6 +221,14 @@ function optionalBoolean(value, field) {
214
221
  throw new Error(`${field} must be true or false.`);
215
222
  return value;
216
223
  }
224
+ function optionalResetMinHours(value, field) {
225
+ if (value === undefined)
226
+ return DEFAULT_RESET_MIN_HOURS;
227
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
228
+ throw new Error(`${field} must be a number of hours, 0 or more.`);
229
+ }
230
+ return value;
231
+ }
217
232
  function optionalRetries(value, field) {
218
233
  if (value === undefined)
219
234
  return undefined;
@@ -222,8 +237,8 @@ function optionalRetries(value, field) {
222
237
  }
223
238
  return value;
224
239
  }
225
- const SPEC_FIELDS = ["name", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
226
- const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast"];
240
+ const SPEC_FIELDS = ["name", "reset_min_hours", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
241
+ const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast", "sources"];
227
242
  const PAYMENT_KINDS = ["subscription", "key", "credits"];
228
243
  const SPEC_NAME_MAX_LENGTH = 120;
229
244
  /** Read a router spec's YAML (or JSON) text; YAML 1.2, so `off` stays a thinking level. */
@@ -275,7 +290,7 @@ export function parseRouterSpec(id, raw) {
275
290
  roleModels: parseRoleMap("roles", roleValues("model"), (field, model) => roleModel(`${field}.model`, model, [models, ...Object.values(agentModels)].flat())),
276
291
  rolePrompts: parseRoleMap("roles", roleValues("prompt"), (field, prompt) => rolePrompt(`${field}.prompt`, prompt)),
277
292
  retries: optionalRetries(routing.retries ?? undefined, "routing.retries") ?? 1,
278
- subscriptions: allow.includes("subscription"),
293
+ resetMinHours: optionalResetMinHours(spec.reset_min_hours ?? undefined, "reset_min_hours"),
279
294
  sessionPinning: optionalBoolean(routing.session_pinning ?? undefined, "routing.session_pinning") ?? false,
280
295
  nativeCompaction: optionalBoolean(spec.native_compaction ?? undefined, "native_compaction") ?? false,
281
296
  zdr: false,
@@ -294,11 +309,12 @@ export function routerSpecFor(name, router) {
294
309
  const agents = Object.entries(router.agentModels);
295
310
  return {
296
311
  name,
312
+ reset_min_hours: router.resetMinHours,
297
313
  models: router.models.map(specModel),
298
314
  ...(Object.keys(roles).length > 0 ? { roles } : {}),
299
315
  routing: { session_pinning: router.sessionPinning, retries: router.retries },
300
316
  // The gateway pays with plans and API keys; it has no credits.
301
- payment: { allow: router.subscriptions ? ["subscription", "key"] : ["key"] },
317
+ payment: { allow: ["subscription", "key"] },
302
318
  native_compaction: router.nativeCompaction,
303
319
  ...(agents.length > 0
304
320
  ? { agents: Object.fromEntries(agents.map(([agent, models]) => [agent, models.map(specModel)])) }
@@ -311,7 +327,7 @@ export function routerSpecYaml(spec) {
311
327
  return `${Bun.YAML.stringify(spec, null, 2).replace(/: $/gm, ":")}\n`;
312
328
  }
313
329
  function specModel(model) {
314
- return model.thinking === undefined && model.provider === undefined ? model.id : { ...model };
330
+ return model.thinking === undefined && model.provider === undefined && model.sources === undefined ? model.id : { ...model };
315
331
  }
316
332
  // A spec section as a map, refusing fields the spec does not have; absent is empty.
317
333
  function specMap(field, raw, fields) {
@@ -3,7 +3,7 @@ import { isReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
3
3
  import { anthropicToken, bearerToken } from "../http/auth.js";
4
4
  import { errorResponse, HttpError } from "../http/errors.js";
5
5
  import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
6
- import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
6
+ import { DEFAULT_ROUTER_ALIAS, GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
7
7
  import { explicitModelId } from "../protocol/input/router_model.js";
8
8
  import { parseGatewayConfig } from "./config.js";
9
9
  import { createSelfHostedPlatform } from "./platform.js";
@@ -84,7 +84,8 @@ function hostedRouters(hosted, fetchImpl) {
84
84
  async function readHostedRouter(hosted, fetchImpl, routerId) {
85
85
  const prefix = routerId === DEFAULT_ROUTER_ALIAS ? "" : `/${encodeURIComponent(routerId)}`;
86
86
  const response = await fetchImpl(`${hosted.url}${prefix}/v1/models`, {
87
- headers: { authorization: `Bearer ${hosted.apiKey}` },
87
+ // Lists the models this gateway's plans serve, though hosted holds none.
88
+ headers: { authorization: `Bearer ${hosted.apiKey}`, [GATEWAY_ID_HEADER]: hosted.gatewayId },
88
89
  signal: AbortSignal.timeout(30_000),
89
90
  });
90
91
  if (!response.ok)
@@ -104,7 +105,7 @@ async function readHostedRouter(hosted, fetchImpl, routerId) {
104
105
  throw new Error("it lists no models");
105
106
  return parseGatewayConfig({
106
107
  routers: {
107
- [routerId]: { models, subscriptions: true, nativeCompaction: catalog.remote_compaction === "v2" },
108
+ [routerId]: { models, nativeCompaction: catalog.remote_compaction === "v2" },
108
109
  },
109
110
  }).routers[routerId];
110
111
  }
@@ -176,6 +177,8 @@ async function forward(request, body, deps, fail) {
176
177
  headers.delete(name);
177
178
  }
178
179
  headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
180
+ // An agent's model list includes the models this gateway's plans serve.
181
+ headers.set(GATEWAY_ID_HEADER, deps.hosted.gatewayId);
179
182
  let response;
180
183
  try {
181
184
  response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
@@ -49,7 +49,7 @@ export function createSelfHostedPlatform(deps) {
49
49
  apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
50
50
  };
51
51
  },
52
- async markSubscriptionUnavailable({ credentialId, limit, linkGrantId }) {
52
+ async markSubscriptionUnavailable({ credentialId, limit, linkGrantId, sources, resetMinHours }) {
53
53
  if (credentialId === undefined)
54
54
  return false;
55
55
  if (limit.model !== undefined) {
@@ -68,7 +68,7 @@ export function createSelfHostedPlatform(deps) {
68
68
  store: deps.subscriptions,
69
69
  fetch: deps.fetch,
70
70
  baseUrls: providerBaseUrls(deps.config.providers),
71
- }, held);
71
+ }, held, { sources, resetMinHours });
72
72
  }
73
73
  // A grant's retry may use only its own subscriptions.
74
74
  const provider = deps.subscriptions.get(credentialId)?.provider;