@mupt-ai/dari-gateway 1.0.327 → 1.0.329

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 CHANGED
@@ -129,57 +129,47 @@ Dari Link lets another app send one user's model requests through the gateway on
129
129
 
130
130
  **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.
131
131
 
132
- 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
+ An app with a server (a confidential client) is a button, one endpoint, and one string stored per user:
133
133
 
134
134
  ```ts
135
- // On your server: start a connection and keep the verifier with the session.
136
- import { createAuthorization } from "@mupt-ai/dari-gateway/link/client";
137
-
138
- app.post("/api/dari/start", async (req, res) => {
139
- const { codeVerifier, codeChallenge, state } = await createAuthorization();
140
- req.session.dariLink = { codeVerifier, state };
141
- res.json({ codeChallenge, state });
142
- });
143
- ```
144
-
145
- ```ts
146
- // In your app's bundle. The client uses only fetch (and Web Crypto when it makes PKCE itself).
135
+ // In your app's bundle. The client uses only fetch and Web Crypto.
147
136
  import { DariLink } from "@mupt-ai/dari-gateway/link/client";
148
137
 
149
138
  DariLink.renderButton(document.getElementById("connect-dari"), {
150
139
  onClick: async () => {
151
- // The settings come from your server after the popup opens; resolves with { code, state }.
152
- const { code, state } = await DariLink.open(async () => ({
140
+ const { code, codeVerifier } = await DariLink.open({
153
141
  gatewayUrl: "https://routing.dari.dev",
154
142
  clientId: "lnk_…",
155
143
  redirectUri: "https://app.example.com/dari/callback",
156
- ...(await (await fetch("/api/dari/start", { method: "POST" })).json()),
157
144
  onExit: ({ error, step }) => analytics.track("dari_link_exit", { error, step }),
158
- }));
159
- await fetch("/api/dari/exchange", {
145
+ });
146
+ await fetch("/api/dari/connect", {
160
147
  method: "POST",
161
148
  headers: { "content-type": "application/json" },
162
- body: JSON.stringify({ code, state }),
149
+ body: JSON.stringify({ code, codeVerifier }),
163
150
  });
164
151
  },
165
152
  });
166
153
  ```
167
154
 
168
- Your server checks `state`, redeems the code with the verifier it kept, and keeps the tokens with the user:
155
+ Your server redeems the code and keeps the grant's refresh token with the user. It never changes and is useless without the client secret, and every later call takes it:
169
156
 
170
157
  ```ts
171
158
  import { exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
172
159
 
173
160
  const client = { gatewayUrl: "https://routing.dari.dev", clientId, clientSecret };
174
- const { codeVerifier, state: expected } = req.session.dariLink;
175
- if (req.body.state !== expected) throw new Error("state mismatch");
176
- await db.save(user, await exchange({ ...client, redirectUri, code: req.body.code, codeVerifier }));
161
+ const { refreshToken } = await exchange({ ...client, redirectUri, code: req.body.code, codeVerifier: req.body.codeVerifier });
162
+ // Save refreshToken to your database, with the signed-in user.
177
163
 
178
- const dari = linkFetch({ ...client, loadTokens: () => db.load(user), saveTokens: (next) => db.save(user, next) });
164
+ const dari = linkFetch({ ...client, refreshToken });
179
165
  await dari("/v1/chat/completions", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "dari/routing", messages }) });
180
166
  ```
181
167
 
182
- - 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.
168
+ The gateway refuses a model the grant cannot serve, a plan at its limit, a spent budget, and a revoked grant on every request, each with its own code (see the error table below), so the app checks none of them first.
169
+
170
+ - `DariLink.open` makes the PKCE pair in the page and resolves with `{ code, state, codeVerifier }`. That needs a secure page (https, or localhost); elsewhere it rejects with `insecure_context` before opening anything. To keep the verifier off the page, or to connect from a page that is not secure, make the pair on your server with `createAuthorization()`, keep `codeVerifier` and `state` with the user's session, and pass `codeChallenge` and `state` to `DariLink.open`: it then resolves with a null `codeVerifier`, and your server checks `state` and redeems the code with the verifier it kept.
171
+ - The endpoint that redeems the code changes the user's account, so protect it from cross-site requests like any other.
172
+ - A browser-only app (a public client) has no secret and redeems the code itself; its refresh token rotates on every use, so it keeps the whole token set and passes `loadTokens` and `saveTokens` wherever a server passes `refreshToken`.
183
173
  - 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.
