@mupt-ai/dari-gateway 1.0.339 → 1.0.341

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +9 -7
  2. package/dist/index.d.ts +1 -1
  3. package/dist/link/assets.js +7 -0
  4. package/dist/link/budget.d.ts +18 -7
  5. package/dist/link/budget.js +58 -16
  6. package/dist/link/endpoints.js +64 -45
  7. package/dist/link/errors.js +4 -1
  8. package/dist/link/self_hosted.d.ts +3 -1
  9. package/dist/link/self_hosted.js +25 -9
  10. package/dist/link/service.d.ts +4 -4
  11. package/dist/link/service.js +41 -22
  12. package/dist/models/catalog.js +1 -0
  13. package/dist/models/execution_provider.d.ts +6 -1
  14. package/dist/models/execution_provider.js +12 -0
  15. package/dist/models/provider_defaults.js +9 -0
  16. package/dist/models/provider_models.json +217 -0
  17. package/dist/models/subscriptions.d.ts +5 -0
  18. package/dist/models/subscriptions.js +21 -2
  19. package/dist/platform/platform.d.ts +11 -7
  20. package/dist/providers/execution.d.ts +5 -0
  21. package/dist/providers/execution.js +12 -2
  22. package/dist/providers/github_copilot.d.ts +8 -0
  23. package/dist/providers/github_copilot.js +21 -0
  24. package/dist/providers/pi.js +3 -0
  25. package/dist/providers/provider_attempt_runner.d.ts +2 -0
  26. package/dist/providers/provider_attempt_runner.js +9 -0
  27. package/dist/providers/provider_call.js +6 -2
  28. package/dist/providers/subscription_limits.d.ts +6 -5
  29. package/dist/providers/subscription_limits.js +20 -9
  30. package/dist/runtime/routed_runtime.js +68 -3
  31. package/dist/self_host/resolve.d.ts +11 -9
  32. package/dist/self_host/resolve.js +249 -182
  33. package/dist/self_host/subscriptions/index.d.ts +6 -5
  34. package/dist/self_host/subscriptions/index.js +6 -5
  35. package/dist/self_host/subscriptions/oauth.d.ts +7 -3
  36. package/dist/self_host/subscriptions/oauth.js +195 -5
  37. package/dist/self_host/subscriptions/store.js +3 -0
  38. package/dist/telemetry/prefix_state.d.ts +1 -0
  39. package/dist/telemetry/prefix_state.js +1 -1
  40. package/dist/telemetry/report.js +2 -3
  41. package/dist/types.d.ts +6 -2
  42. package/package.json +2 -2
  43. package/src/index.ts +1 -1
  44. package/src/link/assets.ts +7 -0
  45. package/src/link/budget.ts +53 -18
  46. package/src/link/endpoints.ts +66 -45
  47. package/src/link/errors.ts +4 -1
  48. package/src/link/self_hosted.ts +26 -8
  49. package/src/link/service.ts +45 -23
  50. package/src/models/catalog.ts +1 -0
  51. package/src/models/execution_provider.ts +24 -1
  52. package/src/models/provider_defaults.ts +9 -0
  53. package/src/models/provider_models.json +217 -0
  54. package/src/models/subscriptions.ts +22 -2
  55. package/src/platform/platform.ts +13 -8
  56. package/src/providers/execution.ts +22 -2
  57. package/src/providers/github_copilot.ts +24 -0
  58. package/src/providers/pi.ts +2 -0
  59. package/src/providers/provider_attempt_runner.ts +15 -0
  60. package/src/providers/provider_call.ts +6 -2
  61. package/src/providers/subscription_limits.ts +20 -10
  62. package/src/runtime/routed_runtime.ts +79 -3
  63. package/src/self_host/resolve.ts +255 -187
  64. package/src/self_host/subscriptions/index.ts +7 -4
  65. package/src/self_host/subscriptions/oauth.ts +264 -8
  66. package/src/self_host/subscriptions/store.ts +3 -0
  67. package/src/telemetry/prefix_state.ts +4 -1
  68. package/src/telemetry/report.ts +2 -3
  69. package/src/types.ts +27 -3
@@ -62,7 +62,7 @@ import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy
62
62
  import { bearerToken } from "../http/auth.js";
63
63
  import { errorResponse, HttpError } from "../http/errors.js";
64
64
  import { SUBSCRIPTION_PLAN_LABELS } from "./errors.js";
65
- import { subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
65
+ import { modelSubscriptions, subscriptionClient } from "../models/subscriptions.js";
66
66
  import type {
67
67
  GatewayPlatform,
68
68
  LinkApp,
@@ -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
  );
@@ -970,8 +970,10 @@ async function grantBody(platform: GatewayPlatform, request: Request, accessToke
970
970
  utilization: window.utilization,
971
971
  resets_at: window.resetsAt,
972
972
  })),
