@mupt-ai/dari-gateway 1.0.340 → 1.0.342
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/dist/activity/tool_exchanges.d.ts +0 -1
- package/dist/activity/values.d.ts +0 -1
- package/dist/activity/values.js +0 -4
- package/dist/ingress/codex_models.d.ts +2 -2
- package/dist/ingress/codex_models.js +34 -7
- package/dist/link/budget.d.ts +20 -7
- package/dist/link/budget.js +68 -18
- package/dist/link/endpoints.js +38 -39
- package/dist/link/errors.js +1 -1
- package/dist/link/grant_access.js +9 -4
- package/dist/link/grants.d.ts +0 -1
- package/dist/link/self_hosted.d.ts +3 -1
- package/dist/link/self_hosted.js +17 -7
- package/dist/link/service.d.ts +4 -4
- package/dist/link/service.js +41 -22
- package/dist/platform/platform.d.ts +13 -7
- package/dist/providers/subscription_limits.d.ts +6 -0
- package/dist/providers/subscription_limits.js +14 -0
- package/dist/self_host/resolve.js +2 -1
- package/dist/self_host/subscriptions/index.d.ts +3 -3
- package/dist/self_host/subscriptions/index.js +3 -3
- package/dist/self_host/subscriptions/usage.d.ts +1 -1
- package/dist/self_host/subscriptions/usage.js +28 -11
- package/dist/strategies/auto_routing_selector.js +7 -18
- package/dist/telemetry/tools/git_events.d.ts +0 -2
- package/dist/telemetry/tools/git_events.js +0 -4
- package/package.json +2 -2
- package/src/activity/tool_exchanges.ts +0 -1
- package/src/activity/values.ts +0 -5
- package/src/ingress/codex_models.ts +43 -10
- package/src/link/budget.ts +64 -21
- package/src/link/endpoints.ts +39 -38
- package/src/link/errors.ts +1 -1
- package/src/link/grant_access.ts +8 -3
- package/src/link/grants.ts +0 -2
- package/src/link/self_hosted.ts +17 -7
- package/src/link/service.ts +45 -23
- package/src/platform/platform.ts +16 -8
- package/src/providers/subscription_limits.ts +18 -0
- package/src/self_host/resolve.ts +2 -1
- package/src/self_host/subscriptions/index.ts +3 -3
- package/src/self_host/subscriptions/usage.ts +32 -10
- package/src/strategies/auto_routing_selector.ts +7 -22
- package/src/telemetry/tools/git_events.ts +0 -5
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,55 +85,96 @@ 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();
|
|
94
|
-
const spent = new Map<string, number>();
|
|
97
|
+
const spent = new Map<string, { usd: number; requests: number; tokens: number }>();
|
|
95
98
|
for (const use of uses) {
|
|
96
99
|
if (use.credentialId === null || use.at.getTime() < since) continue;
|
|
97
|
-
|
|
100
|
+
const total = spent.get(use.credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
|
|
101
|
+
total.usd += use.costUsd;
|
|
102
|
+
total.requests += 1;
|
|
103
|
+
total.tokens += use.inputTokens + use.outputTokens + use.cacheReadTokens + use.cacheWriteTokens;
|
|
104
|
+
spent.set(use.credentialId, total);
|
|
98
105
|
}
|
|
99
106
|
return [...credentialIds].map((credentialId) => {
|
|
100
|
-
const spentUsd = spent.get(credentialId) ?? 0;
|
|
101
|
-
const
|
|
102
|
-
|
|
107
|
+
const { usd: spentUsd, requests, tokens } = spent.get(credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
|
|
108
|
+
const limit = limits.find((entry) => entry.credentialId === credentialId);
|
|
109
|
+
const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
|
|
110
|
+
.filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
|
|
111
|
+
const usedPercent = windows.length === 0 ? null : Math.max(...windows.map((window) => window.utilization * 100));
|
|
112
|
+
let resetsAt: Date | null = null;
|
|
113
|
+
if (limit?.maxPercent !== undefined) {
|
|
114
|
+
const full = windows.filter((window) => window.utilization * 100 >= limit.maxPercent!);
|
|
115
|
+
if (full.length > 0) resetsAt = new Date(Math.max(...full.map((window) => Date.parse(window.resetsAt))));
|
|
116
|
+
} else if (limit?.monthlyUsd !== undefined && spentUsd >= limit.monthlyUsd) {
|
|
117
|
+
resetsAt = nextMonthStart(now);
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
credentialId,
|
|
121
|
+
spentUsd,
|
|
122
|
+
requests,
|
|
123
|
+
tokens,
|
|
124
|
+
monthlyUsd: limit?.monthlyUsd ?? null,
|
|
125
|
+
maxPercent: limit?.maxPercent ?? null,
|
|
126
|
+
usedPercent,
|
|
127
|
+
reached: resetsAt !== null,
|
|
128
|
+
resetsAt: resetsAt?.toISOString() ?? null,
|
|
129
|
+
};
|
|
103
130
|
});
|
|
104
131
|
}
|
|
105
132
|
|
|
106
|
-
/**
|
|
133
|
+
/**
|
|
134
|
+
* Limits from a request: `[{credential_id, max_percent}]` for a plan or
|
|
135
|
+
* `[{credential_id, monthly_usd}]` for an API key (the other field absent or
|
|
136
|
+
* null), each a distinct plan or key;
|
|
137
|
+
* `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
|
|
138
|
+
*/
|
|
107
139
|
export function validLimits(value: unknown): LinkLimit[] | null {
|
|
108
140
|
if (!Array.isArray(value)) return null;
|
|
109
141
|
const limits: LinkLimit[] = [];
|
|
110
142
|
for (const entry of value) {
|
|
111
143
|
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
|
-
|
|
144
|
+
const { credential_id: credentialId, monthly_usd: monthlyUsd, max_percent: maxPercent } = entry as Record<string, unknown>;
|
|
145
|
+
if (typeof credentialId !== "string" || credentialId.length === 0) return null;
|
|
146
|
+
if (limits.some((other) => other.credentialId === credentialId)) return null;
|
|
147
|
+
if (monthlyUsd == null
|
|
148
|
+
&& typeof maxPercent === "number" && Number.isFinite(maxPercent) && maxPercent > 0 && maxPercent <= 100) {
|
|
149
|
+
limits.push({ credentialId, maxPercent });
|
|
150
|
+
} else if (maxPercent == null
|
|
151
|
+
&& typeof monthlyUsd === "number" && Number.isFinite(monthlyUsd) && monthlyUsd >= 0) {
|
|
152
|
+
limits.push({ credentialId, monthlyUsd });
|
|
153
|
+
} else {
|
|
118
154
|
return null;
|
|
119
155
|
}
|
|
120
|
-
limits.push({ credentialId, monthlyUsd });
|
|
121
156
|
}
|
|
122
157
|
return limits;
|
|
123
158
|
}
|
|
124
159
|
|
|
125
160
|
export function limitsBody(limits: readonly LinkLimit[]) {
|
|
126
|
-
return limits.map((limit) => ({
|
|
161
|
+
return limits.map((limit) => ({
|
|
162
|
+
credential_id: limit.credentialId,
|
|
163
|
+
...(limit.maxPercent === undefined ? { monthly_usd: limit.monthlyUsd } : { max_percent: limit.maxPercent }),
|
|
164
|
+
}));
|
|
127
165
|
}
|
|
128
166
|
|
|
129
167
|
export function spendBody(spend: readonly LinkSpend[]) {
|
|
130
168
|
return spend.map((entry) => ({
|
|
131
169
|
credential_id: entry.credentialId,
|
|
132
170
|
spent_usd: entry.spentUsd,
|
|
171
|
+
requests: entry.requests,
|
|
172
|
+
tokens: entry.tokens,
|
|
133
173
|
monthly_usd: entry.monthlyUsd,
|
|
174
|
+
max_percent: entry.maxPercent,
|
|
175
|
+
used_percent: entry.usedPercent,
|
|
134
176
|
reached: entry.reached,
|
|
177
|
+
resets_at: entry.resetsAt,
|
|
135
178
|
}));
|
|
136
179
|
}
|
|
137
180
|
|
package/src/link/endpoints.ts
CHANGED
|
@@ -87,7 +87,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
87
87
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
88
88
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
89
89
|
import { gatewayFor } from "../models/gateways.js";
|
|
90
|
-
import { budgetBody, limitsBody,
|
|
90
|
+
import { budgetBody, limitsBody, spendBody, validBudget, validLimits } from "./budget.js";
|
|
91
91
|
import { catalogModelFor } from "./grant_access.js";
|
|
92
92
|
import { requestTags } from "../runtime/request_tags.js";
|
|
93
93
|
import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
@@ -307,7 +307,7 @@ function limitsFrom(value: unknown) {
|
|
|
307
307
|
if (limits === null) {
|
|
308
308
|
throw new HttpError(
|
|
309
309
|
400,
|
|
310
|
-
"limits must be a list of {credential_id, monthly_usd} with distinct credential_ids and monthly_usd a dollar amount of 0 or more; [] removes them.",
|
|
310
|
+
"limits must be a list of {credential_id, max_percent} for plans and {credential_id, monthly_usd} for API keys, with distinct credential_ids, max_percent above 0 and at most 100, and monthly_usd a dollar amount of 0 or more; [] removes them.",
|
|
311
311
|
"invalid_request_error",
|
|
312
312
|
"limits",
|
|
313
313
|
);
|
|
@@ -1372,30 +1372,34 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
|
|
|
1372
1372
|
}
|
|
1373
1373
|
|
|
1374
1374
|
function connectionCard(connection: LinkConnection, csrf: string): string {
|
|
1375
|
-
const
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
// The most the grant may spend on each plan or key a month.
|
|
1383
|
-
const spendLimit = (plan: LinkSubscription) => {
|
|
1375
|
+
const names = connection.subscriptions.map(planName);
|
|
1376
|
+
// A plan's account tells it apart only when the app shares two of the same name.
|
|
1377
|
+
const shown = (plan: LinkSubscription) =>
|
|
1378
|
+
names.filter((name) => name === planName(plan)).length > 1 ? `${planName(plan)} (${planLabel(plan)})` : planName(plan);
|
|
1379
|
+
// One row per shared plan or key: a plan's use of its quota and the most of
|
|
1380
|
+
// it the app may use; a key's spend this month and the most it may spend.
|
|
1381
|
+
const row = (plan: LinkSubscription) => {
|
|
1384
1382
|
const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1383
|
+
// A plan still limited in dollars, as before shares, keeps its dollars.
|
|
1384
|
+
const key = plan.apiKeyProvider !== undefined || (spend?.monthlyUsd ?? null) !== null;
|
|
1385
|
+
const field = `${key ? "usd" : "pct"}_${escapeHtml(plan.id)}`;
|
|
1386
|
+
const id = `${field}_${escapeHtml(connection.id)}`;
|
|
1387
|
+
const used = key
|
|
1388
|
+
? `${dollars(spend?.spentUsd ?? 0)} this month`
|
|
1389
|
+
: spend?.usedPercent == null ? "Usage not reported yet" : `Plan ${Math.round(spend.usedPercent)}% used`;
|
|
1390
|
+
const value = key ? spend?.monthlyUsd : spend?.maxPercent;
|
|
1391
|
+
return `<div class="limit">${logo(plan.apiKeyProvider ?? plan.provider, planName(plan))}<label class="grow" for="${id}"><strong>${escapeHtml(shown(plan))}</strong><small>${used}${spend?.reached ? ", at the limit" : ""}</small></label>
|
|
1392
|
+
<input id="${id}" type="text" inputmode="decimal" name="${field}" value="${value ?? ""}" placeholder="${key ? "$ / Month" : "% Of Plan"}" aria-label="${escapeHtml(shown(plan))} ${key ? "Monthly Limit ($)" : "Most Of Plan (%)"}" autocomplete="off"></div>`;
|
|
1389
1393
|
};
|
|
1394
|
+
const limited = connection.spend.some((entry) => entry.monthlyUsd !== null || entry.maxPercent !== null);
|
|
1390
1395
|
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1391
1396
|
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1392
1397
|
<strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
|
|
1393
|
-
<small>
|
|
1394
|
-
|
|
1395
|
-
${
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
<div class="row"><button class="btn outline" type="submit" name="decision" value="budget">Save Limits</button><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
|
|
1398
|
+
${connection.subscriptions.length === 0 ? "<small>Shares nothing</small>" : `<span class="logos" role="img" aria-label="Shares ${escapeHtml(connection.subscriptions.map(shown).join(", "))}">${[...new Map(connection.subscriptions.map((plan) => [plan.apiKeyProvider ?? plan.provider, plan])).values()].map((plan) => logo(plan.apiKeyProvider ?? plan.provider, planName(plan))).join("")}</span>`}
|
|
1399
|
+
${connection.subscriptions.length === 0 ? "" : `<details${limited ? " open" : ""}><summary>Set Limit</summary>
|
|
1400
|
+
${connection.subscriptions.map(row).join("\n")}
|
|
1401
|
+
<button class="btn outline" type="submit" name="decision" value="limits">Save</button></details>`}
|
|
1402
|
+
<div class="row"><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
|
|
1399
1403
|
</form>`;
|
|
1400
1404
|
}
|
|
1401
1405
|
|
|
@@ -1417,20 +1421,17 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
|
|
|
1417
1421
|
await approval.disconnect(session.subject, grantId);
|
|
1418
1422
|
return back;
|
|
1419
1423
|
}
|
|
1420
|
-
if (decision === "
|
|
1421
|
-
const entries = [300, 10080].flatMap((minutes) => {
|
|
1422
|
-
const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
|
|
1423
|
-
return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
|
|
1424
|
-
});
|
|
1425
|
-
const budget = validBudget(entries);
|
|
1426
|
-
if (budget === null) return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1424
|
+
if (decision === "limits") {
|
|
1427
1425
|
const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
|
|
1428
|
-
const value = raw.replace(/[\s
|
|
1429
|
-
|
|
1430
|
-
|
|
1426
|
+
const value = raw.replace(/[\s,$%]/g, "");
|
|
1427
|
+
const kind = field.slice(0, 4);
|
|
1428
|
+
if ((kind !== "usd_" && kind !== "pct_") || value === "") return [];
|
|
1429
|
+
const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
|
|
1430
|
+
return [{ credential_id: field.slice(4), [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
|
|
1431
1431
|
}));
|
|
1432
|
-
if (limits === null)
|
|
1433
|
-
|
|
1432
|
+
if (limits === null) {
|
|
1433
|
+
return await connectionsPage(approval, request, "Each plan limit is a percent above 0 and at most 100, and each key limit a dollar amount; leave it empty for none.");
|
|
1434
|
+
}
|
|
1434
1435
|
await approval.setLimits(session.subject, grantId, limits);
|
|
1435
1436
|
return back;
|
|
1436
1437
|
}
|
|
@@ -1462,10 +1463,6 @@ function planName(subscription: LinkSubscription): string {
|
|
|
1462
1463
|
: KINDS[subscription.provider as SubscriptionKind]?.name ?? subscription.name;
|
|
1463
1464
|
}
|
|
1464
1465
|
|
|
1465
|
-
function count(value: number): string {
|
|
1466
|
-
return value.toLocaleString("en-US");
|
|
1467
|
-
}
|
|
1468
|
-
|
|
1469
1466
|
// Back to the approval page by GET, so no form is left to resubmit.
|
|
1470
1467
|
function seeAuthorize(authorize: AuthorizeRequest, cookies: string[]): Response {
|
|
1471
1468
|
const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
|
|
@@ -2042,13 +2039,17 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
|
|
|
2042
2039
|
.bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
|
|
2043
2040
|
.actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
|
|
2044
2041
|
.fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
|
|
2042
|
+
.card:has(details[open]) .logos{display:none}
|
|
2043
|
+
.logos{display:flex;gap:8px;margin:8px 0 0}.logos .logo,.limit .logo{width:16px;height:16px}
|
|
2044
|
+
.limit{display:flex;align-items:center;gap:10px;margin:10px 0 0}.limit small{display:block}.limit input{width:110px;margin:0}
|
|
2045
|
+
details{margin:12px 0 0}summary{cursor:pointer;list-style:none;display:inline-block;font-size:13px;color:var(--faint);text-decoration:underline;text-underline-offset:3px}summary::-webkit-details-marker{display:none}summary:hover{color:inherit}details[open] summary{display:none}details .btn{margin:12px 0 0}
|
|
2045
2046
|
.card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
|
|
2046
2047
|
.row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
|
|
2047
2048
|
.nav{position:absolute;top:10px;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--muted);cursor:pointer}
|
|
2048
2049
|
.nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
|
|
2049
2050
|
.done{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;margin:0 0 20px;border:1px solid rgba(142,230,189,.4);border-radius:6px;background:rgba(142,230,189,.1);color:var(--mint)}.done .icon{width:22px;height:22px}
|
|
2050
2051
|
a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
|
|
2051
|
-
[role=alert]{margin:16px 0
|
|
2052
|
+
[role=alert]{margin:16px 0 24px;padding:10px 12px;border:1px solid rgba(214,69,72,.5);border-radius:6px;background:rgba(214,69,72,.1);color:var(--ink);font-size:13px}
|
|
2052
2053
|
::selection{background:var(--mint);color:var(--page)}`;
|
|
2053
2054
|
|
|
2054
2055
|
function escapeHtml(value: string): string {
|
package/src/link/errors.ts
CHANGED
|
@@ -100,7 +100,7 @@ export function budgetExhausted(resetsAt: Date): LinkUnavailable {
|
|
|
100
100
|
export function limitsReached(resetsAt: Date): LinkUnavailable {
|
|
101
101
|
return {
|
|
102
102
|
code: "grant_budget_exhausted",
|
|
103
|
-
message: `Every plan and API key of this Dari Link grant is at the
|
|
103
|
+
message: `Every plan and API key of this Dari Link grant is at the limit the user set. The first is back at ${resetsAt.toISOString()}.`,
|
|
104
104
|
resets_at: resetsAt.toISOString(),
|
|
105
105
|
};
|
|
106
106
|
}
|
package/src/link/grant_access.ts
CHANGED
|
@@ -105,11 +105,16 @@ const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
|
105
105
|
|
|
106
106
|
/* The model id in `models` a name means: the id itself, the one id it is the
|
|
107
107
|
bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
|
|
108
|
-
of those for a dated snapshot of it. A name two models share means neither.
|
|
108
|
+
of those for a dated snapshot of it. A name two models share means neither.
|
|
109
|
+
Names match in any case and answer the catalog's own id: some ids carry
|
|
110
|
+
capitals (`deepseek-ai/DeepSeek-V4.1-Flash-1017`), which a lowercased name
|
|
111
|
+
would never equal. */
|
|
109
112
|
export function catalogModelFor(name: string, models: readonly string[]): string | null {
|
|
113
|
+
const lower = models.map((id) => id.toLowerCase());
|
|
110
114
|
for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
const exact = lower.indexOf(candidate);
|
|
116
|
+
if (exact >= 0) return models[exact]!;
|
|
117
|
+
const matches = models.filter((_, i) => lower[i]!.endsWith(`/${candidate}`));
|
|
113
118
|
if (matches.length === 1) return matches[0]!;
|
|
114
119
|
}
|
|
115
120
|
return null;
|
package/src/link/grants.ts
CHANGED
|
@@ -334,8 +334,6 @@ export function linkGrants(repo: LinkRepo) {
|
|
|
334
334
|
};
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
-
export type LinkGrants = ReturnType<typeof linkGrants>;
|
|
338
|
-
|
|
339
337
|
export const TOKEN_PREFIX: Record<LinkTokenKind, string> = {
|
|
340
338
|
access: LINK_ACCESS_TOKEN_PREFIX,
|
|
341
339
|
child: LINK_CHILD_TOKEN_PREFIX,
|
package/src/link/self_hosted.ts
CHANGED
|
@@ -176,7 +176,7 @@ function linkKey(key: LinkApiKey): LinkSubscription {
|
|
|
176
176
|
};
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
|
|
179
|
+
export function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
|
|
180
180
|
const now = new Date();
|
|
181
181
|
return {
|
|
182
182
|
id: credential.id,
|
|
@@ -187,11 +187,21 @@ function linkSubscription(credential: SubscriptionCredential): LinkSubscription
|
|
|
187
187
|
unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
|
|
188
188
|
? credential.unavailableUntil.toISOString()
|
|
189
189
|
: null,
|
|
190
|
-
usage: (currentUsage(credential, now)
|
|
191
|
-
...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
|
|
192
|
-
minutes: window.minutes,
|
|
193
|
-
utilization: window.utilization,
|
|
194
|
-
resetsAt: window.resetsAt.toISOString(),
|
|
195
|
-
})),
|
|
190
|
+
usage: linkUsageWindows(currentUsage(credential, now), now),
|
|
196
191
|
};
|
|
197
192
|
}
|
|
193
|
+
|
|
194
|
+
// Usage reported without per-window detail has only its binding window; it
|
|
195
|
+
// still counts against a plan's share limit, so it is one window here.
|
|
196
|
+
function linkUsageWindows(usage: ReturnType<typeof currentUsage>, now: Date): LinkSubscription["usage"] {
|
|
197
|
+
if (usage === null || usage === undefined) return [];
|
|
198
|
+
const windows = usage.windows.length > 0
|
|
199
|
+
? usage.windows
|
|
200
|
+
: [{ minutes: Math.max(1, Math.ceil((usage.resetsAt.getTime() - now.getTime()) / 60_000)), utilization: usage.utilization, resetsAt: usage.resetsAt }];
|
|
201
|
+
return windows.map((window) => ({
|
|
202
|
+
...("modelFamily" in window && window.modelFamily !== undefined ? { modelFamily: window.modelFamily } : {}),
|
|
203
|
+
minutes: window.minutes,
|
|
204
|
+
utilization: window.utilization,
|
|
205
|
+
resetsAt: window.resetsAt.toISOString(),
|
|
206
|
+
}));
|
|
207
|
+
}
|
package/src/link/service.ts
CHANGED
|
@@ -32,7 +32,6 @@ import {
|
|
|
32
32
|
type BudgetUse,
|
|
33
33
|
budgetStandings,
|
|
34
34
|
grantSpend,
|
|
35
|
-
nextMonthStart,
|
|
36
35
|
overBudgetUntil,
|
|
37
36
|
usesSince,
|
|
38
37
|
} from "./budget.js";
|
|
@@ -172,13 +171,16 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
172
171
|
budget: LinkBudgetStanding[];
|
|
173
172
|
spend: LinkSpend[];
|
|
174
173
|
}> => {
|
|
175
|
-
const uses = await
|
|
174
|
+
const [uses, plans] = await Promise.all([
|
|
175
|
+
store.budgetUses(grant.id, usesSince(grant.budget, now)),
|
|
176
|
+
users.plansWithIds(grant.credentialIds),
|
|
177
|
+
]);
|
|
176
178
|
return {
|
|
177
179
|
budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
|
|
178
180
|
...standing,
|
|
179
181
|
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
180
182
|
})),
|
|
181
|
-
spend: grantSpend(grant.credentialIds, grant.limits, uses, now),
|
|
183
|
+
spend: grantSpend(grant.credentialIds, grant.limits, uses, plans, now),
|
|
182
184
|
};
|
|
183
185
|
};
|
|
184
186
|
|
|
@@ -194,13 +196,12 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
194
196
|
|
|
195
197
|
// Plans and keys the user can grant, and limits only on them.
|
|
196
198
|
const ownedCredentials = async (subject: string, credentialIds: readonly string[], limits: readonly LinkLimit[] = []) => {
|
|
197
|
-
const
|
|
199
|
+
const plans = await users.plans(subject);
|
|
200
|
+
const owned = new Set(plans.map((plan) => plan.id));
|
|
198
201
|
if (credentialIds.length === 0 || !credentialIds.every((id) => owned.has(id))) {
|
|
199
202
|
throw new HttpError(400, "Choose one or more of your connected plans or API keys.", "invalid_request");
|
|
200
203
|
}
|
|
201
|
-
|
|
202
|
-
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
203
|
-
}
|
|
204
|
+
requireLimitsFit(limits, credentialIds, plans);
|
|
204
205
|
return [...new Set(credentialIds)].sort();
|
|
205
206
|
};
|
|
206
207
|
|
|
@@ -303,9 +304,6 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
303
304
|
async disconnect(subject, grantId) {
|
|
304
305
|
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
305
306
|
},
|
|
306
|
-
async setBudget(subject, grantId, budget) {
|
|
307
|
-
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
308
|
-
},
|
|
309
307
|
async setLimits(subject, grantId, limits) {
|
|
310
308
|
const grant = await ownGrant(subject, grantId);
|
|
311
309
|
if (grant === null) return false;
|
|
@@ -401,9 +399,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
|
|
|
401
399
|
const subject = await users.manager(apiKey);
|
|
402
400
|
const grant = await ownGrant(subject, grantId);
|
|
403
401
|
if (grant === null) return false;
|
|
404
|
-
|
|
405
|
-
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
406
|
-
}
|
|
402
|
+
requireLimitsFit(limits, grant.credentialIds, await users.plansWithIds(grant.credentialIds));
|
|
407
403
|
return await store.updateGrant(grantId, { limits });
|
|
408
404
|
},
|
|
409
405
|
async setBudget({ apiKey, grantId, budget }) {
|
|
@@ -437,6 +433,23 @@ export function newLinkApp(request: { name: string; redirectUris: string[]; conf
|
|
|
437
433
|
return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
|
|
438
434
|
}
|
|
439
435
|
|
|
436
|
+
/**
|
|
437
|
+
* Limits only on the grant's plans and keys, and a share of quota only on a
|
|
438
|
+
* plan. A plan may still carry dollars a month, as limits did before shares;
|
|
439
|
+
* the apps offer a share for a plan that has none.
|
|
440
|
+
*/
|
|
441
|
+
function requireLimitsFit(limits: readonly LinkLimit[], credentialIds: readonly string[], plans: readonly LinkSubscription[]): void {
|
|
442
|
+
if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
|
|
443
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
444
|
+
}
|
|
445
|
+
for (const limit of limits) {
|
|
446
|
+
const key = plans.find((plan) => plan.id === limit.credentialId)?.apiKeyProvider !== undefined;
|
|
447
|
+
if (key && limit.monthlyUsd === undefined) {
|
|
448
|
+
throw new HttpError(400, "Limit an API key with monthly_usd; max_percent is for plans.", "invalid_request");
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
440
453
|
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
441
454
|
export function newLinkClientSecret(): { secret: string; hash: string } {
|
|
442
455
|
const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
|
|
@@ -445,11 +458,16 @@ export function newLinkClientSecret(): { secret: string; hash: string } {
|
|
|
445
458
|
|
|
446
459
|
/**
|
|
447
460
|
* The grant a link token serves a request for: null when the key is no link
|
|
448
|
-
* token. Its plans and keys at their
|
|
449
|
-
*
|
|
450
|
-
*
|
|
461
|
+
* token. Its plans and keys at their limit are left out. Throws the 401 a dead
|
|
462
|
+
* token gets, and the 424 a grant at its budget, or with every plan and key at
|
|
463
|
+
* its limit, gets until it serves again.
|
|
451
464
|
*/
|
|
452
|
-
export async function linkTokenGrant(
|
|
465
|
+
export async function linkTokenGrant(
|
|
466
|
+
store: LinkStore,
|
|
467
|
+
users: Pick<LinkUsers, "plansWithIds">,
|
|
468
|
+
token: string,
|
|
469
|
+
now = new Date(),
|
|
470
|
+
): Promise<ActiveLinkGrant | null> {
|
|
453
471
|
const auth = await linkGrants(store).authenticate(token, now);
|
|
454
472
|
if (auth === null) return null;
|
|
455
473
|
if (auth.status === "expired") throw linkTokenExpired();
|
|
@@ -459,12 +477,16 @@ export async function linkTokenGrant(store: LinkStore, token: string, now = new
|
|
|
459
477
|
const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
|
|
460
478
|
const back = overBudgetUntil(budgetStandings(grant.budget, uses, now));
|
|
461
479
|
if (back !== undefined) throw linkUnavailableError(budgetExhausted(back));
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
const
|
|
467
|
-
if (
|
|
480
|
+
if (grant.limits.length === 0) return grant;
|
|
481
|
+
const plans = grant.limits.some((limit) => limit.maxPercent !== undefined)
|
|
482
|
+
? await users.plansWithIds(grant.limits.map((limit) => limit.credentialId))
|
|
483
|
+
: [];
|
|
484
|
+
const reached = grantSpend(grant.credentialIds, grant.limits, uses, plans, now).filter((entry) => entry.reached);
|
|
485
|
+
if (reached.length === 0) return grant;
|
|
486
|
+
const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.some((entry) => entry.credentialId === id)));
|
|
487
|
+
if (credentialIds.size === 0) {
|
|
488
|
+
throw linkUnavailableError(limitsReached(new Date(Math.min(...reached.map((entry) => Date.parse(entry.resetsAt!))))));
|
|
489
|
+
}
|
|
468
490
|
return { ...grant, credentialIds };
|
|
469
491
|
}
|
|
470
492
|
|
package/src/platform/platform.ts
CHANGED
|
@@ -266,8 +266,6 @@ export type LinkApprovalPage = {
|
|
|
266
266
|
connections(subject: string): Promise<LinkConnection[]>;
|
|
267
267
|
/** The user ends one of their grants; false when they have none by that id. */
|
|
268
268
|
disconnect(subject: string, grantId: string): Promise<boolean>;
|
|
269
|
-
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
270
|
-
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
271
269
|
/** Replace one of the user's grants' monthly spend limits; false when they have none by that id. */
|
|
272
270
|
setLimits(subject: string, grantId: string, limits: LinkLimit[]): Promise<boolean>;
|
|
273
271
|
};
|
|
@@ -317,19 +315,29 @@ export type LinkConnect = {
|
|
|
317
315
|
export type LinkBudget = { windowMinutes: number; maxTokens: number };
|
|
318
316
|
|
|
319
317
|
/**
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
*
|
|
318
|
+
* A grant's limit on one of its plans or API keys; exactly one field is set.
|
|
319
|
+
* A plan leaves the grant while any of its plan-wide quota windows is at
|
|
320
|
+
* `maxPercent` used, whoever used it, until that window resets: the rest is
|
|
321
|
+
* the user's. An API key leaves it once the grant's spend on it this calendar
|
|
322
|
+
* month (UTC) reaches `monthlyUsd`. See link/budget.ts.
|
|
323
323
|
*/
|
|
324
|
-
export type LinkLimit = { credentialId: string; monthlyUsd
|
|
324
|
+
export type LinkLimit = { credentialId: string; maxPercent?: number; monthlyUsd?: number };
|
|
325
325
|
|
|
326
|
-
/** A granted plan or key's spend
|
|
326
|
+
/** A granted plan or key's spend and standing, and its limit when it has one. */
|
|
327
327
|
export type LinkSpend = {
|
|
328
328
|
credentialId: string;
|
|
329
|
+
// What the grant spent on it this month: for a plan, at API prices.
|
|
329
330
|
spentUsd: number;
|
|
331
|
+
// The grant's requests it served this month, and their tokens.
|
|
332
|
+
requests: number;
|
|
333
|
+
tokens: number;
|
|
330
334
|
monthlyUsd: number | null;
|
|
331
|
-
|
|
335
|
+
maxPercent: number | null;
|
|
336
|
+
// A plan's most-used plan-wide window, in percent; null when unknown.
|
|
337
|
+
usedPercent: number | null;
|
|
338
|
+
// At its limit: the grant leaves it out until `resetsAt`.
|
|
332
339
|
reached: boolean;
|
|
340
|
+
resetsAt: string | null;
|
|
333
341
|
};
|
|
334
342
|
|
|
335
343
|
/** A budget window as it stands for a grant. */
|
|
@@ -132,6 +132,24 @@ export function museSubscriptionUsage(snapshot: unknown, now: Date): Subscriptio
|
|
|
132
132
|
// the billing cycle.
|
|
133
133
|
const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]] as const;
|
|
134
134
|
|
|
135
|
+
// Each Token Pass billing period grants $150 of credit; Vercel reports only
|
|
136
|
+
// what remains, so usage is measured against the full grant.
|
|
137
|
+
const TOKEN_PASS_CREDIT_USD = 150;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The Token Pass usage AI Gateway reports at `GET /v1/credits`:
|
|
141
|
+
* `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
|
|
142
|
+
* or null while Vercel cannot read the balance.
|
|
143
|
+
*/
|
|
144
|
+
export function tokenPassUsageFromCredits(credits: unknown, now: Date): SubscriptionUsage | null {
|
|
145
|
+
const pass = isRecord(credits) && isRecord(credits.token_pass) ? credits.token_pass : null;
|
|
146
|
+
if (pass === null || typeof pass.remaining !== "string" || typeof pass.resets_at !== "string") return null;
|
|
147
|
+
return subscriptionUsageFromWindows(
|
|
148
|
+
[{ minutes: 30 * 24 * 60, used: 1 - Number(pass.remaining) / TOKEN_PASS_CREDIT_USD, resetsAt: new Date(pass.resets_at) }],
|
|
149
|
+
now,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
135
153
|
/**
|
|
136
154
|
* The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
|
|
137
155
|
* own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
} from "./config.js";
|
|
38
38
|
import type { ActiveLinkGrant } from "../link/grants.js";
|
|
39
39
|
import type { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
40
|
+
import { linkSubscription } from "../link/self_hosted.js";
|
|
40
41
|
import { linkTokenGrant } from "../link/service.js";
|
|
41
42
|
import type { RouterModelStore } from "./router_models.js";
|
|
42
43
|
import { servedRouter, type RouterSpecStore } from "./router_specs.js";
|
|
@@ -101,7 +102,7 @@ export async function resolveSelfHostedRouter(
|
|
|
101
102
|
request: ResolveRouterRequest,
|
|
102
103
|
): Promise<ResolvedRouter> {
|
|
103
104
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
104
|
-
const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
|
|
105
|
+
const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
|
|
105
106
|
if (keyIndex === null && grant === null) {
|
|
106
107
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
107
108
|
}
|
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
* database file; protect that file like a secret.
|
|
11
11
|
* - `access.ts`: `freshAccessToken` refreshes a token expiring within five
|
|
12
12
|
* minutes before handing it out, one refresh per credential at a time.
|
|
13
|
-
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go
|
|
14
|
-
* usage
|
|
15
|
-
* asks.
|
|
13
|
+
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
|
|
14
|
+
* plan usage from their usage endpoints, which their responses never report,
|
|
15
|
+
* when the accounts view asks.
|
|
16
16
|
* - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
|
|
17
17
|
* Dari CLI uses to connect, list, rename, release, and disconnect
|
|
18
18
|
* subscriptions. The caller authenticates the request first.
|