184
174
  - 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`.
185
175
  - `onEvent(step)` hears each step the user reaches in the popup (`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 while connecting a plan" 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`.
@@ -296,48 +286,49 @@ A sandbox given a child token needs to reach only the gateway's host (for hosted
296
286
 
297
287
  Error text replaces anything shaped like an `sk-` key with `sk-…`, and responses replace the serving plan's own credential wherever it appears.
298
288
 
299
- **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:
289
+ **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`), `exchange`, `linkFetch`, `grant`, `childToken`, `usage`, `revoke`, `refresh`, `createAuthorization` (a PKCE pair and state made on your server), `registerClient`, and `authorizeUrl` (the approval URL without a popup; takes `clients`, `plans`, `purposes`, and `grantId`). Every call takes `clientSecret` for a confidential client.
290
+
291
+ `linkFetch`, `grant`, `childToken`, and `usage` take one grant's tokens in either of two ways:
300
292
 
301
- - `loadTokens` returning null makes both throw `LinkError` `not_linked`, with no call to the gateway;
302
- - a `LinkError` with code `invalid_grant` from a refresh means the grant is gone;
303
- - a revoked grant's tokens, access tokens included, answer 401 `grant_revoked` at once, which `linkFetch` returns as it is, with no refresh attempted.
293
+ - `refreshToken`, for a confidential client: its refresh token never rotates, so it is all the app stores. The client makes an access token from it, keeps it in the process, replaces it before it expires or once after a 401 for an expired token, and shares one refresh among concurrent calls. Any number of processes can do this at once.
294
+ - `loadTokens` and `saveTokens`, for a public client, whose refresh token rotates on every use: your storage is the source of truth. The client reads the token set with `loadTokens` on every call and passes every new one to `saveTokens` before using it, so processes that share the storage share the rotation. `loadTokens` returning null throws `LinkError` `not_linked`, with no call to the gateway.
304
295
 
305
- 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.
296
+ `grant` returns what `GET /v1/link/grant` does, with its top-level fields in camelCase (`grantId`, `availableAt`, `manageUrl`). `usage({ tags, since, until, groupByTag })` reads the grant's usage, and `childToken({ models: [{ model, thinking? }] })` mints for several models at once. `grant` and `usage` also take a `linkFetch` you already made as `fetcher` in place of the tokens, and `childToken` an `accessToken`. `registerClient({ ..., confidential: true })` returns a `clientSecret` too.
297
+
298
+ A refused call throws a `LinkError` with the most specific `code`. Its `unlinked` is true when the grant is gone (`invalid_grant` from a refresh, `grant_revoked`, or `not_linked`): show the user Reconnect. `linkFetch` is a fetch, so a revoked grant's 401 `grant_revoked` comes back as the response it is, with no refresh attempted.
306
299
 
307
300
  A server-side integration, start to finish:
308
301
 
309
302
  ```ts
310
- import { authorizeUrl, childToken, exchange, linkFetch, revoke } from "@mupt-ai/dari-gateway/link/client";
303
+ import { childToken, exchange, grant, LinkError, revoke, usage } from "@mupt-ai/dari-gateway/link/client";
311
304
 
312
305
  // Registered once, under Settings → Dari Link Apps or with POST /v1/link/register.
313
306
  const client = { gatewayUrl, clientId, clientSecret: process.env.DARI_LINK_CLIENT_SECRET };
314
307
 
315
- // 1. Send the user to approve. Keep codeVerifier and state in their session.
316
- const { url, codeVerifier, state } = await authorizeUrl({ ...client, redirectUri, plans: ["openai_codex"] });
317
-
318
- // 2. On the redirect back, check state, redeem the code, and store the tokens.
319
- await db.saveTokens(userId, await exchange({ ...client, redirectUri, code, codeVerifier }));
308
+ // 1. Redeem the code Connect with Dari handed your page, and store the refresh token.
309
+ const { refreshToken } = await exchange({ ...client, redirectUri, code, codeVerifier });
310
+ // Save refreshToken to your database, with the signed-in user.
320
311
 
