@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.
- package/README.md +4 -3
- package/dist/ingress/models.js +8 -1
- package/dist/link/self_hosted.js +1 -0
- package/dist/models/execution_provider.d.ts +2 -3
- package/dist/models/execution_provider.js +7 -6
- package/dist/models/sources.d.ts +37 -0
- package/dist/models/sources.js +88 -0
- package/dist/platform/platform.d.ts +5 -1
- package/dist/platform/routing_contract.d.ts +1 -0
- package/dist/platform/routing_contract.js +3 -0
- package/dist/providers/execution.js +9 -3
- package/dist/providers/provider_call.d.ts +3 -0
- package/dist/providers/provider_call.js +3 -5
- package/dist/runtime/routed_runtime.js +12 -5
- package/dist/self_host/config.d.ts +11 -5
- package/dist/self_host/config.js +22 -6
- package/dist/self_host/connected.js +6 -3
- package/dist/self_host/platform.js +2 -2
- package/dist/self_host/resolve.js +41 -24
- package/dist/self_host/subscriptions/http.js +8 -10
- package/dist/self_host/subscriptions/resets.d.ts +11 -5
- package/dist/self_host/subscriptions/resets.js +23 -17
- package/dist/self_host/subscriptions/store.d.ts +1 -3
- package/dist/self_host/subscriptions/store.js +7 -17
- package/dist/strategies/routing.js +1 -3
- package/dist/telemetry/report.js +3 -3
- package/dist/types.d.ts +6 -0
- package/package.json +2 -2
- package/src/ingress/models.ts +8 -1
- package/src/link/self_hosted.ts +1 -0
- package/src/models/execution_provider.ts +5 -5
- package/src/models/sources.ts +114 -0
- package/src/platform/platform.ts +10 -1
- package/src/platform/routing_contract.ts +4 -0
- package/src/providers/execution.ts +9 -3
- package/src/providers/provider_call.ts +7 -10
- package/src/runtime/routed_runtime.ts +10 -4
- package/src/self_host/config.ts +34 -11
- package/src/self_host/connected.ts +6 -3
- package/src/self_host/platform.ts +2 -2
- package/src/self_host/resolve.ts +36 -20
- package/src/self_host/subscriptions/http.ts +9 -9
- package/src/self_host/subscriptions/resets.ts +27 -19
- package/src/self_host/subscriptions/store.ts +11 -21
- package/src/strategies/routing.ts +1 -3
- package/src/telemetry/report.ts +3 -3
- package/src/types.ts +14 -0
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
|
|
12
|
+
export type Source = "plan" | "reset" | "key" | "managed";
|
|
13
|
+
|
|
14
|
+
export const SOURCES: readonly Source[] = ["plan", "reset", "key", "managed"];
|
|
15
|
+
|
|
16
|
+
// A model added to a hosted router without a list: its plans only, so
|
|
17
|
+
// nothing is ever billed unless the router says so.
|
|
18
|
+
export const HOSTED_DEFAULT_SOURCES: readonly Source[] = ["plan"];
|
|
19
|
+
|
|
20
|
+
// A model on a self-hosted gateway's router without a list: its plans, then
|
|
21
|
+
// the provider key the gateway was given. A self-hosted gateway has no
|
|
22
|
+
// managed keys.
|
|
23
|
+
export const SELF_HOSTED_DEFAULT_SOURCES: readonly Source[] = ["plan", "key"];
|
|
24
|
+
|
|
25
|
+
// Spend a banked reset only when the plan would otherwise stay out this long.
|
|
26
|
+
export const DEFAULT_RESET_MIN_HOURS = 24;
|
|
27
|
+
|
|
28
|
+
/** The list as given, or why it is not a valid list of sources. */
|
|
29
|
+
export function checkSources(list: unknown): { sources: Source[] } | { error: string } {
|
|
30
|
+
if (!Array.isArray(list)) return { error: "Sources must be a list of plan, reset, key, and managed." };
|
|
31
|
+
const sources: Source[] = [];
|
|
32
|
+
for (const item of list) {
|
|
33
|
+
if (!SOURCES.includes(item as Source)) return { error: `Unknown source ${JSON.stringify(item)}; use plan, reset, key, or managed.` };
|
|
34
|
+
if (sources.includes(item as Source)) return { error: `Source ${item} is listed twice.` };
|
|
35
|
+
sources.push(item as Source);
|
|
36
|
+
}
|
|
37
|
+
const reset = sources.indexOf("reset");
|
|
38
|
+
if (reset !== -1 && sources[reset - 1] !== "plan") return { error: "Source reset must come right after plan." };
|
|
39
|
+
return { sources };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One plan that offers the model, and how to serve with it. */
|
|
43
|
+
export type PlanOption<Candidate> = {
|
|
44
|
+
// Whether this plan serves the client asking (a Claude Code plan serves
|
|
45
|
+
// only Claude Code, a Muse Code plan only Muse Code).
|
|
46
|
+
servesClient: boolean;
|
|
47
|
+
// The way to serve with the user's plan of this kind, or null when they
|
|
48
|
+
// have none or it is at its limit.
|
|
49
|
+
candidate: () => Promise<Candidate | null>;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The ways to serve one model, in its sources' order. The first serves the
|
|
54
|
+
* request; the rest are its fallbacks.
|
|
55
|
+
*/
|
|
56
|
+
export async function candidatesFor<Candidate>(
|
|
57
|
+
sources: readonly Source[],
|
|
58
|
+
plans: readonly PlanOption<Candidate>[],
|
|
59
|
+
keys: {
|
|
60
|
+
// The way to serve with the router's saved key for the provider, or null
|
|
61
|
+
// when it has none.
|
|
62
|
+
key: () => Promise<Candidate | null>;
|
|
63
|
+
// The way to serve with Dari's managed key, or null when there is none
|
|
64
|
+
// for this provider (always null on a self-hosted gateway).
|
|
65
|
+
managed: () => Promise<Candidate | null>;
|
|
66
|
+
},
|
|
67
|
+
): Promise<Candidate[]> {
|
|
68
|
+
const candidates: Candidate[] = [];
|
|
69
|
+
for (const source of sources) {
|
|
70
|
+
if (source === "plan") {
|
|
71
|
+
for (const plan of plans) {
|
|
72
|
+
if (!plan.servesClient) continue;
|
|
73
|
+
const candidate = await plan.candidate();
|
|
74
|
+
if (candidate !== null) candidates.push(candidate);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (source === "key") {
|
|
78
|
+
const candidate = await keys.key();
|
|
79
|
+
if (candidate !== null) candidates.push(candidate);
|
|
80
|
+
}
|
|
81
|
+
if (source === "managed") {
|
|
82
|
+
const candidate = await keys.managed();
|
|
83
|
+
if (candidate !== null) candidates.push(candidate);
|
|
84
|
+
}
|
|
85
|
+
// "reset" adds no candidate here: it decides what happens when a plan
|
|
86
|
+
// runs out mid-request (shouldSpendReset).
|
|
87
|
+
}
|
|
88
|
+
return candidates;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A plan just hit its limit and no other plan of its kind can serve. Whether
|
|
93
|
+
* to spend one of its banked resets to bring it back now.
|
|
94
|
+
*/
|
|
95
|
+
export function shouldSpendReset(args: {
|
|
96
|
+
sources: readonly Source[];
|
|
97
|
+
resetMinHours: number;
|
|
98
|
+
// When the plan comes back on its own.
|
|
99
|
+
returnsAt: Date;
|
|
100
|
+
// The plan's banked resets; a null expiry never expires.
|
|
101
|
+
resets: ReadonlyArray<{ expiresAt: Date | null }>;
|
|
102
|
+
now: Date;
|
|
103
|
+
}): boolean {
|
|
104
|
+
if (!args.sources.includes("reset")) return false;
|
|
105
|
+
if (args.resets.length === 0) return false;
|
|
106
|
+
// A long wait is worth a reset.
|
|
107
|
+
const waitHours = (args.returnsAt.getTime() - args.now.getTime()) / 3_600_000;
|
|
108
|
+
if (waitHours >= args.resetMinHours) return true;
|
|
109
|
+
// A reset that would expire before the plan comes back is lost anyway.
|
|
110
|
+
for (const reset of args.resets) {
|
|
111
|
+
if (reset.expiresAt !== null && reset.expiresAt < args.returnsAt) return true;
|
|
112
|
+
}
|
|
113
|
+
return false;
|
|
114
|
+
}
|
package/src/platform/platform.ts
CHANGED
|
@@ -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 {
|
|
3
4
|
Provider,
|
|
@@ -80,7 +81,7 @@ export type GatewayPlatform = {
|
|
|
80
81
|
nextSubscription?(request: NextSubscriptionRequest): Promise<NextSubscription | undefined>;
|
|
81
82
|
/**
|
|
82
83
|
* Account one call served on a platform-managed provider key. Only reached
|
|
83
|
-
*
|
|
84
|
+
* for a model whose supplied credential is `managed`.
|
|
84
85
|
*/
|
|
85
86
|
recordUsage(usage: Record<string, unknown>): Promise<void>;
|
|
86
87
|
/** Receive the finished request's log row. Must not throw. */
|
|
@@ -512,6 +513,10 @@ export type ResolveRouterRequest = {
|
|
|
512
513
|
conversationId?: string;
|
|
513
514
|
includePublicEvalCatalog?: boolean;
|
|
514
515
|
clientHarness?: ClientHarness;
|
|
516
|
+
// The connected gateway listing this router's models: a model a plan on
|
|
517
|
+
// that gateway serves is listed though hosted Dari holds no plan for it.
|
|
518
|
+
// Model lists only; that gateway serves those models itself.
|
|
519
|
+
gatewayId?: string;
|
|
515
520
|
// A later resolve with this request's `conversationId` replaces this one's
|
|
516
521
|
// credentials, so none from it serve the request: a platform should not
|
|
517
522
|
// mark a credential used or refresh it for this resolve.
|
|
@@ -570,6 +575,10 @@ export type SubscriptionHold = {
|
|
|
570
575
|
// The Dari Link grant the request ran under; another plan serves a retry
|
|
571
576
|
// only when the grant may use it.
|
|
572
577
|
linkGrantId?: string;
|
|
578
|
+
// The model's sources and its router's reset threshold, for deciding
|
|
579
|
+
// whether to spend a banked reset (models/sources.ts shouldSpendReset).
|
|
580
|
+
sources: Source[];
|
|
581
|
+
resetMinHours: number;
|
|
573
582
|
};
|
|
574
583
|
|
|
575
584
|
export type NextSubscriptionRequest = {
|
|
@@ -4,3 +4,7 @@ export const DEFAULT_ROUTER_ALIAS = "default";
|
|
|
4
4
|
|
|
5
5
|
// The most prefix hashes one router resolution looks up.
|
|
6
6
|
export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
|
|
7
|
+
|
|
8
|
+
// Names the gateway connected to hosted Dari that sent a request, so a model
|
|
9
|
+
// list counts the plans that gateway keeps on its computer.
|
|
10
|
+
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 type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|
|
2
3
|
import { HttpError } from "../http/errors.js";
|
|
3
4
|
import { linkUnavailableError, plansExhausted } from "../link/errors.js";
|
|
@@ -765,9 +766,12 @@ async function providerFailedAttempt(
|
|
|
765
766
|
if (execution.providerKeySource === "subscription") logUnclassifiedRefusal(execution, responseCapture);
|
|
766
767
|
// The customer's own key was refused: theirs to fix, not a gateway fault.
|
|
767
768
|
const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
|
|
768
|
-
// A plan
|
|
769
|
-
//
|
|
769
|
+
// A plan or saved key that is refused cannot serve; the model's next
|
|
770
|
+
// candidate (such as Dari's managed key) may. A refused token is not a
|
|
771
|
+
// usage limit, so nothing is held.
|
|
770
772
|
const planRefused = execution.providerKeySource === "subscription" && (status === 401 || status === 403);
|
|
773
|
+
// The user's own key ran out (rate limit or quota): Dari's key may serve.
|
|
774
|
+
const keyLimited = execution.providerKeySource === "user" && status === 429;
|
|
771
775
|
return {
|
|
772
776
|
kind: "provider_failed",
|
|
773
777
|
message: rejected
|
|
@@ -775,7 +779,7 @@ async function providerFailedAttempt(
|
|
|
775
779
|
: message,
|
|
776
780
|
latencyMs,
|
|
777
781
|
retryable: !isPromptPolicyRejection(message),
|
|
778
|
-
...(planRefused ? { failover: true as const } : {}),
|
|
782
|
+
...(planRefused || rejected || keyLimited ? { failover: true as const } : {}),
|
|
779
783
|
};
|
|
780
784
|
}
|
|
781
785
|
const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
|
|
@@ -792,6 +796,8 @@ async function providerFailedAttempt(
|
|
|
792
796
|
userId: execution.subscriptionUserId,
|
|
793
797
|
credentialId: execution.subscriptionCredentialId,
|
|
794
798
|
limit,
|
|
799
|
+
sources: execution.subscriptionSources ?? [],
|
|
800
|
+
resetMinHours: execution.subscriptionResetMinHours ?? DEFAULT_RESET_MIN_HOURS,
|
|
795
801
|
...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
|
|
796
802
|
});
|
|
797
803
|
// Nothing reached the client yet, so the same request is retried on the
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_RESET_MIN_HOURS, type Source } from "../models/sources.js";
|
|
1
2
|
import {
|
|
2
3
|
isRecord,
|
|
3
4
|
type CandidateCostEstimate,
|
|
@@ -79,6 +80,10 @@ export type ProviderExecution = ProviderCallConfig & {
|
|
|
79
80
|
subscriptionCredentialId?: string;
|
|
80
81
|
// The Dari Link grant whose subscriptions alone may serve this call.
|
|
81
82
|
subscriptionLinkGrantId?: string;
|
|
83
|
+
// The model's sources and the router's reset threshold, carried onto the
|
|
84
|
+
// hold when the plan hits its limit.
|
|
85
|
+
subscriptionSources?: Source[];
|
|
86
|
+
subscriptionResetMinHours?: number;
|
|
82
87
|
// The thinking the provider was sent, as X-Dari-Thinking-Level reports it.
|
|
83
88
|
thinkingLevel: string;
|
|
84
89
|
usageContext: RoutingUsageContext | undefined;
|
|
@@ -134,16 +139,6 @@ export function prepareProviderExecution(args: {
|
|
|
134
139
|
const thinkingLevel: string = args.clientThinking ?? args.decision.reasoningEffort;
|
|
135
140
|
const supplied = args.credentials.provider_credentials?.[model];
|
|
136
141
|
const providerKeySource = keySourceForModel(args.credentials, model);
|
|
137
|
-
// A strict router serves a plan only when the platform supplied it for this
|
|
138
|
-
// request, never a pooled or personal one it resolved.
|
|
139
|
-
if (args.credentials.strict === true && providerKeySource === "subscription" && !supplied) {
|
|
140
|
-
throw new HttpError(
|
|
141
|
-
400,
|
|
142
|
-
`Strict routers do not serve '${model}' from a personal subscription.`,
|
|
143
|
-
"strict_subscription_refused",
|
|
144
|
-
"model",
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
142
|
const auth: ProviderAuth = supplied
|
|
148
143
|
? { type: "bearer", apiKey: supplied.apiKey.trim() }
|
|
149
144
|
: providerAuthForSelectedModel({ selectedModel: model, credentials: args.credentials });
|
|
@@ -175,6 +170,8 @@ export function prepareProviderExecution(args: {
|
|
|
175
170
|
? {
|
|
176
171
|
subscriptionUserId: args.credentials.attributed_user_id,
|
|
177
172
|
subscriptionCredentialId: supplied?.credentialId,
|
|
173
|
+
subscriptionSources: args.credentials.model_sources?.[model] ?? [],
|
|
174
|
+
subscriptionResetMinHours: args.credentials.reset_min_hours ?? DEFAULT_RESET_MIN_HOURS,
|
|
178
175
|
...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
|
|
179
176
|
}
|
|
180
177
|
: {}),
|
|
@@ -631,10 +631,16 @@ async function nextProviderChoice(
|
|
|
631
631
|
for (let index = (choice.fallback ?? -1) + 1; index < fallbacks.length; index += 1) {
|
|
632
632
|
const fallback = fallbacks[index]!;
|
|
633
633
|
if (!fallback.subscription && credentials.credit_exhausted === true) continue;
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
634
|
+
let plan: ProviderCredential | undefined;
|
|
635
|
+
if (fallback.subscription) {
|
|
636
|
+
plan = await fallbackPlan(credentials, fallback, model, prepared.routing.conversationId);
|
|
637
|
+
if (plan === undefined) continue;
|
|
638
|
+
}
|
|
639
|
+
if (fallback.managed) {
|
|
640
|
+
const key = credentials.managed_keys?.[fallback.config.provider];
|
|
641
|
+
if (!key) continue;
|
|
642
|
+
plan = { apiKey: key, managed: true };
|
|
643
|
+
}
|
|
638
644
|
try {
|
|
639
645
|
return {
|
|
640
646
|
decision: choice.decision,
|
package/src/self_host/config.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
369
|
-
*
|
|
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
|
-
|
|
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:
|
|
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.
|
|
@@ -5,7 +5,7 @@ import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
|
5
5
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
6
6
|
import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
|
|
7
7
|
import type { GatewayPlatform } from "../platform/platform.js";
|
|
8
|
-
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
8
|
+
import { DEFAULT_ROUTER_ALIAS, GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
|
|
9
9
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
10
10
|
import { parseGatewayConfig, type RouterConfig } from "./config.js";
|
|
11
11
|
import type { HostedSync } from "./hosted_sync.js";
|
|
@@ -116,7 +116,8 @@ function hostedRouters(hosted: HostedConnection, fetchImpl: typeof fetch) {
|
|
|
116
116
|
async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetch, routerId: string): Promise<RouterConfig> {
|
|
117
117
|
const prefix = routerId === DEFAULT_ROUTER_ALIAS ? "" : `/${encodeURIComponent(routerId)}`;
|
|
118
118
|
const response = await fetchImpl(`${hosted.url}${prefix}/v1/models`, {
|
|
119
|
-
|
|
119
|
+
// Lists the models this gateway's plans serve, though hosted holds none.
|
|
120
|
+
headers: { authorization: `Bearer ${hosted.apiKey}`, [GATEWAY_ID_HEADER]: hosted.gatewayId },
|
|
120
121
|
signal: AbortSignal.timeout(30_000),
|
|
121
122
|
});
|
|
122
123
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
@@ -136,7 +137,7 @@ async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetc
|
|
|
136
137
|
if (models.length === 0) throw new Error("it lists no models");
|
|
137
138
|
return parseGatewayConfig({
|
|
138
139
|
routers: {
|
|
139
|
-
[routerId]: { models,
|
|
140
|
+
[routerId]: { models, nativeCompaction: catalog.remote_compaction === "v2" },
|
|
140
141
|
},
|
|
141
142
|
}).routers[routerId]!;
|
|
142
143
|
}
|
|
@@ -219,6 +220,8 @@ async function forward(
|
|
|
219
220
|
headers.delete(name);
|
|
220
221
|
}
|
|
221
222
|
headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
|
|
223
|
+
// An agent's model list includes the models this gateway's plans serve.
|
|
224
|
+
headers.set(GATEWAY_ID_HEADER, deps.hosted.gatewayId);
|
|
222
225
|
let response: Response;
|
|
223
226
|
try {
|
|
224
227
|
response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
|
|
@@ -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;
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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
|
|
223
|
-
|
|
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
|
|
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|\/
|
|
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));
|
|
@@ -170,6 +164,11 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
|
|
|
170
164
|
// A reconnected plan stays where it was unless the caller says otherwise.
|
|
171
165
|
const isPrivate = body.private ?? reconnecting?.private ?? false;
|
|
172
166
|
if (typeof isPrivate !== "boolean") throw new HttpError(400, "private must be true or false.");
|
|
167
|
+
// `dari accounts subscription move` names the hosted plan it moves here.
|
|
168
|
+
const movingFrom = body.moving_from ?? null;
|
|
169
|
+
if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
|
|
170
|
+
throw new HttpError(400, "moving_from must be a non-empty string.");
|
|
171
|
+
}
|
|
173
172
|
const authorization = await startOAuth(provider as SubscriptionProvider, { fetch: deps.fetch, now });
|
|
174
173
|
const session = deps.store.createSession(
|
|
175
174
|
{
|
|
@@ -178,6 +177,7 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
|
|
|
178
177
|
credentialName,
|
|
179
178
|
owner: null,
|
|
180
179
|
private: isPrivate,
|
|
180
|
+
movingFrom,
|
|
181
181
|
expiresAt: authorization.expiresAt,
|
|
182
182
|
},
|
|
183
183
|
now,
|
|
@@ -216,7 +216,8 @@ async function completeSession(deps: SubscriptionHttpDeps, body: Record<string,
|
|
|
216
216
|
let elsewhere: ConnectedAccount[] = [];
|
|
217
217
|
if (deps.hostedAccounts !== undefined && !reconnectsSameAccount) {
|
|
218
218
|
try {
|
|
219
|
-
elsewhere = await deps.hostedAccounts()
|
|
219
|
+
elsewhere = (await deps.hostedAccounts()).filter((account) =>
|
|
220
|
+
!(account.place === "dari" && account.name === session.movingFrom));
|
|
220
221
|
} catch (error) {
|
|
221
222
|
// The provider code is spent: keep the sign-in, checked against this
|
|
222
223
|
// gateway's own plans only, rather than make the user start over.
|
|
@@ -324,7 +325,6 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
|
|
|
324
325
|
// The share of its tightest window the plan last reported used, and
|
|
325
326
|
// every window as shown; null when it reports none and is not held.
|
|
326
327
|
usage: usageBody(credential, now),
|
|
327
|
-
auto_redeem_resets: credential.autoRedeemResets,
|
|
328
328
|
};
|
|
329
329
|
}
|
|
330
330
|
|