@mupt-ai/dari-gateway 1.0.339 → 1.0.341
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -7
- package/dist/index.d.ts +1 -1
- package/dist/link/assets.js +7 -0
- package/dist/link/budget.d.ts +18 -7
- package/dist/link/budget.js +58 -16
- package/dist/link/endpoints.js +64 -45
- package/dist/link/errors.js +4 -1
- package/dist/link/self_hosted.d.ts +3 -1
- package/dist/link/self_hosted.js +25 -9
- package/dist/link/service.d.ts +4 -4
- package/dist/link/service.js +41 -22
- package/dist/models/catalog.js +1 -0
- package/dist/models/execution_provider.d.ts +6 -1
- package/dist/models/execution_provider.js +12 -0
- package/dist/models/provider_defaults.js +9 -0
- package/dist/models/provider_models.json +217 -0
- package/dist/models/subscriptions.d.ts +5 -0
- package/dist/models/subscriptions.js +21 -2
- package/dist/platform/platform.d.ts +11 -7
- package/dist/providers/execution.d.ts +5 -0
- package/dist/providers/execution.js +12 -2
- package/dist/providers/github_copilot.d.ts +8 -0
- package/dist/providers/github_copilot.js +21 -0
- package/dist/providers/pi.js +3 -0
- package/dist/providers/provider_attempt_runner.d.ts +2 -0
- package/dist/providers/provider_attempt_runner.js +9 -0
- package/dist/providers/provider_call.js +6 -2
- package/dist/providers/subscription_limits.d.ts +6 -5
- package/dist/providers/subscription_limits.js +20 -9
- package/dist/runtime/routed_runtime.js +68 -3
- package/dist/self_host/resolve.d.ts +11 -9
- package/dist/self_host/resolve.js +249 -182
- package/dist/self_host/subscriptions/index.d.ts +6 -5
- package/dist/self_host/subscriptions/index.js +6 -5
- package/dist/self_host/subscriptions/oauth.d.ts +7 -3
- package/dist/self_host/subscriptions/oauth.js +195 -5
- package/dist/self_host/subscriptions/store.js +3 -0
- package/dist/telemetry/prefix_state.d.ts +1 -0
- package/dist/telemetry/prefix_state.js +1 -1
- package/dist/telemetry/report.js +2 -3
- package/dist/types.d.ts +6 -2
- package/package.json +2 -2
- package/src/index.ts +1 -1
- package/src/link/assets.ts +7 -0
- package/src/link/budget.ts +53 -18
- package/src/link/endpoints.ts +66 -45
- package/src/link/errors.ts +4 -1
- package/src/link/self_hosted.ts +26 -8
- package/src/link/service.ts +45 -23
- package/src/models/catalog.ts +1 -0
- package/src/models/execution_provider.ts +24 -1
- package/src/models/provider_defaults.ts +9 -0
- package/src/models/provider_models.json +217 -0
- package/src/models/subscriptions.ts +22 -2
- package/src/platform/platform.ts +13 -8
- package/src/providers/execution.ts +22 -2
- package/src/providers/github_copilot.ts +24 -0
- package/src/providers/pi.ts +2 -0
- package/src/providers/provider_attempt_runner.ts +15 -0
- package/src/providers/provider_call.ts +6 -2
- package/src/providers/subscription_limits.ts +20 -10
- package/src/runtime/routed_runtime.ts +79 -3
- package/src/self_host/resolve.ts +255 -187
- package/src/self_host/subscriptions/index.ts +7 -4
- package/src/self_host/subscriptions/oauth.ts +264 -8
- package/src/self_host/subscriptions/store.ts +3 -0
- package/src/telemetry/prefix_state.ts +4 -1
- package/src/telemetry/report.ts +2 -3
- package/src/types.ts +27 -3
package/README.md
CHANGED
|
@@ -27,7 +27,8 @@ The gateway is the runtime behind Dari's hosted routing service, packaged to run
|
|
|
27
27
|
## Features
|
|
28
28
|
|
|
29
29
|
- **One endpoint, three protocols.** `/v1/messages`, `/v1/chat/completions`, and `/v1/responses` (plus `/v1/models`) reach API-key providers in the [Pi AI](https://www.npmjs.com/package/@mupt-ai/pi-ai) catalog, such as Anthropic, OpenAI, and OpenRouter, or any OpenAI-compatible server.
|
|
30
|
-
- **Subscription pooling.** Connect several Claude Code (Max/Pro) or ChatGPT plans. Each conversation stays on one plan so its prompt cache stays warm. Claude Code plans report their usage on every response: once a plan has used 95% of a window, its conversations move to another plan at their next turn, and new conversations start on the plan whose quota resets soonest. A plan that reports a usage limit is held until its reset, and the request it refused is served by the next plan at once.
|
|
30
|
+
- **Subscription pooling.** Connect several Claude Code (Max/Pro) or ChatGPT plans. Each conversation stays on one plan so its prompt cache stays warm. Claude Code plans report their usage on every response: once a plan has used 95% of a window, its conversations move to another plan at their next turn, and new conversations start on the plan whose quota resets soonest. A plan that reports a usage limit is held until its reset, and the request it refused is served by the next plan at once.
|
|
31
|
+
- **Cross-plan failover.** One model can be served by several kinds of plan: GitHub Copilot serves Claude and GPT models, and OpenCode Go and Vercel Token Pass serve the Kimi and GLM models. Each model tries the plans that serve it in a fixed order, the maker's plan first: Claude Code, ChatGPT, Grok, Muse Code, OpenCode Go, GitHub Copilot, Vercel Token Pass, then its provider's API key if you set one. When a plan reaches its usage limit with no other plan of its kind left, or refuses its token, the same request moves to the model's next plan, then to the key, before anything reaches the client.
|
|
31
32
|
- **Failover.** A provider failure retries the router's next model.
|
|
32
33
|
- **Prompt-cache aware.** Conversations keep their identity and serving model across turns, so provider caches stay warm. Responses carry `X-Dari-Selected-Model`, `X-Dari-Thinking-Level`, and `X-Dari-Conversation-Id` headers for status lines.
|
|
33
34
|
- **Coding agents.** `dari claude`, `dari codex`, `dari opencode`, and `dari pi` from the [Dari CLI](https://github.com/mupt-ai/dari) launch straight against your gateway.
|
|
@@ -100,7 +101,7 @@ providers: # endpoints outside the built-in catalog
|
|
|
100
101
|
apiKeyEnv: LOCAL_API_KEY
|
|
101
102
|
```
|
|
102
103
|
|
|
103
|
-
Model ids are `provider/model`. Clients send `model: "dari/routing"` to let the router choose, or `model: "dari/model/<id>"` to pin one of its models. A Claude Code subscription serves Anthropic models only for Claude Code itself; a ChatGPT subscription serves OpenAI models for every client. Each coding agent is offered the router's models that a credential can serve it, or its own `agentModels` list (`claude_code`, `codex`, `muse_code`, `opencode`, `pi`, `openclaw`, `hermes`) when the router has one.
|
|
104
|
+
Model ids are `provider/model`. Clients send `model: "dari/routing"` to let the router choose, or `model: "dari/model/<id>"` to pin one of its models. A Claude Code subscription serves Anthropic models only for Claude Code itself; a ChatGPT subscription serves OpenAI models for every client; other plans serve every client the models they serve (see **Cross-plan failover**). Each coding agent is offered the router's models that a credential can serve it, or its own `agentModels` list (`claude_code`, `codex`, `muse_code`, `opencode`, `pi`, `openclaw`, `hermes`) when the router has one.
|
|
104
105
|
|
|
105
106
|
`dari setup <agent>` opens the model picker on a running gateway, with any gateway key. It calls `PUT /v1/router/models[/<agent>]` (`GET` reads the lists, `DELETE` removes a saved one). The gateway saves the list in its database and serves it at once in place of the config file's.
|
|
106
107
|
|
|
@@ -124,7 +125,7 @@ native_compaction: false
|
|
|
124
125
|
agents: { codex: [openai/gpt-6.1-sol] }
|
|
125
126
|
```
|
|
126
127
|
|
|
127
|
-
The gateway pays with connected subscriptions when `payment.allow` lists `subscription`,
|
|
128
|
+
The gateway pays with connected subscriptions when `payment.allow` lists `subscription`, then with provider API keys; it has no Dari credits. On hosted Dari the same setting is the router's `subscription_providers`: it can name any provider whose models some plan serves, such as `fireworks` or `google`, and those models try the user's plans first. `hosted` settings and a model's `fast` apply only on hosted Dari and are ignored here; `routing.rules` runs only on hosted Dari and is refused. A model's `provider` must be one that serves it, such as `opencode-go` or `fireworks` for the DeepSeek, Kimi, and GLM models; the plan-only providers `github-copilot` and `vercel-token-pass` serve through a connected subscription.
|
|
128
129
|
|
|
129
130
|
With any gateway key:
|
|
130
131
|
|
|
@@ -143,7 +144,7 @@ With any gateway key:
|
|
|
143
144
|
export DARI_GATEWAY_URL=http://localhost:8080
|
|
144
145
|
export DARI_GATEWAY_KEY=<one of DARI_GATEWAY_KEYS>
|
|
145
146
|
|
|
146
|
-
dari accounts subscription connect claude-code # or codex
|
|
147
|
+
dari accounts subscription connect claude-code # or codex, muse-code, opencode-go, github-copilot, grok, vercel-token-pass; repeat to pool plans
|
|
147
148
|
dari claude
|
|
148
149
|
```
|
|
149
150
|
|
|
@@ -153,7 +154,7 @@ In gateway mode the CLI makes no calls to Dari's hosted API; `dari activity` rea
|
|
|
153
154
|
|
|
154
155
|
Dari Link lets another app send one user's model requests through the gateway on only the subscriptions that user grants it: never an API key, credits, or any other plan.
|
|
155
156
|
|
|
156
|
-
**Which plans serve which apps.** A ChatGPT plan (`openai_codex`) serves any app, including a plain OpenAI `chat/completions` or Responses client, through the Codex backend. A Claude Pro/Max/Ultra plan (`anthropic_claude_code`) serves only Claude Code itself, and a Muse Code plan only Muse Code; the gateway never presents another app as those clients. An OpenCode Go plan (`opencode_go`) serves any app its `opencode-go` models. So an app that calls the API itself needs the user to grant
|
|
157
|
+
**Which plans serve which apps.** A ChatGPT plan (`openai_codex`) serves any app, including a plain OpenAI `chat/completions` or Responses client, through the Codex backend. A Claude Pro/Max/Ultra plan (`anthropic_claude_code`) serves only Claude Code itself, and a Muse Code plan only Muse Code; the gateway never presents another app as those clients. An OpenCode Go plan (`opencode_go`) serves any app its `opencode-go` models, and GitHub Copilot (`github_copilot`), Grok (`xai_grok`), and Vercel Token Pass (`vercel_token_pass`, a pasted Token Pass key that serves Vercel AI Gateway's featured models) plans serve any app theirs. So an app that calls the API itself needs the user to grant one of those plans, or an API key. The approval page offers only what the app can use: a Claude or Muse plan appears when the app runs Claude Code or Muse Code itself and says so with `client` on the authorize request.
|
|
157
158
|
|
|
158
159
|
**API keys.** A user without a plan can add an API key on the same page instead: one per model provider (Anthropic, OpenAI, Meta, Moonshot AI, xAI) or gateway (OpenRouter, Vercel AI Gateway). A key is shared like a plan, shows on the grant as `kind: "api_key"` with `provider` (never the key itself), and serves that provider's catalog models to any app, so an Anthropic key serves a plain client where a Claude plan would not. A gateway key serves any model of its gateway named by its full id, such as `openrouter/anthropic/claude-sonnet-4.5`; the grant's `models` lists none of them. A child token can be pinned to such a model the same way (`model=openrouter/anthropic/claude-sonnet-4.5`). Such a plan entry carries `model_prefix` (`"openrouter/"`): any id the gateway lists, with that prefix, is a model name here, sent as `dari/model/openrouter/<id>` or just `openrouter/<id>`. Every plan entry has a `title` to show ("Claude", "ChatGPT", "OpenRouter"). Where a grant holds both a plan and a key for a provider, the plan serves first. The usage a provider bills on the user's key is the user's cost. `plans` on the authorize request lists what the app wants offered, plan kinds and `api_key`; omit it to offer everything the app can use. `key_providers` (`keyProviders` in the client) narrows the API keys to the providers the app can run, such as `anthropic openrouter`, so a user is never offered, or shown ticked, a key the app cannot use. A user can connect as many plans and keys as they like, several accounts of one kind included, and share any of them.
|
|
159
160
|
|
|
@@ -223,7 +224,7 @@ The gateway refuses a model the grant cannot serve, a plan at its limit, a spent
|
|
|
223
224
|
- `response_mode=web_message`: for a page opened as a popup. The result is posted to the window that opened it (`{"type": "dari-link", "code" | "error", "state"}`, addressed to the redirect URI's origin) instead of sent on a redirect; a page with no opener left redirects to `redirect_uri` instead. `DariLink.open` does this for you.
|
|
224
225
|
- `grant_id`: update mode (above).
|
|
225
226
|
|
|
226
|
-
The gateway serves the page itself, hosted and self-hosted alike. A new user sees what connecting means, picks a subscription (Claude, ChatGPT, Meta Muse, OpenCode Go) or a provider to add an API key for, signs in to that provider (Claude shows a code to paste back; the others take a code the page shows and continue on their own), and allows the app with what they connected ticked. A self-hosted gateway needs no sign-in: their first plan or key makes them a user. A platform with accounts (`LinkApprovalPage.signIn`; on hosted Dari, the user's Dari account) has them sign in first, and they are that account, with the plans it already has. Either way the gateway remembers them in a signed HttpOnly cookie, so the next app that asks finds their plans connected and takes one click: for a year without accounts, since the cookie is who they are; for 30 days with them, and they can sign out from the approval and connections pages. A self-hosted gateway takes their subscriptions and keys only when it encrypts what it stores (`DARI_GATEWAY_ENCRYPTION_KEY`). A plan a user connects this way is theirs alone: it serves only the grants they approve, never a gateway key, and the gateway owner's own plans are never offered on the page.
|
|
227
|
+
The gateway serves the page itself, hosted and self-hosted alike. A new user sees what connecting means, picks a subscription (Claude, ChatGPT, Meta Muse, OpenCode Go, GitHub Copilot, Grok, Vercel Token Pass) or a provider to add an API key for, signs in to that provider (Claude shows a code to paste back, and Vercel Token Pass takes a key the user creates at Vercel; the others take a code the page shows and continue on their own), and allows the app with what they connected ticked. A self-hosted gateway needs no sign-in: their first plan or key makes them a user. A platform with accounts (`LinkApprovalPage.signIn`; on hosted Dari, the user's Dari account) has them sign in first, and they are that account, with the plans it already has. Either way the gateway remembers them in a signed HttpOnly cookie, so the next app that asks finds their plans connected and takes one click: for a year without accounts, since the cookie is who they are; for 30 days with them, and they can sign out from the approval and connections pages. A self-hosted gateway takes their subscriptions and keys only when it encrypts what it stores (`DARI_GATEWAY_ENCRYPTION_KEY`). A plan a user connects this way is theirs alone: it serves only the grants they approve, never a gateway key, and the gateway owner's own plans are never offered on the page.
|
|
227
228
|
|
|
228
229
|
The user approves; they can later cap the tokens the app may use per 5 hours and per week (see **Budgets**). The app gets `code` and `state`, or `error=access_denied`, on `redirect_uri` or as the popup's message.
|
|
229
230
|
3. `POST /v1/link/token` (form or JSON; CORS open) with `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `code_verifier` returns an access token (`dlk_at_…`, one hour) and a refresh token (`dlk_rt_…`), with the grant's fields below. `grant_type=refresh_token` with `refresh_token` returns a new access token:
|
|
@@ -232,7 +233,7 @@ The gateway refuses a model the grant cannot serve, a plan at its limit, a spent
|
|
|
232
233
|
- A confidential client's refresh token never rotates, so any number of instances can refresh one grant.
|
|
233
234
|
4. Call the gateway's ordinary endpoints (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/models`) with `Authorization: Bearer dlk_at_…`. A link token serves only the default router, and is served exactly what it names:
|
|
234
235
|
- `dari/routing` chooses among the router's models that a granted plan serves.
|
|
235
|
-
- Any other name is a model, served as exactly that model: any catalog model of a granted plan's provider, whether or not the user's router lists it. It may be named `dari/model/<provider>/<model>`, by its bare id (`gpt-5.5`, `claude-sonnet-5-5`), or as a dated snapshot of either (`claude-haiku-4-5-20251001` is `claude-haiku-4-5`), so an app forwarding Claude Code or Codex traffic needs no model map. A name no catalog model has, or one two models share, fails with `model_not_granted`. It is served with the client's own thinking settings: a level the request names is served exactly or refused (400 `thinking_level_unavailable`); Anthropic's `thinking: {"type": "disabled"}` is sent as it is, on every Claude model (`X-Dari-Thinking-Level: off`); a thinking budget (`thinking: {"type": "enabled", "budget_tokens": 8000}`) is sent as it is (`X-Dari-Thinking-Level: budget:8000`); and when it names none, none is chosen for it and the provider's default applies (`X-Dari-Thinking-Level: default`). `X-Dari-Thinking-Level` is what the provider was sent: a level, `off`, `default`, or `budget:<tokens>`. It never fails over to another model: a provider failure is returned as it is. Only when a granted plan hits its usage limit
|
|
236
|
+
- Any other name is a model, served as exactly that model: any catalog model of a granted plan's provider, whether or not the user's router lists it. It may be named `dari/model/<provider>/<model>`, by its bare id (`gpt-5.5`, `claude-sonnet-5-5`), or as a dated snapshot of either (`claude-haiku-4-5-20251001` is `claude-haiku-4-5`), so an app forwarding Claude Code or Codex traffic needs no model map. A name no catalog model has, or one two models share, fails with `model_not_granted`. It is served with the client's own thinking settings: a level the request names is served exactly or refused (400 `thinking_level_unavailable`); Anthropic's `thinking: {"type": "disabled"}` is sent as it is, on every Claude model (`X-Dari-Thinking-Level: off`); a thinking budget (`thinking: {"type": "enabled", "budget_tokens": 8000}`) is sent as it is (`X-Dari-Thinking-Level: budget:8000`); and when it names none, none is chosen for it and the provider's default applies (`X-Dari-Thinking-Level: default`). `X-Dari-Thinking-Level` is what the provider was sent: a level, `off`, `default`, or `budget:<tokens>`. It never fails over to another model: a provider failure is returned as it is. Only when a granted plan hits its usage limit or refuses its token is the request retried on the same model, on the next granted plan that serves it (in the order under **Cross-plan failover**), then on the grant's API key for the model's provider.
|
|
236
237
|
- `opus`, `sonnet`, `haiku`, and the other Anthropic tier names route, as `dari/routing` does.
|
|
237
238
|
- `POST /v1/messages/count_tokens` is not served: it answers an Anthropic-shaped 404, on which Claude Code estimates locally.
|
|
238
239
|
- A non-streamed response carries `X-Dari-Usage: {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}` (input excludes cache reads and writes) beside `X-Dari-Selected-Model` and `X-Dari-Thinking-Level`, the same whatever protocol the app speaks. A stream reports usage in its protocol's own final event; `GET /v1/link/usage` has both.
|
|
@@ -425,6 +426,7 @@ The root entry needs no Bun APIs, so any runtime with web-standard `fetch`, `Req
|
|
|
425
426
|
Platforms can also:
|
|
426
427
|
|
|
427
428
|
- implement `resolveProviderCredential({ provider, model, routerId, organizationId, apiKey, clientHarness? })` to supply a per-request `{ apiKey, baseUrl?, headers?, subscription? }`, such as a tenant's own key, in place of the router's resolved key. With `subscription` (`"openai_codex"`, `"anthropic_claude_code"`, or `"meta_muse"`), `apiKey` is that plan's access token: Codex's `auth.json` `tokens.access_token`, the token `claude setup-token` prints, or the Model API key a Meta sign-in mints. The platform keeps it fresh. Strict routers serve these supplied plans, but never subscriptions the gateway resolved itself. A plan serves only its own provider's models; a Claude Code plan serves only Claude Code clients, and a Muse Code plan only Muse Code clients (recognized by their `x-client-id`);
|
|
429
|
+
- resolve a model's plans per model: `provider_credentials[model]` is `{ apiKey, subscription, credentialId }` for the plan that serves it first, and `provider_keys` hold only API keys. `model_fallbacks[model]` lists what serves it next, in order, each `{ config, subscription }`: a plan kind, whose token the gateway asks `nextSubscription` for when it gets there, or `null` for the API key of `config.provider`. The gateway moves down the list within a request when a plan reaches its usage limit with no other plan of its kind left or refuses its token, and skips API keys while `credit_exhausted` is set;
|
|
428
430
|
- resolve routers with `strict: true` to serve only the requested `dari/model/<id>` at the requested thinking level, with no selector, lease, or personal subscription. Set `strict_providers: ["openai"]` on the resolved router to permit any bundled-catalog model from that provider without enumerating `enabled_models`. Use `dari/model/openai/gpt-6.2-sol`; bare IDs and unknown models remain refused. This grant is ignored on non-strict routers and does not discover uncatalogued models;
|
|
429
431
|
- resolve routers with `session_pinning: true` to route each session once and serve that pair for the rest of the session. Each subagent (Claude Code agent id, Codex subagent thread, OpenCode child session) is routed once on its own. Pins are kept through `readSessionPin` and `writeSessionPin`, keyed by router and an opaque pin key; background requests and `dari/model/<id>` requests never use them;
|
|
430
432
|
- resolve routers with `native_compaction: true` to let Codex compact context server-side with the provider's native compaction. Requests carrying compaction state are routed only to models that support it;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,4 +4,4 @@ export { DEFAULT_CATALOG_PROVIDERS, listModelCatalog, type CatalogModel, type Ca
|
|
|
4
4
|
export { createAutoRoutingSelectorBackend } from "./strategies/auto_routing_selector.js";
|
|
5
5
|
export { createPrioritySelectorBackend } from "./strategies/priority_selector.js";
|
|
6
6
|
export { createLlmSelectorBackend, type SelectorBackend } from "./strategies/routing.js";
|
|
7
|
-
export type { ProviderCredential, ResolvedRouter, SubscriptionKind } from "./types.js";
|
|
7
|
+
export type { ModelFallback, ProviderCredential, ResolvedRouter, SubscriptionKind } from "./types.js";
|
package/dist/link/assets.js
CHANGED
|
@@ -9,6 +9,8 @@ const MARKS = {
|
|
|
9
9
|
anthropic: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.46H0L6.57 3.522zm4.132 9.959L8.453 7.687 6.205 13.48H10.7z"></path></svg>`,
|
|
10
10
|
claude: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"></path></svg>`,
|
|
11
11
|
gemini: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M12 24A14.304 14.304 0 000 12 14.304 14.304 0 0012 0a14.305 14.305 0 0012 12 14.305 14.305 0 00-12 12"></path></svg>`,
|
|
12
|
+
githubcopilot: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M19.245 5.364c1.322 1.36 1.877 3.216 2.11 5.817.622 0 1.2.135 1.592.654l.73.964c.21.278.323.61.323.955v2.62c0 .339-.173.669-.453.868C20.239 19.602 16.157 21.5 12 21.5c-4.6 0-9.205-2.583-11.547-4.258-.28-.2-.452-.53-.453-.868v-2.62c0-.345.113-.679.321-.956l.73-.963c.392-.517.974-.654 1.593-.654l.029-.297c.25-2.446.81-4.213 2.082-5.52 2.461-2.54 5.71-2.851 7.146-2.864h.198c1.436.013 4.685.323 7.146 2.864zm-7.244 4.328c-.284 0-.613.016-.962.05-.123.447-.305.85-.57 1.108-1.05 1.023-2.316 1.18-2.994 1.18-.638 0-1.306-.13-1.851-.464-.516.165-1.012.403-1.044.996a65.882 65.882 0 00-.063 2.884l-.002.48c-.002.563-.005 1.126-.013 1.69.002.326.204.63.51.765 2.482 1.102 4.83 1.657 6.99 1.657 2.156 0 4.504-.555 6.985-1.657a.854.854 0 00.51-.766c.03-1.682.006-3.372-.076-5.053-.031-.596-.528-.83-1.046-.996-.546.333-1.212.464-1.85.464-.677 0-1.942-.157-2.993-1.18-.266-.258-.447-.661-.57-1.108-.32-.032-.64-.049-.96-.05zm-2.525 4.013c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zm5 0c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zM7.635 5.087c-1.05.102-1.935.438-2.385.906-.975 1.037-.765 3.668-.21 4.224.405.394 1.17.657 1.995.657h.09c.649-.013 1.785-.176 2.73-1.11.435-.41.705-1.433.675-2.47-.03-.834-.27-1.52-.63-1.813-.39-.336-1.275-.482-2.265-.394zm6.465.394c-.36.292-.6.98-.63 1.813-.03 1.037.24 2.06.675 2.47.968.957 2.136 1.104 2.776 1.11h.044c.825 0 1.59-.263 1.995-.657.555-.556.765-3.187-.21-4.224-.45-.468-1.335-.804-2.385-.906-.99-.088-1.875.058-2.265.394zM12 7.615c-.24 0-.525.015-.84.044.03.16.045.336.06.526l-.001.159a2.94 2.94 0 01-.014.25c.225-.022.425-.027.612-.028h.366c.187 0 .387.006.612.028-.015-.146-.015-.277-.015-.409.015-.19.03-.365.06-.526a9.29 9.29 0 00-.84-.044z"></path></svg>`,
|
|
13
|
+
grok: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>`,
|
|
12
14
|
meta: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M6.897 4c1.915 0 3.516.932 5.43 3.376l.282-.373c.19-.246.383-.484.58-.71l.313-.35C14.588 4.788 15.792 4 17.225 4c1.273 0 2.469.557 3.491 1.516l.218.213c1.73 1.765 2.917 4.71 3.053 8.026l.011.392.002.25c0 1.501-.28 2.759-.818 3.7l-.14.23-.108.153c-.301.42-.664.758-1.086 1.009l-.265.142-.087.04a3.493 3.493 0 01-.302.118 4.117 4.117 0 01-1.33.208c-.524 0-.996-.067-1.438-.215-.614-.204-1.163-.56-1.726-1.116l-.227-.235c-.753-.812-1.534-1.976-2.493-3.586l-1.43-2.41-.544-.895-1.766 3.13-.343.592C7.597 19.156 6.227 20 4.356 20c-1.21 0-2.205-.42-2.936-1.182l-.168-.184c-.484-.573-.837-1.311-1.043-2.189l-.067-.32a8.69 8.69 0 01-.136-1.288L0 14.468c.002-.745.06-1.49.174-2.23l.1-.573c.298-1.53.828-2.958 1.536-4.157l.209-.34c1.177-1.83 2.789-3.053 4.615-3.16L6.897 4zm-.033 2.615l-.201.01c-.83.083-1.606.673-2.252 1.577l-.138.199-.01.018c-.67 1.017-1.185 2.378-1.456 3.845l-.004.022a12.591 12.591 0 00-.207 2.254l.002.188c.004.18.017.36.04.54l.043.291c.092.503.257.908.486 1.208l.117.137c.303.323.698.492 1.17.492 1.1 0 1.796-.676 3.696-3.641l2.175-3.4.454-.701-.139-.198C9.11 7.3 8.084 6.616 6.864 6.616zm10.196-.552l-.176.007c-.635.048-1.223.359-1.82.933l-.196.198c-.439.462-.887 1.064-1.367 1.807l.266.398c.18.274.362.56.55.858l.293.475 1.396 2.335.695 1.114c.583.926 1.03 1.6 1.408 2.082l.213.262c.282.326.529.54.777.673l.102.05c.227.1.457.138.718.138.176.002.35-.023.518-.073.338-.104.61-.32.813-.637l.095-.163.077-.162c.194-.459.29-1.06.29-1.785l-.006-.449c-.08-2.871-.938-5.372-2.2-6.798l-.176-.189c-.67-.683-1.444-1.074-2.27-1.074z"></path></svg>`,
|
|
13
15
|
moonshot: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M1.052 16.916l9.539 2.552a21.007 21.007 0 00.06 2.033l5.956 1.593a11.997 11.997 0 01-5.586.865l-.18-.016-.044-.004-.084-.009-.094-.01a11.605 11.605 0 01-.157-.02l-.107-.014-.11-.016a11.962 11.962 0 01-.32-.051l-.042-.008-.075-.013-.107-.02-.07-.015-.093-.019-.075-.016-.095-.02-.097-.023-.094-.022-.068-.017-.088-.022-.09-.024-.095-.025-.082-.023-.109-.03-.062-.02-.084-.025-.093-.028-.105-.034-.058-.019-.08-.026-.09-.031-.066-.024a6.293 6.293 0 01-.044-.015l-.068-.025-.101-.037-.057-.022-.08-.03-.087-.035-.088-.035-.079-.032-.095-.04-.063-.028-.063-.027a5.655 5.655 0 01-.041-.018l-.066-.03-.103-.047-.052-.024-.096-.046-.062-.03-.084-.04-.086-.044-.093-.047-.052-.027-.103-.055-.057-.03-.058-.032a6.49 6.49 0 01-.046-.026l-.094-.053-.06-.034-.051-.03-.072-.041-.082-.05-.093-.056-.052-.032-.084-.053-.061-.039-.079-.05-.07-.047-.053-.035a7.785 7.785 0 01-.054-.036l-.044-.03-.044-.03a6.066 6.066 0 01-.04-.028l-.057-.04-.076-.054-.069-.05-.074-.054-.056-.042-.076-.057-.076-.059-.086-.067-.045-.035-.064-.052-.074-.06-.089-.073-.046-.039-.046-.039a7.516 7.516 0 01-.043-.037l-.045-.04-.061-.053-.07-.062-.068-.06-.062-.058-.067-.062-.053-.05-.088-.084a13.28 13.28 0 01-.099-.097l-.029-.028-.041-.042-.069-.07-.05-.051-.05-.053a6.457 6.457 0 01-.168-.179l-.08-.088-.062-.07-.071-.08-.042-.049-.053-.062-.058-.068-.046-.056a7.175 7.175 0 01-.027-.033l-.045-.055-.066-.082-.041-.052-.05-.064-.02-.025a11.99 11.99 0 01-1.44-2.402zm-1.02-5.794l11.353 3.037a20.468 20.468 0 00-.469 2.011l10.817 2.894a12.076 12.076 0 01-1.845 2.005L.657 15.923l-.016-.046-.035-.104a11.965 11.965 0 01-.05-.153l-.007-.023a11.896 11.896 0 01-.207-.741l-.03-.126-.018-.08-.021-.097-.018-.081-.018-.09-.017-.084-.018-.094c-.026-.141-.05-.283-.071-.426l-.017-.118-.011-.083-.013-.102a12.01 12.01 0 01-.019-.161l-.005-.047a12.12 12.12 0 01-.034-2.145zm1.593-5.15l11.948 3.196c-.368.605-.705 1.231-1.01 1.875l11.295 3.022c-.142.82-.368 1.612-.668 2.365l-11.55-3.09L.124 10.26l.015-.1.008-.049.01-.067.015-.087.018-.098c.026-.148.056-.295.088-.442l.028-.124.02-.085.024-.097c.022-.09.045-.18.07-.268l.028-.102.023-.083.03-.1.025-.082.03-.096.026-.082.031-.095a11.896 11.896 0 011.01-2.232zm4.442-4.4L17.352 4.59a20.77 20.77 0 00-1.688 1.721l7.823 2.093c.267.852.442 1.744.513 2.665L2.106 5.213l.045-.065.027-.04.04-.055.046-.065.055-.076.054-.072.064-.086.05-.065.057-.073.055-.07.06-.074.055-.069.065-.077.054-.066.066-.077.053-.06.072-.082.053-.06.067-.074.054-.058.073-.078.058-.06.063-.067.168-.17.1-.098.059-.056.076-.071a12.084 12.084 0 012.272-1.677zM12.017 0h.097l.082.001.069.001.054.002.068.002.046.001.076.003.047.002.06.003.054.002.087.005.105.007.144.011.088.007.044.004.077.008.082.008.047.005.102.012.05.006.108.014.081.01.042.006.065.01.207.032.07.012.065.011.14.026.092.018.11.022.046.01.075.016.041.01L14.7.3l.042.01.065.015.049.012.071.017.096.024.112.03.113.03.113.032.05.015.07.02.078.024.073.023.05.016.05.016.076.025.099.033.102.036.048.017.064.023.093.034.11.041.116.045.1.04.047.02.06.024.041.018.063.026.04.018.057.025.11.048.1.046.074.035.075.036.06.028.092.046.091.045.102.052.053.028.049.026.046.024.06.033.041.022.052.029.088.05.106.06.087.051.057.034.053.032.096.059.088.055.098.062.036.024.064.041.084.056.04.027.062.042.062.043.023.017c.054.037.108.075.161.114l.083.06.065.048.056.043.086.065.082.064.04.03.05.041.086.069.079.065.085.071c.712.6 1.353 1.283 1.909 2.031L7.222.994l.062-.027.065-.028.081-.034.086-.035c.113-.045.227-.09.341-.131l.096-.035.093-.033.084-.03.096-.031c.087-.03.176-.058.264-.085l.091-.027.086-.025.102-.03.085-.023.1-.026L9.04.37l.09-.023.091-.022.095-.022.09-.02.098-.021.091-.02.095-.018.092-.018.1-.018.091-.016.098-.017.092-.014.097-.015.092-.013.102-.013.091-.012.105-.012.09-.01.105-.01c.093-.01.186-.018.28-.024l.106-.008.09-.005.11-.006.093-.004.1-.004.097-.002.099-.002.197-.002z"></path></svg>`,
|
|
14
16
|
openai: `<svg class="logo" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></svg>`,
|
|
@@ -23,6 +25,9 @@ const MARK_FOR = {
|
|
|
23
25
|
openai_codex: "openai",
|
|
24
26
|
meta_muse: "meta",
|
|
25
27
|
opencode_go: "opencode",
|
|
28
|
+
github_copilot: "githubcopilot",
|
|
29
|
+
xai_grok: "grok",
|
|
30
|
+
vercel_token_pass: "vercel",
|
|
26
31
|
anthropic: "anthropic",
|
|
27
32
|
openai: "openai",
|
|
28
33
|
meta: "meta",
|
|
@@ -31,6 +36,8 @@ const MARK_FOR = {
|
|
|
31
36
|
google: "gemini",
|
|
32
37
|
openrouter: "openrouter",
|
|
33
38
|
"vercel-ai-gateway": "vercel",
|
|
39
|
+
"github-copilot": "githubcopilot",
|
|
40
|
+
"vercel-token-pass": "vercel",
|
|
34
41
|
};
|
|
35
42
|
/** The mark of a plan kind (`openai_codex`), key provider (`anthropic`), or gateway (`openrouter`); undefined when it has none. */
|
|
36
43
|
export function linkLogo(id) {
|
package/dist/link/budget.d.ts
CHANGED
|
@@ -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
|
|
37
|
-
export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], now: Date): LinkSpend[];
|
|
38
|
-
/**
|
|
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
|
-
|
|
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;
|
package/dist/link/budget.js
CHANGED
|
@@ -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
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
A grant may also limit each of its plans and API keys. A plan's limit is a
|
|
14
|
+
share of its own quota: while any plan-wide window the provider last
|
|
15
|
+
reported is at `maxPercent` used (by anyone, so the rest stays the user's),
|
|
16
|
+
the plan leaves the grant until that window resets. A plan with no reported
|
|
17
|
+
usage is never at its limit. An API key's limit is what the grant may spend
|
|
18
|
+
on it in a calendar month (UTC), as its provider charged; at the limit it
|
|
19
|
+
leaves the grant until the month ends. The grant serves on the rest. */
|
|
18
20
|
/** 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
|
|
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
|
|
76
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
90
|
-
|
|
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) => ({
|
|
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. */
|
package/dist/link/endpoints.js
CHANGED
|
@@ -59,12 +59,12 @@ import { isReasoningEffort, providerForModel } from "@mupt-ai/dari-router/policy
|
|
|
59
59
|
import { bearerToken } from "../http/auth.js";
|
|
60
60
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
61
61
|
import { SUBSCRIPTION_PLAN_LABELS } from "./errors.js";
|
|
62
|
-
import {
|
|
62
|
+
import { modelSubscriptions, subscriptionClient } from "../models/subscriptions.js";
|
|
63
63
|
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,
|
|
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
|
}
|
|
@@ -872,8 +872,10 @@ async function grantBody(platform, request, accessToken, detail) {
|
|
|
872
872
|
utilization: window.utilization,
|
|
873
873
|
resets_at: window.resetsAt,
|
|
874
874
|
})),
|
|
875
|
+
// A key's provider's models; a plan's are the ones it has an offering
|
|
876
|
+
// of, whoever makes them (every OpenCode Go model is another maker's).
|
|
875
877
|
models: models(served.get(client))
|
|
876
|
-
.filter((model) =>
|
|
878
|
+
.filter((model) => keyFor === undefined ? modelSubscriptions(model).includes(kind) : providerForModel(model) === keyFor)
|
|
877
879
|
.map(namedModel),
|
|
878
880
|
};
|
|
879
881
|
}),
|
|
@@ -1223,30 +1225,33 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
|
|
|
1223
1225
|
</div>`);
|
|
1224
1226
|
}
|
|
1225
1227
|
function connectionCard(connection, csrf) {
|
|
1226
|
-
const
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
};
|
|
1233
|
-
// The most the grant may spend on each plan or key a month.
|
|
1234
|
-
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) => {
|
|
1235
1234
|
const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
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>`;
|
|
1240
1245
|
};
|
|
1246
|
+
const limited = connection.spend.some((entry) => entry.monthlyUsd !== null || entry.maxPercent !== null);
|
|
1241
1247
|
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1242
1248
|
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1243
1249
|
<strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
|
|
1244
|
-
<small>
|
|
1245
|
-
|
|
1246
|
-
${
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
<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>
|
|
1250
1255
|
</form>`;
|
|
1251
1256
|
}
|
|
1252
1257
|
async function connectionsSubmit(approval, request, form) {
|
|
@@ -1269,23 +1274,18 @@ async function connectionsSubmit(approval, request, form) {
|
|
|
1269
1274
|
await approval.disconnect(session.subject, grantId);
|
|
1270
1275
|
return back;
|
|
1271
1276
|
}
|
|
1272
|
-
if (decision === "
|
|
1273
|
-
const entries = [300, 10080].flatMap((minutes) => {
|
|
1274
|
-
const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
|
|
1275
|
-
return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
|
|
1276
|
-
});
|
|
1277
|
-
const budget = validBudget(entries);
|
|
1278
|
-
if (budget === null)
|
|
1279
|
-
return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1277
|
+
if (decision === "limits") {
|
|
1280
1278
|
const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
|
|
1281
|
-
const value = raw.replace(/[\s
|
|
1282
|
-
|
|
1279
|
+
const value = raw.replace(/[\s,$%]/g, "");
|
|
1280
|
+
const kind = field.slice(0, 4);
|
|
1281
|
+
if ((kind !== "usd_" && kind !== "pct_") || value === "")
|
|
1283
1282
|
return [];
|
|
1284
|
-
|
|
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 }];
|
|
1285
1285
|
}));
|
|
1286
|
-
if (limits === null)
|
|
1287
|
-
return await connectionsPage(approval, request, "Each
|
|
1288
|
-
|
|
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
|
+
}
|
|
1289
1289
|
await approval.setLimits(session.subject, grantId, limits);
|
|
1290
1290
|
return back;
|
|
1291
1291
|
}
|
|
@@ -1315,9 +1315,6 @@ function planName(subscription) {
|
|
|
1315
1315
|
? `${subscription.name} API Key`
|
|
1316
1316
|
: KINDS[subscription.provider]?.name ?? subscription.name;
|
|
1317
1317
|
}
|
|
1318
|
-
function count(value) {
|
|
1319
|
-
return value.toLocaleString("en-US");
|
|
1320
|
-
}
|
|
1321
1318
|
// Back to the approval page by GET, so no form is left to resubmit.
|
|
1322
1319
|
function seeAuthorize(authorize, cookies) {
|
|
1323
1320
|
const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
|
|
@@ -1510,12 +1507,16 @@ function eventFor(authorize, step) {
|
|
|
1510
1507
|
origin: new URL(authorize.redirectUri).origin,
|
|
1511
1508
|
};
|
|
1512
1509
|
}
|
|
1513
|
-
// How a kind of plan reads on the page, and whose sign-in connects it.
|
|
1510
|
+
// How a kind of plan reads on the page, and whose sign-in connects it. A
|
|
1511
|
+
// `pastedKey` plan connects with a key the user creates there instead.
|
|
1514
1512
|
const KINDS = {
|
|
1515
1513
|
anthropic_claude_code: { name: "Claude", plan: "Pro, Max or Ultra plan", at: "Claude" },
|
|
1516
1514
|
openai_codex: { name: "ChatGPT", plan: "Plus or Pro plan", at: "OpenAI" },
|
|
1517
1515
|
meta_muse: { name: "Meta Muse", plan: "Muse Code plan", at: "Meta" },
|
|
1518
1516
|
opencode_go: { name: "OpenCode Go", plan: "Go plan", at: "OpenCode" },
|
|
1517
|
+
github_copilot: { name: "GitHub Copilot", plan: "Copilot plan", at: "GitHub" },
|
|
1518
|
+
xai_grok: { name: "Grok", plan: "SuperGrok plan", at: "xAI" },
|
|
1519
|
+
vercel_token_pass: { name: "Vercel Token Pass", plan: "Token Pass", at: "Vercel", pastedKey: true },
|
|
1519
1520
|
};
|
|
1520
1521
|
// The first page a new user sees: what connecting means, and one button.
|
|
1521
1522
|
function introPage(approval, authorize) {
|
|
@@ -1574,10 +1575,24 @@ function keyPage(authorize, provider, error, cookies = []) {
|
|
|
1574
1575
|
footer: `<button class="btn primary" type="submit" name="decision" value="add_key">Continue</button>`,
|
|
1575
1576
|
});
|
|
1576
1577
|
}
|
|
1577
|
-
// The provider's sign-in: a link to it, and the code to bring back or take
|
|
1578
|
+
// The provider's sign-in: a link to it, and the code to bring back or take
|
|
1579
|
+
// there; or, for a plan that is a key, where to create the key to paste back.
|
|
1578
1580
|
function providerPage(authorize, connect, error) {
|
|
1579
|
-
const { name, at } = KINDS[connect.kind];
|
|
1580
|
-
const open = (style) => `<a class="btn ${style}" href="${escapeHtml(connect.url)}" target="_blank" rel="noopener noreferrer">Open ${name}${ICONS.external}</a>`;
|
|
1581
|
+
const { name, at, pastedKey } = KINDS[connect.kind];
|
|
1582
|
+
const open = (style) => `<a class="btn ${style}" href="${escapeHtml(connect.url)}" target="_blank" rel="noopener noreferrer">Open ${pastedKey ? at : name}${ICONS.external}</a>`;
|
|
1583
|
+
if (pastedKey) {
|
|
1584
|
+
return pane(authorize, {
|
|
1585
|
+
title: `Add Your ${name} Key`,
|
|
1586
|
+
step: "connect_subscription",
|
|
1587
|
+
back: "select",
|
|
1588
|
+
error,
|
|
1589
|
+
body: `<span class="who">${logo(connect.kind, name)}</span>
|
|
1590
|
+
<h1>Add Your ${name} Key</h1>
|
|
1591
|
+
<div class="step"><span class="n">1</span><div><p>Create a ${name} key at ${at}.</p>${open("outline")}</div></div>
|
|
1592
|
+
<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>`,
|
|
1593
|
+
footer: `<button class="btn primary" type="submit" name="decision" value="complete">Continue</button>`,
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1581
1596
|
const head = `<span class="who">${logo(connect.kind, name)}</span>
|
|
1582
1597
|
<h1>Sign In To ${name}</h1>`;
|
|
1583
1598
|
if (connect.userCode === null) {
|
|
@@ -1791,13 +1806,17 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
|
|
|
1791
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}
|
|
1792
1807
|
.actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
|
|
1793
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}
|
|
1794
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}
|
|
1795
1814
|
.row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
|
|
1796
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}
|
|
1797
1816
|
.nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
|
|
1798
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}
|
|
1799
1818
|
a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
|
|
1800
|
-
[role=alert]{margin:16px 0
|
|
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}
|
|
1801
1820
|
::selection{background:var(--mint);color:var(--page)}`;
|
|
1802
1821
|
function escapeHtml(value) {
|
|
1803
1822
|
return value
|
package/dist/link/errors.js
CHANGED
|
@@ -38,6 +38,9 @@ export const SUBSCRIPTION_PLAN_LABELS = {
|
|
|
38
38
|
openai_codex: "ChatGPT Plus/Pro",
|
|
39
39
|
meta_muse: "Meta Muse",
|
|
40
40
|
opencode_go: "OpenCode Go",
|
|
41
|
+
github_copilot: "GitHub Copilot",
|
|
42
|
+
xai_grok: "Grok",
|
|
43
|
+
vercel_token_pass: "Vercel Token Pass",
|
|
41
44
|
};
|
|
42
45
|
const ONLY_CLIENT = {
|
|
43
46
|
anthropic_claude_code: "Claude Code itself",
|
|
@@ -80,7 +83,7 @@ export function budgetExhausted(resetsAt) {
|
|
|
80
83
|
export function limitsReached(resetsAt) {
|
|
81
84
|
return {
|
|
82
85
|
code: "grant_budget_exhausted",
|
|
83
|
-
message: `Every plan and API key of this Dari Link grant is at the
|
|
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()}.`,
|
|
84
87
|
resets_at: resetsAt.toISOString(),
|
|
85
88
|
};
|
|
86
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;
|
package/dist/link/self_hosted.js
CHANGED
|
@@ -5,7 +5,7 @@ import { randomBytes, randomUUID } from "node:crypto";
|
|
|
5
5
|
import { HttpError } from "../http/errors.js";
|
|
6
6
|
import { checkProviderKey } from "../providers/key_check.js";
|
|
7
7
|
import { gatewayKeyIndex } from "../self_host/resolve.js";
|
|
8
|
-
import { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, currentUsage, startOAuth, } from "../self_host/subscriptions/index.js";
|
|
8
|
+
import { CODEX_APPROVAL_PENDING, GITHUB_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, currentUsage, startOAuth, } from "../self_host/subscriptions/index.js";
|
|
9
9
|
import { linkCompleteThrough } from "./in_flight.js";
|
|
10
10
|
import { LINK_KEY_PROVIDERS, linkKeyProviderName } from "./key_providers.js";
|
|
11
11
|
import { linkPlatform } from "./service.js";
|
|
@@ -113,7 +113,13 @@ export function selfHostedLink(deps) {
|
|
|
113
113
|
}
|
|
114
114
|
catch (error) {
|
|
115
115
|
if (error instanceof SubscriptionOAuthInputError) {
|
|
116
|
-
if ([
|
|
116
|
+
if ([
|
|
117
|
+
CODEX_APPROVAL_PENDING,
|
|
118
|
+
META_APPROVAL_PENDING,
|
|
119
|
+
OPENCODE_APPROVAL_PENDING,
|
|
120
|
+
GITHUB_APPROVAL_PENDING,
|
|
121
|
+
XAI_APPROVAL_PENDING,
|
|
122
|
+
].includes(error.message))
|
|
117
123
|
return null;
|
|
118
124
|
throw new HttpError(400, error.message, "invalid_request");
|
|
119
125
|
}
|
|
@@ -148,7 +154,7 @@ function linkKey(key) {
|
|
|
148
154
|
usage: [],
|
|
149
155
|
};
|
|
150
156
|
}
|
|
151
|
-
function linkSubscription(credential) {
|
|
157
|
+
export function linkSubscription(credential) {
|
|
152
158
|
const now = new Date();
|
|
153
159
|
return {
|
|
154
160
|
id: credential.id,
|
|
@@ -159,11 +165,21 @@ function linkSubscription(credential) {
|
|
|
159
165
|
unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
|
|
160
166
|
? credential.unavailableUntil.toISOString()
|
|
161
167
|
: null,
|
|
162
|
-
usage: (currentUsage(credential, now)
|
|
163
|
-
...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
|
|
164
|
-
minutes: window.minutes,
|
|
165
|
-
utilization: window.utilization,
|
|
166
|
-
resetsAt: window.resetsAt.toISOString(),
|
|
167
|
-
})),
|
|
168
|
+
usage: linkUsageWindows(currentUsage(credential, now), now),
|
|
168
169
|
};
|
|
169
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
|
+
}
|