321
- // 3. Call the gateway from any instance.
322
- const gatewayFetch = linkFetch({
323
- ...client,
324
- loadTokens: () => db.loadTokens(userId),
325
- saveTokens: (tokens) => db.saveTokens(userId, tokens),
326
- });
327
- const grant = await (await gatewayFetch("/v1/link/grant")).json(); // the cheap check before a long run
312
+ // 2. From any instance: what the user shared, the cheap check before a long run.
313
+ const { plans, models, manageUrl } = await grant({ ...client, refreshToken });
328
314
 
329
- // 4. Hand a sandbox one model for one trial; it calls the gateway itself.
315
+ // 3. Hand a sandbox one model for one trial; it calls the gateway itself.
330
316
  const sandbox = await childToken({
331
317
  ...client,
332
- loadTokens: () => db.loadTokens(userId),
333
- saveTokens: (tokens) => db.saveTokens(userId, tokens),
334
- models: [{ model: grant.models[0], thinking: "high" }],
318
+ refreshToken,
319
+ models: [{ model: models[0].id, thinking: "high" }],
335
320
  expiresIn: 6 * 3600,
336
321
  tags: { run, trial },
337
322
  });
338
323
 
324
+ // 4. What the trial used.
325
+ const used = await usage({ ...client, refreshToken, tags: { trial } });
326
+
339
327
  // 5. When the user disconnects in the app.
340
- await revoke({ ...client, token: (await db.loadTokens(userId)).refreshToken });
328
+ await revoke({ ...client, token: refreshToken });
329
+
330
+ // Anywhere: the grant is gone, so offer Reconnect.
331
+ if (error instanceof LinkError && error.unlinked) await markUnlinked(userId);
341
332
  ```
342
333
 
343
334
  **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:
@@ -345,32 +336,29 @@ await revoke({ ...client, token: (await db.loadTokens(userId)).refreshToken });
345
336
  - 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_…`;
346
337
  - keep the model as the client named it: bare and dated ids are served as exactly that model;
347
338
  - 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;
348
- - treat `invalid_grant`, `grant_revoked`, and `not_linked` as unlinked: stop the agent and show Reconnect.
339
+ - treat a `LinkError` whose `unlinked` is true, and a 401 `grant_revoked` response, as unlinked: stop the agent and show Reconnect.
349
340
 
350
341
  ```ts
351
342
  import { LinkError, linkFetch } from "@mupt-ai/dari-gateway/link/client";
352
343
 
353
344
  const DROP = new Set(["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "te", "trailer", "authorization", "x-api-key"]);
354
345
 
355
- async function forward(request: Request, userId: string): Promise<Response> {
346
+ // user: your own record of the signed-in user, with the refresh token you saved.
347
+ async function forward(request: Request, user: { id: string; refreshToken: string }): Promise<Response> {
356
348
  const headers = new Headers();
357
349
  request.headers.forEach((value, name) => {
358
350
  if (!DROP.has(name) && !name.startsWith("proxy-")) headers.set(name, value);
359
351
  });
360
- const gatewayFetch = linkFetch({
361
- ...client,
362
- loadTokens: () => db.loadTokens(userId),
363
- saveTokens: (tokens) => db.saveTokens(userId, tokens),
364
- });
352
+ const gatewayFetch = linkFetch({ ...client, refreshToken: user.refreshToken });
365
353
  const { pathname, search } = new URL(request.url);
366
354
  try {
367
355
  // linkFetch sets the bearer and refreshes; the body (and its model) is unchanged.
368
356
  const body = request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer();
369
357
  const response = await gatewayFetch(`${pathname}${search}`, { method: request.method, headers, body });
370
- if (response.status === 401 && (await response.clone().json()).error?.code === "grant_revoked") await markUnlinked(userId);
358
+ if (response.status === 401 && (await response.clone().json()).error?.code === "grant_revoked") await markUnlinked(user.id);
371
359
  return response;
372
360
  } catch (error) {
373
- if (error instanceof LinkError && (error.code === "invalid_grant" || error.code === "not_linked")) await markUnlinked(userId);
361
+ if (error instanceof LinkError && error.unlinked) await markUnlinked(user.id);
374
362
  throw error;
375
363
  }
376
364
  }
@@ -389,7 +377,7 @@ A child token is simpler still when the agent runs somewhere you control: give t
389
377
 
390
378
  **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.
391
379
 
392
- **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`.
380
+ **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.app` is a server app already registered on it (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`: your app's Dari Link settings in the test), and `gateway.connect({ credentialIds?, deny?, clients?, plans?, keyProviders?, grantId? })` is its user approving it: it resolves with what `DariLink.open` hands your page, `{ code, codeVerifier, state }`, or rejects with the `LinkError` it would. For an app you registered yourself, `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", "app"}` (the stand-in plans belong to the approval page's user, and `userCookie` is the `Cookie` header that opens the page as them); `POST <controlUrl>/connect` takes `connect`'s options in snake case and answers `{"code", "code_verifier", "state"}`, `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`.
393
381
 
