@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
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { type BankedReset } from "../../providers/subscription_resets.js";
|
|
2
|
+
import { type Source } from "../../models/sources.js";
|
|
2
3
|
import type { OAuthFetch } from "./oauth.js";
|
|
3
4
|
import { type SubscriptionCredential, type SubscriptionStore } from "./store.js";
|
|
4
5
|
/**
|
|
5
6
|
* Banked limit resets of the gateway owner's ChatGPT and Claude Code plans, as
|
|
6
7
|
* hosted Dari spends them (dari-routing-backend subscription_recovery.ts and
|
|
7
8
|
* the control plane's subscription_resets.py): listed and spent on request,
|
|
8
|
-
* and
|
|
9
|
-
*
|
|
9
|
+
* and spent once every plan of its provider is held when the model's sources
|
|
10
|
+
* say so (models/sources.ts shouldSpendReset).
|
|
10
11
|
*/
|
|
12
|
+
/** The held model's sources and its router's reset threshold. */
|
|
13
|
+
export type ResetPolicy = {
|
|
14
|
+
sources: readonly Source[];
|
|
15
|
+
resetMinHours: number;
|
|
16
|
+
};
|
|
11
17
|
/** Where the gateway reaches Claude and ChatGPT: the config's endpoints, or the providers'. */
|
|
12
18
|
export type ProviderBaseUrls = {
|
|
13
19
|
claude?: string;
|
|
@@ -35,7 +41,7 @@ export declare function useReset(deps: ResetDeps, credential: SubscriptionCreden
|
|
|
35
41
|
* After a usage-limit hold on one of the owner's plans: correct a ChatGPT
|
|
36
42
|
* plan's hold from Codex's report, and once every plan of the provider is
|
|
37
43
|
* held, release one the provider already serves again or spend one banked
|
|
38
|
-
* reset on the plan that would stay out longest,
|
|
39
|
-
*
|
|
44
|
+
* reset on the plan that would stay out longest, when the policy says so.
|
|
45
|
+
* Returns whether a plan of the provider serves now.
|
|
40
46
|
*/
|
|
41
|
-
export declare function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential): Promise<boolean>;
|
|
47
|
+
export declare function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy): Promise<boolean>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { claimClaudeReset, claudeOrganizationUuid, claudeResetsFromReport, claudeUsageFromReport, claudeUsageReport, codexResets, codexUsage, consumeCodexReset, nextClaudeGrant, uuidv5, } from "../../providers/subscription_resets.js";
|
|
2
2
|
import { codexUsageFromReport, fetchCodexUsageReport } from "../../providers/codex_usage.js";
|
|
3
|
+
import { shouldSpendReset } from "../../models/sources.js";
|
|
3
4
|
import { refreshedAccessToken } from "./access.js";
|
|
4
5
|
import { isHeld } from "./store.js";
|
|
5
6
|
export function providerBaseUrls(providers) {
|
|
@@ -63,40 +64,44 @@ export async function useReset(deps, credential, resetId) {
|
|
|
63
64
|
* After a usage-limit hold on one of the owner's plans: correct a ChatGPT
|
|
64
65
|
* plan's hold from Codex's report, and once every plan of the provider is
|
|
65
66
|
* held, release one the provider already serves again or spend one banked
|
|
66
|
-
* reset on the plan that would stay out longest,
|
|
67
|
-
*
|
|
67
|
+
* reset on the plan that would stay out longest, when the policy says so.
|
|
68
|
+
* Returns whether a plan of the provider serves now.
|
|
68
69
|
*/
|
|
69
|
-
export async function recoverHeldPlans(deps, held) {
|
|
70
|
+
export async function recoverHeldPlans(deps, held, policy) {
|
|
70
71
|
const now = deps.now ?? new Date();
|
|
71
72
|
const serving = () => deps.store.activeCredential(held.provider, now) !== null;
|
|
72
73
|
try {
|
|
73
74
|
if (held.provider === "openai_codex")
|
|
74
|
-
await recoverCodex(deps, held, now, serving);
|
|
75
|
+
await recoverCodex(deps, held, policy, now, serving);
|
|
75
76
|
else if (held.provider === "anthropic_claude_code" && !serving())
|
|
76
|
-
await recoverClaude(deps, now);
|
|
77
|
+
await recoverClaude(deps, policy, now);
|
|
77
78
|
}
|
|
78
79
|
catch (error) {
|
|
79
80
|
console.error("subscription recovery failed", error instanceof Error ? error.message : String(error));
|
|
80
81
|
}
|
|
81
82
|
return serving();
|
|
82
83
|
}
|
|
83
|
-
async function recoverClaude(deps, now) {
|
|
84
|
+
async function recoverClaude(deps, policy, now) {
|
|
84
85
|
const candidates = deps.store.list("anthropic_claude_code")
|
|
85
|
-
.filter((plan) =>
|
|
86
|
+
.filter((plan) => isHeld(plan, now))
|
|
86
87
|
.sort((a, b) => b.unavailableUntil.getTime() - a.unavailableUntil.getTime());
|
|
87
88
|
for (const plan of candidates) {
|
|
88
|
-
const outcome = await claimOnHold(deps, plan, now);
|
|
89
|
+
const outcome = await claimOnHold(deps, plan, policy, now);
|
|
89
90
|
// At most one reset per outage.
|
|
90
91
|
if (outcome !== "skipped")
|
|
91
92
|
return;
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
|
-
async function claimOnHold(deps, plan, now) {
|
|
95
|
+
async function claimOnHold(deps, plan, policy, now) {
|
|
95
96
|
let token;
|
|
96
97
|
let grant = null;
|
|
97
98
|
try {
|
|
98
99
|
token = await refreshedAccessToken(deps.store, plan, deps);
|
|
99
|
-
const
|
|
100
|
+
const report = await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude);
|
|
101
|
+
const resets = claudeResetsFromReport(report);
|
|
102
|
+
if (!shouldSpendReset({ ...policy, returnsAt: plan.unavailableUntil, resets, now }))
|
|
103
|
+
return "skipped";
|
|
104
|
+
const grantId = nextClaudeGrant(report);
|
|
100
105
|
const organizationUuid = grantId === null ? null : await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
|
|
101
106
|
if (grantId !== null && organizationUuid !== null)
|
|
102
107
|
grant = { grantId, organizationUuid };
|
|
@@ -127,7 +132,7 @@ async function claimOnHold(deps, plan, now) {
|
|
|
127
132
|
// Claude declined without spending a reset; another plan may claim one.
|
|
128
133
|
return ["not_limited", "ineligible", "cooldown"].includes(result) ? "skipped" : "spent";
|
|
129
134
|
}
|
|
130
|
-
async function recoverCodex(deps, held, now, serving) {
|
|
135
|
+
async function recoverCodex(deps, held, policy, now, serving) {
|
|
131
136
|
const usages = new Map();
|
|
132
137
|
const usageOf = async (plan) => {
|
|
133
138
|
if (!usages.has(plan.id)) {
|
|
@@ -160,31 +165,32 @@ async function recoverCodex(deps, held, now, serving) {
|
|
|
160
165
|
return;
|
|
161
166
|
}
|
|
162
167
|
const back = naturalRecovery(usage, now);
|
|
163
|
-
if (
|
|
168
|
+
if (back !== null && usage.availableResets > 0)
|
|
164
169
|
candidates.push({ plan, recovery: back });
|
|
165
170
|
}
|
|
166
171
|
// The plan that would stay out longest gains the most from a reset.
|
|
167
172
|
candidates.sort((a, b) => b.recovery.getTime() - a.recovery.getTime());
|
|
168
173
|
for (const { plan, recovery: back } of candidates) {
|
|
169
|
-
const outcome = await redeemOnHold(deps, plan, back, now);
|
|
174
|
+
const outcome = await redeemOnHold(deps, plan, back, policy, now);
|
|
170
175
|
// At most one credit per outage, even when Codex has not caught up.
|
|
171
176
|
if (outcome !== "skipped")
|
|
172
177
|
return;
|
|
173
178
|
}
|
|
174
179
|
}
|
|
175
|
-
async function redeemOnHold(deps, plan, recovery, now) {
|
|
180
|
+
async function redeemOnHold(deps, plan, recovery, policy, now) {
|
|
176
181
|
let access;
|
|
177
|
-
let
|
|
182
|
+
let resets;
|
|
178
183
|
try {
|
|
179
184
|
access = codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps));
|
|
180
|
-
|
|
185
|
+
resets = await codexResets(deps.fetch, access);
|
|
181
186
|
}
|
|
182
187
|
catch (error) {
|
|
183
188
|
console.error("codex reset credit read failed", error instanceof Error ? error.message : String(error));
|
|
184
189
|
return "skipped";
|
|
185
190
|
}
|
|
186
|
-
if (
|
|
191
|
+
if (!shouldSpendReset({ ...policy, returnsAt: recovery, resets, now }))
|
|
187
192
|
return "skipped";
|
|
193
|
+
const creditId = resets[0].id;
|
|
188
194
|
let code;
|
|
189
195
|
try {
|
|
190
196
|
// One outage is one exhausted window, so its reset names it.
|
|
@@ -38,7 +38,6 @@ export type SubscriptionCredential = {
|
|
|
38
38
|
accountId: string | null;
|
|
39
39
|
owner: string | null;
|
|
40
40
|
private: boolean;
|
|
41
|
-
autoRedeemResets: boolean;
|
|
42
41
|
accessToken: string;
|
|
43
42
|
refreshToken: string;
|
|
44
43
|
expiresAt: Date;
|
|
@@ -170,8 +169,6 @@ export declare class SubscriptionStore {
|
|
|
170
169
|
rename(name: string, label: string | null, now?: Date): SubscriptionCredential | null;
|
|
171
170
|
/** Make the gateway owner's subscription private, or not. Null when it is not connected. */
|
|
172
171
|
setPrivate(name: string, isPrivate: boolean, now?: Date): SubscriptionCredential | null;
|
|
173
|
-
/** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
|
|
174
|
-
setAutoRedeemResets(name: string, enabled: boolean, now?: Date): SubscriptionCredential | null;
|
|
175
172
|
/** Remove a subscription. Returns what was removed, or null when it was not connected. */
|
|
176
173
|
disconnect(name: string, owner?: string | null): SubscriptionCredential | null;
|
|
177
174
|
/**
|
|
@@ -62,7 +62,7 @@ const ADDED_COLUMNS = {
|
|
|
62
62
|
model_holds: "TEXT",
|
|
63
63
|
owner: "TEXT",
|
|
64
64
|
private: "INTEGER",
|
|
65
|
-
auto_redeem_resets: "INTEGER",
|
|
65
|
+
auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
|
|
66
66
|
};
|
|
67
67
|
export class SubscriptionStore {
|
|
68
68
|
db;
|
|
@@ -429,18 +429,6 @@ export class SubscriptionStore {
|
|
|
429
429
|
this.onChange?.("plans");
|
|
430
430
|
return this.get(credential.id);
|
|
431
431
|
}
|
|
432
|
-
/** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
|
|
433
|
-
setAutoRedeemResets(name, enabled, now = new Date()) {
|
|
434
|
-
const credential = this.getByName(name);
|
|
435
|
-
if (credential === null)
|
|
436
|
-
return null;
|
|
437
|
-
this.db.run("UPDATE subscription_credentials SET auto_redeem_resets = ?, updated_at = ? WHERE id = ?", [
|
|
438
|
-
enabled ? 1 : 0,
|
|
439
|
-
now.getTime(),
|
|
440
|
-
credential.id,
|
|
441
|
-
]);
|
|
442
|
-
return this.get(credential.id);
|
|
443
|
-
}
|
|
444
432
|
/** Remove a subscription. Returns what was removed, or null when it was not connected. */
|
|
445
433
|
disconnect(name, owner = null) {
|
|
446
434
|
const credential = this.getByName(name, owner);
|
|
@@ -629,7 +617,6 @@ function credentialFromRow(row) {
|
|
|
629
617
|
accountId: row.account_id,
|
|
630
618
|
owner: row.owner,
|
|
631
619
|
private: row.private === 1,
|
|
632
|
-
autoRedeemResets: row.auto_redeem_resets === 1,
|
|
633
620
|
accessToken: row.access_token,
|
|
634
621
|
refreshToken: row.refresh_token,
|
|
635
622
|
expiresAt: new Date(row.expires_at),
|
|
@@ -168,9 +168,7 @@ export function providerAuthForSelectedModel(args) {
|
|
|
168
168
|
}
|
|
169
169
|
if (key)
|
|
170
170
|
return { type: "bearer", apiKey: key };
|
|
171
|
-
|
|
172
|
-
const prefix = source === "managed" ? "Dari-managed" : "stored";
|
|
173
|
-
throw new HttpError(401, `No ${prefix} ${providerLabel(provider)} provider credential is configured for this router.`, "missing_provider_key");
|
|
171
|
+
throw new HttpError(401, `No stored ${providerLabel(provider)} provider credential is configured for this router.`, "missing_provider_key");
|
|
174
172
|
}
|
|
175
173
|
function isAwsAssumeRoleProviderAuth(value) {
|
|
176
174
|
return (isRecord(value)
|
package/dist/telemetry/report.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { linkRequestRecorded, linkRequestStarted } from "../link/in_flight.js";
|
|
7
7
|
import { selectPrefixHit, } from "@mupt-ai/dari-router/policy-engine";
|
|
8
8
|
import { errorCode } from "../http/errors.js";
|
|
9
|
-
import { executionProviderForModel } from "../models/execution_provider.js";
|
|
9
|
+
import { executionProviderForModel, keySourceForModel } from "../models/execution_provider.js";
|
|
10
10
|
import { isBackgroundRequest, } from "../interaction/types.js";
|
|
11
11
|
import { captureOperationalError } from "../observability/errors.js";
|
|
12
12
|
import { gatewayPlatform } from "../platform/platform.js";
|
|
@@ -229,8 +229,8 @@ export class RequestReporter {
|
|
|
229
229
|
const selectedProvider = outcome.providerExecution?.provider ?? (selectedModel
|
|
230
230
|
? executionProviderForModel(a.credentials, selectedModel)
|
|
231
231
|
: null);
|
|
232
|
-
const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
|
|
233
|
-
? (a.credentials
|
|
232
|
+
const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
|
|
233
|
+
? keySourceForModel(a.credentials, selectedModel)
|
|
234
234
|
: null);
|
|
235
235
|
const selectedEstimate = a.costEstimates.find((item) => item.model === selectedModel &&
|
|
236
236
|
item.reasoning_effort === reasoningBucket);
|
package/dist/types.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Source } from "./models/sources.js";
|
|
1
2
|
import type { CustomRouterConfig, Provider, ReasoningEffort, RouterEval, RouterEvalScore, RouterModelPrice, RouterPrefixHit, RoutingDecision, RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
|
|
2
3
|
export type ProviderKeySource = "user" | "managed" | "subscription";
|
|
3
4
|
export type BearerProviderAuth = {
|
|
@@ -25,6 +26,7 @@ export type ProviderCredential = {
|
|
|
25
26
|
headers?: Record<string, string>;
|
|
26
27
|
subscription?: SubscriptionKind;
|
|
27
28
|
credentialId?: string;
|
|
29
|
+
managed?: true;
|
|
28
30
|
};
|
|
29
31
|
export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
|
|
30
32
|
export type AwsProviderAuth = AwsSigV4ProviderAuth | AwsAssumeRoleProviderAuth;
|
|
@@ -67,6 +69,7 @@ export type ResolvedRouterModelConfig = {
|
|
|
67
69
|
export type ModelFallback = {
|
|
68
70
|
config: ResolvedRouterModelConfig;
|
|
69
71
|
subscription?: SubscriptionKind | null;
|
|
72
|
+
managed?: true;
|
|
70
73
|
};
|
|
71
74
|
/** Why a Dari Link grant cannot serve one provider's models now. */
|
|
72
75
|
export type LinkUnavailable = {
|
|
@@ -86,6 +89,7 @@ export type ResolvedRouter = {
|
|
|
86
89
|
provider_keys: Partial<Record<Provider, string>>;
|
|
87
90
|
provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
|
|
88
91
|
provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
|
|
92
|
+
managed_keys?: Partial<Record<Provider, string>>;
|
|
89
93
|
provider_credentials?: Record<string, ProviderCredential>;
|
|
90
94
|
model_fallbacks?: Record<string, ModelFallback[]>;
|
|
91
95
|
link_key_credential_ids?: Partial<Record<Provider, string>>;
|
|
@@ -107,6 +111,8 @@ export type ResolvedRouter = {
|
|
|
107
111
|
session_pinning?: boolean;
|
|
108
112
|
native_compaction?: boolean;
|
|
109
113
|
primary_retries?: number;
|
|
114
|
+
model_sources?: Record<string, Source[]>;
|
|
115
|
+
reset_min_hours?: number;
|
|
110
116
|
strict?: boolean;
|
|
111
117
|
strict_providers?: string[];
|
|
112
118
|
evals?: RouterEval[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.358",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.358",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -16,17 +16,17 @@ export function executionProviderForModel(
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* user-owned so unknown platform data cannot trigger managed-key billing.
|
|
19
|
+
* Who pays for the key that serves a model: a supplied plan, Dari's managed
|
|
20
|
+
* key (billed to credits), or otherwise the router's own saved key.
|
|
22
21
|
*/
|
|
23
22
|
export function keySourceForModel(
|
|
24
23
|
credentials: ResolvedRouter,
|
|
25
24
|
model: string,
|
|
26
25
|
): ProviderKeySource {
|
|
27
26
|
const supplied = credentials.provider_credentials?.[model];
|
|
28
|
-
if (supplied) return
|
|
29
|
-
|
|
27
|
+
if (supplied?.subscription) return "subscription";
|
|
28
|
+
if (supplied?.managed) return "managed";
|
|
29
|
+
return "user";
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
/**
|
|
@@ -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. */
|
|
@@ -574,6 +575,10 @@ export type SubscriptionHold = {
|
|
|
574
575
|
// The Dari Link grant the request ran under; another plan serves a retry
|
|
575
576
|
// only when the grant may use it.
|
|
576
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;
|
|
577
582
|
};
|
|
578
583
|
|
|
579
584
|
export type NextSubscriptionRequest = {
|
|
@@ -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,
|