973
+ // A key's provider's models; a plan's are the ones it has an offering
974
+ // of, whoever makes them (every OpenCode Go model is another maker's).
973
975
  models: models(served.get(client))
974
- .filter((model) => providerForModel(model) === (keyFor ?? subscriptionModelProvider(kind)))
976
+ .filter((model) => keyFor === undefined ? modelSubscriptions(model).includes(kind) : providerForModel(model) === keyFor)
975
977
  .map(namedModel),
976
978
  };
977
979
  }),
@@ -1370,30 +1372,34 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
1370
1372
  }
1371
1373
 
1372
1374
  function connectionCard(connection: LinkConnection, csrf: string): string {
1373
- const tokens = linkTokens(connection.usage);
1374
- const limit = (minutes: number, label: string) => {
1375
- const standing = connection.budget.find((window) => window.windowMinutes === minutes);
1376
- return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
1377
- <input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
1378
- ${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
1379
- };
1380
- // The most the grant may spend on each plan or key a month.
1381
- 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) => {
1382
1382
  const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
1383
- const id = `usd_${escapeHtml(plan.id)}_${escapeHtml(connection.id)}`;
1384
- return `<label class="field" for="${id}">${escapeHtml(planName(plan))} Per Month ($)</label>
1385
- <input id="${id}" type="text" inputmode="decimal" name="usd_${escapeHtml(plan.id)}" value="${spend?.monthlyUsd ?? ""}" placeholder="No Limit" autocomplete="off">
1386
- <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>`;
1387
1393
  };
1394
+ const limited = connection.spend.some((entry) => entry.monthlyUsd !== null || entry.maxPercent !== null);
1388
1395
  return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
1389
1396
  <input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
1390
1397
  <strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
1391
- <small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} &middot; ${count(connection.usage.requests)} requests &middot; ${count(tokens)} tokens</small>
1392
- <small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
1393
- ${limit(300, "Per 5 Hours")}
1394
- ${limit(10080, "Per Week")}
1395
- ${connection.subscriptions.map(spendLimit).join("\n")}
1396
- <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>
1397
1403
  </form>`;
1398
1404
  }
1399
1405
 
@@ -1415,20 +1421,17 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
1415
1421
  await approval.disconnect(session.subject, grantId);
1416
1422
  return back;
1417
1423
  }
1418
- if (decision === "budget") {
1419
- const entries = [300, 10080].flatMap((minutes) => {
1420
- const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
1421
- return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
1422
- });
1423
- const budget = validBudget(entries);
1424
- 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") {
1425
1425
  const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
1426
- const value = raw.replace(/[\s,$]/g, "");
1427
- if (!field.startsWith("usd_") || value === "") return [];
1428
- 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 }];
1429
1431
  }));
1430
- if (limits === null) return await connectionsPage(approval, request, "Each monthly limit is a dollar amount; leave it empty for none.");
1431
- 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
+ }
1432
1435
  await approval.setLimits(session.subject, grantId, limits);
1433
1436
  return back;
1434
1437
  }
@@ -1460,10 +1463,6 @@ function planName(subscription: LinkSubscription): string {
1460
1463
  : KINDS[subscription.provider as SubscriptionKind]?.name ?? subscription.name;
1461
1464
  }
1462
1465
 
1463
- function count(value: number): string {
1464
- return value.toLocaleString("en-US");
1465
- }
1466
-
1467
1466
  // Back to the approval page by GET, so no form is left to resubmit.
1468
1467
  function seeAuthorize(authorize: AuthorizeRequest, cookies: string[]): Response {
1469
1468
  const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
@@ -1696,12 +1695,16 @@ function eventFor(authorize: AuthorizeRequest, step: LinkStep): PageEvent | unde
1696
1695
  };
1697
1696
  }
1698
1697
 
1699
- // How a kind of plan reads on the page, and whose sign-in connects it.
1700
- const KINDS: Record<SubscriptionKind, { name: string; plan: string; at: string }> = {
1698
+ // How a kind of plan reads on the page, and whose sign-in connects it. A
1699
+ // `pastedKey` plan connects with a key the user creates there instead.
1700
+ const KINDS: Record<SubscriptionKind, { name: string; plan: string; at: string; pastedKey?: true }> = {
1701
1701
  anthropic_claude_code: { name: "Claude", plan: "Pro, Max or Ultra plan", at: "Claude" },
1702
1702
  openai_codex: { name: "ChatGPT", plan: "Plus or Pro plan", at: "OpenAI" },
1703
1703
  meta_muse: { name: "Meta Muse", plan: "Muse Code plan", at: "Meta" },
1704
1704
  opencode_go: { name: "OpenCode Go", plan: "Go plan", at: "OpenCode" },
1705
+ github_copilot: { name: "GitHub Copilot", plan: "Copilot plan", at: "GitHub" },
1706
+ xai_grok: { name: "Grok", plan: "SuperGrok plan", at: "xAI" },
1707
+ vercel_token_pass: { name: "Vercel Token Pass", plan: "Token Pass", at: "Vercel", pastedKey: true },
1705
1708
  };
1706
1709
 
1707
1710
  // The first page a new user sees: what connecting means, and one button.
@@ -1770,11 +1773,25 @@ function keyPage(authorize: AuthorizeRequest, provider: LinkKeyProvider, error?:
1770
1773
  });
1771
1774
  }
1772
1775
 
1773
- // The provider's sign-in: a link to it, and the code to bring back or take there.
1776
+ // The provider's sign-in: a link to it, and the code to bring back or take
1777
+ // there; or, for a plan that is a key, where to create the key to paste back.
1774
1778
  function providerPage(authorize: AuthorizeRequest, connect: Connect, error?: string): Response {
1775
- const { name, at } = KINDS[connect.kind];
1779
+ const { name, at, pastedKey } = KINDS[connect.kind];
1776
1780
  const open = (style: string) =>
1777
- `<a class="btn ${style}" href="${escapeHtml(connect.url)}" target="_blank" rel="noopener noreferrer">Open ${name}${ICONS.external}</a>`;
1781
+ `<a class="btn ${style}" href="${escapeHtml(connect.url)}" target="_blank" rel="noopener noreferrer">Open ${pastedKey ? at : name}${ICONS.external}</a>`;
1782
+ if (pastedKey) {
1783
+ return pane(authorize, {
1784
+ title: `Add Your ${name} Key`,
1785
+ step: "connect_subscription",
1786
+ back: "select",
1787
+ error,
1788
+ body: `<span class="who">${logo(connect.kind, name)}</span>
1789
+ <h1>Add Your ${name} Key</h1>
1790
+ <div class="step"><span class="n">1</span><div><p>Create a ${name} key at ${at}.</p>${open("outline")}</div></div>
1791
+ <div class="step"><span class="n">2</span><div><label for="authorization_response">Paste the key.</label><input id="authorization_response" type="password" name="authorization_response" autocomplete="off" spellcheck="false" placeholder="Paste Key" required></div></div>`,
1792
+ footer: `<button class="btn primary" type="submit" name="decision" value="complete">Continue</button>`,
1793
+ });
1794
+ }
1778
1795
  const head = `<span class="who">${logo(connect.kind, name)}</span>