394
382
  ## Embed
395
383
 
@@ -4,47 +4,51 @@
4
4
  * themselves. It uses only `fetch` and Web Crypto, so it runs in browsers,
5
5
  * Node, Bun, and Deno.
6
6
  *
7
- * In a browser, one button does the approval: `DariLink.open` opens Dari in a
8
- * popup, the user signs in, picks plans, and approves, and the popup closes.
7
+ * An app with a server is three calls. In the browser, one button does the
8
+ * approval: `DariLink.open` opens Dari in a popup, the user signs in, picks
9
+ * plans, and approves, and the popup closes.
9
10
  *
10
11
  * ```ts
11
12
  * import { DariLink } from "@mupt-ai/dari-gateway/link/client";
12
13
  *
13
14
  * button.onclick = async () => {
14
15
  * const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
15
- * await fetch("/api/dari/exchange", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
+ * await fetch("/api/dari/connect", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
17
  * };
17
18
  * ```
18
19
  *
19
- * Without a popup, send the user to the approval URL yourself:
20
+ * The server, registered as a confidential client (`registerClient({
21
+ * confidential: true })`, or Settings → Dari Link Apps on hosted Dari),
22
+ * redeems the code and stores one string per user: the refresh token. It
23
+ * never changes, and it is useless without the client secret. Every later
24
+ * call takes it, and makes its own access tokens:
20
25
  *
21
26
  * ```ts
22
- * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
27
+ * import { exchange, linkFetch } from "@mupt-ai/dari-gateway/link/client";
23
28
  *
24
- * const { url, codeVerifier, state } = await authorizeUrl({ gatewayUrl, clientId, redirectUri });
25
- * // Keep codeVerifier and state with the user's session, send them to `url`;
26
- * // on the redirect back, check `state`, then:
27
- * await db.save(user, await exchange({ gatewayUrl, clientId, redirectUri, code, codeVerifier }));
28
- * const gatewayFetch = linkFetch({
29
- * gatewayUrl,
30
- * clientId,
31
- * loadTokens: () => db.load(user),
32
- * saveTokens: (next) => db.save(user, next),
33
- * });
34
- * await gatewayFetch("/v1/chat/completions", {
29
+ * const client = { gatewayUrl, clientId, clientSecret };
30
+ * const { refreshToken } = await exchange({ ...client, redirectUri, code, codeVerifier });
31
+ * await db.save(user, refreshToken);
32
+ *
33
+ * const dari = linkFetch({ ...client, refreshToken });
34
+ * await dari("/v1/chat/completions", {
35
35
  * method: "POST",
36
36
  * headers: { "content-type": "application/json" },
37
37
  * body: JSON.stringify({ model: "dari/routing", messages }),
38
38
  * });
39
39
  * ```
40
40
  *
