@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
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
type CodexUsage,
|
|
15
15
|
} from "../../providers/subscription_resets.js";
|
|
16
16
|
import { codexUsageFromReport, fetchCodexUsageReport } from "../../providers/codex_usage.js";
|
|
17
|
+
import { shouldSpendReset, type Source } from "../../models/sources.js";
|
|
17
18
|
import { refreshedAccessToken } from "./access.js";
|
|
18
19
|
import type { OAuthFetch, SubscriptionProvider } from "./oauth.js";
|
|
19
20
|
import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./store.js";
|
|
@@ -22,10 +23,13 @@ import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./s
|
|
|
22
23
|
* Banked limit resets of the gateway owner's ChatGPT and Claude Code plans, as
|
|
23
24
|
* hosted Dari spends them (dari-routing-backend subscription_recovery.ts and
|
|
24
25
|
* the control plane's subscription_resets.py): listed and spent on request,
|
|
25
|
-
* and
|
|
26
|
-
*
|
|
26
|
+
* and spent once every plan of its provider is held when the model's sources
|
|
27
|
+
* say so (models/sources.ts shouldSpendReset).
|
|
27
28
|
*/
|
|
28
29
|
|
|
30
|
+
/** The held model's sources and its router's reset threshold. */
|
|
31
|
+
export type ResetPolicy = { sources: readonly Source[]; resetMinHours: number };
|
|
32
|
+
|
|
29
33
|
/** Where the gateway reaches Claude and ChatGPT: the config's endpoints, or the providers'. */
|
|
30
34
|
export type ProviderBaseUrls = { claude?: string; codex?: string };
|
|
31
35
|
|
|
@@ -97,38 +101,41 @@ export async function useReset(deps: ResetDeps, credential: SubscriptionCredenti
|
|
|
97
101
|
* After a usage-limit hold on one of the owner's plans: correct a ChatGPT
|
|
98
102
|
* plan's hold from Codex's report, and once every plan of the provider is
|
|
99
103
|
* held, release one the provider already serves again or spend one banked
|
|
100
|
-
* reset on the plan that would stay out longest,
|
|
101
|
-
*
|
|
104
|
+
* reset on the plan that would stay out longest, when the policy says so.
|
|
105
|
+
* Returns whether a plan of the provider serves now.
|
|
102
106
|
*/
|
|
103
|
-
export async function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential): Promise<boolean> {
|
|
107
|
+
export async function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy): Promise<boolean> {
|
|
104
108
|
const now = deps.now ?? new Date();
|
|
105
109
|
const serving = () => deps.store.activeCredential(held.provider, now) !== null;
|
|
106
110
|
try {
|
|
107
|
-
if (held.provider === "openai_codex") await recoverCodex(deps, held, now, serving);
|
|
108
|
-
else if (held.provider === "anthropic_claude_code" && !serving()) await recoverClaude(deps, now);
|
|
111
|
+
if (held.provider === "openai_codex") await recoverCodex(deps, held, policy, now, serving);
|
|
112
|
+
else if (held.provider === "anthropic_claude_code" && !serving()) await recoverClaude(deps, policy, now);
|
|
109
113
|
} catch (error) {
|
|
110
114
|
console.error("subscription recovery failed", error instanceof Error ? error.message : String(error));
|
|
111
115
|
}
|
|
112
116
|
return serving();
|
|
113
117
|
}
|
|
114
118
|
|
|
115
|
-
async function recoverClaude(deps: ResetDeps, now: Date): Promise<void> {
|
|
119
|
+
async function recoverClaude(deps: ResetDeps, policy: ResetPolicy, now: Date): Promise<void> {
|
|
116
120
|
const candidates = deps.store.list("anthropic_claude_code")
|
|
117
|
-
.filter((plan) =>
|
|
121
|
+
.filter((plan) => isHeld(plan, now))
|
|
118
122
|
.sort((a, b) => b.unavailableUntil!.getTime() - a.unavailableUntil!.getTime());
|
|
119
123
|
for (const plan of candidates) {
|
|
120
|
-
const outcome = await claimOnHold(deps, plan, now);
|
|
124
|
+
const outcome = await claimOnHold(deps, plan, policy, now);
|
|
121
125
|
// At most one reset per outage.
|
|
122
126
|
if (outcome !== "skipped") return;
|
|
123
127
|
}
|
|
124
128
|
}
|
|
125
129
|
|
|
126
|
-
async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, now: Date): Promise<"skipped" | "spent" | "restored"> {
|
|
130
|
+
async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, policy: ResetPolicy, now: Date): Promise<"skipped" | "spent" | "restored"> {
|
|
127
131
|
let token: string;
|
|
128
132
|
let grant: { grantId: string; organizationUuid: string } | null = null;
|
|
129
133
|
try {
|
|
130
134
|
token = await refreshedAccessToken(deps.store, plan, deps);
|
|
131
|
-
const
|
|
135
|
+
const report = await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude);
|
|
136
|
+
const resets = claudeResetsFromReport(report);
|
|
137
|
+
if (!shouldSpendReset({ ...policy, returnsAt: plan.unavailableUntil!, resets, now })) return "skipped";
|
|
138
|
+
const grantId = nextClaudeGrant(report);
|
|
132
139
|
const organizationUuid = grantId === null ? null : await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
|
|
133
140
|
if (grantId !== null && organizationUuid !== null) grant = { grantId, organizationUuid };
|
|
134
141
|
} catch (error) {
|
|
@@ -156,7 +163,7 @@ async function claimOnHold(deps: ResetDeps, plan: SubscriptionCredential, now: D
|
|
|
156
163
|
return ["not_limited", "ineligible", "cooldown"].includes(result) ? "skipped" : "spent";
|
|
157
164
|
}
|
|
158
165
|
|
|
159
|
-
async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, now: Date, serving: () => boolean): Promise<void> {
|
|
166
|
+
async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, policy: ResetPolicy, now: Date, serving: () => boolean): Promise<void> {
|
|
160
167
|
const usages = new Map<string, CodexUsage | null>();
|
|
161
168
|
const usageOf = async (plan: SubscriptionCredential) => {
|
|
162
169
|
if (!usages.has(plan.id)) {
|
|
@@ -185,28 +192,29 @@ async function recoverCodex(deps: ResetDeps, held: SubscriptionCredential, now:
|
|
|
185
192
|
return;
|
|
186
193
|
}
|
|
187
194
|
const back = naturalRecovery(usage, now);
|
|
188
|
-
if (
|
|
195
|
+
if (back !== null && usage.availableResets > 0) candidates.push({ plan, recovery: back });
|
|
189
196
|
}
|
|
190
197
|
// The plan that would stay out longest gains the most from a reset.
|
|
191
198
|
candidates.sort((a, b) => b.recovery.getTime() - a.recovery.getTime());
|
|
192
199
|
for (const { plan, recovery: back } of candidates) {
|
|
193
|
-
const outcome = await redeemOnHold(deps, plan, back, now);
|
|
200
|
+
const outcome = await redeemOnHold(deps, plan, back, policy, now);
|
|
194
201
|
// At most one credit per outage, even when Codex has not caught up.
|
|
195
202
|
if (outcome !== "skipped") return;
|
|
196
203
|
}
|
|
197
204
|
}
|
|
198
205
|
|
|
199
|
-
async function redeemOnHold(deps: ResetDeps, plan: SubscriptionCredential, recovery: Date, now: Date): Promise<"skipped" | "spent" | "restored"> {
|
|
206
|
+
async function redeemOnHold(deps: ResetDeps, plan: SubscriptionCredential, recovery: Date, policy: ResetPolicy, now: Date): Promise<"skipped" | "spent" | "restored"> {
|
|
200
207
|
let access: CodexAccess;
|
|
201
|
-
let
|
|
208
|
+
let resets: BankedReset[];
|
|
202
209
|
try {
|
|
203
210
|
access = codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps));
|
|
204
|
-
|
|
211
|
+
resets = await codexResets(deps.fetch, access);
|
|
205
212
|
} catch (error) {
|
|
206
213
|
console.error("codex reset credit read failed", error instanceof Error ? error.message : String(error));
|
|
207
214
|
return "skipped";
|
|
208
215
|
}
|
|
209
|
-
if (
|
|
216
|
+
if (!shouldSpendReset({ ...policy, returnsAt: recovery, resets, now })) return "skipped";
|
|
217
|
+
const creditId = resets[0]!.id;
|
|
210
218
|
let code: string;
|
|
211
219
|
try {
|
|
212
220
|
// One outage is one exhausted window, so its reset names it.
|
|
@@ -53,9 +53,6 @@ export type SubscriptionCredential = {
|
|
|
53
53
|
// Kept off hosted Dari: a gateway connected to it neither serves nor
|
|
54
54
|
// reports the plan.
|
|
55
55
|
private: boolean;
|
|
56
|
-
// Whether routing may spend the plan's banked limit resets once every plan
|
|
57
|
-
// of its provider is held (ChatGPT and Claude Code).
|
|
58
|
-
autoRedeemResets: boolean;
|
|
59
56
|
accessToken: string;
|
|
60
57
|
refreshToken: string;
|
|
61
58
|
expiresAt: Date;
|
|
@@ -87,6 +84,9 @@ export type PendingOAuthSession = {
|
|
|
87
84
|
owner: string | null;
|
|
88
85
|
// Whether the plan connects as private (see SubscriptionCredential).
|
|
89
86
|
private: boolean;
|
|
87
|
+
// The plan on hosted Dari this sign-in moves here, by name: its account is
|
|
88
|
+
// not a second copy, since the caller disconnects it there next.
|
|
89
|
+
movingFrom: string | null;
|
|
90
90
|
expiresAt: Date;
|
|
91
91
|
};
|
|
92
92
|
|
|
@@ -165,7 +165,6 @@ type CredentialRow = {
|
|
|
165
165
|
account_id: string | null;
|
|
166
166
|
owner: string | null;
|
|
167
167
|
private: number | null;
|
|
168
|
-
auto_redeem_resets: number | null;
|
|
169
168
|
access_token: string;
|
|
170
169
|
refresh_token: string;
|
|
171
170
|
expires_at: number;
|
|
@@ -192,7 +191,7 @@ const ADDED_COLUMNS = {
|
|
|
192
191
|
model_holds: "TEXT",
|
|
193
192
|
owner: "TEXT",
|
|
194
193
|
private: "INTEGER",
|
|
195
|
-
auto_redeem_resets: "INTEGER",
|
|
194
|
+
auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
|
|
196
195
|
} as const;
|
|
197
196
|
|
|
198
197
|
type SessionRow = {
|
|
@@ -202,6 +201,7 @@ type SessionRow = {
|
|
|
202
201
|
credential_name: string | null;
|
|
203
202
|
owner: string | null;
|
|
204
203
|
private: number | null;
|
|
204
|
+
moving_from: string | null;
|
|
205
205
|
expires_at: number;
|
|
206
206
|
};
|
|
207
207
|
|
|
@@ -268,12 +268,13 @@ export class SubscriptionStore {
|
|
|
268
268
|
credential_name TEXT,
|
|
269
269
|
owner TEXT,
|
|
270
270
|
private INTEGER,
|
|
271
|
+
moving_from TEXT,
|
|
271
272
|
expires_at INTEGER NOT NULL
|
|
272
273
|
)`);
|
|
273
274
|
const sessionColumns = new Set(
|
|
274
275
|
db.query<{ name: string }, []>("PRAGMA table_info(subscription_oauth_sessions)").all().map((column) => column.name),
|
|
275
276
|
);
|
|
276
|
-
for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"]] as const) {
|
|
277
|
+
for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"], ["moving_from", "TEXT"]] as const) {
|
|
277
278
|
if (!sessionColumns.has(column)) db.run(`ALTER TABLE subscription_oauth_sessions ADD COLUMN ${column} ${type}`);
|
|
278
279
|
}
|
|
279
280
|
this.encryptStored();
|
|
@@ -629,18 +630,6 @@ export class SubscriptionStore {
|
|
|
629
630
|
return this.get(credential.id);
|
|
630
631
|
}
|
|
631
632
|
|
|
632
|
-
/** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
|
|
633
|
-
setAutoRedeemResets(name: string, enabled: boolean, now = new Date()): SubscriptionCredential | null {
|
|
634
|
-
const credential = this.getByName(name);
|
|
635
|
-
if (credential === null) return null;
|
|
636
|
-
this.db.run("UPDATE subscription_credentials SET auto_redeem_resets = ?, updated_at = ? WHERE id = ?", [
|
|
637
|
-
enabled ? 1 : 0,
|
|
638
|
-
now.getTime(),
|
|
639
|
-
credential.id,
|
|
640
|
-
]);
|
|
641
|
-
return this.get(credential.id);
|
|
642
|
-
}
|
|
643
|
-
|
|
644
633
|
/** Remove a subscription. Returns what was removed, or null when it was not connected. */
|
|
645
634
|
disconnect(name: string, owner: string | null = null): SubscriptionCredential | null {
|
|
646
635
|
const credential = this.getByName(name, owner);
|
|
@@ -711,8 +700,8 @@ export class SubscriptionStore {
|
|
|
711
700
|
const token = randomBytes(32).toString("base64url");
|
|
712
701
|
this.db.run("DELETE FROM subscription_oauth_sessions WHERE expires_at <= ?", [now.getTime()]);
|
|
713
702
|
this.db.run(
|
|
714
|
-
`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, expires_at)
|
|
715
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
703
|
+
`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, moving_from, expires_at)
|
|
704
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
716
705
|
[
|
|
717
706
|
token,
|
|
718
707
|
session.provider,
|
|
@@ -720,6 +709,7 @@ export class SubscriptionStore {
|
|
|
720
709
|
session.credentialName,
|
|
721
710
|
session.owner,
|
|
722
711
|
session.private ? 1 : 0,
|
|
712
|
+
session.movingFrom,
|
|
723
713
|
session.expiresAt.getTime(),
|
|
724
714
|
],
|
|
725
715
|
);
|
|
@@ -739,6 +729,7 @@ export class SubscriptionStore {
|
|
|
739
729
|
credentialName: row.credential_name,
|
|
740
730
|
owner: row.owner,
|
|
741
731
|
private: row.private === 1,
|
|
732
|
+
movingFrom: row.moving_from,
|
|
742
733
|
expiresAt: new Date(row.expires_at),
|
|
743
734
|
};
|
|
744
735
|
}
|
|
@@ -852,7 +843,6 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
|
|
|
852
843
|
accountId: row.account_id,
|
|
853
844
|
owner: row.owner,
|
|
854
845
|
private: row.private === 1,
|
|
855
|
-
autoRedeemResets: row.auto_redeem_resets === 1,
|
|
856
846
|
accessToken: row.access_token,
|
|
857
847
|
refreshToken: row.refresh_token,
|
|
858
848
|
expiresAt: new Date(row.expires_at),
|
|
@@ -313,11 +313,9 @@ export function providerAuthForSelectedModel(args: {
|
|
|
313
313
|
return structured;
|
|
314
314
|
}
|
|
315
315
|
if (key) return { type: "bearer", apiKey: key };
|
|
316
|
-
const source = args.credentials.provider_key_sources?.[provider] ?? "user";
|
|
317
|
-
const prefix = source === "managed" ? "Dari-managed" : "stored";
|
|
318
316
|
throw new HttpError(
|
|
319
317
|
401,
|
|
320
|
-
`No
|
|
318
|
+
`No stored ${providerLabel(provider)} provider credential is configured for this router.`,
|
|
321
319
|
"missing_provider_key",
|
|
322
320
|
);
|
|
323
321
|
}
|
package/src/telemetry/report.ts
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
} from "@mupt-ai/dari-router/policy-engine";
|
|
19
19
|
import type { ImageCapabilityPrunedModel } from "../context/routing_context.js";
|
|
20
20
|
import { HttpError, errorCode } from "../http/errors.js";
|
|
21
|
-
import { executionProviderForModel } from "../models/execution_provider.js";
|
|
21
|
+
import { executionProviderForModel, keySourceForModel } from "../models/execution_provider.js";
|
|
22
22
|
import {
|
|
23
23
|
isBackgroundRequest,
|
|
24
24
|
type InteractionOutput,
|
|
@@ -396,8 +396,8 @@ export class RequestReporter {
|
|
|
396
396
|
const selectedProvider = outcome.providerExecution?.provider ?? (selectedModel
|
|
397
397
|
? executionProviderForModel(a.credentials, selectedModel)
|
|
398
398
|
: null);
|
|
399
|
-
const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
|
|
400
|
-
? (a.credentials
|
|
399
|
+
const keySource = outcome.providerExecution?.providerKeySource ?? (selectedModel
|
|
400
|
+
? keySourceForModel(a.credentials, selectedModel)
|
|
401
401
|
: null);
|
|
402
402
|
const selectedEstimate = a.costEstimates.find(
|
|
403
403
|
(item) =>
|
package/src/types.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Source } from "./models/sources.js";
|
|
1
2
|
import type {
|
|
2
3
|
CustomRouterConfig,
|
|
3
4
|
Provider,
|
|
@@ -74,6 +75,8 @@ export type ProviderCredential = {
|
|
|
74
75
|
subscription?: SubscriptionKind;
|
|
75
76
|
// A resolved personal plan: quota holds and usage belong to this credential.
|
|
76
77
|
credentialId?: string;
|
|
78
|
+
// Dari's managed key: billed to the organization's credits.
|
|
79
|
+
managed?: true;
|
|
77
80
|
};
|
|
78
81
|
|
|
79
82
|
export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
|
|
@@ -138,6 +141,8 @@ export type ResolvedRouterModelConfig = {
|
|
|
138
141
|
export type ModelFallback = {
|
|
139
142
|
config: ResolvedRouterModelConfig;
|
|
140
143
|
subscription?: SubscriptionKind | null;
|
|
144
|
+
// Served by Dari's managed key for config.provider (managed_keys).
|
|
145
|
+
managed?: true;
|
|
141
146
|
};
|
|
142
147
|
|
|
143
148
|
/** Why a Dari Link grant cannot serve one provider's models now. */
|
|
@@ -160,7 +165,11 @@ export type ResolvedRouter = {
|
|
|
160
165
|
enabled_models: string[];
|
|
161
166
|
provider_keys: Partial<Record<Provider, string>>;
|
|
162
167
|
provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
|
|
168
|
+
// Describes only the router's saved keys above ("user"); a managed key is
|
|
169
|
+
// supplied per model (provider_credentials, managed_keys).
|
|
163
170
|
provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
|
|
171
|
+
// Dari's managed key per provider, for managed fallbacks.
|
|
172
|
+
managed_keys?: Partial<Record<Provider, string>>;
|
|
164
173
|
// Model -> the platform-supplied credential that replaces the provider key
|
|
165
174
|
// above for this request. Supplied by resolveRouter or resolveProviderCredential.
|
|
166
175
|
provider_credentials?: Record<string, ProviderCredential>;
|
|
@@ -202,6 +211,11 @@ export type ResolvedRouter = {
|
|
|
202
211
|
// support it.
|
|
203
212
|
native_compaction?: boolean;
|
|
204
213
|
primary_retries?: number;
|
|
214
|
+
// Each enabled model's sources (models/sources.ts), and how long a plan must
|
|
215
|
+
// otherwise stay out before a banked reset is spent on it. A model with no
|
|
216
|
+
// entry never spends one.
|
|
217
|
+
model_sources?: Record<string, Source[]>;
|
|
218
|
+
reset_min_hours?: number;
|
|
205
219
|
// Serve only the requested `dari/model/<id>` at the requested thinking
|
|
206
220
|
// level: no selector, lease, or personal subscription the platform did not
|
|
207
221
|
// supply through resolveProviderCredential, and an error for anything
|