@mupt-ai/dari-gateway 1.0.340 → 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.
@@ -1,4 +1,4 @@
1
- import type { LinkBudget, LinkLimit, LinkSpend, LinkUsageTotals } from "../platform/platform.js";
1
+ import type { LinkBudget, LinkLimit, LinkSpend, LinkSubscription, LinkUsageTotals } from "../platform/platform.js";
2
2
  /** The windows a budget can cap: five hours and one week. */
3
3
  export declare const LINK_BUDGET_WINDOW_MINUTES: readonly [300, 10080];
4
4
  /** The tokens a request used, as each kind is recorded. */
@@ -33,19 +33,30 @@ export declare function monthStart(now: Date): Date;
33
33
  export declare function nextMonthStart(now: Date): Date;
34
34
  /** The earliest use a grant's budget and spend need: its windows, and this month. */
35
35
  export declare function usesSince(budget: readonly LinkBudget[], now: Date): number;
36
- /** Each granted plan or key's spend this month, with its limit when it has one. */
37
- export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], now: Date): LinkSpend[];
38
- /** Limits from a request: `[{credential_id, monthly_usd}]`, each a distinct plan or key and a dollar amount of 0 or more. */
36
+ /** Each granted plan or key's spend this month and standing against its limit. */
37
+ export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], plans: readonly LinkSubscription[], now: Date): LinkSpend[];
38
+ /**
39
+ * Limits from a request: `[{credential_id, max_percent}]` for a plan or
40
+ * `[{credential_id, monthly_usd}]` for an API key (the other field absent or
41
+ * null), each a distinct plan or key;
42
+ * `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
43
+ */
39
44
  export declare function validLimits(value: unknown): LinkLimit[] | null;
40
- export declare function limitsBody(limits: readonly LinkLimit[]): {
45
+ export declare function limitsBody(limits: readonly LinkLimit[]): ({
46
+ monthly_usd: number | undefined;
41
47
  credential_id: string;
42
- monthly_usd: number;
43
- }[];
48
+ } | {
49
+ max_percent: number;
50
+ credential_id: string;
51
+ })[];
44
52
  export declare function spendBody(spend: readonly LinkSpend[]): {
45
53
  credential_id: string;
46
54
  spent_usd: number;
47
55
  monthly_usd: number | null;
56
+ max_percent: number | null;
57
+ used_percent: number | null;
48
58
  reached: boolean;
59
+ resets_at: string | null;
49
60
  }[];
50
61
  /** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
51
62
  export declare function validBudget(value: unknown): LinkBudget[] | null;
@@ -10,11 +10,13 @@
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 what it spends on each of its plans and API keys in
14
- a calendar month (UTC): an API key's spend is what its provider charged,
15
- and a plan's is what its requests would have cost at API prices. A plan or
16
- key at its limit leaves the grant until the month ends; the grant serves on
17
- the rest. */
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
  /** The windows a budget can cap: five hours and one week. */
19
21
  export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080];
20
22
  /** What a budget counts, and Connected Apps shows: every token, of every kind. */