41
- * A server keeps a secret: register it as a confidential client
42
- * (`registerClient({ confidential: true })`, or Settings → Dari Link Apps on
43
- * hosted Dari) and pass `clientSecret` to every
44
- * call. Its refresh token then never rotates, so any number of processes can
45
- * refresh the same grant. A public client's refresh token rotates on every
46
- * use; `linkFetch` reads the tokens from your storage on each call, so
47
- * processes that share that storage share the rotation.
41
+ * `grant`, `usage`, and `childToken` take the same `refreshToken`, and
42
+ * `revoke` ends the grant. Dari refuses a model the grant cannot serve, a
43
+ * plan at its limit, and a revoked grant itself, so an app checks none of
44
+ * that before calling: it shows the error, and Reconnect when
45
+ * `LinkError.unlinked` is true.
46
+ *
47
+ * An app with no server (a public client) has no secret, and its refresh
48
+ * token rotates on every use: it passes its storage (`loadTokens` and
49
+ * `saveTokens`) instead of `refreshToken`, and processes that share that
50
+ * storage share the rotation. Without a popup, `authorizeUrl` gives the
51
+ * approval URL to send the user to.
48
52
  */
49
53
  export type LinkPlan = {
50
54
  id: string;
@@ -77,11 +81,9 @@ export type LinkBudgetWindow = {
77
81
  used_tokens: number;
78
82
  resets_at: string | null;
79
83
  };
80
- export type LinkTokenSet = {
81
- accessToken: string;
82
- refreshToken: string;
83
- expiresAt: number;
84
- grantId: string | null;
84
+ /** What a grant holds now: what `grant` reads, and what comes with every token set. */
85
+ export type LinkGrant = {
86
+ grantId: string;
85
87
  scope: string;
86
88
  budget: LinkBudgetWindow[];
87
89
  state: "ready" | "budget_limit";
@@ -91,6 +93,11 @@ export type LinkTokenSet = {
91
93
  manageUrl: string;
92
94
  routes: boolean;
93
95
  };
96
+ export type LinkTokenSet = LinkGrant & {
97
+ accessToken: string;
98
+ refreshToken: string;
99
+ expiresAt: number;
100
+ };
94
101
  export type LinkChildToken = {
95
102
  accessToken: string;
96
103
  expiresAt: number;
@@ -110,6 +117,8 @@ export declare class LinkError extends Error {
110
117
  readonly status: number;
111
118
  readonly detail: Record<string, unknown>;
112
119
  constructor(code: string, message: string, status: number, detail?: Record<string, unknown>);
120
+ /** Whether the user's grant is gone, so the app should offer Reconnect. */
121
+ get unlinked(): boolean;
113
122
  }
114
123
  type Fetch = typeof fetch;
115
124
  type Gateway = {
@@ -302,14 +311,15 @@ export declare function refresh(args: Client & {
302
311
  refreshToken: string;
303
312
  }): Promise<LinkTokenSet>;
304
313
  /**
305
- * Mint a child token for a sandbox or worker, from the grant's access token
306
- * or from your token storage (refreshed as `linkFetch` does): it serves only
307
- * its models (each at one thinking level when pinned) for up to twelve
308
- * hours, cannot refresh, mint, or read the grant, and dies with the grant.
314
+ * Mint a child token for a sandbox or worker, from the grant's refresh token
315
+ * or token storage (as `linkFetch` takes them), or from an access token: it
316
+ * serves only its models (each at one thinking level when pinned) for up to
317
+ * twelve hours, cannot refresh, mint, or read the grant, and dies with the
318
+ * grant.
309
319
  */
310
320
  export declare function childToken(args: Client & ({
311
321
  accessToken: string;
312
- } | TokenStorage) & {
322
+ } | LinkTokens) & {
313
323
  models: Array<{
314
324
  model: string;
315
325
  thinking?: string;
@@ -324,16 +334,17 @@ export declare function revoke(args: Client & {
324
334
  }): Promise<void>;
325
335
  /**
326
336
  * A fetch for the gateway on one grant: paths resolve against `gatewayUrl`
327
- * and the access token is attached. Your storage is the source of truth: the
328
- * tokens are read with `loadTokens` on every call, refreshed shortly before
329
- * they expire and once after a 401 for an expired token, and every new token
330
- * set reaches `saveTokens` before use. Concurrent calls in a process share
331
- * one refresh. A grant that is gone throws LinkError with code
337
+ * and the access token is attached, refreshed shortly before it expires and
338
+ * once after a 401 for an expired token. A server passes the grant's
339
+ * `refreshToken`; a public client passes its storage, which is then the
340
+ * source of truth: the tokens are read with `loadTokens` on every call, and
341
+ * every new token set reaches `saveTokens` before use. Concurrent calls in a
342
+ * process share one refresh. A grant that is gone throws LinkError with code
332
343
  * `invalid_grant` from the refresh, and a revoked access token's 401
333
344
  * (`grant_revoked`) is returned as it is: either way the user is unlinked and
334
345
  * must link again. With no tokens stored it throws `not_linked`.
335
346
  */
336
- export declare function linkFetch(args: Client & TokenStorage & {
347
+ export declare function linkFetch(args: Client & LinkTokens & {
337
348
  now?: () => number;
338
349
  }): (input: string, init?: RequestInit) => Promise<Response>;
339
350
  export type LinkUsageTotals = {
@@ -354,30 +365,47 @@ export type LinkUsage = LinkUsageTotals & {
354
365
  value: string | null;
355
366
  }>;
356
367
  };
368
+ type GrantCall = {
369
+ fetcher: (input: string, init?: RequestInit) => Promise<Response>;
370
+ } | (Client & LinkTokens & {
371
+ now?: () => number;
372
+ });
373
+ /**
374
+ * What the grant holds now: its plans and API keys, whether each can serve,
375
+ * the models they serve, and the user's budget. It makes no provider call,
376
+ * so it is the cheap check before a long run, and what a connections list
377
+ * shows. A grant that is gone throws a LinkError whose `unlinked` is true.
378
+ */
379
+ export declare function grant(args: GrantCall): Promise<LinkGrant>;
357
380
  /**
358
381
  * What the grant's requests used, child tokens' included: only requests
359
382
  * carrying every given tag (X-Dari-Tags or a child token's tags), received
360
383
  * in [since, until), and with `groupByTag` also totalled per value of that
361
- * tag. Pass the `linkFetch` your app already uses as `fetcher` so this shares
362
- * its refresh; otherwise pass the client and token storage.
384
+ * tag. Takes the grant's `refreshToken` or token storage as `linkFetch`
385
+ * does, or the `linkFetch` your app already made as `fetcher`.
363
386
  */
364
- export declare function usage(args: ({
365
- fetcher: (input: string, init?: RequestInit) => Promise<Response>;
366
- } | (Client & TokenStorage & {
367
- now?: () => number;
368
- })) & {
387
+ export declare function usage(args: GrantCall & {
369
388
  tags?: Record<string, string>;
370
389
  since?: Date;
371
390
  until?: Date;
372
391
  groupByTag?: string;
373
392
  }): Promise<LinkUsage>;
374
393
  /**
375
- * Where an app keeps one grant's tokens. `loadTokens` returns null when the
376
- * user has not linked (or unlinked): calls then throw LinkError `not_linked`
377
- * without reaching the gateway.
394
+ * Where a public client keeps one grant's tokens. `loadTokens` returns null
395
+ * when the user has not linked (or unlinked): calls then throw LinkError
396
+ * `not_linked` without reaching the gateway.
378
397
  */
379
398
  export type TokenStorage = {
380
399
  loadTokens: () => LinkTokenSet | null | Promise<LinkTokenSet | null>;
381
400
  saveTokens: (tokens: LinkTokenSet) => void | Promise<void>;
382
401
  };
402
+ /**
403
+ * One grant's tokens. A server with a client secret passes `refreshToken`,
404
+ * the one string it stores for the grant: it never changes, and the access
405
+ * tokens made from it are kept in this process. A public client's refresh
406
+ * token rotates on every use, so it passes its storage.
407
+ */
408
+ export type LinkTokens = {
409
+ refreshToken: string;
410
+ } | TokenStorage;
383
411
  export {};