@mupt-ai/dari-gateway 1.0.311 → 1.0.313
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 +279 -2
- package/dist/context/provider_prompt_accounting.js +7 -0
- package/dist/context/routing_context.js +4 -1
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +12 -2
- package/dist/ingress/anthropic_messages.js +15 -3
- package/dist/ingress/chat_completions.js +6 -1
- package/dist/ingress/codex.js +2 -2
- package/dist/ingress/link.d.ts +24 -0
- package/dist/ingress/link.js +1519 -0
- package/dist/ingress/link_assets.d.ts +14 -0
- package/dist/ingress/link_assets.js +49 -0
- package/dist/ingress/link_font.d.ts +1 -0
- package/dist/ingress/link_font.js +6 -0
- package/dist/ingress/models.js +46 -2
- package/dist/interaction/types.d.ts +1 -0
- package/dist/link_client.d.ts +386 -0
- package/dist/link_client.js +579 -0
- package/dist/models/gateways.d.ts +2 -0
- package/dist/models/gateways.js +2 -0
- package/dist/models/link_errors.d.ts +30 -0
- package/dist/models/link_errors.js +120 -0
- package/dist/models/subscriptions.d.ts +8 -1
- package/dist/models/subscriptions.js +13 -2
- package/dist/platform/platform.d.ts +303 -1
- package/dist/protocol/input/router_model.d.ts +4 -0
- package/dist/protocol/input/router_model.js +31 -1
- package/dist/providers/execution.js +31 -5
- package/dist/providers/pi_options.js +57 -1
- package/dist/providers/provider_call.d.ts +4 -0
- package/dist/providers/provider_call.js +9 -2
- package/dist/providers/response_capture.d.ts +4 -1
- package/dist/providers/response_capture.js +81 -2
- package/dist/providers/stream_finalization.d.ts +1 -0
- package/dist/providers/subscription_limits.d.ts +15 -0
- package/dist/providers/subscription_limits.js +45 -0
- package/dist/runtime/explicit_model.js +16 -4
- package/dist/runtime/harness_identity/extract.js +20 -36
- package/dist/runtime/link_budget.d.ts +27 -0
- package/dist/runtime/link_budget.js +62 -0
- package/dist/runtime/link_grant_access.d.ts +7 -0
- package/dist/runtime/link_grant_access.js +99 -0
- package/dist/runtime/link_in_flight.d.ts +4 -0
- package/dist/runtime/link_in_flight.js +43 -0
- package/dist/runtime/prepare_routed_completion.js +5 -1
- package/dist/runtime/routed_runtime.js +8 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/config.d.ts +9 -0
- package/dist/self_host/config.js +11 -1
- package/dist/self_host/link_store.d.ts +167 -0
- package/dist/self_host/link_store.js +564 -0
- package/dist/self_host/main.d.ts +10 -3
- package/dist/self_host/main.js +19 -4
- package/dist/self_host/platform.d.ts +2 -2
- package/dist/self_host/platform.js +284 -10
- package/dist/self_host/resolve.d.ts +8 -0
- package/dist/self_host/resolve.js +146 -15
- package/dist/self_host/secret_box.d.ts +23 -0
- package/dist/self_host/secret_box.js +105 -0
- package/dist/self_host/stub_gateway.d.ts +60 -0
- package/dist/self_host/stub_gateway.js +397 -0
- package/dist/self_host/stub_main.d.ts +2 -0
- package/dist/self_host/stub_main.js +69 -0
- package/dist/self_host/subscription_test_gateway.d.ts +12 -9
- package/dist/self_host/subscription_test_gateway.js +25 -91
- package/dist/self_host/subscriptions/access.d.ts +5 -0
- package/dist/self_host/subscriptions/access.js +5 -1
- package/dist/self_host/subscriptions/http.js +8 -1
- package/dist/self_host/subscriptions/index.d.ts +5 -2
- package/dist/self_host/subscriptions/index.js +5 -2
- package/dist/self_host/subscriptions/store.d.ts +41 -16
- package/dist/self_host/subscriptions/store.js +136 -32
- package/dist/self_host/subscriptions/usage.d.ts +7 -0
- package/dist/self_host/subscriptions/usage.js +52 -0
- package/dist/telemetry/report.js +18 -0
- package/dist/types.d.ts +18 -0
- package/package.json +4 -3
- package/src/context/provider_prompt_accounting.ts +7 -0
- package/src/context/routing_context.ts +3 -1
- package/src/http/handler.ts +14 -2
- package/src/ingress/anthropic_messages.ts +19 -4
- package/src/ingress/chat_completions.ts +6 -1
- package/src/ingress/codex.ts +2 -2
- package/src/ingress/link.ts +1731 -0
- package/src/ingress/link_assets.ts +56 -0
- package/src/ingress/link_font.ts +9 -0
- package/src/ingress/models.ts +48 -2
- package/src/interaction/types.ts +4 -0
- package/src/link_client.ts +796 -0
- package/src/models/gateways.ts +3 -0
- package/src/models/link_errors.ts +157 -0
- package/src/models/subscriptions.ts +15 -1
- package/src/platform/platform.ts +330 -1
- package/src/protocol/input/router_model.ts +36 -1
- package/src/providers/execution.ts +31 -4
- package/src/providers/pi_options.ts +57 -1
- package/src/providers/provider_call.ts +20 -2
- package/src/providers/response_capture.ts +88 -2
- package/src/providers/stream_finalization.ts +1 -0
- package/src/providers/subscription_limits.ts +53 -0
- package/src/runtime/explicit_model.ts +21 -8
- package/src/runtime/harness_identity/extract.ts +21 -60
- package/src/runtime/link_budget.ts +75 -0
- package/src/runtime/link_grant_access.ts +116 -0
- package/src/runtime/link_in_flight.ts +46 -0
- package/src/runtime/prepare_routed_completion.ts +6 -1
- package/src/runtime/routed_runtime.ts +8 -0
- package/src/runtime/runtime_reporter.ts +3 -0
- package/src/self_host/config.ts +24 -1
- package/src/self_host/link_store.ts +782 -0
- package/src/self_host/main.ts +21 -4
- package/src/self_host/platform.ts +305 -11
- package/src/self_host/resolve.ts +172 -15
- package/src/self_host/secret_box.ts +112 -0
- package/src/self_host/stub_gateway.ts +497 -0
- package/src/self_host/stub_main.ts +72 -0
- package/src/self_host/subscription_test_gateway.ts +26 -95
- package/src/self_host/subscriptions/access.ts +10 -1
- package/src/self_host/subscriptions/http.ts +9 -1
- package/src/self_host/subscriptions/index.ts +6 -0
- package/src/self_host/subscriptions/store.ts +167 -36
- package/src/self_host/subscriptions/usage.ts +64 -0
- package/src/telemetry/report.ts +17 -1
- package/src/types.ts +26 -0
- package/dist/self_host/subscriptions/test_support.d.ts +0 -15
- package/dist/self_host/subscriptions/test_support.js +0 -34
package/README.md
CHANGED
|
@@ -63,7 +63,9 @@ docker run -p 8080:8080 \
|
|
|
63
63
|
| --- | --- |
|
|
64
64
|
| `DARI_GATEWAY_KEYS` | Required. Comma-separated bearer keys clients authenticate with. |
|
|
65
65
|
| `DARI_GATEWAY_CONFIG` | Router config file. Default `dari-gateway.yaml`. |
|
|
66
|
-
| `DARI_GATEWAY_DB` | SQLite database for subscriptions, model lists saved with `dari gateway models`, and conversation state. Default `dari-gateway.db`.
|
|
66
|
+
| `DARI_GATEWAY_DB` | SQLite database for subscriptions, Dari Link grants, model lists saved with `dari gateway models`, and conversation state. Default `dari-gateway.db`. Without `DARI_GATEWAY_ENCRYPTION_KEY` it stores subscription tokens in plaintext; protect it like a secret either way. |
|
|
67
|
+
| `DARI_GATEWAY_ENCRYPTION_KEY` | Encrypts the subscription tokens, pending sign-ins, and API keys in the database: a 32-byte key in base64 (`openssl rand -base64 32`). Each value is sealed with AES-256-GCM and bound to its own row, so a copied database, or a token moved into another row, is useless without the key. Keep the key outside the database's storage and backups (a secret manager, not the same disk). To rotate, list the new key first and the old one after a comma, start the gateway once (it re-encrypts everything under the first), then drop the old one. Required for Dari Link: without it the approval page takes nobody's subscriptions or keys. Losing the key loses the stored subscriptions; users connect again. |
|
|
68
|
+
| `DARI_LINK_SESSION_SECRET` | Signs the cookie that remembers a Dari Link approval page's user. Unset, each gateway process makes its own, so a restart forgets who connected which plans. Set it on any gateway that serves Dari Link. |
|
|
67
69
|
| `DARI_AUTO_ROUTING_API_KEY` | Optional. Select among a router's models with Dari Auto Routing. |
|
|
68
70
|
| `PORT` | Listen port. Default `8080`. |
|
|
69
71
|
| `DARI_GATEWAY_HOST` | Listen address. Default `127.0.0.1`, so only this machine can connect. The container image sets `0.0.0.0`; set it yourself to expose a process on your network. |
|
|
@@ -116,9 +118,284 @@ dari claude
|
|
|
116
118
|
|
|
117
119
|
In gateway mode the CLI makes no calls to Dari's hosted API, and `dari activity` is unavailable.
|
|
118
120
|
|
|
121
|
+
## Dari Link
|
|
122
|
+
|
|
123
|
+
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.
|
|
124
|
+
|
|
125
|
+
**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 a ChatGPT or OpenCode Go plan, 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.
|
|
126
|
+
|
|
127
|
+
**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.
|
|
128
|
+
|
|
129
|
+
**Connect with Dari.** For the user it is one button. It opens Dari in a popup, where they connect a Claude or ChatGPT subscription by signing in to it (or already have), pick which plans the app may use, and approve; the popup closes and the app has a code. Nobody pastes a key, and nobody needs the CLI.
|
|
130
|
+
|
|
131
|
+
For a server app (a confidential client), the server makes the PKCE pair and state, so the verifier never reaches the browser and the page needs no Web Crypto:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
// On your server: start a connection and keep the verifier with the session.
|
|
135
|
+
import { createAuthorization } from "@mupt-ai/dari-gateway/link_client";
|
|
136
|
+
|
|
137
|
+
app.post("/api/dari/start", async (req, res) => {
|
|
138
|
+
const { codeVerifier, codeChallenge, state } = await createAuthorization();
|
|
139
|
+
req.session.dariLink = { codeVerifier, state };
|
|
140
|
+
res.json({ codeChallenge, state });
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
// In your app's bundle. The client uses only fetch (and Web Crypto when it makes PKCE itself).
|
|
146
|
+
import { DariLink } from "@mupt-ai/dari-gateway/link_client";
|
|
147
|
+
|
|
148
|
+
DariLink.renderButton(document.getElementById("connect-dari"), {
|
|
149
|
+
onClick: async () => {
|
|
150
|
+
// The settings come from your server after the popup opens; resolves with { code, state }.
|
|
151
|
+
const { code, state } = await DariLink.open(async () => ({
|
|
152
|
+
gatewayUrl: "https://routing.dari.dev",
|
|
153
|
+
clientId: "lnk_…",
|
|
154
|
+
redirectUri: "https://app.example.com/dari/callback",
|
|
155
|
+
...(await (await fetch("/api/dari/start", { method: "POST" })).json()),
|
|
156
|
+
onExit: ({ error, step }) => analytics.track("dari_link_exit", { error, step }),
|
|
157
|
+
}));
|
|
158
|
+
await fetch("/api/dari/exchange", {
|
|
159
|
+
method: "POST",
|
|
160
|
+
headers: { "content-type": "application/json" },
|
|
161
|
+
body: JSON.stringify({ code, state }),
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Your server checks `state`, redeems the code with the verifier it kept, and keeps the tokens with the user:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import { exchange, linkFetch } from "@mupt-ai/dari-gateway/link_client";
|
|
171
|
+
|
|
172
|
+
const client = { gatewayUrl: "https://routing.dari.dev", clientId, clientSecret };
|
|
173
|
+
const { codeVerifier, state: expected } = req.session.dariLink;
|
|
174
|
+
if (req.body.state !== expected) throw new Error("state mismatch");
|
|
175
|
+
await db.save(user, await exchange({ ...client, redirectUri, code: req.body.code, codeVerifier }));
|
|
176
|
+
|
|
177
|
+
const dari = linkFetch({ ...client, loadTokens: () => db.load(user), saveTokens: (next) => db.save(user, next) });
|
|
178
|
+
await dari("/v1/chat/completions", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "dari/routing", messages }) });
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
- A browser-only app (a public client) leaves out `codeChallenge` and `state`: `DariLink.open` makes the PKCE pair in the page and resolves with `{ code, state, codeVerifier }` (`codeVerifier` is null when the server made it). That needs a secure page (https, or localhost); elsewhere it rejects with `insecure_context` before opening anything.
|
|
182
|
+
- Get `clientId` (and a server's `clientSecret`) by registering the app: on hosted Dari under **Settings → Dari Link Apps**, or with the API or CLI in step 1 below.
|
|
183
|
+
- Call `DariLink.open` from the click handler, so the browser allows the popup. It opens the popup before awaiting anything, so its options may be a function returning a promise (`DariLink.open(async () => ({ ...await fetchConfig() }))`), fetched after the popup is open; Safari blocks a popup opened after an `await`. It rejects with a `LinkError`: `access_denied` when the user denies, `popup_closed`, or `popup_blocked`.
|
|
184
|
+
- `onEvent(step)` hears each step the user reaches in the popup (`sign_in`, `connect_subscription` when they have no plan to share yet, `choose_plans`), and `onExit({ error, step })` says where they left before it rejects (`step` is `denied` when they denied, null when they reached none), so you can tell "closed at sign-in" from "closed after seeing the plans". The popup posts each step as `{"type": "dari-link-event", "version": "1", "event": "<step>", "state"}` to your redirect URI's origin; only the result is `{"type": "dari-link", ...}`, with `code` or `error`. A client reading the messages itself should ignore any other type, and any `dari-link` message with neither `code` nor `error`.
|
|
185
|
+
- The popup posts its result to your window with `response_mode=web_message`, readable only by your redirect URI's origin; `DariLink.open` accepts it only from the popup, from the origin the gateway's metadata names (`web_message_origin`), and with the state it made.
|
|
186
|
+
- Put `DariLink.callback()` on your redirect URI's page. A popup that signed the user in along the way can lose its link to your window; the approval then arrives on that page inside the popup, and `callback()` hands it to the window that opened it and closes the popup. A page whose CSP keeps it from bundling the client can load `<script src="<gateway>/v1/link/callback.js"></script>` (the metadata's `callback_script`) instead. The contract is stable: on the `BroadcastChannel` named `dari-link`, the page posts `{"type": "dari-link", "state", "code"}` or `{"type": "dari-link", "state", "error", "error_description"}`, then closes.
|
|
187
|
+
- Users see and disconnect the apps they connected under **Subscriptions & Keys → Connected Apps** on hosted Dari. Link there with the grant's `manage_url` (that app's row, highlighted) or the metadata's `connected_apps_uri` (the section); both are null on a self-hosted gateway, which has no such page.
|
|
188
|
+
- **Update mode.** To let the user change which plans an app has, open the same flow with `grantId` (`grant_id=<lgr_…>` on the authorize request): the page is titled "Update Plans For <App>", starts with the grant's plans and budget, and saves to the same grant. Its id and every token it issued keep working; the new code redeems for more tokens of it, which you may keep or drop. A `grant_id` that is not this browser's user's grant for this app (another browser, cleared cookies) starts a new connection instead, and leaves that grant as it was.
|
|
189
|
+
- One grant may back several records in your app (one per plan, say) only with a confidential client: a public client's refresh token rotates on every use, so two records holding it race.
|
|
190
|
+
|
|
191
|
+
**Flow** (OAuth 2.0 authorization code with PKCE S256; `GET /.well-known/oauth-authorization-server` lists the endpoints):
|
|
192
|
+
|
|
193
|
+
1. Register once.
|
|
194
|
+
- A browser, desktop, or CLI app is a public client: `POST /v1/link/register` with `{"client_name", "redirect_uris"}` (RFC 7591; no key; https URIs or http on localhost; 20 registrations a minute per gateway) returns `{"client_id", ...}`. A self-hosted gateway also allows http on the private dev hosts its config lists under `link.allowHttpRedirectHosts` (exact names, or `*.example.ts.net` for any subdomain); by default there are none.
|
|
195
|
+
- On hosted Dari, an organization owner or admin can register either kind under **Settings → Dari Link Apps** instead.
|
|
196
|
+
- A server is a confidential client: the same `POST /v1/link/register` with `"token_endpoint_auth_method": "client_secret_basic"`, or `POST /v1/link/apps` with your key and `"confidential": true` (hosted Dari: **Settings → Dari Link Apps**), also returns a `client_secret` (`dlk_cs_…`), shown once. The app sends it with HTTP Basic (`client_id:client_secret`) on every `/v1/link/token` and `/v1/link/revoke` call. Registering hands out no access: the user still approves every grant.
|
|
197
|
+
2. Send the user to `GET /v1/link/authorize?response_type=code&client_id=…&redirect_uri=…&state=…&code_challenge=…&code_challenge_method=S256`. Optional parameters:
|
|
198
|
+
- `scope=route`, the only scope.
|
|
199
|
+
- `client`: the clients the app runs, space-separated, such as `client=claude_code codex`. Naming `claude_code` or `muse_code` lets the user grant plans that serve only that client.
|
|
200
|
+
- `plans`: the plan kinds to offer, such as `plans=openai_codex`; the page lists only those.
|
|
201
|
+
- `purpose_any_app`, `purpose_claude_code`, `purpose_muse_code`: up to 200 characters each, shown beside the plans of that audience as what the app says it does with them.
|
|
202
|
+
- `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.
|
|
203
|
+
- `grant_id`: update mode (above).
|
|
204
|
+
|
|
205
|
+
On hosted Dari the gateway checks the request and sends the user to Dari's own consent page, where they are signed in to their Dari account (Google or an emailed link; a new user gets an account). It shows the app's name, the host it returns to, and who is signed in; the plans the app can use start ticked, and the user can connect another subscription right there. It never asks for a key.
|
|
206
|
+
|
|
207
|
+
The self-hosted gateway serves the page itself, and it needs no account, like a bank link. 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. The gateway remembers them in a signed HttpOnly cookie, so the next app that asks finds their plans connected and takes one click. The 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.
|
|
208
|
+
|
|
209
|
+
Either way 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.
|
|
210
|
+
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:
|
|
211
|
+
- Every access token lives until its own expiry, so requests in flight on an older one complete.
|
|
212
|
+
- A public client's refresh token rotates on every use. Presenting the rotated one again within a minute is refused as `invalid_grant` with `"error_code": "refresh_race"` and nothing is revoked: use the tokens the winning request received. Presenting it later revokes the grant.
|
|
213
|
+
- A confidential client's refresh token never rotates, so any number of instances can refresh one grant.
|
|
214
|
+
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:
|
|
215
|
+
- `dari/routing` chooses among the router's models that a granted plan serves.
|
|
216
|
+
- 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 and the grant holds another plan for the same provider is the request retried there, on the same model.
|
|
217
|
+
- `opus`, `sonnet`, `haiku`, and the other Anthropic tier names route, as `dari/routing` does.
|
|
218
|
+
- `POST /v1/messages/count_tokens` is not served: it answers an Anthropic-shaped 404, on which Claude Code estimates locally.
|
|
219
|
+
- 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.
|
|
220
|
+
5. The app ends its grant with `POST /v1/link/revoke` (RFC 7009: `client_id` and `token`, any of the grant's tokens; always 200). The user lists and revokes grants under **Subscriptions & Keys → Connected Apps** on hosted Dari, or with `GET` and `DELETE /v1/link/grants[/<id>]` (with their key), and changes a grant's budget there or with `PUT /v1/link/grants/<id>/budget`. A revoked grant's tokens, access tokens included, stop working at once.
|
|
221
|
+
|
|
222
|
+
**The grant.** The token response and `GET /v1/link/grant` (bearer: the access token) describe the grant:
|
|
223
|
+
|
|
224
|
+
```json
|
|
225
|
+
{
|
|
226
|
+
"grant_id": "lgr_…", "client_id": "lnk_…", "app_name": "Notes", "created_at": "…", "scope": "route",
|
|
227
|
+
"budget": [{"window_minutes": 10080, "max_tokens": 5000000, "used_tokens": 312000, "resets_at": null}],
|
|
228
|
+
"state": "ready", "available_at": null,
|
|
229
|
+
"user": {"email": "you@example.com", "name": "You"},
|
|
230
|
+
"manage_url": "https://app.dari.dev/connected-apps&grant=lgr_…",
|
|
231
|
+
"plans": [{
|
|
232
|
+
"id": "…", "kind": "openai_codex", "plan": "ChatGPT Plus/Pro", "label": "a@example.com", "account_email": "a@example.com",
|
|
233
|
+
"serves": "any_app", "state": "ready", "available_at": null, "unavailable_until": null,
|
|
234
|
+
"usage": [{"window_minutes": 300, "utilization": 0.42, "resets_at": "…"}, {"window_minutes": 10080, "utilization": 0.1, "resets_at": "…"}],
|
|
235
|
+
"models": [{"id": "dari/model/openai/gpt-5.5", "name": "GPT-5.5"}, {"id": "dari/model/openai/gpt-6.1-sol", "name": "GPT-6.1 Sol"}]
|
|
236
|
+
}],
|
|
237
|
+
"models": [{"id": "dari/model/openai/gpt-5.5", "name": "GPT-5.5"}, {"id": "dari/model/openai/gpt-6.1-sol", "name": "GPT-6.1 Sol"}],
|
|
238
|
+
"routes": true
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`serves` is `any_app`, `claude_code_only`, or `muse_code_only`. A plan's `state` is the one answer to "can this plan serve the app now": `ready`, or `plan_limit`, the plan is at its own usage limit; `available_at` is when it serves again (null when ready or unknown). The grant's own `state` is `budget_limit` while a window of its budget is at its cap, until `available_at` (see **Budgets**). `user` is the Dari account that approved the grant (null on a self-hosted gateway, which has no accounts), so an app can show "Dari · you@example.com" even when the plans belong to other accounts. `label` is the user's name for the plan, else its account. `usage` lists the quota windows the plan last reported (five hours and a week for these plans), each with the share used from 0 to 1 and when it resets; it is empty until the plan has served a request through Dari (any request, not only this app's, including the user's own Claude Code or Codex through Dari), because plans report their windows only on responses. Dari does not read a fresh plan's windows when it connects: that takes a call to the provider with the user's credential that neither Claude nor ChatGPT documents for third parties, so a just-connected plan shows no usage until its first request. A plan's `models` are those it serves its clients now, each with the name a request uses (`id`) and the catalog's display name (`name`); the top-level `models` are what a plain API client can name now, and `routes` says whether `dari/routing` serves it. `GET /v1/models` with a link token lists the same models in the OpenAI list shape, empty when none can serve. `GET /v1/link/grant` makes no provider call, so it is the cheap check before a long run: a dead grant answers 401, and `unavailable_until` and `usage` say whether the plans have room.
|
|
243
|
+
|
|
244
|
+
**Budgets.** A user can cap the tokens an app may use per five hours and per week: on hosted Dari's Connected Apps page, or with `PUT /v1/link/grants/<id>/budget` and `{"budget": [{"window_minutes": 10080, "max_tokens": 5000000}]}` (the user's key; `window_minutes` is `300` or `10080`; `[]` removes it). The budget covers the whole grant: all its plans and API keys together.
|
|
245
|
+
|
|
246
|
+
Tokens are what Dari recorded for the grant's requests, child tokens' included: input + output + cache read + cache write, the same total `GET /v1/link/usage` and the Connected Apps page show. Windows roll: a window's `used_tokens` are those of requests received in its last `window_minutes`. Before each request, a grant with any window at its cap is refused with 424 `grant_budget_exhausted`, with `resets_at` (and `Retry-After`) set to when enough of the window's oldest requests roll off to bring it under the cap; a budget window's `resets_at` is that same time, and null while under the cap. A request is counted once it finishes, so requests in flight may take a window past its cap.
|
|
247
|
+
|
|
248
|
+
**Usage.** Every request a grant's tokens make, child tokens' included, streamed or not, is recorded once it finishes (a moment after the response). `GET /v1/link/usage` (bearer: the access token; CORS open) reads it back:
|
|
249
|
+
|
|
250
|
+
- `tag=<key>=<value>`, repeatable: only requests carrying every given tag, from `X-Dari-Tags` or the child token's `tags`;
|
|
251
|
+
- `since`, `until`: ISO 8601 times bounding when a request was received (`since` inclusive, `until` exclusive);
|
|
252
|
+
- `group_by=tag:<key>`: also total per value of that tag, in `by_tag` (`value` null for requests without it).
|
|
253
|
+
|
|
254
|
+
Every response to a link token carries `X-Request-Id`. `GET /v1/link/usage/requests/<id>` (same bearer) answers that one request's usage in the same shape once it is recorded, and 404 until then.
|
|
255
|
+
|
|
256
|
+
```json
|
|
257
|
+
{
|
|
258
|
+
"requests": 7, "errors": 1, "input_tokens": 70, "output_tokens": 14, "cache_read_tokens": 28, "cache_write_tokens": 2,
|
|
259
|
+
"complete_through": "2026-11-14T07:00:00.000Z",
|
|
260
|
+
"by_model": [{"model": "openai/gpt-5.5", "thinking": "high", "requests": 4, "errors": 0, "input_tokens": 40, "output_tokens": 8, "cache_read_tokens": 16, "cache_write_tokens": 0}],
|
|
261
|
+
"by_tag": [{"value": "7", "requests": 3, "errors": 0, "input_tokens": 30, "output_tokens": 6, "cache_read_tokens": 12, "cache_write_tokens": 0}]
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`errors` counts the requests the provider or Dari failed (they count in `requests` too); a request the client aborted is not an error. `complete_through` says how far the counts are complete: every request received before it has been recorded. On the self-hosted gateway, which serves and records every request itself, it is the time the oldest request still being served was received, or 30 seconds ago when none is (a request still resolving has not started being tracked). On hosted Dari it is `null`: requests are recorded from several instances after they finish, so no instance can say; read again until the counts stop changing.
|
|
266
|
+
|
|
267
|
+
Token counts mean the same for every protocol: `input_tokens` excludes cache reads and writes (an OpenAI response's cached tokens are moved out of its input count). `by_model` has one entry per model and thinking level served (`thinking` as `X-Dari-Thinking-Level` reported it), most requests first. A provider failure counts in `requests` and `errors`, with the tokens the provider reported, if any; a request refused before any provider call (such as a 424) is not counted. A child token cannot read usage (403 `permission_denied`). So a server that gives each trial a child token tagged `trial=<id>` gets that trial's cost with `?tag=trial=<id>`, with no relay in between.
|
|
268
|
+
|
|
269
|
+
**Child tokens.** A server that hands work to sandboxes or workers trades its access token for a child token (RFC 8693) instead of relaying their traffic: `POST /v1/link/token` with `grant_type=urn:ietf:params:oauth:grant-type:token-exchange`, `subject_token=<dlk_at_…>`, `subject_token_type=urn:ietf:params:oauth:token-type:access_token`, and
|
|
270
|
+
|
|
271
|
+
- `model` (required, repeatable up to 16 times): the models the token serves, each named as a request may name it (`dari/model/openai/gpt-5.5`, `gpt-5.5`, a dated snapshot); each must be one the grant serves now, or the whole mint fails with `invalid_target`;
|
|
272
|
+
- `thinking`: the level requests for a model are served at, whatever the request asks for. Give it once to pin every model to it, or once per `model` in the same order, with `default` for a model left unpinned (`model=a&thinking=high&model=b&thinking=default`). A level a model does not offer fails with `invalid_target`;
|
|
273
|
+
- `expires_in`: 60 to 43200 seconds (default 3600), so it can outlive the access token that minted it;
|
|
274
|
+
- `tags`: labels for its requests, like the `X-Dari-Tags` header (`run=r1,trial=7`).
|
|
275
|
+
|
|
276
|
+
It returns `{"access_token": "dlk_ct_…", "issued_token_type", "token_type": "Bearer", "expires_in", "grant_id", "models": [{"model", "thinking"}], "tags"}`, each `model` by its catalog name and `thinking` null when not pinned. A child token serves only those models on the gateway's ordinary endpoints, and `GET /v1/models` lists just them: any other model, and `dari/routing`, fail with `model_not_granted`. It cannot refresh, mint another token, or read `/v1/link/grant`, and it stops working when the grant is revoked.
|
|
277
|
+
|
|
278
|
+
A sandbox given a child token needs to reach only the gateway's host (for hosted Dari, `routing.dari.dev`) over HTTPS; it never talks to a provider, the approval page, or the app.
|
|
279
|
+
|
|
280
|
+
**Errors.** Token and revocation endpoints answer in the OAuth shape, `{"error", "error_description"}`; every other endpoint in the gateway's, `{"error": {"code", "message", ...}}`.
|
|
281
|
+
|
|
282
|
+
| Status | Code | Meaning | What to do |
|
|
283
|
+
| --- | --- | --- | --- |
|
|
284
|
+
| 400 | `invalid_grant` | The code or refresh token is used, expired, or revoked | Send the user through approval again |
|
|
285
|
+
| 400 | `invalid_grant` + `error_code: refresh_race` | Another request rotated this refresh token a moment ago | Use the tokens that request saved |
|
|
286
|
+
| 400 | `invalid_target` | The grant serves no model by the child token's `model` now, or the model lacks its `thinking` level | Mint for a model in the grant's `models`, at a level it offers |
|
|
287
|
+
| 400 | `invalid_request`, `unsupported_grant_type` | A missing or malformed parameter | Fix the request |
|
|
288
|
+
| 401 | `invalid_client` | Unknown client, or a missing or wrong client secret | Check the client id and secret |
|
|
289
|
+
| 401 | `link_token_expired` | The access or child token passed its expiry | Refresh (or mint a new child token) and retry |
|
|
290
|
+
| 401 | `grant_revoked` | The grant is gone; `revoked_by` is `user`, `app`, or `reuse_detected`, and `revoked_at` says when | Show the user Reconnect |
|
|
291
|
+
| 403 | `permission_denied` | A child token read the grant or its usage | Use the access token |
|
|
292
|
+
| 400 | `thinking_level_unavailable`, `unsupported_reasoning_effort` | The model does not offer the level the request names | Name a level the model supports |
|
|
293
|
+
| 424 | `grant_budget_exhausted` | The plans that serve this client are at the budget the user set for this app; `resets_at` and `Retry-After` say when the first is back, when known | Wait for the window, or ask the user to raise the budget |
|
|
294
|
+
| 424 | `subscription_exhausted` | The plans that serve this client are at their limits; `resets_at` and `Retry-After` say when the first is back, when known | Wait, or ask the user for another plan |
|
|
295
|
+
| 424 | `subscription_client_mismatch` | The granted plans serve only another client | Ask the user to grant a plan that serves any app |
|
|
296
|
+
| 424 | `model_not_granted` | The name is no catalog model, or no granted plan serves it, or any model the router lists | Name a model in the grant's `models` |
|
|
297
|
+
| 5xx | `link_request_failed` and others | The gateway failed; the message carries only a `request_id`, which its log line has with the cause | Retry, and report the request id |
|
|
298
|
+
|
|
299
|
+
Error text replaces anything shaped like an `sk-` key with `sk-…`, and responses replace the serving plan's own credential wherever it appears.
|
|
300
|
+
|
|
301
|
+
**Client.** `@mupt-ai/dari-gateway/link_client` (fetch and Web Crypto only; browsers, Node, Bun, Deno; erasable TypeScript only, so `node` runs the `.ts` file as is) has `DariLink` (`open`, `callback`, `renderButton`), `createAuthorization` (a PKCE pair and state for your server), `registerClient`, `authorizeUrl` (makes the PKCE verifier and state; takes `clients`, `plans`, `purposes`, and `grantId`), `exchange`, `refresh`, `childToken`, `revoke`, and `linkFetch`. Every call takes `clientSecret` for a confidential client. `linkFetch` is a fetch that treats your storage as the source of truth: it reads the tokens with your `loadTokens` on every call, attaches the access token, refreshes it before it expires or once after a 401 for an expired token with one refresh at a time, and passes every new token set to your `saveTokens` before using it. `childToken` takes the same `loadTokens` and `saveTokens` instead of an `accessToken`, refreshing the grant's access token as needed. When the user is unlinked:
|
|
302
|
+
|
|
303
|
+
- `loadTokens` returning null makes both throw `LinkError` `not_linked`, with no call to the gateway;
|
|
304
|
+
- a `LinkError` with code `invalid_grant` from a refresh means the grant is gone;
|
|
305
|
+
- a revoked grant's tokens, access tokens included, answer 401 `grant_revoked` at once, which `linkFetch` returns as it is, with no refresh attempted.
|
|
306
|
+
|
|
307
|
+
Each means: show the user Reconnect. `usage({ fetcher: gatewayFetch, tags, since, until, groupByTag })` reads the grant's usage through the `linkFetch` your app already has, sharing its refresh (or pass the client with `loadTokens` and `saveTokens` instead of `fetcher`). `childToken({ ..., models: [{ model, thinking? }] })` mints for several models at once, and `registerClient({ ..., confidential: true })` returns a `clientSecret` too.
|
|
308
|
+
|
|
309
|
+
A server-side integration, start to finish:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
import { authorizeUrl, childToken, exchange, linkFetch, revoke } from "@mupt-ai/dari-gateway/link_client";
|
|
313
|
+
|
|
314
|
+
// Registered once, under Settings → Dari Link Apps or with POST /v1/link/register.
|
|
315
|
+
const client = { gatewayUrl, clientId, clientSecret: process.env.DARI_LINK_CLIENT_SECRET };
|
|
316
|
+
|
|
317
|
+
// 1. Send the user to approve. Keep codeVerifier and state in their session.
|
|
318
|
+
const { url, codeVerifier, state } = await authorizeUrl({ ...client, redirectUri, plans: ["openai_codex"] });
|
|
319
|
+
|
|
320
|
+
// 2. On the redirect back, check state, redeem the code, and store the tokens.
|
|
321
|
+
await db.saveTokens(userId, await exchange({ ...client, redirectUri, code, codeVerifier }));
|
|
322
|
+
|
|
323
|
+
// 3. Call the gateway from any instance.
|
|
324
|
+
const gatewayFetch = linkFetch({
|
|
325
|
+
...client,
|
|
326
|
+
loadTokens: () => db.loadTokens(userId),
|
|
327
|
+
saveTokens: (tokens) => db.saveTokens(userId, tokens),
|
|
328
|
+
});
|
|
329
|
+
const grant = await (await gatewayFetch("/v1/link/grant")).json(); // the cheap check before a long run
|
|
330
|
+
|
|
331
|
+
// 4. Hand a sandbox one model for one trial; it calls the gateway itself.
|
|
332
|
+
const sandbox = await childToken({
|
|
333
|
+
...client,
|
|
334
|
+
loadTokens: () => db.loadTokens(userId),
|
|
335
|
+
saveTokens: (tokens) => db.saveTokens(userId, tokens),
|
|
336
|
+
models: [{ model: grant.models[0], thinking: "high" }],
|
|
337
|
+
expiresIn: 6 * 3600,
|
|
338
|
+
tags: { run, trial },
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
// 5. When the user disconnects in the app.
|
|
342
|
+
await revoke({ ...client, token: (await db.loadTokens(userId)).refreshToken });
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
**Forwarding proxy.** An app that fronts real Claude Code or Codex processes (agents it runs for the user) forwards their requests to the gateway as they are:
|
|
346
|
+
|
|
347
|
+
- pass the client's own headers through, dropping only hop-by-hop headers (`host`, `connection`, `content-length`, `transfer-encoding`, `keep-alive`, `upgrade`, `te`, `trailer`, `proxy-*`) and the client's own auth (`authorization`, `x-api-key`), and set `Authorization: Bearer dlk_…`;
|
|
348
|
+
- keep the model as the client named it: bare and dated ids are served as exactly that model;
|
|
349
|
+
- never add or change `user-agent`, `x-app`, or other client headers. A Claude Code plan serves only what really is Claude Code; anything else that sends Claude Code's headers is impersonating it;
|
|
350
|
+
- treat `invalid_grant`, `grant_revoked`, and `not_linked` as unlinked: stop the agent and show Reconnect.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
import { LinkError, linkFetch } from "@mupt-ai/dari-gateway/link_client";
|
|
354
|
+
|
|
355
|
+
const DROP = new Set(["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "te", "trailer", "authorization", "x-api-key"]);
|
|
356
|
+
|
|
357
|
+
async function forward(request: Request, userId: string): Promise<Response> {
|
|
358
|
+
const headers = new Headers();
|
|
359
|
+
request.headers.forEach((value, name) => {
|
|
360
|
+
if (!DROP.has(name) && !name.startsWith("proxy-")) headers.set(name, value);
|
|
361
|
+
});
|
|
362
|
+
const gatewayFetch = linkFetch({
|
|
363
|
+
...client,
|
|
364
|
+
loadTokens: () => db.loadTokens(userId),
|
|
365
|
+
saveTokens: (tokens) => db.saveTokens(userId, tokens),
|
|
366
|
+
});
|
|
367
|
+
const { pathname, search } = new URL(request.url);
|
|
368
|
+
try {
|
|
369
|
+
// linkFetch sets the bearer and refreshes; the body (and its model) is unchanged.
|
|
370
|
+
const body = request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer();
|
|
371
|
+
const response = await gatewayFetch(`${pathname}${search}`, { method: request.method, headers, body });
|
|
372
|
+
if (response.status === 401 && (await response.clone().json()).error?.code === "grant_revoked") await markUnlinked(userId);
|
|
373
|
+
return response;
|
|
374
|
+
} catch (error) {
|
|
375
|
+
if (error instanceof LinkError && (error.code === "invalid_grant" || error.code === "not_linked")) await markUnlinked(userId);
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
A child token is simpler still when the agent runs somewhere you control: give the agent the `dlk_ct_…` token as its API key and base URL, and it calls the gateway itself.
|
|
382
|
+
|
|
383
|
+
**Connect with Dari button.** Use `DariLink.renderButton(container, { onClick, theme })`, or this markup, rather than drawing your own: the Dari mark (`DARI_MARK_SVG` from the client) at 20px, then "Connect with Dari" in your UI font at 14px, medium weight; 40px tall, 8px radius, 12px padding before the mark and 16px after the text, 8px between them. `theme: "dark"` (the default, for light pages) is a black button with white text and an inverted mark; `light` (for dark pages) is white with black text and a light gray border. Keep the words "Connect with Dari" (or "Reconnect Dari" for a revoked grant), and do not recolor the mark.
|
|
384
|
+
|
|
385
|
+
```html
|
|
386
|
+
<button type="button" style="display:inline-flex;align-items:center;gap:8px;height:40px;padding:0 16px 0 12px;border-radius:8px;border:1px solid #000;background:#000;color:#fff;font:500 14px/1 system-ui,sans-serif;cursor:pointer">
|
|
387
|
+
<!-- DARI_MARK_SVG, with its disc white and its figure black on this dark button -->
|
|
388
|
+
Connect with Dari
|
|
389
|
+
</button>
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
**Users with their own gateway.** A user who runs their own gateway links it the same way: ask for its base URL, read `GET <base>/.well-known/oauth-authorization-server`, and register there with `POST /v1/link/register` (a server registers as a confidential client with `"token_endpoint_auth_method": "client_secret_basic"`). Keep each registration (client id, endpoints) keyed by the metadata's `issuer`, and show the issuer's host to the user wherever the link appears, so they can see which gateway an app is using.
|
|
393
|
+
|
|
394
|
+
**Testing an integration.** `startStubGateway` from `@mupt-ai/dari-gateway/self_host/stub_gateway` (Bun) runs a self-hosted gateway on stand-in plans, for example `{ plans: ["openai_codex"] }`, whose provider calls go to a local stand-in that answers "hi" (or your `upstream`), so tests make no paid calls. `gateway.approve(authorizeUrl, { credentialIds?, deny? })` goes through the approval page as a user would and returns what it hands your app, `{message, targetOrigin}` (the popup's `web_message` post, or the redirect's query), also kept in `gateway.messages`. `gateway.setState({ limited: true })` makes every provider call a usage-limit refusal (plans go `plan_limit` with `unavailable_until`, requests get 424 `subscription_exhausted`), and `{ five_hour: 0.4, weekly: 0.9 }` makes each reply report that plan usage (filling `plans[].usage`, and against a grant's budget leading to `grant_budget_exhausted`). `gateway.calls` records each provider call's path, model, thinking settings, the effort it is served at (for Claude models that take a per-turn effort, the latest effort message, not the top-level `output_config.effort` that stays fixed for caching), and client headers, to assert on. Under any other test runner, run it as a process: `dari-gateway-stub --plans openai_codex,anthropic_claude_code` (Bun runs it) prints one JSON line, `{"baseUrl", "gatewayKey", "planIds", "userCookie", "controlUrl"}` (the stand-in plans belong to the approval page's user, and `userCookie` is the `Cookie` header that opens the page as them); `GET <controlUrl>/served` answers `{"calls": [...]}`, `POST <controlUrl>/approve` with `{"url", "credential_ids"?, "deny"?}` answers `{"message", "target_origin"}` (listed at `GET <controlUrl>/messages`), and `POST <controlUrl>/state` takes the same fields as `setState`. A gateway config can send ChatGPT plan traffic elsewhere the same way, with `providers.openai-codex.baseUrl`.
|
|
395
|
+
|
|
119
396
|
## Embed
|
|
120
397
|
|
|
121
|
-
Deployments with their own storage and accounting compose the runtime with a `GatewayPlatform` (router resolution, conversation state, session pins, subscription holds, request records, error reporting) and a selector backend:
|
|
398
|
+
Deployments with their own storage and accounting compose the runtime with a `GatewayPlatform` (router resolution, conversation state, session pins, subscription holds, request records, error reporting, and optionally Dari Link grants through `link`) and a selector backend:
|
|
122
399
|
|
|
123
400
|
```ts
|
|
124
401
|
import { createPrioritySelectorBackend, createRequestHandler } from "@mupt-ai/dari-gateway";
|
|
@@ -169,6 +169,13 @@ function sanitizeProviderContent(value) {
|
|
|
169
169
|
if (part.type === "providerItem" && isRecord(part.item)) {
|
|
170
170
|
return part.item;
|
|
171
171
|
}
|
|
172
|
+
// A thinking signature is an opaque continuation token (encrypted
|
|
173
|
+
// reasoning, an Anthropic signature), not prompt text: its base64 would
|
|
174
|
+
// count far more tokens than the provider bills for it.
|
|
175
|
+
if (part.type === "thinking" && "thinkingSignature" in part) {
|
|
176
|
+
const { thinkingSignature: _signature, ...visible } = part;
|
|
177
|
+
return visible;
|
|
178
|
+
}
|
|
172
179
|
if (part.type === "image"
|
|
173
180
|
&& typeof part.mimeType === "string"
|
|
174
181
|
&& typeof part.data === "string") {
|
|
@@ -242,12 +242,15 @@ function derivePrefixContext(args) {
|
|
|
242
242
|
// An explicit `dari/model/<id>` serves the requested thinking level when the
|
|
243
243
|
// model offers it and otherwise its default level, so the request itself drops
|
|
244
244
|
// an unsupported level before routing and provider validation see it. A strict
|
|
245
|
-
// router never
|
|
245
|
+
// router and a Dari Link token never substitute, so they keep the level and
|
|
246
|
+
// fail on it.
|
|
246
247
|
export function clampRequestedEffort(interaction, credentials, metadataLookup) {
|
|
247
248
|
const requested = interaction.reasoning?.effort;
|
|
248
249
|
const modelId = explicitModelId(interaction.model);
|
|
249
250
|
if (requested === undefined || modelId === null || credentials.strict === true)
|
|
250
251
|
return interaction;
|
|
252
|
+
if (interaction.reasoning?.clientOnly === true)
|
|
253
|
+
return interaction;
|
|
251
254
|
const supported = metadataLookup(modelId).supportedThinkingLevels.filter(isReasoningEffort);
|
|
252
255
|
const configured = credentials.model_thinking_levels?.[modelId] ?? supported;
|
|
253
256
|
if (configured.includes(requested) && supported.includes(requested))
|
package/dist/http/handler.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export type GatewayHandlerOptions = {
|
|
|
7
7
|
/**
|
|
8
8
|
* The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
|
|
9
9
|
* messages,models}` on the default router and `/{router_id}/v1/...` on a
|
|
10
|
-
* named one
|
|
10
|
+
* named one, and the Dari Link grant endpoints under `/v1/link/`. Binds
|
|
11
|
+
* `options.platform` for every request it serves.
|
|
11
12
|
*/
|
|
12
13
|
export declare function createRequestHandler(options: GatewayHandlerOptions): (request: Request) => Promise<Response>;
|
package/dist/http/handler.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { handleResponses, handleResponsesWebSocketFallback, } from "../ingress/codex.js";
|
|
2
|
+
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../ingress/link.js";
|
|
2
3
|
import { handleModels } from "../ingress/models.js";
|
|
3
4
|
import { handleMuseCodeModels } from "../ingress/muse_models.js";
|
|
4
5
|
import { handleChatCompletions } from "../ingress/chat_completions.js";
|
|
5
|
-
import { handleAnthropicMessages } from "../ingress/anthropic_messages.js";
|
|
6
|
+
import { anthropicErrorResponse, handleAnthropicMessages } from "../ingress/anthropic_messages.js";
|
|
6
7
|
import { bindGatewayPlatform } from "../platform/platform.js";
|
|
7
8
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
8
9
|
import { errorResponse, HttpError } from "./errors.js";
|
|
9
10
|
/**
|
|
10
11
|
* The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
|
|
11
12
|
* messages,models}` on the default router and `/{router_id}/v1/...` on a
|
|
12
|
-
* named one
|
|
13
|
+
* named one, and the Dari Link grant endpoints under `/v1/link/`. Binds
|
|
14
|
+
* `options.platform` for every request it serves.
|
|
13
15
|
*/
|
|
14
16
|
export function createRequestHandler(options) {
|
|
15
17
|
const { selectorBackend } = options;
|
|
@@ -31,6 +33,9 @@ export function createRequestHandler(options) {
|
|
|
31
33
|
if (request.method === "HEAD" && url.pathname === "/api/hello") {
|
|
32
34
|
return new Response(null, { status: 200 });
|
|
33
35
|
}
|
|
36
|
+
if (url.pathname.startsWith(LINK_ROUTE_PREFIX) || url.pathname === LINK_METADATA_PATH) {
|
|
37
|
+
return await handleLinkRequest(request, options.platform);
|
|
38
|
+
}
|
|
34
39
|
const endpoint = routedEndpoint(url.pathname);
|
|
35
40
|
if (endpoint?.protocol === "chat" && request.method === "POST") {
|
|
36
41
|
return await handleChatCompletions(request, endpoint.routerId, selectorBackend);
|
|
@@ -48,6 +53,11 @@ export function createRequestHandler(options) {
|
|
|
48
53
|
if (endpoint?.protocol === "models" && request.method === "GET") {
|
|
49
54
|
return await handleModels(request, endpoint.routerId);
|
|
50
55
|
}
|
|
56
|
+
// The gateway counts no tokens. Claude Code calls this for any Anthropic
|
|
57
|
+
// base URL and estimates locally when it fails, so it gets an error it parses.
|
|
58
|
+
if (request.method === "POST" && url.pathname.endsWith("/messages/count_tokens")) {
|
|
59
|
+
return anthropicErrorResponse(new HttpError(404, "Token counting is not available on this gateway; estimate locally.", "not_found"));
|
|
60
|
+
}
|
|
51
61
|
return errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
52
62
|
};
|
|
53
63
|
}
|
|
@@ -2,10 +2,11 @@ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
|
2
2
|
import { anthropicMessagesResponse } from "../protocol/output/anthropic_messages.js";
|
|
3
3
|
import { anthropicMessagesSseStream } from "../protocol/output/anthropic_messages_stream.js";
|
|
4
4
|
import { anthropicToken } from "../http/auth.js";
|
|
5
|
-
import { errorResponseHeaders, normalizeError } from "../http/errors.js";
|
|
5
|
+
import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
|
|
6
|
+
import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../models/link_errors.js";
|
|
6
7
|
import { captureRequestError } from "../observability/errors.js";
|
|
7
8
|
import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
|
|
8
|
-
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
9
|
+
import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
|
|
9
10
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
10
11
|
import { claudeCodeRequestContext } from "./claude_code/request_context.js";
|
|
11
12
|
import { claimedClientHarness } from "./client_harness.js";
|
|
@@ -18,7 +19,7 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
18
19
|
try {
|
|
19
20
|
const apiKey = anthropicToken(request.headers);
|
|
20
21
|
const rawPayload = await parseJsonRequest(request);
|
|
21
|
-
const interaction = anthropicMessagesToInteraction(rawPayload);
|
|
22
|
+
const interaction = anthropicMessagesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
22
23
|
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
23
24
|
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
24
25
|
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
@@ -115,10 +116,20 @@ function isClaudeCodeRequest(headers) {
|
|
|
115
116
|
}
|
|
116
117
|
// Dari-specific codes clients act on; every other code stays internal.
|
|
117
118
|
const CLIENT_VISIBLE_ERROR_CODES = new Set([
|
|
119
|
+
...LINK_GRANT_ERROR_CODES,
|
|
120
|
+
...LINK_TOKEN_ERROR_CODES,
|
|
118
121
|
"personal_subscription_unavailable",
|
|
119
122
|
"subscription_switched",
|
|
120
123
|
"subscription_usage_limit",
|
|
121
124
|
]);
|
|
125
|
+
// What a Dari Link error carries beside its code: when a plan resets, and who
|
|
126
|
+
// revoked a grant and when.
|
|
127
|
+
function linkErrorFields(error) {
|
|
128
|
+
return Object.fromEntries(["resets_at", "revoked_by", "revoked_at"].flatMap((field) => {
|
|
129
|
+
const value = error.body?.[field];
|
|
130
|
+
return typeof value === "string" ? [[field, value]] : [];
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
122
133
|
export function anthropicErrorResponse(error) {
|
|
123
134
|
const { status, message, code } = normalizeError(error);
|
|
124
135
|
return Response.json({
|
|
@@ -127,6 +138,7 @@ export function anthropicErrorResponse(error) {
|
|
|
127
138
|
type: anthropicErrorType(status),
|
|
128
139
|
message,
|
|
129
140
|
...(CLIENT_VISIBLE_ERROR_CODES.has(code) ? { code } : {}),
|
|
141
|
+
...(error instanceof HttpError ? linkErrorFields(error) : {}),
|
|
130
142
|
},
|
|
131
143
|
}, { status, headers: errorResponseHeaders(error) });
|
|
132
144
|
}
|
|
@@ -3,6 +3,7 @@ import { errorResponse } from "../http/errors.js";
|
|
|
3
3
|
import { captureRequestError } from "../observability/errors.js";
|
|
4
4
|
import { chatCompletionResponse, chatCompletionsSseStream } from "../protocol/output/chat_completions.js";
|
|
5
5
|
import { chatCompletionsToInteraction } from "../protocol/input/chat_completions.js";
|
|
6
|
+
import { linkTokenModel } from "../protocol/input/router_model.js";
|
|
6
7
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
7
8
|
import { chatCompletionsConversationIdentity, openCodeRequestContext, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
8
9
|
import { claimedClientHarness } from "./client_harness.js";
|
|
@@ -12,7 +13,11 @@ export async function handleChatCompletions(request, routerId, selectorBackend)
|
|
|
12
13
|
try {
|
|
13
14
|
const apiKey = bearerToken(request.headers);
|
|
14
15
|
const payload = await parseJsonRequest(request);
|
|
15
|
-
const interaction = chatCompletionsToInteraction({
|
|
16
|
+
const interaction = chatCompletionsToInteraction({
|
|
17
|
+
...payload,
|
|
18
|
+
model: linkTokenModel(apiKey, payload.model),
|
|
19
|
+
source_protocol: "openai_chat",
|
|
20
|
+
});
|
|
16
21
|
const piContext = piRequestContext(request.headers);
|
|
17
22
|
const openCodeContext = openCodeRequestContext(request.headers);
|
|
18
23
|
const agentContext = piContext ?? openCodeContext;
|
package/dist/ingress/codex.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
1
|
+
import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
|
|
2
2
|
import { bearerToken } from "../http/auth.js";
|
|
3
3
|
import { errorResponse } from "../http/errors.js";
|
|
4
4
|
import { captureRequestError } from "../observability/errors.js";
|
|
@@ -14,7 +14,7 @@ export async function handleResponses(request, routerId, selectorBackend) {
|
|
|
14
14
|
try {
|
|
15
15
|
const apiKey = bearerToken(request.headers);
|
|
16
16
|
const rawPayload = await parseJsonRequest(request);
|
|
17
|
-
const interaction = openAIResponsesToInteraction(rawPayload);
|
|
17
|
+
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
18
18
|
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
19
19
|
const agentContext = codexRequestContext(request.headers, rawPayload);
|
|
20
20
|
const museClientId = museCodeClientId(request.headers);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { GatewayPlatform } from "../platform/platform.js";
|
|
2
|
+
/** The `type` of the message a `web_message` approval posts to its opener. */
|
|
3
|
+
export declare const LINK_MESSAGE_TYPE = "dari-link";
|
|
4
|
+
export declare const LINK_EVENT_TYPE = "dari-link-event";
|
|
5
|
+
export declare const LINK_SCOPE = "route";
|
|
6
|
+
export declare const LINK_ROUTE_PREFIX = "/v1/link/";
|
|
7
|
+
export declare const LINK_METADATA_PATH = "/.well-known/oauth-authorization-server";
|
|
8
|
+
/** The PKCE S256 challenge for a code verifier. */
|
|
9
|
+
export declare function pkceChallenge(verifier: string): string;
|
|
10
|
+
export declare function handleLinkRequest(request: Request, platform: GatewayPlatform): Promise<Response>;
|
|
11
|
+
/**
|
|
12
|
+
* The `Cookie` header value that makes a request this user's on the approval
|
|
13
|
+
* page, for a platform's own tooling (the stub gateway approves with it).
|
|
14
|
+
*/
|
|
15
|
+
export declare function linkUserCookie(secret: string, subject: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* The step of approval the user reached, which a popup posts to the window
|
|
18
|
+
* that opened it (`{type: "dari-link-event", version: 1, event, state}`; the
|
|
19
|
+
* result alone is `type: "dari-link"`), so the app can tell where the user
|
|
20
|
+
* left: `connect_subscription` (connecting a plan) or `choose_plans`. A
|
|
21
|
+
* platform with its own consent page may also post `sign_in`. A user who
|
|
22
|
+
* denies leaves at `denied`, which the `access_denied` result says.
|
|
23
|
+
*/
|
|
24
|
+
export type LinkStep = "sign_in" | "connect_subscription" | "choose_plans";
|