@@ -61,8 +63,8 @@ export function nextMonthStart(now) {
61
63
  export function usesSince(budget, now) {
62
64
  return Math.min(now.getTime() - budgetLookbackMs(budget), monthStart(now).getTime());
63
65
  }
64
- /** Each granted plan or key's spend this month, with its limit when it has one. */
65
- export function grantSpend(credentialIds, limits, uses, now) {
66
+ /** Each granted plan or key's spend this month and standing against its limit. */
67
+ export function grantSpend(credentialIds, limits, uses, plans, now) {
66
68
  const since = monthStart(now).getTime();
67
69
  const spent = new Map();
68
70
  for (const use of uses) {
@@ -72,11 +74,36 @@ export function grantSpend(credentialIds, limits, uses, now) {
72
74
  }
73
75
  return [...credentialIds].map((credentialId) => {
74
76
  const spentUsd = spent.get(credentialId) ?? 0;
75
- const monthlyUsd = limits.find((limit) => limit.credentialId === credentialId)?.monthlyUsd ?? null;
76
- return { credentialId, spentUsd, monthlyUsd, reached: monthlyUsd !== null && spentUsd >= monthlyUsd };
77
+ const limit = limits.find((entry) => entry.credentialId === credentialId);
78
+ const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
79
+ .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
80
+ const usedPercent = windows.length === 0 ? null : Math.max(...windows.map((window) => window.utilization * 100));
81
+ let resetsAt = null;
82
+ if (limit?.maxPercent !== undefined) {
83
+ const full = windows.filter((window) => window.utilization * 100 >= limit.maxPercent);
84
+ if (full.length > 0)
85
+ resetsAt = new Date(Math.max(...full.map((window) => Date.parse(window.resetsAt))));
86
+ }
87
+ else if (limit?.monthlyUsd !== undefined && spentUsd >= limit.monthlyUsd) {
88
+ resetsAt = nextMonthStart(now);
89
+ }
90
+ return {
91
+ credentialId,
92
+ spentUsd,
93
+ monthlyUsd: limit?.monthlyUsd ?? null,
94
+ maxPercent: limit?.maxPercent ?? null,
95
+ usedPercent,
96
+ reached: resetsAt !== null,
97
+ resetsAt: resetsAt?.toISOString() ?? null,
98
+ };
77
99
  });
78
100
  }
79
- /** Limits from a request: `[{credential_id, monthly_usd}]`, each a distinct plan or key and a dollar amount of 0 or more. */
101
+ /**
102
+ * Limits from a request: `[{credential_id, max_percent}]` for a plan or
103
+ * `[{credential_id, monthly_usd}]` for an API key (the other field absent or
104
+ * null), each a distinct plan or key;
105
+ * `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
106
+ */
80
107
  export function validLimits(value) {
81
108
  if (!Array.isArray(value))
82
109
  return null;
@@ -84,25 +111,40 @@ export function validLimits(value) {
84
111
  for (const entry of value) {
85
112
  if (typeof entry !== "object" || entry === null)
86
113
  return null;
87
- const { credential_id: credentialId, monthly_usd: monthlyUsd } = entry;
88
- if (typeof credentialId !== "string" || credentialId.length === 0
89
- || typeof monthlyUsd !== "number" || !Number.isFinite(monthlyUsd) || monthlyUsd < 0
90
- || limits.some((other) => other.credentialId === credentialId)) {
114
+ const { credential_id: credentialId, monthly_usd: monthlyUsd, max_percent: maxPercent } = entry;
115
+ if (typeof credentialId !== "string" || credentialId.length === 0)
116
+ return null;
117
+ if (limits.some((other) => other.credentialId === credentialId))
118
+ return null;
119
+ if (monthlyUsd == null
120
+ && typeof maxPercent === "number" && Number.isFinite(maxPercent) && maxPercent > 0 && maxPercent <= 100) {
121
+ limits.push({ credentialId, maxPercent });
122
+ }
123
+ else if (maxPercent == null
124
+ && typeof monthlyUsd === "number" && Number.isFinite(monthlyUsd) && monthlyUsd >= 0) {
125
+ limits.push({ credentialId, monthlyUsd });
126
+ }
127
+ else {
91
128
  return null;
92
129
  }
93
- limits.push({ credentialId, monthlyUsd });
94
130
  }
95
131
  return limits;
96
132
  }
97
133
  export function limitsBody(limits) {
98
- return limits.map((limit) => ({ credential_id: limit.credentialId, monthly_usd: limit.monthlyUsd }));
134
+ return limits.map((limit) => ({
135
+ credential_id: limit.credentialId,
136
+ ...(limit.maxPercent === undefined ? { monthly_usd: limit.monthlyUsd } : { max_percent: limit.maxPercent }),
137
+ }));
99
138
  }
100
139
  export function spendBody(spend) {
101
140
  return spend.map((entry) => ({
102
141
  credential_id: entry.credentialId,
103
142
  spent_usd: entry.spentUsd,
104
143
  monthly_usd: entry.monthlyUsd,
144
+ max_percent: entry.maxPercent,
145
+ used_percent: entry.usedPercent,
105
146
  reached: entry.reached,
147
+ resets_at: entry.resetsAt,
106
148
  }));
107
149
  }
108
150
  /** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
@@ -64,7 +64,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
64
64
  import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
65
65
  import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
66
66
  import { gatewayFor } from "../models/gateways.js";
67
- import { budgetBody, limitsBody, linkTokens, spendBody, validBudget, validLimits } from "./budget.js";
67
+ import { budgetBody, limitsBody, spendBody, validBudget, validLimits } from "./budget.js";
68
68
  import { catalogModelFor } from "./grant_access.js";
69
69
  import { requestTags } from "../runtime/request_tags.js";
70
70
  import { parseJsonRequest } from "../ingress/json.js";
@@ -270,7 +270,7 @@ function credentialIdsFrom(value) {
270
270
  function limitsFrom(value) {
271
271
  const limits = validLimits(value ?? []);
272
272
  if (limits === null) {
273
- throw new HttpError(400, "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.", "invalid_request_error", "limits");
273
+ throw new HttpError(400, "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.", "invalid_request_error", "limits");
274
274
  }
275
275
  return limits;
276
276
  }
@@ -1225,30 +1225,33 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
1225
1225
  </div>`);
1226
1226
  }
1227
1227
  function connectionCard(connection, csrf) {
1228
- const tokens = linkTokens(connection.usage);
1229
- const limit = (minutes, label) => {
1230
- const standing = connection.budget.find((window) => window.windowMinutes === minutes);
1231
- return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
1232
- <input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
1233
- ${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
1234
- };
1235
- // The most the grant may spend on each plan or key a month.
1236
- const spendLimit = (plan) => {
1228
+ const names = connection.subscriptions.map(planName);
1229
+ // A plan's account tells it apart only when the app shares two of the same name.
1230
+ const shown = (plan) => names.filter((name) => name === planName(plan)).length > 1 ? `${planName(plan)} (${planLabel(plan)})` : planName(plan);
1231
+ // One row per shared plan or key: a plan's use of its quota and the most of
1232
+ // it the app may use; a key's spend this month and the most it may spend.
1233
+ const row = (plan) => {
1237
1234
  const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
1238
- const id = `usd_${escapeHtml(plan.id)}_${escapeHtml(connection.id)}`;
1239
- return `<label class="field" for="${id}">${escapeHtml(planName(plan))} Per Month ($)</label>
1240
- <input id="${id}" type="text" inputmode="decimal" name="usd_${escapeHtml(plan.id)}" value="${spend?.monthlyUsd ?? ""}" placeholder="No Limit" autocomplete="off">
1241
- <p class="hint">${dollars(spend?.spentUsd ?? 0)} this month${spend?.reached ? ", at the limit until the month ends" : ""}</p>`;
1235
+ // A plan still limited in dollars, as before shares, keeps its dollars.
1236
+ const key = plan.apiKeyProvider !== undefined || (spend?.monthlyUsd ?? null) !== null;
1237
+ const field = `${key ? "usd" : "pct"}_${escapeHtml(plan.id)}`;
1238
+ const id = `${field}_${escapeHtml(connection.id)}`;
1239
+ const used = key
1240
+ ? `${dollars(spend?.spentUsd ?? 0)} this month`
1241
+ : spend?.usedPercent == null ? "Usage not reported yet" : `Plan ${Math.round(spend.usedPercent)}% used`;
1242
+ const value = key ? spend?.monthlyUsd : spend?.maxPercent;
1243
+ 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>
1244
+ <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>`;
1242
1245
  };
1246
+ const limited = connection.spend.some((entry) => entry.monthlyUsd !== null || entry.maxPercent !== null);
1243
1247
  return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
1244
1248
  <input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
1245
1249
  <strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
1246
- <small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} &middot; ${count(connection.usage.requests)} requests &middot; ${count(tokens)} tokens</small>
1247
- <small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
1248
- ${limit(300, "Per 5 Hours")}
1249
- ${limit(10080, "Per Week")}
1250
- ${connection.subscriptions.map(spendLimit).join("\n")}
1251
- <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>
1250
+ ${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>`}
1251
+ ${connection.subscriptions.length === 0 ? "" : `<details${limited ? " open" : ""}><summary>Set Limit</summary>
1252
+ ${connection.subscriptions.map(row).join("\n")}
1253
+ <button class="btn outline" type="submit" name="decision" value="limits">Save</button></details>`}
1254
+ <div class="row"><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
1252
1255
  </form>`;
1253
1256
  }
1254
1257
  async function connectionsSubmit(approval, request, form) {
@@ -1271,23 +1274,18 @@ async function connectionsSubmit(approval, request, form) {
1271
1274
  await approval.disconnect(session.subject, grantId);
1272
1275
  return back;
1273
1276
  }
1274
- if (decision === "budget") {
1275
- const entries = [300, 10080].flatMap((minutes) => {
1276
- const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
1277
- return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
1278
- });
1279
- const budget = validBudget(entries);
1280
- if (budget === null)
1281
- return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
1277
+ if (decision === "limits") {
1282
1278
  const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
1283
- const value = raw.replace(/[\s,$]/g, "");
1284
- if (!field.startsWith("usd_") || value === "")
1279
+ const value = raw.replace(/[\s,$%]/g, "");
1280
+ const kind = field.slice(0, 4);
1281
+ if ((kind !== "usd_" && kind !== "pct_") || value === "")
1285
1282
  return [];
1286
- return [{ credential_id: field.slice(4), monthly_usd: /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN }];
1283
+ const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
1284
+ return [{ credential_id: field.slice(4), [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
1287
1285
  }));
1288
- if (limits === null)
1289
- return await connectionsPage(approval, request, "Each monthly limit is a dollar amount; leave it empty for none.");
1290
- await approval.setBudget(session.subject, grantId, budget);
1286
+ if (limits === null) {
1287
+ 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.");
1288
+ }
1291
1289
  await approval.setLimits(session.subject, grantId, limits);
1292
1290
  return back;
1293
1291
  }
@@ -1317,9 +1315,6 @@ function planName(subscription) {
1317
1315
  ? `${subscription.name} API Key`
1318
1316
  : KINDS[subscription.provider]?.name ?? subscription.name;
1319
1317
  }
1320
- function count(value) {
1321
- return value.toLocaleString("en-US");
1322
- }
1323
1318
  // Back to the approval page by GET, so no form is left to resubmit.
1324
1319
  function seeAuthorize(authorize, cookies) {
1325
1320
  const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
@@ -1811,13 +1806,17 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
1811
1806
  .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}
1812
1807
  .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
1813
1808
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1809
+ .card:has(details[open]) .logos{display:none}
1810
+ .logos{display:flex;gap:8px;margin:8px 0 0}.logos .logo,.limit .logo{width:16px;height:16px}
1811
+ .limit{display:flex;align-items:center;gap:10px;margin:10px 0 0}.limit small{display:block}.limit input{width:110px;margin:0}
1812
+ 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}
1814
1813
  .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}
1815
1814
  .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
1816
1815
  .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}
1817
1816
  .nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
1818
1817
  .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}
1819
1818
  a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
1820
- [role=alert]{margin:16px 0 0;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}
1819
+ [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}
1821
1820
  ::selection{background:var(--mint);color:var(--page)}`;
1822
1821
  function escapeHtml(value) {
1823
1822
  return value
@@ -83,7 +83,7 @@ export function budgetExhausted(resetsAt) {
83
83
  export function limitsReached(resetsAt) {
84
84
  return {
85
85
  code: "grant_budget_exhausted",
86
- message: `Every plan and API key of this Dari Link grant is at the monthly spend limit the user set. It is back at ${resetsAt.toISOString()}.`,
86
+ 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()}.`,
87
87
  resets_at: resetsAt.toISOString(),
88
88
  };
89
89
  }
@@ -1,3 +1,5 @@
1
- import type { LinkPlatform } from "../platform/platform.js";
1
+ import type { LinkPlatform, LinkSubscription } from "../platform/platform.js";
2
2
  import { type SelfHostedResolverDeps } from "../self_host/resolve.js";
3
+ import { type SubscriptionCredential } from "../self_host/subscriptions/index.js";
3
4
  export declare function selfHostedLink(deps: Pick<SelfHostedResolverDeps, "gatewayKeys" | "subscriptions" | "links" | "env" | "config" | "fetch">): LinkPlatform;
5
+ export declare function linkSubscription(credential: SubscriptionCredential): LinkSubscription;
@@ -154,7 +154,7 @@ function linkKey(key) {
154
154
  usage: [],
155
155
  };
156
156
  }
157
- function linkSubscription(credential) {
157
+ export function linkSubscription(credential) {
158
158
  const now = new Date();
159
159
  return {
160
160
  id: credential.id,
@@ -165,11 +165,21 @@ function linkSubscription(credential) {
165
165
  unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
166
166
  ? credential.unavailableUntil.toISOString()
167
167
  : null,
168
- usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
169
- ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
170
- minutes: window.minutes,
171
- utilization: window.utilization,
172
- resetsAt: window.resetsAt.toISOString(),
173
- })),
168
+ usage: linkUsageWindows(currentUsage(credential, now), now),
174
169
  };
175
170
  }
171
+ // Usage reported without per-window detail has only its binding window; it
172
+ // still counts against a plan's share limit, so it is one window here.
173
+ function linkUsageWindows(usage, now) {
174
+ if (usage === null || usage === undefined)
175
+ return [];
176
+ const windows = usage.windows.length > 0
177
+ ? usage.windows
178
+ : [{ minutes: Math.max(1, Math.ceil((usage.resetsAt.getTime() - now.getTime()) / 60_000)), utilization: usage.utilization, resetsAt: usage.resetsAt }];
179
+ return windows.map((window) => ({
180
+ ...("modelFamily" in window && window.modelFamily !== undefined ? { modelFamily: window.modelFamily } : {}),
181
+ minutes: window.minutes,
182
+ utilization: window.utilization,
183
+ resetsAt: window.resetsAt.toISOString(),
184
+ }));
185
+ }
@@ -124,9 +124,9 @@ export declare function newLinkClientSecret(): {
124
124
  };
125
125
  /**
126
126
  * The grant a link token serves a request for: null when the key is no link
127
- * token. Its plans and keys at their monthly spend limit are left out. Throws
128
- * the 401 a dead token gets, and the 424 a grant at its budget, or with every
129
- * plan and key at its limit, gets until it serves again.
127
+ * token. Its plans and keys at their limit are left out. Throws the 401 a dead
128
+ * token gets, and the 424 a grant at its budget, or with every plan and key at
129
+ * its limit, gets until it serves again.
130
130
  */
131
- export declare function linkTokenGrant(store: LinkStore, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
131
+ export declare function linkTokenGrant(store: LinkStore, users: Pick<LinkUsers, "plansWithIds">, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
132
132
  export {};
@@ -11,7 +11,7 @@
11
11
  `LINK_PERSONAL_CLIENT_ID`, which nothing can sign in to. */
12
12
  import { randomUUID } from "node:crypto";
13
13
  import { HttpError } from "../http/errors.js";
14
- import { budgetStandings, grantSpend, nextMonthStart, overBudgetUntil, usesSince, } from "./budget.js";
14
+ import { budgetStandings, grantSpend, overBudgetUntil, usesSince, } from "./budget.js";
15
15
  import { budgetExhausted, limitsReached, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
16
16
  import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, LINK_TOKEN_RETENTION_MS, TOKEN_PREFIX, } from "./grants.js";
17
17
  /** The built-in app every personal endpoint's grant belongs to. */
@@ -25,13 +25,16 @@ export function linkPlatform(store, users) {
25
25
  };
26
26
  // A grant's budget windows and each granted plan or key's spend this month.
27
27
  const standings = async (grant, now = new Date()) => {
28
- const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
28
+ const [uses, plans] = await Promise.all([
29
+ store.budgetUses(grant.id, usesSince(grant.budget, now)),
30
+ grant.limits.length === 0 ? [] : users.plansWithIds(grant.credentialIds),
31
+ ]);
29
32
  return {
30
33
  budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
31
34
  ...standing,
32
35
  resetsAt: standing.resetsAt?.toISOString() ?? null,
33
36
  })),
34
- spend: grantSpend(grant.credentialIds, grant.limits, uses, now),
37
+ spend: grantSpend(grant.credentialIds, grant.limits, uses, plans, now),
35
38
  };
36
39
  };
37
40
  const publicGrant = ({ subject: _, ...grant }) => ({
@@ -44,13 +47,12 @@ export function linkPlatform(store, users) {
44
47
  });
45
48
  // Plans and keys the user can grant, and limits only on them.
46
49
  const ownedCredentials = async (subject, credentialIds, limits = []) => {
47
- const owned = new Set((await users.plans(subject)).map((plan) => plan.id));
50
+ const plans = await users.plans(subject);
51
+ const owned = new Set(plans.map((plan) => plan.id));
48
52
  if (credentialIds.length === 0 || !credentialIds.every((id) => owned.has(id))) {
49
53
  throw new HttpError(400, "Choose one or more of your connected plans or API keys.", "invalid_request");
50
54
  }
51
- if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
52
- throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
53
- }
55
+ requireLimitsFit(limits, credentialIds, plans);
54
56
  return [...new Set(credentialIds)].sort();
55
57
  };
56
58
  // The one user a key acts for: endpoints are personal, so an operator key
@@ -152,9 +154,6 @@ export function linkPlatform(store, users) {
152
154
  async disconnect(subject, grantId) {
153
155
  return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
154
156
  },
155
- async setBudget(subject, grantId, budget) {
156
- return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
157
- },
158
157
  async setLimits(subject, grantId, limits) {
159
158
  const grant = await ownGrant(subject, grantId);
160
159
  if (grant === null)
@@ -257,9 +256,7 @@ export function linkPlatform(store, users) {
257
256
  const grant = await ownGrant(subject, grantId);
258
257
  if (grant === null)
259
258
  return false;
260
- if (!limits.every((limit) => grant.credentialIds.includes(limit.credentialId))) {
261
- throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
262
- }
259
+ requireLimitsFit(limits, grant.credentialIds, await users.plansWithIds(grant.credentialIds));
263
260
  return await store.updateGrant(grantId, { limits });
264
261
  },
265
262
  async setBudget({ apiKey, grantId, budget }) {
@@ -288,6 +285,22 @@ export function newLinkApp(request) {
288
285
  };
289
286
  return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
290
287
  }
288
+ /**
289
+ * Limits only on the grant's plans and keys, and a share of quota only on a
290
+ * plan. A plan may still carry dollars a month, as limits did before shares;
291
+ * the apps offer a share for a plan that has none.
292
+ */
293
+ function requireLimitsFit(limits, credentialIds, plans) {
294
+ if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
295
+ throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
296
+ }
297
+ for (const limit of limits) {
298
+ const key = plans.find((plan) => plan.id === limit.credentialId)?.apiKeyProvider !== undefined;
299
+ if (key && limit.monthlyUsd === undefined) {
300
+ throw new HttpError(400, "Limit an API key with monthly_usd; max_percent is for plans.", "invalid_request");
301
+ }
302
+ }
303
+ }
291
304
  /** A confidential app's client secret, and the hash that is kept of it. */
292
305
  export function newLinkClientSecret() {
293
306
  const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
@@ -295,11 +308,11 @@ export function newLinkClientSecret() {
295
308
  }
296
309
  /**
297
310
  * The grant a link token serves a request for: null when the key is no link
298
- * token. Its plans and keys at their monthly spend limit are left out. Throws
299
- * the 401 a dead token gets, and the 424 a grant at its budget, or with every
300
- * plan and key at its limit, gets until it serves again.
311
+ * token. Its plans and keys at their limit are left out. Throws the 401 a dead
312
+ * token gets, and the 424 a grant at its budget, or with every plan and key at
313
+ * its limit, gets until it serves again.
301
314
  */
302
- export async function linkTokenGrant(store, token, now = new Date()) {
315
+ export async function linkTokenGrant(store, users, token, now = new Date()) {
303
316
  const auth = await linkGrants(store).authenticate(token, now);
304
317
  if (auth === null)
305
318
  return null;
@@ -314,12 +327,18 @@ export async function linkTokenGrant(store, token, now = new Date()) {
314
327
  const back = overBudgetUntil(budgetStandings(grant.budget, uses, now));
315
328
  if (back !== undefined)
316
329
  throw linkUnavailableError(budgetExhausted(back));
317
- const reached = new Set(grantSpend(grant.credentialIds, grant.limits, uses, now).filter((entry) => entry.reached).map((entry) => entry.credentialId));
318
- if (reached.size === 0)
330
+ if (grant.limits.length === 0)
319
331
  return grant;
320
- const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.has(id)));
321
- if (credentialIds.size === 0)
322
- throw linkUnavailableError(limitsReached(nextMonthStart(now)));
332
+ const plans = grant.limits.some((limit) => limit.maxPercent !== undefined)
333
+ ? await users.plansWithIds(grant.limits.map((limit) => limit.credentialId))
334
+ : [];
335
+ const reached = grantSpend(grant.credentialIds, grant.limits, uses, plans, now).filter((entry) => entry.reached);
336
+ if (reached.length === 0)
337
+ return grant;
338
+ const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.some((entry) => entry.credentialId === id)));
339
+ if (credentialIds.size === 0) {
340
+ throw linkUnavailableError(limitsReached(new Date(Math.min(...reached.map((entry) => Date.parse(entry.resetsAt))))));
341
+ }
323
342
  return { ...grant, credentialIds };
324
343
  }
325
344
  function endpointName(name) {
@@ -281,8 +281,6 @@ export type LinkApprovalPage = {
281
281
  connections(subject: string): Promise<LinkConnection[]>;
282
282
  /** The user ends one of their grants; false when they have none by that id. */
283
283
  disconnect(subject: string, grantId: string): Promise<boolean>;
284
- /** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
285
- setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
286
284
  /** Replace one of the user's grants' monthly spend limits; false when they have none by that id. */
287
285
  setLimits(subject: string, grantId: string, limits: LinkLimit[]): Promise<boolean>;
288
286
  };
@@ -336,20 +334,26 @@ export type LinkBudget = {
336
334
  maxTokens: number;
337
335
  };
338
336
  /**
339
- * The most a grant may spend on one of its plans or API keys in a calendar
340
- * month (UTC), in US dollars. A plan's spend is what its requests would have
341
- * cost at API prices. See link/budget.ts.
337
+ * A grant's limit on one of its plans or API keys; exactly one field is set.
338
+ * A plan leaves the grant while any of its plan-wide quota windows is at
339
+ * `maxPercent` used, whoever used it, until that window resets: the rest is
340
+ * the user's. An API key leaves it once the grant's spend on it this calendar
341
+ * month (UTC) reaches `monthlyUsd`. See link/budget.ts.
342
342
  */
343
343
  export type LinkLimit = {
344
344
  credentialId: string;
345
- monthlyUsd: number;
345
+ maxPercent?: number;
346
+ monthlyUsd?: number;
346
347
  };
347
- /** A granted plan or key's spend this month, and its limit when it has one. */
348
+ /** A granted plan or key's spend and standing, and its limit when it has one. */
348
349
  export type LinkSpend = {
349
350
  credentialId: string;
350
351
  spentUsd: number;
351
352
  monthlyUsd: number | null;
353
+ maxPercent: number | null;
354
+ usedPercent: number | null;
352
355
  reached: boolean;
356
+ resetsAt: string | null;
353
357
  };
354
358
  /** A budget window as it stands for a grant. */
355
359
  export type LinkBudgetStanding = {
@@ -8,6 +8,7 @@ import { gatewayFor } from "../models/gateways.js";
8
8
  import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
9
9
  import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
10
10
  import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
11
+ import { linkSubscription } from "../link/self_hosted.js";
11
12
  import { linkTokenGrant } from "../link/service.js";
12
13
  import { servedRouter } from "./router_specs.js";
13
14
  import { refreshedAccessToken } from "./subscriptions/access.js";
@@ -31,7 +32,7 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
31
32
  */
32
33
  export async function resolveSelfHostedRouter(deps, request) {
33
34
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
34
- const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
35
+ const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
35
36
  if (keyIndex === null && grant === null) {
36
37
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
37
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.340",
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.340",
55
+ "@mupt-ai/dari-router": "1.0.341",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -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 what it spends on each of its plans and API keys in
14
- a calendar month (UTC): an API key's spend is what its provider charged,
15
- and a plan's is what its requests would have cost at API prices. A plan or
16
- key at its limit leaves the grant until the month ends; the grant serves on
17
- the rest. */
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, with its limit when it has one. */
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 monthlyUsd = limits.find((limit) => limit.credentialId === credentialId)?.monthlyUsd ?? null;
102
- return { credentialId, spentUsd, monthlyUsd, reached: monthlyUsd !== null && spentUsd >= monthlyUsd };
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
- /** Limits from a request: `[{credential_id, monthly_usd}]`, each a distinct plan or key and a dollar amount of 0 or more. */
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
- typeof credentialId !== "string" || credentialId.length === 0
115
- || typeof monthlyUsd !== "number" || !Number.isFinite(monthlyUsd) || monthlyUsd < 0
116
- || limits.some((other) => other.credentialId === credentialId)
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) => ({ credential_id: limit.credentialId, monthly_usd: limit.monthlyUsd }));
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
 
@@ -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, linkTokens, spendBody, validBudget, validLimits } from "./budget.js";
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 tokens = linkTokens(connection.usage);
1376
- const limit = (minutes: number, label: string) => {
1377
- const standing = connection.budget.find((window) => window.windowMinutes === minutes);
1378
- return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
1379
- <input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
1380
- ${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
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
- const id = `usd_${escapeHtml(plan.id)}_${escapeHtml(connection.id)}`;
1386
- return `<label class="field" for="${id}">${escapeHtml(planName(plan))} Per Month ($)</label>
1387
- <input id="${id}" type="text" inputmode="decimal" name="usd_${escapeHtml(plan.id)}" value="${spend?.monthlyUsd ?? ""}" placeholder="No Limit" autocomplete="off">
1388
- <p class="hint">${dollars(spend?.spentUsd ?? 0)} this month${spend?.reached ? ", at the limit until the month ends" : ""}</p>`;
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>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} &middot; ${count(connection.usage.requests)} requests &middot; ${count(tokens)} tokens</small>
1394
- <small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
1395
- ${limit(300, "Per 5 Hours")}
1396
- ${limit(10080, "Per Week")}
1397
- ${connection.subscriptions.map(spendLimit).join("\n")}
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 === "budget") {
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,$]/g, "");
1429
- if (!field.startsWith("usd_") || value === "") return [];
1430
- return [{ credential_id: field.slice(4), monthly_usd: /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN }];
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) return await connectionsPage(approval, request, "Each monthly limit is a dollar amount; leave it empty for none.");
1433
- await approval.setBudget(session.subject, grantId, budget);
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 0;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
+ [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 {
@@ -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 monthly spend limit the user set. It is back at ${resetsAt.toISOString()}.`,
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
  }
@@ -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)?.windows ?? []).map((window) => ({
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
+ }
@@ -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 store.budgetUses(grant.id, usesSince(grant.budget, now));
174
+ const [uses, plans] = await Promise.all([
175
+ store.budgetUses(grant.id, usesSince(grant.budget, now)),
176
+ grant.limits.length === 0 ? [] : 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 owned = new Set((await users.plans(subject)).map((plan) => plan.id));
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
- if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
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
- if (!limits.every((limit) => grant.credentialIds.includes(limit.credentialId))) {
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 monthly spend limit are left out. Throws
449
- * the 401 a dead token gets, and the 424 a grant at its budget, or with every
450
- * plan and key at its limit, gets until it serves again.
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(store: LinkStore, token: string, now = new Date()): Promise<ActiveLinkGrant | null> {
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
- const reached = new Set(
463
- grantSpend(grant.credentialIds, grant.limits, uses, now).filter((entry) => entry.reached).map((entry) => entry.credentialId),
464
- );
465
- if (reached.size === 0) return grant;
466
- const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.has(id)));
467
- if (credentialIds.size === 0) throw linkUnavailableError(limitsReached(nextMonthStart(now)));
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
 
@@ -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,26 @@ export type LinkConnect = {
317
315
  export type LinkBudget = { windowMinutes: number; maxTokens: number };
318
316
 
319
317
  /**
320
- * The most a grant may spend on one of its plans or API keys in a calendar
321
- * month (UTC), in US dollars. A plan's spend is what its requests would have
322
- * cost at API prices. See link/budget.ts.
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: number };
324
+ export type LinkLimit = { credentialId: string; maxPercent?: number; monthlyUsd?: number };
325
325
 
326
- /** A granted plan or key's spend this month, and its limit when it has one. */
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;
330
331
  monthlyUsd: number | null;
331
- // At its limit: the grant leaves it out until the month ends.
332
+ maxPercent: number | null;
333
+ // A plan's most-used plan-wide window, in percent; null when unknown.
334
+ usedPercent: number | null;
335
+ // At its limit: the grant leaves it out until `resetsAt`.
332
336
  reached: boolean;
337
+ resetsAt: string | null;
333
338
  };
334
339
 
335
340
  /** A budget window as it stands for a grant. */
@@ -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
  }