@mupt-ai/dari-gateway 1.0.339 → 1.0.341
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 +9 -7
- package/dist/index.d.ts +1 -1
- package/dist/link/assets.js +7 -0
- package/dist/link/budget.d.ts +18 -7
- package/dist/link/budget.js +58 -16
- package/dist/link/endpoints.js +64 -45
- package/dist/link/errors.js +4 -1
- package/dist/link/self_hosted.d.ts +3 -1
- package/dist/link/self_hosted.js +25 -9
- package/dist/link/service.d.ts +4 -4
- package/dist/link/service.js +41 -22
- package/dist/models/catalog.js +1 -0
- package/dist/models/execution_provider.d.ts +6 -1
- package/dist/models/execution_provider.js +12 -0
- package/dist/models/provider_defaults.js +9 -0
- package/dist/models/provider_models.json +217 -0
- package/dist/models/subscriptions.d.ts +5 -0
- package/dist/models/subscriptions.js +21 -2
- package/dist/platform/platform.d.ts +11 -7
- package/dist/providers/execution.d.ts +5 -0
- package/dist/providers/execution.js +12 -2
- package/dist/providers/github_copilot.d.ts +8 -0
- package/dist/providers/github_copilot.js +21 -0
- package/dist/providers/pi.js +3 -0
- package/dist/providers/provider_attempt_runner.d.ts +2 -0
- package/dist/providers/provider_attempt_runner.js +9 -0
- package/dist/providers/provider_call.js +6 -2
- package/dist/providers/subscription_limits.d.ts +6 -5
- package/dist/providers/subscription_limits.js +20 -9
- package/dist/runtime/routed_runtime.js +68 -3
- package/dist/self_host/resolve.d.ts +11 -9
- package/dist/self_host/resolve.js +249 -182
- package/dist/self_host/subscriptions/index.d.ts +6 -5
- package/dist/self_host/subscriptions/index.js +6 -5
- package/dist/self_host/subscriptions/oauth.d.ts +7 -3
- package/dist/self_host/subscriptions/oauth.js +195 -5
- package/dist/self_host/subscriptions/store.js +3 -0
- package/dist/telemetry/prefix_state.d.ts +1 -0
- package/dist/telemetry/prefix_state.js +1 -1
- package/dist/telemetry/report.js +2 -3
- package/dist/types.d.ts +6 -2
- package/package.json +2 -2
- package/src/index.ts +1 -1
- package/src/link/assets.ts +7 -0
- package/src/link/budget.ts +53 -18
- package/src/link/endpoints.ts +66 -45
- package/src/link/errors.ts +4 -1
- package/src/link/self_hosted.ts +26 -8
- package/src/link/service.ts +45 -23
- package/src/models/catalog.ts +1 -0
- package/src/models/execution_provider.ts +24 -1
- package/src/models/provider_defaults.ts +9 -0
- package/src/models/provider_models.json +217 -0
- package/src/models/subscriptions.ts +22 -2
- package/src/platform/platform.ts +13 -8
- package/src/providers/execution.ts +22 -2
- package/src/providers/github_copilot.ts +24 -0
- package/src/providers/pi.ts +2 -0
- package/src/providers/provider_attempt_runner.ts +15 -0
- package/src/providers/provider_call.ts +6 -2
- package/src/providers/subscription_limits.ts +20 -10
- package/src/runtime/routed_runtime.ts +79 -3
- package/src/self_host/resolve.ts +255 -187
- package/src/self_host/subscriptions/index.ts +7 -4
- package/src/self_host/subscriptions/oauth.ts +264 -8
- package/src/self_host/subscriptions/store.ts +3 -0
- package/src/telemetry/prefix_state.ts +4 -1
- package/src/telemetry/report.ts +2 -3
- package/src/types.ts +27 -3
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { COPILOT_HEADERS } from "../../providers/github_copilot.js";
|
|
2
3
|
export const SUBSCRIPTION_PROVIDERS = [
|
|
3
4
|
"anthropic_claude_code",
|
|
4
5
|
"openai_codex",
|
|
5
6
|
"meta_muse",
|
|
6
7
|
"opencode_go",
|
|
8
|
+
"github_copilot",
|
|
9
|
+
"xai_grok",
|
|
10
|
+
"vercel_token_pass",
|
|
7
11
|
];
|
|
8
12
|
const OPENCODE_CONSOLE_URL = "https://opencode.ai/console";
|
|
9
13
|
export const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
@@ -59,8 +63,66 @@ const MUSE_KEY_LIFETIME_MS = 12 * 60 * 60_000;
|
|
|
59
63
|
// token before each mint. Without it the stored value is the sign-in token.
|
|
60
64
|
const MUSE_SIGN_IN_REFRESH_PREFIX = "refresh:";
|
|
61
65
|
export const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
|
|
66
|
+
// GitHub Copilot's sign-in, as VS Code's Copilot Chat runs it, for github.com
|
|
67
|
+
// accounts. The GitHub token it grants is the refresh token: it mints the
|
|
68
|
+
// short-lived Copilot token that serves requests.
|
|
69
|
+
const GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
70
|
+
const COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token";
|
|
71
|
+
const GITHUB_USER_URL = "https://api.github.com/user";
|
|
72
|
+
// Copilot tokens live about half an hour; mint the next one before then.
|
|
73
|
+
const COPILOT_TOKEN_SKEW_MS = 5 * 60_000;
|
|
74
|
+
// SuperGrok and X Premium sign in as xAI's Grok CLI does.
|
|
75
|
+
const XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
76
|
+
const DEVICE_SIGN_INS = {
|
|
77
|
+
github_copilot: {
|
|
78
|
+
vendor: "GitHub",
|
|
79
|
+
clientId: GITHUB_COPILOT_CLIENT_ID,
|
|
80
|
+
deviceCodeUrl: "https://github.com/login/device/code",
|
|
81
|
+
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
82
|
+
scope: "read:user",
|
|
83
|
+
headers: { "User-Agent": COPILOT_HEADERS["User-Agent"] },
|
|
84
|
+
},
|
|
85
|
+
xai_grok: {
|
|
86
|
+
vendor: "xAI",
|
|
87
|
+
clientId: XAI_CLIENT_ID,
|
|
88
|
+
deviceCodeUrl: "https://auth.x.ai/oauth2/device/code",
|
|
89
|
+
tokenUrl: "https://auth.x.ai/oauth2/token",
|
|
90
|
+
scope: "openid profile email offline_access grok-cli:access api:access",
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
function isDeviceProvider(provider) {
|
|
94
|
+
return provider in DEVICE_SIGN_INS;
|
|
95
|
+
}
|
|
96
|
+
export const GITHUB_APPROVAL_PENDING = approvalPending("GitHub");
|
|
97
|
+
export const XAI_APPROVAL_PENDING = approvalPending("xAI");
|
|
98
|
+
function approvalPending(vendor) {
|
|
99
|
+
return `${vendor} approval is still pending. Enter the code at ${vendor}, finish approval, then try again.`;
|
|
100
|
+
}
|
|
101
|
+
// Device-flow access tokens that state no lifetime last an hour.
|
|
102
|
+
const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
|
|
103
|
+
// A Token Pass is an AI Gateway key restricted to Token Pass, created on
|
|
104
|
+
// Vercel's Token Pass page (or with `vercel token-pass`) and pasted back.
|
|
105
|
+
const VERCEL_TOKEN_PASS_URL = "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Ftoken-pass";
|
|
106
|
+
// A Token Pass key carries no expiry; this only keeps refresh idle.
|
|
107
|
+
const VERCEL_KEY_LIFETIME_MS = 3650 * 24 * 60 * 60_000;
|
|
62
108
|
export async function startOAuth(provider, options) {
|
|
63
109
|
const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
|
|
110
|
+
if (provider === "vercel_token_pass") {
|
|
111
|
+
return { authorizationUrl: VERCEL_TOKEN_PASS_URL, expiresAt, userCode: null, flow: {} };
|
|
112
|
+
}
|
|
113
|
+
if (isDeviceProvider(provider)) {
|
|
114
|
+
const signIn = DEVICE_SIGN_INS[provider];
|
|
115
|
+
const device = await postForm(options.fetch, signIn.deviceCodeUrl, { client_id: signIn.clientId, ...(signIn.scope === undefined ? {} : { scope: signIn.scope }) }, `${signIn.vendor} device code request`, signIn.headers);
|
|
116
|
+
const complete = device.verification_uri_complete;
|
|
117
|
+
return {
|
|
118
|
+
authorizationUrl: typeof complete === "string" && complete.startsWith("https://")
|
|
119
|
+
? complete
|
|
120
|
+
: requiredString(device, "verification_uri"),
|
|
121
|
+
expiresAt,
|
|
122
|
+
userCode: requiredString(device, "user_code"),
|
|
123
|
+
flow: { device_code: requiredString(device, "device_code") },
|
|
124
|
+
};
|
|
125
|
+
}
|
|
64
126
|
if (provider === "opencode_go") {
|
|
65
127
|
const device = await postJson(options.fetch, `${OPENCODE_CONSOLE_URL}/auth/device/code`, { client_id: OPENCODE_CLIENT_ID, supports_org_scope: true }, "OpenCode device code request");
|
|
66
128
|
const verification = requiredString(device, "verification_uri_complete");
|
|
@@ -120,6 +182,23 @@ export async function startOAuth(provider, options) {
|
|
|
120
182
|
*/
|
|
121
183
|
export async function completeOAuth(provider, flow, authorizationResponse, options) {
|
|
122
184
|
const now = options.now ?? new Date();
|
|
185
|
+
if (provider === "vercel_token_pass")
|
|
186
|
+
return vercelTokenPassTokens(authorizationResponse, now);
|
|
187
|
+
if (isDeviceProvider(provider)) {
|
|
188
|
+
const token = await deviceApproval(provider, requiredString(flow, "device_code"), options.fetch);
|
|
189
|
+
if (provider === "github_copilot") {
|
|
190
|
+
const githubToken = requiredString(token, "access_token");
|
|
191
|
+
const tokens = await copilotTokens(githubToken, options.fetch, now).catch((error) => {
|
|
192
|
+
// GitHub mints no Copilot token for an account without a plan.
|
|
193
|
+
if (error instanceof SubscriptionOAuthProviderError && [401, 403, 404].includes(error.status ?? 0)) {
|
|
194
|
+
throw new SubscriptionOAuthInputError("This GitHub account has no active Copilot plan. Subscribe at https://github.com/features/copilot/plans, then connect again.");
|
|
195
|
+
}
|
|
196
|
+
throw error;
|
|
197
|
+
});
|
|
198
|
+
return { ...tokens, accountEmail: await githubAccount(options.fetch, githubToken) };
|
|
199
|
+
}
|
|
200
|
+
return deviceTokens(provider, token, now, null);
|
|
201
|
+
}
|
|
123
202
|
if (provider === "opencode_go") {
|
|
124
203
|
let token;
|
|
125
204
|
try {
|
|
@@ -215,6 +294,15 @@ export async function completeOAuth(provider, flow, authorizationResponse, optio
|
|
|
215
294
|
}
|
|
216
295
|
export async function refreshOAuth(credential, options) {
|
|
217
296
|
const now = options.now ?? new Date();
|
|
297
|
+
if (credential.provider === "vercel_token_pass")
|
|
298
|
+
return vercelTokenPassTokens(credential.refreshToken, now);
|
|
299
|
+
if (credential.provider === "github_copilot")
|
|
300
|
+
return await copilotTokens(credential.refreshToken, options.fetch, now);
|
|
301
|
+
if (isDeviceProvider(credential.provider)) {
|
|
302
|
+
const signIn = DEVICE_SIGN_INS[credential.provider];
|
|
303
|
+
const token = await postForm(options.fetch, signIn.tokenUrl, { grant_type: "refresh_token", client_id: signIn.clientId, refresh_token: credential.refreshToken }, `${signIn.vendor} sign-in refresh`, signIn.headers);
|
|
304
|
+
return deviceTokens(credential.provider, token, now, credential.refreshToken);
|
|
305
|
+
}
|
|
218
306
|
if (credential.provider === "opencode_go") {
|
|
219
307
|
const token = await postJson(options.fetch, OPENCODE_TOKEN_URL, { grant_type: "refresh_token", refresh_token: credential.refreshToken, client_id: OPENCODE_CLIENT_ID }, "OpenCode sign-in refresh");
|
|
220
308
|
return await opencodeGoTokens(token, credential.accountId, options.fetch, now);
|
|
@@ -376,16 +464,22 @@ function jwtPayload(token) {
|
|
|
376
464
|
function postJson(fetch, url, payload, operation) {
|
|
377
465
|
return requestJson(fetch, url, JSON.stringify(payload), "application/json", operation);
|
|
378
466
|
}
|
|
379
|
-
function postForm(fetch, url, payload, operation) {
|
|
380
|
-
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation);
|
|
467
|
+
function postForm(fetch, url, payload, operation, headers = {}) {
|
|
468
|
+
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation, headers);
|
|
381
469
|
}
|
|
470
|
+
// A null body is a GET.
|
|
382
471
|
async function requestJson(fetch, url, body, contentType, operation, headers = {}) {
|
|
383
472
|
let response;
|
|
384
473
|
try {
|
|
385
474
|
response = await fetch(url, {
|
|
386
|
-
method: "POST",
|
|
387
|
-
headers: {
|
|
388
|
-
|
|
475
|
+
method: body === null ? "GET" : "POST",
|
|
476
|
+
headers: {
|
|
477
|
+
Accept: "application/json",
|
|
478
|
+
...(body === null ? {} : { "Content-Type": contentType }),
|
|
479
|
+
"User-Agent": "Dari/1.0",
|
|
480
|
+
...headers,
|
|
481
|
+
},
|
|
482
|
+
...(body === null ? {} : { body }),
|
|
389
483
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
390
484
|
});
|
|
391
485
|
}
|
|
@@ -449,3 +543,99 @@ async function opencodeEmail(fetch, accessToken) {
|
|
|
449
543
|
return null;
|
|
450
544
|
}
|
|
451
545
|
}
|
|
546
|
+
// Ask a device sign-in whether the user approved its code. GitHub answers an
|
|
547
|
+
// unfinished sign-in with HTTP 200 and an `error`; the others with HTTP 400.
|
|
548
|
+
async function deviceApproval(provider, deviceCode, fetch) {
|
|
549
|
+
const signIn = DEVICE_SIGN_INS[provider];
|
|
550
|
+
let token;
|
|
551
|
+
let errorCode;
|
|
552
|
+
try {
|
|
553
|
+
token = await postForm(fetch, signIn.tokenUrl, {
|
|
554
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
555
|
+
device_code: deviceCode,
|
|
556
|
+
client_id: signIn.clientId,
|
|
557
|
+
}, `${signIn.vendor} device approval check`, signIn.headers);
|
|
558
|
+
errorCode = typeof token.error === "string" ? token.error : undefined;
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
if (!(error instanceof SubscriptionOAuthProviderError) || error.errorCode === undefined)
|
|
562
|
+
throw error;
|
|
563
|
+
token = {};
|
|
564
|
+
errorCode = error.errorCode;
|
|
565
|
+
}
|
|
566
|
+
if (errorCode === undefined)
|
|
567
|
+
return token;
|
|
568
|
+
if (errorCode === "authorization_pending" || errorCode === "slow_down") {
|
|
569
|
+
throw new SubscriptionOAuthInputError(approvalPending(signIn.vendor));
|
|
570
|
+
}
|
|
571
|
+
if (errorCode === "access_denied" || errorCode === "authorization_denied") {
|
|
572
|
+
throw new SubscriptionOAuthInputError(`The sign-in was declined on ${signIn.vendor}. Start again to retry.`);
|
|
573
|
+
}
|
|
574
|
+
if (errorCode === "expired_token") {
|
|
575
|
+
throw new SubscriptionOAuthInputError(`The ${signIn.vendor} sign-in code expired. Start again.`);
|
|
576
|
+
}
|
|
577
|
+
throw new SubscriptionOAuthProviderError(`${signIn.vendor} device approval check failed.`, undefined, errorCode);
|
|
578
|
+
}
|
|
579
|
+
// Grok tokens. A refresh that rotates no refresh token keeps the
|
|
580
|
+
// stored one; Grok's ID token names the account.
|
|
581
|
+
function deviceTokens(provider, payload, now, fallbackRefreshToken) {
|
|
582
|
+
const idToken = typeof payload.id_token === "string" ? payload.id_token : null;
|
|
583
|
+
const email = idToken === null ? undefined : jwtPayload(idToken)?.email;
|
|
584
|
+
const lifetime = payload.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveInt(payload.expires_in);
|
|
585
|
+
return {
|
|
586
|
+
provider,
|
|
587
|
+
accessToken: requiredString(payload, "access_token"),
|
|
588
|
+
refreshToken: refreshTokenFrom(payload, fallbackRefreshToken),
|
|
589
|
+
expiresAt: new Date(now.getTime() + lifetime * 1000),
|
|
590
|
+
accountId: null,
|
|
591
|
+
accountEmail: typeof email === "string" && email ? email : null,
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
// Mints the Copilot token that serves requests from the GitHub token.
|
|
595
|
+
async function copilotTokens(githubToken, fetch, now) {
|
|
596
|
+
const minted = await requestJson(fetch, COPILOT_TOKEN_URL, null, "", "GitHub Copilot token request", { ...COPILOT_HEADERS, Authorization: `Bearer ${githubToken}` });
|
|
597
|
+
const expiresAt = minted.expires_at;
|
|
598
|
+
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) {
|
|
599
|
+
throw new SubscriptionOAuthProviderError(INCOMPLETE);
|
|
600
|
+
}
|
|
601
|
+
return {
|
|
602
|
+
provider: "github_copilot",
|
|
603
|
+
accessToken: requiredString(minted, "token"),
|
|
604
|
+
refreshToken: githubToken,
|
|
605
|
+
expiresAt: new Date(Math.max(now.getTime(), expiresAt * 1000 - COPILOT_TOKEN_SKEW_MS)),
|
|
606
|
+
accountId: null,
|
|
607
|
+
accountEmail: null,
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
// The signed-in GitHub account's email, else its login; best effort.
|
|
611
|
+
async function githubAccount(fetch, githubToken) {
|
|
612
|
+
try {
|
|
613
|
+
const user = await requestJson(fetch, GITHUB_USER_URL, null, "", "GitHub account lookup", {
|
|
614
|
+
Authorization: `Bearer ${githubToken}`,
|
|
615
|
+
});
|
|
616
|
+
for (const field of ["email", "login"]) {
|
|
617
|
+
const value = user[field];
|
|
618
|
+
if (typeof value === "string" && value)
|
|
619
|
+
return value;
|
|
620
|
+
}
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
catch {
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
// The pasted key is both tokens; refreshing hands the same key back.
|
|
628
|
+
function vercelTokenPassTokens(key, now) {
|
|
629
|
+
const apiKey = key.trim();
|
|
630
|
+
if (!apiKey || /\s/.test(apiKey)) {
|
|
631
|
+
throw new SubscriptionOAuthInputError("Paste the Token Pass key you created at Vercel.");
|
|
632
|
+
}
|
|
633
|
+
return {
|
|
634
|
+
provider: "vercel_token_pass",
|
|
635
|
+
accessToken: apiKey,
|
|
636
|
+
refreshToken: apiKey,
|
|
637
|
+
expiresAt: new Date(now.getTime() + VERCEL_KEY_LIFETIME_MS),
|
|
638
|
+
accountId: null,
|
|
639
|
+
accountEmail: null,
|
|
640
|
+
};
|
|
641
|
+
}
|
|
@@ -11,6 +11,9 @@ const BASE_NAMES = {
|
|
|
11
11
|
openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
|
|
12
12
|
meta_muse: "META_MUSE_OAUTH_TOKEN",
|
|
13
13
|
opencode_go: "OPENCODE_GO_OAUTH_TOKEN",
|
|
14
|
+
github_copilot: "GITHUB_COPILOT_OAUTH_TOKEN",
|
|
15
|
+
xai_grok: "XAI_GROK_OAUTH_TOKEN",
|
|
16
|
+
vercel_token_pass: "VERCEL_TOKEN_PASS_API_KEY",
|
|
14
17
|
};
|
|
15
18
|
// Columns added after the table first shipped; existing databases gain them
|
|
16
19
|
// on open.
|
|
@@ -21,7 +21,7 @@ export function buildCompletedPrefixHit(args) {
|
|
|
21
21
|
loose_hash: looseOutputHash(args.looseChain, args.output, args.request.sourceProtocol),
|
|
22
22
|
conversation_id: args.conversationId,
|
|
23
23
|
model: args.model,
|
|
24
|
-
provider: args.
|
|
24
|
+
provider: args.provider,
|
|
25
25
|
next_model: args.nextModel,
|
|
26
26
|
next_reasoning_effort: args.nextReasoningEffort,
|
|
27
27
|
message_depth: args.chain.length + outputExtension.length,
|
package/dist/telemetry/report.js
CHANGED
|
@@ -289,6 +289,7 @@ export class RequestReporter {
|
|
|
289
289
|
chain: selectedChain,
|
|
290
290
|
looseChain: a.looseChain,
|
|
291
291
|
target: selectedTarget,
|
|
292
|
+
provider: selectedProvider ?? selectedTarget.provider,
|
|
292
293
|
conversationId: a.conversationId,
|
|
293
294
|
leaseDepth: a.leaseDepth,
|
|
294
295
|
providerBlockDepth: a.providerBlockDepthFor(selectedModel),
|
|
@@ -334,9 +335,7 @@ export class RequestReporter {
|
|
|
334
335
|
thinking: outcome.providerExecution?.thinkingLevel ?? reasoningBucket,
|
|
335
336
|
costUsd: costSource === null || !isRecord(usage?.cost) ? null : finiteNumber(usage.cost.total),
|
|
336
337
|
credentialId: keySource === "subscription"
|
|
337
|
-
? outcome.providerExecution?.subscriptionCredentialId ??
|
|
338
|
-
? a.credentials.subscription_credential_ids?.[selectedProvider] ?? null
|
|
339
|
-
: null)
|
|
338
|
+
? outcome.providerExecution?.subscriptionCredentialId ?? null
|
|
340
339
|
: selectedProvider ? a.credentials.link_key_credential_ids?.[selectedProvider] ?? null : null,
|
|
341
340
|
}
|
|
342
341
|
: undefined;
|
package/dist/types.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export type AwsAssumeRoleProviderAuth = {
|
|
|
18
18
|
region: string;
|
|
19
19
|
};
|
|
20
20
|
export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
|
|
21
|
-
export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go";
|
|
21
|
+
export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go" | "github_copilot" | "xai_grok" | "vercel_token_pass";
|
|
22
22
|
export type ProviderCredential = {
|
|
23
23
|
apiKey: string;
|
|
24
24
|
baseUrl?: string;
|
|
@@ -64,6 +64,10 @@ export type ResolvedRouterModelConfig = {
|
|
|
64
64
|
fast_mode_cost?: RouterModelPrice | null;
|
|
65
65
|
zdr?: boolean;
|
|
66
66
|
};
|
|
67
|
+
export type ModelFallback = {
|
|
68
|
+
config: ResolvedRouterModelConfig;
|
|
69
|
+
subscription?: SubscriptionKind | null;
|
|
70
|
+
};
|
|
67
71
|
/** Why a Dari Link grant cannot serve one provider's models now. */
|
|
68
72
|
export type LinkUnavailable = {
|
|
69
73
|
code: "subscription_exhausted" | "subscription_client_mismatch" | "grant_budget_exhausted";
|
|
@@ -83,7 +87,7 @@ export type ResolvedRouter = {
|
|
|
83
87
|
provider_auth?: Partial<Record<Provider, AwsProviderAuth>>;
|
|
84
88
|
provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
|
|
85
89
|
provider_credentials?: Record<string, ProviderCredential>;
|
|
86
|
-
|
|
90
|
+
model_fallbacks?: Record<string, ModelFallback[]>;
|
|
87
91
|
link_key_credential_ids?: Partial<Record<Provider, string>>;
|
|
88
92
|
link_grant_id?: string | null;
|
|
89
93
|
link_models?: string[];
|
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.341",
|
|
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.341",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
package/src/index.ts
CHANGED
|
@@ -27,4 +27,4 @@ export {
|
|
|
27
27
|
export { createAutoRoutingSelectorBackend } from "./strategies/auto_routing_selector.js";
|
|
28
28
|
export { createPrioritySelectorBackend } from "./strategies/priority_selector.js";
|
|
29
29
|
export { createLlmSelectorBackend, type SelectorBackend } from "./strategies/routing.js";
|
|
30
|
-
export type { ProviderCredential, ResolvedRouter, SubscriptionKind } from "./types.js";
|
|
30
|
+
export type { ModelFallback, ProviderCredential, ResolvedRouter, SubscriptionKind } from "./types.js";
|
package/src/link/assets.ts
CHANGED
|
@@ -11,6 +11,8 @@ const MARKS: Record<string, string> = {
|
|
|
11
11
|
anthropic: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.46H0L6.57 3.522zm4.132 9.959L8.453 7.687 6.205 13.48H10.7z"></path></svg>`,
|
|
12
12
|
claude: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"></path></svg>`,
|
|
13
13
|
gemini: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M12 24A14.304 14.304 0 000 12 14.304 14.304 0 0012 0a14.305 14.305 0 0012 12 14.305 14.305 0 00-12 12"></path></svg>`,
|
|
14
|
+
githubcopilot: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M19.245 5.364c1.322 1.36 1.877 3.216 2.11 5.817.622 0 1.2.135 1.592.654l.73.964c.21.278.323.61.323.955v2.62c0 .339-.173.669-.453.868C20.239 19.602 16.157 21.5 12 21.5c-4.6 0-9.205-2.583-11.547-4.258-.28-.2-.452-.53-.453-.868v-2.62c0-.345.113-.679.321-.956l.73-.963c.392-.517.974-.654 1.593-.654l.029-.297c.25-2.446.81-4.213 2.082-5.52 2.461-2.54 5.71-2.851 7.146-2.864h.198c1.436.013 4.685.323 7.146 2.864zm-7.244 4.328c-.284 0-.613.016-.962.05-.123.447-.305.85-.57 1.108-1.05 1.023-2.316 1.18-2.994 1.18-.638 0-1.306-.13-1.851-.464-.516.165-1.012.403-1.044.996a65.882 65.882 0 00-.063 2.884l-.002.48c-.002.563-.005 1.126-.013 1.69.002.326.204.63.51.765 2.482 1.102 4.83 1.657 6.99 1.657 2.156 0 4.504-.555 6.985-1.657a.854.854 0 00.51-.766c.03-1.682.006-3.372-.076-5.053-.031-.596-.528-.83-1.046-.996-.546.333-1.212.464-1.85.464-.677 0-1.942-.157-2.993-1.18-.266-.258-.447-.661-.57-1.108-.32-.032-.64-.049-.96-.05zm-2.525 4.013c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zm5 0c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zM7.635 5.087c-1.05.102-1.935.438-2.385.906-.975 1.037-.765 3.668-.21 4.224.405.394 1.17.657 1.995.657h.09c.649-.013 1.785-.176 2.73-1.11.435-.41.705-1.433.675-2.47-.03-.834-.27-1.52-.63-1.813-.39-.336-1.275-.482-2.265-.394zm6.465.394c-.36.292-.6.98-.63 1.813-.03 1.037.24 2.06.675 2.47.968.957 2.136 1.104 2.776 1.11h.044c.825 0 1.59-.263 1.995-.657.555-.556.765-3.187-.21-4.224-.45-.468-1.335-.804-2.385-.906-.99-.088-1.875.058-2.265.394zM12 7.615c-.24 0-.525.015-.84.044.03.16.045.336.06.526l-.001.159a2.94 2.94 0 01-.014.25c.225-.022.425-.027.612-.028h.366c.187 0 .387.006.612.028-.015-.146-.015-.277-.015-.409.015-.19.03-.365.06-.526a9.29 9.29 0 00-.84-.044z"></path></svg>`,
|
|
15
|
+
grok: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>`,
|
|
14
16
|
meta: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M6.897 4c1.915 0 3.516.932 5.43 3.376l.282-.373c.19-.246.383-.484.58-.71l.313-.35C14.588 4.788 15.792 4 17.225 4c1.273 0 2.469.557 3.491 1.516l.218.213c1.73 1.765 2.917 4.71 3.053 8.026l.011.392.002.25c0 1.501-.28 2.759-.818 3.7l-.14.23-.108.153c-.301.42-.664.758-1.086 1.009l-.265.142-.087.04a3.493 3.493 0 01-.302.118 4.117 4.117 0 01-1.33.208c-.524 0-.996-.067-1.438-.215-.614-.204-1.163-.56-1.726-1.116l-.227-.235c-.753-.812-1.534-1.976-2.493-3.586l-1.43-2.41-.544-.895-1.766 3.13-.343.592C7.597 19.156 6.227 20 4.356 20c-1.21 0-2.205-.42-2.936-1.182l-.168-.184c-.484-.573-.837-1.311-1.043-2.189l-.067-.32a8.69 8.69 0 01-.136-1.288L0 14.468c.002-.745.06-1.49.174-2.23l.1-.573c.298-1.53.828-2.958 1.536-4.157l.209-.34c1.177-1.83 2.789-3.053 4.615-3.16L6.897 4zm-.033 2.615l-.201.01c-.83.083-1.606.673-2.252 1.577l-.138.199-.01.018c-.67 1.017-1.185 2.378-1.456 3.845l-.004.022a12.591 12.591 0 00-.207 2.254l.002.188c.004.18.017.36.04.54l.043.291c.092.503.257.908.486 1.208l.117.137c.303.323.698.492 1.17.492 1.1 0 1.796-.676 3.696-3.641l2.175-3.4.454-.701-.139-.198C9.11 7.3 8.084 6.616 6.864 6.616zm10.196-.552l-.176.007c-.635.048-1.223.359-1.82.933l-.196.198c-.439.462-.887 1.064-1.367 1.807l.266.398c.18.274.362.56.55.858l.293.475 1.396 2.335.695 1.114c.583.926 1.03 1.6 1.408 2.082l.213.262c.282.326.529.54.777.673l.102.05c.227.1.457.138.718.138.176.002.35-.023.518-.073.338-.104.61-.32.813-.637l.095-.163.077-.162c.194-.459.29-1.06.29-1.785l-.006-.449c-.08-2.871-.938-5.372-2.2-6.798l-.176-.189c-.67-.683-1.444-1.074-2.27-1.074z"></path></svg>`,
|
|
15
17
|
moonshot: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M1.052 16.916l9.539 2.552a21.007 21.007 0 00.06 2.033l5.956 1.593a11.997 11.997 0 01-5.586.865l-.18-.016-.044-.004-.084-.009-.094-.01a11.605 11.605 0 01-.157-.02l-.107-.014-.11-.016a11.962 11.962 0 01-.32-.051l-.042-.008-.075-.013-.107-.02-.07-.015-.093-.019-.075-.016-.095-.02-.097-.023-.094-.022-.068-.017-.088-.022-.09-.024-.095-.025-.082-.023-.109-.03-.062-.02-.084-.025-.093-.028-.105-.034-.058-.019-.08-.026-.09-.031-.066-.024a6.293 6.293 0 01-.044-.015l-.068-.025-.101-.037-.057-.022-.08-.03-.087-.035-.088-.035-.079-.032-.095-.04-.063-.028-.063-.027a5.655 5.655 0 01-.041-.018l-.066-.03-.103-.047-.052-.024-.096-.046-.062-.03-.084-.04-.086-.044-.093-.047-.052-.027-.103-.055-.057-.03-.058-.032a6.49 6.49 0 01-.046-.026l-.094-.053-.06-.034-.051-.03-.072-.041-.082-.05-.093-.056-.052-.032-.084-.053-.061-.039-.079-.05-.07-.047-.053-.035a7.785 7.785 0 01-.054-.036l-.044-.03-.044-.03a6.066 6.066 0 01-.04-.028l-.057-.04-.076-.054-.069-.05-.074-.054-.056-.042-.076-.057-.076-.059-.086-.067-.045-.035-.064-.052-.074-.06-.089-.073-.046-.039-.046-.039a7.516 7.516 0 01-.043-.037l-.045-.04-.061-.053-.07-.062-.068-.06-.062-.058-.067-.062-.053-.05-.088-.084a13.28 13.28 0 01-.099-.097l-.029-.028-.041-.042-.069-.07-.05-.051-.05-.053a6.457 6.457 0 01-.168-.179l-.08-.088-.062-.07-.071-.08-.042-.049-.053-.062-.058-.068-.046-.056a7.175 7.175 0 01-.027-.033l-.045-.055-.066-.082-.041-.052-.05-.064-.02-.025a11.99 11.99 0 01-1.44-2.402zm-1.02-5.794l11.353 3.037a20.468 20.468 0 00-.469 2.011l10.817 2.894a12.076 12.076 0 01-1.845 2.005L.657 15.923l-.016-.046-.035-.104a11.965 11.965 0 01-.05-.153l-.007-.023a11.896 11.896 0 01-.207-.741l-.03-.126-.018-.08-.021-.097-.018-.081-.018-.09-.017-.084-.018-.094c-.026-.141-.05-.283-.071-.426l-.017-.118-.011-.083-.013-.102a12.01 12.01 0 01-.019-.161l-.005-.047a12.12 12.12 0 01-.034-2.145zm1.593-5.15l11.948 3.196c-.368.605-.705 1.231-1.01 1.875l11.295 3.022c-.142.82-.368 1.612-.668 2.365l-11.55-3.09L.124 10.26l.015-.1.008-.049.01-.067.015-.087.018-.098c.026-.148.056-.295.088-.442l.028-.124.02-.085.024-.097c.022-.09.045-.18.07-.268l.028-.102.023-.083.03-.1.025-.082.03-.096.026-.082.031-.095a11.896 11.896 0 011.01-2.232zm4.442-4.4L17.352 4.59a20.77 20.77 0 00-1.688 1.721l7.823 2.093c.267.852.442 1.744.513 2.665L2.106 5.213l.045-.065.027-.04.04-.055.046-.065.055-.076.054-.072.064-.086.05-.065.057-.073.055-.07.06-.074.055-.069.065-.077.054-.066.066-.077.053-.06.072-.082.053-.06.067-.074.054-.058.073-.078.058-.06.063-.067.168-.17.1-.098.059-.056.076-.071a12.084 12.084 0 012.272-1.677zM12.017 0h.097l.082.001.069.001.054.002.068.002.046.001.076.003.047.002.06.003.054.002.087.005.105.007.144.011.088.007.044.004.077.008.082.008.047.005.102.012.05.006.108.014.081.01.042.006.065.01.207.032.07.012.065.011.14.026.092.018.11.022.046.01.075.016.041.01L14.7.3l.042.01.065.015.049.012.071.017.096.024.112.03.113.03.113.032.05.015.07.02.078.024.073.023.05.016.05.016.076.025.099.033.102.036.048.017.064.023.093.034.11.041.116.045.1.04.047.02.06.024.041.018.063.026.04.018.057.025.11.048.1.046.074.035.075.036.06.028.092.046.091.045.102.052.053.028.049.026.046.024.06.033.041.022.052.029.088.05.106.06.087.051.057.034.053.032.096.059.088.055.098.062.036.024.064.041.084.056.04.027.062.042.062.043.023.017c.054.037.108.075.161.114l.083.06.065.048.056.043.086.065.082.064.04.03.05.041.086.069.079.065.085.071c.712.6 1.353 1.283 1.909 2.031L7.222.994l.062-.027.065-.028.081-.034.086-.035c.113-.045.227-.09.341-.131l.096-.035.093-.033.084-.03.096-.031c.087-.03.176-.058.264-.085l.091-.027.086-.025.102-.03.085-.023.1-.026L9.04.37l.09-.023.091-.022.095-.022.09-.02.098-.021.091-.02.095-.018.092-.018.1-.018.091-.016.098-.017.092-.014.097-.015.092-.013.102-.013.091-.012.105-.012.09-.01.105-.01c.093-.01.186-.018.28-.024l.106-.008.09-.005.11-.006.093-.004.1-.004.097-.002.099-.002.197-.002z"></path></svg>`,
|
|
16
18
|
openai: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></svg>`,
|
|
@@ -26,6 +28,9 @@ const MARK_FOR: Record<string, string> = {
|
|
|
26
28
|
openai_codex: "openai",
|
|
27
29
|
meta_muse: "meta",
|
|
28
30
|
opencode_go: "opencode",
|
|
31
|
+
github_copilot: "githubcopilot",
|
|
32
|
+
xai_grok: "grok",
|
|
33
|
+
vercel_token_pass: "vercel",
|
|
29
34
|
anthropic: "anthropic",
|
|
30
35
|
openai: "openai",
|
|
31
36
|
meta: "meta",
|
|
@@ -34,6 +39,8 @@ const MARK_FOR: Record<string, string> = {
|
|
|
34
39
|
google: "gemini",
|
|
35
40
|
openrouter: "openrouter",
|
|
36
41
|
"vercel-ai-gateway": "vercel",
|
|
42
|
+
"github-copilot": "githubcopilot",
|
|
43
|
+
"vercel-token-pass": "vercel",
|
|
37
44
|
};
|
|
38
45
|
|
|
39
46
|
/** The mark of a plan kind (`openai_codex`), key provider (`anthropic`), or gateway (`openrouter`); undefined when it has none. */
|
package/src/link/budget.ts
CHANGED
|
@@ -10,13 +10,15 @@
|
|
|
10
10
|
A window at its cap is back once enough of its oldest requests roll off to
|
|
11
11
|
bring it under the cap again: `resetsAt` is when that happens.
|
|
12
12
|
|
|
13
|
-
A grant may also limit
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
A grant may also limit each of its plans and API keys. A plan's limit is a
|
|
14
|
+
share of its own quota: while any plan-wide window the provider last
|
|
15
|
+
reported is at `maxPercent` used (by anyone, so the rest stays the user's),
|
|
16
|
+
the plan leaves the grant until that window resets. A plan with no reported
|
|
17
|
+
usage is never at its limit. An API key's limit is what the grant may spend
|
|
18
|
+
on it in a calendar month (UTC), as its provider charged; at the limit it
|
|
19
|
+
leaves the grant until the month ends. The grant serves on the rest. */
|
|
18
20
|
|
|
19
|
-
import type { LinkBudget, LinkLimit, LinkSpend, LinkUsageTotals } from "../platform/platform.js";
|
|
21
|
+
import type { LinkBudget, LinkLimit, LinkSpend, LinkSubscription, LinkUsageTotals } from "../platform/platform.js";
|
|
20
22
|
|
|
21
23
|
/** The windows a budget can cap: five hours and one week. */
|
|
22
24
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080] as const;
|
|
@@ -83,11 +85,12 @@ export function usesSince(budget: readonly LinkBudget[], now: Date): number {
|
|
|
83
85
|
return Math.min(now.getTime() - budgetLookbackMs(budget), monthStart(now).getTime());
|
|
84
86
|
}
|
|
85
87
|
|
|
86
|
-
/** Each granted plan or key's spend this month
|
|
88
|
+
/** Each granted plan or key's spend this month and standing against its limit. */
|
|
87
89
|
export function grantSpend(
|
|
88
90
|
credentialIds: Iterable<string>,
|
|
89
91
|
limits: readonly LinkLimit[],
|
|
90
92
|
uses: readonly BudgetUse[],
|
|
93
|
+
plans: readonly LinkSubscription[],
|
|
91
94
|
now: Date,
|
|
92
95
|
): LinkSpend[] {
|
|
93
96
|
const since = monthStart(now).getTime();
|
|
@@ -98,32 +101,61 @@ export function grantSpend(
|
|
|
98
101
|
}
|
|
99
102
|
return [...credentialIds].map((credentialId) => {
|
|
100
103
|
const spentUsd = spent.get(credentialId) ?? 0;
|
|
101
|
-
const
|
|
102
|
-
|
|
104
|
+
const limit = limits.find((entry) => entry.credentialId === credentialId);
|
|
105
|
+
const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
|
|
106
|
+
.filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
|
|
107
|
+
const usedPercent = windows.length === 0 ? null : Math.max(...windows.map((window) => window.utilization * 100));
|
|
108
|
+
let resetsAt: Date | null = null;
|
|
109
|
+
if (limit?.maxPercent !== undefined) {
|
|
110
|
+
const full = windows.filter((window) => window.utilization * 100 >= limit.maxPercent!);
|
|
111
|
+
if (full.length > 0) resetsAt = new Date(Math.max(...full.map((window) => Date.parse(window.resetsAt))));
|
|
112
|
+
} else if (limit?.monthlyUsd !== undefined && spentUsd >= limit.monthlyUsd) {
|
|
113
|
+
resetsAt = nextMonthStart(now);
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
credentialId,
|
|
117
|
+
spentUsd,
|
|
118
|
+
monthlyUsd: limit?.monthlyUsd ?? null,
|
|
119
|
+
maxPercent: limit?.maxPercent ?? null,
|
|
120
|
+
usedPercent,
|
|
121
|
+
reached: resetsAt !== null,
|
|
122
|
+
resetsAt: resetsAt?.toISOString() ?? null,
|
|
123
|
+
};
|
|
103
124
|
});
|
|
104
125
|
}
|
|
105
126
|
|
|
106
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* Limits from a request: `[{credential_id, max_percent}]` for a plan or
|
|
129
|
+
* `[{credential_id, monthly_usd}]` for an API key (the other field absent or
|
|
130
|
+
* null), each a distinct plan or key;
|
|
131
|
+
* `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
|
|
132
|
+
*/
|
|
107
133
|
export function validLimits(value: unknown): LinkLimit[] | null {
|
|
108
134
|
if (!Array.isArray(value)) return null;
|
|
109
135
|
const limits: LinkLimit[] = [];
|
|
110
136
|
for (const entry of value) {
|
|
111
137
|
if (typeof entry !== "object" || entry === null) return null;
|
|
112
|
-
const { credential_id: credentialId, monthly_usd: monthlyUsd } = entry as Record<string, unknown>;
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
138
|
+
const { credential_id: credentialId, monthly_usd: monthlyUsd, max_percent: maxPercent } = entry as Record<string, unknown>;
|
|
139
|
+
if (typeof credentialId !== "string" || credentialId.length === 0) return null;
|
|
140
|
+
if (limits.some((other) => other.credentialId === credentialId)) return null;
|
|
141
|
+
if (monthlyUsd == null
|
|
142
|
+
&& typeof maxPercent === "number" && Number.isFinite(maxPercent) && maxPercent > 0 && maxPercent <= 100) {
|
|
143
|
+
limits.push({ credentialId, maxPercent });
|
|
144
|
+
} else if (maxPercent == null
|
|
145
|
+
&& typeof monthlyUsd === "number" && Number.isFinite(monthlyUsd) && monthlyUsd >= 0) {
|
|
146
|
+
limits.push({ credentialId, monthlyUsd });
|
|
147
|
+
} else {
|
|
118
148
|
return null;
|
|
119
149
|
}
|
|
120
|
-
limits.push({ credentialId, monthlyUsd });
|
|
121
150
|
}
|
|
122
151
|
return limits;
|
|
123
152
|
}
|
|
124
153
|
|
|
125
154
|
export function limitsBody(limits: readonly LinkLimit[]) {
|
|
126
|
-
return limits.map((limit) => ({
|
|
155
|
+
return limits.map((limit) => ({
|
|
156
|
+
credential_id: limit.credentialId,
|
|
157
|
+
...(limit.maxPercent === undefined ? { monthly_usd: limit.monthlyUsd } : { max_percent: limit.maxPercent }),
|
|
158
|
+
}));
|
|
127
159
|
}
|
|
128
160
|
|
|
129
161
|
export function spendBody(spend: readonly LinkSpend[]) {
|
|
@@ -131,7 +163,10 @@ export function spendBody(spend: readonly LinkSpend[]) {
|
|
|
131
163
|
credential_id: entry.credentialId,
|
|
132
164
|
spent_usd: entry.spentUsd,
|
|
133
165
|
monthly_usd: entry.monthlyUsd,
|
|
166
|
+
max_percent: entry.maxPercent,
|
|
167
|
+
used_percent: entry.usedPercent,
|
|
134
168
|
reached: entry.reached,
|
|
169
|
+
resets_at: entry.resetsAt,
|
|
135
170
|
}));
|
|
136
171
|
}
|
|
137
172
|
|