@mupt-ai/dari-gateway 1.0.356 → 1.0.358
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/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 +4 -1
- 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 +1 -1
- package/dist/self_host/platform.js +2 -2
- package/dist/self_host/resolve.js +41 -24
- package/dist/self_host/subscriptions/http.js +1 -9
- 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 +0 -3
- package/dist/self_host/subscriptions/store.js +1 -14
- 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/models/execution_provider.ts +5 -5
- package/src/models/sources.ts +114 -0
- package/src/platform/platform.ts +6 -1
- 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 +1 -1
- package/src/self_host/platform.ts +2 -2
- package/src/self_host/resolve.ts +36 -20
- package/src/self_host/subscriptions/http.ts +1 -8
- package/src/self_host/subscriptions/resets.ts +27 -19
- package/src/self_host/subscriptions/store.ts +1 -18
- package/src/strategies/routing.ts +1 -3
- package/src/telemetry/report.ts +3 -3
- 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
|
-
|
|
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
|
|
|
@@ -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
|
-
*
|
|
6
|
-
*
|
|
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
|
-
*
|
|
9
|
-
*
|
|
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
|
|
16
|
-
|
|
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
|
-
*
|
|
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. */
|
|
@@ -537,6 +538,8 @@ export type SubscriptionHold = {
|
|
|
537
538
|
credentialId: string | undefined;
|
|
538
539
|
limit: SubscriptionUsageLimit;
|
|
539
540
|
linkGrantId?: string;
|
|
541
|
+
sources: Source[];
|
|
542
|
+
resetMinHours: number;
|
|
540
543
|
};
|
|
541
544
|
export type NextSubscriptionRequest = {
|
|
542
545
|
userId: string;
|
|
@@ -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
|
|
458
|
-
//
|
|
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
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
110
|
-
*
|
|
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
|
*/
|
package/dist/self_host/config.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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:
|
|
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) {
|
|
@@ -105,7 +105,7 @@ async function readHostedRouter(hosted, fetchImpl, routerId) {
|
|
|
105
105
|
throw new Error("it lists no models");
|
|
106
106
|
return parseGatewayConfig({
|
|
107
107
|
routers: {
|
|
108
|
-
[routerId]: { models,
|
|
108
|
+
[routerId]: { models, nativeCompaction: catalog.remote_compaction === "v2" },
|
|
109
109
|
},
|
|
110
110
|
}).routers[routerId];
|
|
111
111
|
}
|
|
@@ -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;
|
|
@@ -5,6 +5,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
5
5
|
import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
|
|
6
6
|
import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
|
|
7
7
|
import { gatewayFor } from "../models/gateways.js";
|
|
8
|
+
import { candidatesFor, DEFAULT_RESET_MIN_HOURS, SELF_HOSTED_DEFAULT_SOURCES } from "../models/sources.js";
|
|
8
9
|
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
9
10
|
import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
|
|
10
11
|
import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
|
|
@@ -53,8 +54,6 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
53
54
|
const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
|
|
54
55
|
const now = new Date();
|
|
55
56
|
const servable = grant === null ? undefined : new Set(grant.credentialIds);
|
|
56
|
-
// A grant uses the subscriptions its user chose, whatever the router allows.
|
|
57
|
-
const plansServe = router?.subscriptions === true || grant !== null;
|
|
58
57
|
// The plan of each kind that serves this conversation, chosen once.
|
|
59
58
|
const conversationPlans = new Map();
|
|
60
59
|
const conversationPlan = (kind) => {
|
|
@@ -119,6 +118,8 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
119
118
|
model_thinking_levels: thinkingLevels(listed),
|
|
120
119
|
model_prices: {},
|
|
121
120
|
model_configs: {},
|
|
121
|
+
model_sources: {},
|
|
122
|
+
reset_min_hours: router?.resetMinHours ?? DEFAULT_RESET_MIN_HOURS,
|
|
122
123
|
};
|
|
123
124
|
// Each model is served by the user's plans that serve it, in order, then by
|
|
124
125
|
// its provider's API key; the first serves and the rest are its fallbacks.
|
|
@@ -131,31 +132,45 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
131
132
|
const models = [];
|
|
132
133
|
for (const model of listed) {
|
|
133
134
|
const base = modelProvider(model);
|
|
134
|
-
const candidates = [];
|
|
135
135
|
const heldKinds = [];
|
|
136
136
|
const modelHolds = [];
|
|
137
|
-
|
|
137
|
+
// A grant serves its plans, then its keys; a router model its own list.
|
|
138
|
+
let sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
|
|
139
|
+
if (grant !== null)
|
|
140
|
+
sources = SELF_HOSTED_DEFAULT_SOURCES;
|
|
141
|
+
const plans = [];
|
|
142
|
+
for (const kind of modelSubscriptions(model.id)) {
|
|
138
143
|
const client = subscriptionClient(kind);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
144
|
+
plans.push({
|
|
145
|
+
servesClient: client === undefined || client === request.clientHarness,
|
|
146
|
+
candidate: async () => {
|
|
147
|
+
const plan = planFor(kind, model.id);
|
|
148
|
+
if (plan !== null)
|
|
149
|
+
return { provider: subscriptionModelProvider(kind), plan };
|
|
150
|
+
// Held at its limit: remember why, for the error when nothing serves.
|
|
151
|
+
const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
|
|
152
|
+
if (connected.length > 0)
|
|
153
|
+
heldKinds.push(kind);
|
|
154
|
+
for (const credential of connected) {
|
|
155
|
+
for (const hold of activeModelHolds(credential, now)) {
|
|
156
|
+
if (hold.model === model.id)
|
|
157
|
+
modelHolds.push(hold.until);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return null;
|
|
161
|
+
},
|
|
162
|
+
});
|
|
155
163
|
}
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
164
|
+
const candidates = await candidatesFor(sources, plans, {
|
|
165
|
+
key: async () => {
|
|
166
|
+
const key = await apiKey(base);
|
|
167
|
+
if (key === undefined)
|
|
168
|
+
return null;
|
|
169
|
+
return { provider: base, key };
|
|
170
|
+
},
|
|
171
|
+
// A self-hosted gateway has no managed keys.
|
|
172
|
+
managed: async () => null,
|
|
173
|
+
});
|
|
159
174
|
if (candidates.length === 0) {
|
|
160
175
|
for (const kind of heldKinds)
|
|
161
176
|
exhausted.add(kind);
|
|
@@ -170,6 +185,7 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
170
185
|
continue;
|
|
171
186
|
}
|
|
172
187
|
models.push(model);
|
|
188
|
+
resolved.model_sources[model.id] = [...sources];
|
|
173
189
|
const [first, ...rest] = candidates;
|
|
174
190
|
const firstConfig = candidateConfig(deps, model.id, first);
|
|
175
191
|
const price = priceFor(model.id, first.provider);
|
|
@@ -379,7 +395,8 @@ export async function providersWithoutCredentials(deps, router) {
|
|
|
379
395
|
const provider = modelProvider(model);
|
|
380
396
|
if (missing.has(provider))
|
|
381
397
|
continue;
|
|
382
|
-
const
|
|
398
|
+
const sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
|
|
399
|
+
const plans = sources.includes("plan") ? modelSubscriptions(model.id) : [];
|
|
383
400
|
if (plans.some((plan) => deps.subscriptions.list(plan).length > 0))
|
|
384
401
|
continue;
|
|
385
402
|
if (await configuredProviderApiKey(deps, provider) === undefined)
|
|
@@ -12,7 +12,7 @@ import { refreshStaleUsage } from "./usage.js";
|
|
|
12
12
|
const BASE = "/v1/organizations/current/credentials";
|
|
13
13
|
// Subscription names are env-var-style, which keeps other credential routes
|
|
14
14
|
// such as `provider-credentials/...` out of these matches.
|
|
15
|
-
const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/
|
|
15
|
+
const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
|
|
16
16
|
class HttpError extends Error {
|
|
17
17
|
status;
|
|
18
18
|
constructor(status, message) {
|
|
@@ -81,13 +81,6 @@ export async function handleSubscriptionRequest(request, deps) {
|
|
|
81
81
|
if (action === "/mark-available" && request.method === "POST") {
|
|
82
82
|
return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
|
|
83
83
|
}
|
|
84
|
-
if (action === "/auto-reset" && request.method === "PUT") {
|
|
85
|
-
const body = await readBody(request);
|
|
86
|
-
if (typeof body.enabled !== "boolean")
|
|
87
|
-
throw new HttpError(400, "enabled must be true or false.");
|
|
88
|
-
const credential = resettable(found(deps.store.getByName(name), name));
|
|
89
|
-
return json(200, summary(deps.store, found(deps.store.setAutoRedeemResets(credential.name, body.enabled, now), name), now));
|
|
90
|
-
}
|
|
91
84
|
if (action === "/resets" && request.method === "GET") {
|
|
92
85
|
const credential = resettable(found(deps.store.getByName(name), name));
|
|
93
86
|
const resets = await fromProvider(() => listResets({ ...deps, now }, credential));
|
|
@@ -300,7 +293,6 @@ function credentialBody(credential, active, now) {
|
|
|
300
293
|
// The share of its tightest window the plan last reported used, and
|
|
301
294
|
// every window as shown; null when it reports none and is not held.
|
|
302
295
|
usage: usageBody(credential, now),
|
|
303
|
-
auto_redeem_resets: credential.autoRedeemResets,
|
|
304
296
|
};
|
|
305
297
|
}
|
|
306
298
|
function resettable(credential) {
|