1779
1796
  <h1>Sign In To ${name}</h1>`;
1780
1797
  if (connect.userCode === null) {
@@ -2022,13 +2039,17 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
2022
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}
2023
2040
  .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
2024
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}
2025
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}
2026
2047
  .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
2027
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}
2028
2049
  .nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
2029
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}
2030
2051
  a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
2031
- [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}
2032
2053
  ::selection{background:var(--mint);color:var(--page)}`;
2033
2054
 
2034
2055
  function escapeHtml(value: string): string {
@@ -49,6 +49,9 @@ export const SUBSCRIPTION_PLAN_LABELS: Record<SubscriptionKind, string> = {
49
49
  openai_codex: "ChatGPT Plus/Pro",
50
50
  meta_muse: "Meta Muse",
51
51
  opencode_go: "OpenCode Go",
52
+ github_copilot: "GitHub Copilot",
53
+ xai_grok: "Grok",
54
+ vercel_token_pass: "Vercel Token Pass",
52
55
  };
53
56
 
54
57
  const ONLY_CLIENT: Partial<Record<SubscriptionKind, string>> = {
@@ -97,7 +100,7 @@ export function budgetExhausted(resetsAt: Date): LinkUnavailable {
97
100
  export function limitsReached(resetsAt: Date): LinkUnavailable {
98
101
  return {
99
102
  code: "grant_budget_exhausted",
100
- 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()}.`,
101
104
  resets_at: resetsAt.toISOString(),
102
105
  };
103
106
  }
@@ -10,8 +10,10 @@ import { checkProviderKey } from "../providers/key_check.js";
10
10
  import { gatewayKeyIndex, type SelfHostedResolverDeps } from "../self_host/resolve.js";
11
11
  import {
12
12
  CODEX_APPROVAL_PENDING,
13
+ GITHUB_APPROVAL_PENDING,
13
14
  META_APPROVAL_PENDING,
14
15
  OPENCODE_APPROVAL_PENDING,
16
+ XAI_APPROVAL_PENDING,
15
17
  SUBSCRIPTION_PROVIDERS,
16
18
  SubscriptionOAuthInputError,
17
19
  SubscriptionOAuthProviderError,
@@ -132,7 +134,13 @@ export function selfHostedLink(
132
134
  tokens = await completeOAuth(session.provider, session.flow, authorizationResponse, { fetch: deps.fetch });
133
135
  } catch (error) {
134
136
  if (error instanceof SubscriptionOAuthInputError) {
135
- if ([CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING].includes(error.message)) return null;
137
+ if ([
138
+ CODEX_APPROVAL_PENDING,
139
+ META_APPROVAL_PENDING,
140
+ OPENCODE_APPROVAL_PENDING,
141
+ GITHUB_APPROVAL_PENDING,
142
+ XAI_APPROVAL_PENDING,
143
+ ].includes(error.message)) return null;
136
144
  throw new HttpError(400, error.message, "invalid_request");
137
145
  }
138
146
  if (error instanceof SubscriptionOAuthProviderError) {
@@ -168,7 +176,7 @@ function linkKey(key: LinkApiKey): LinkSubscription {
168
176
  };
169
177
  }
170
178
 
171
- function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
179
+ export function linkSubscription(credential: SubscriptionCredential): LinkSubscription {
172
180
  const now = new Date();
173
181
  return {
174
182
  id: credential.id,
@@ -179,11 +187,21 @@ function linkSubscription(credential: SubscriptionCredential): LinkSubscription
179
187
  unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
180
188
  ? credential.unavailableUntil.toISOString()
181
189
  : null,
182
- usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
183
- ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
184
- minutes: window.minutes,
185
- utilization: window.utilization,
186
- resetsAt: window.resetsAt.toISOString(),
187
- })),
190
+ usage: linkUsageWindows(currentUsage(credential, now), now),
188
191
  };
189
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
 
@@ -69,6 +69,7 @@ export const DEFAULT_CATALOG_PROVIDERS: readonly string[] = [
69
69
  "google",
70
70
  "fireworks",
71
71
  "opencode-go",
72
+ "github-copilot",
72
73
  "openrouter",
73
74
  "vercel-ai-gateway",
74
75
  ];
@@ -1,5 +1,10 @@
1
1
  import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
2
- import type { ProviderKeySource, ResolvedRouter } from "../types.js";
2
+ import type {
3
+ ProviderCredential,
4
+ ProviderKeySource,
5
+ ResolvedRouter,
6
+ ResolvedRouterModelConfig,
7
+ } from "../types.js";
3
8
 
4
9
  /** Actual serving provider for a canonical model on a resolved managed router. */
5
10
  export function executionProviderForModel(
@@ -23,3 +28,21 @@ export function keySourceForModel(
23
28
  if (supplied) return supplied.subscription ? "subscription" : "user";
24
29
  return credentials.provider_key_sources?.[executionProviderForModel(credentials, model)] ?? "user";
25
30
  }
31
+
32
+ /**
33
+ * The router as one of a model's fallbacks serves it: the fallback's config,
34
+ * and its plan's credential or, without one, the router's API credential.
35
+ */
36
+ export function credentialsServedBy(
37
+ credentials: ResolvedRouter,
38
+ model: string,
39
+ config: ResolvedRouterModelConfig,
40
+ plan: ProviderCredential | undefined,
41
+ ): ResolvedRouter {
42
+ const { [model]: _replaced, ...others } = credentials.provider_credentials ?? {};
43
+ return {
44
+ ...credentials,
45
+ model_configs: { ...credentials.model_configs, [model]: config },
46
+ provider_credentials: plan === undefined ? others : { ...others, [model]: plan },
47
+ };
48
+ }
@@ -12,6 +12,8 @@ const PROVIDER_LABELS: Record<string, string> = {
12
12
  xai: "xAI",
13
13
  google: "Google",
14
14
  "opencode-go": "OpenCode Go",
15
+ "github-copilot": "GitHub Copilot",
16
+ "vercel-token-pass": "Vercel Token Pass",
15
17
  dari: "Dari",
16
18
  "amazon-bedrock": "Amazon Bedrock",
17
19
  azure: "Microsoft Azure",
@@ -39,6 +41,13 @@ const PROVIDER_BASE_URLS: Record<string, string> = {
39
41
  // A flat-rate plan for open models; each model keeps its own API path
40
42
  // under https://opencode.ai/inference/go/, and this is chat completions.
41
43
  "opencode-go": "https://opencode.ai/inference/go/openai/v1",
44
+ // Flat plans served only by personal subscriptions. Each Copilot account
45
+ // has its own API origin, named in its token (see github_copilot.ts); this
46
+ // one is the individual plans'.
47
+ "github-copilot": "https://api.individual.githubcopilot.com",
48
+ // A Token Pass key on Vercel AI Gateway, which serves only the gateway's
49
+ // featured models, over Anthropic Messages.
50
+ "vercel-token-pass": "https://ai-gateway.vercel.sh",
42
51
  // Meta's Model API serves OpenAI Responses and Chat Completions here, and
43
52
  // Anthropic Messages at https://api.meta.ai.
44
53
  meta: "https://api.meta.ai/v1",