@mupt-ai/dari-gateway 1.0.327 → 1.0.328

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.
@@ -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
  /**
50
54
  * A refused Dari Link call. `code` is the most specific error code: an OAuth
@@ -65,6 +69,10 @@ export class LinkError extends Error {
65
69
  this.status = status;
66
70
  this.detail = detail;
67
71
  }
72
+ /** Whether the user's grant is gone, so the app should offer Reconnect. */
73
+ get unlinked() {
74
+ return this.code === "invalid_grant" || this.code === "grant_revoked" || this.code === "not_linked";
75
+ }
68
76
  }
69
77
  // Access tokens are refreshed this long before they expire.
70
78
  const REFRESH_EARLY_MS = 60_000;
@@ -339,10 +347,11 @@ export async function refresh(args) {
339
347
  return tokenSet(await tokenCall(args, { grant_type: "refresh_token", refresh_token: args.refreshToken }));
340
348
  }
341
349
  /**
342
- * Mint a child token for a sandbox or worker, from the grant's access token
343
- * or from your token storage (refreshed as `linkFetch` does): it serves only
344
- * its models (each at one thinking level when pinned) for up to twelve
345
- * hours, cannot refresh, mint, or read the grant, and dies with the grant.
350
+ * Mint a child token for a sandbox or worker, from the grant's refresh token
351
+ * or token storage (as `linkFetch` takes them), or from an access token: it
352
+ * serves only its models (each at one thinking level when pinned) for up to
353
+ * twelve hours, cannot refresh, mint, or read the grant, and dies with the
354
+ * grant.
346
355
  */
347
356
  export async function childToken(args) {
348
357
  const pinned = args.models.some((entry) => entry.thinking);
@@ -363,7 +372,7 @@ export async function childToken(args) {
363
372
  payload = await mint(args.accessToken);
364
373
  }
365
374
  else {
366
- // From storage, refreshing the grant's access token as linkFetch does.
375
+ // Refreshing the grant's access token as linkFetch does.
367
376
  const source = tokenSource(args);
368
377
  const tokens = await source.fresh();
369
378
  try {
@@ -393,11 +402,12 @@ export async function revoke(args) {
393
402
  }
394
403
  /**
395
404
  * A fetch for the gateway on one grant: paths resolve against `gatewayUrl`
396
- * and the access token is attached. Your storage is the source of truth: the
397
- * tokens are read with `loadTokens` on every call, refreshed shortly before
398
- * they expire and once after a 401 for an expired token, and every new token
399
- * set reaches `saveTokens` before use. Concurrent calls in a process share
400
- * one refresh. A grant that is gone throws LinkError with code
405
+ * and the access token is attached, refreshed shortly before it expires and
406
+ * once after a 401 for an expired token. A server passes the grant's
407
+ * `refreshToken`; a public client passes its storage, which is then the
408
+ * source of truth: the tokens are read with `loadTokens` on every call, and
409
+ * every new token set reaches `saveTokens` before use. Concurrent calls in a
410
+ * process share one refresh. A grant that is gone throws LinkError with code
401
411
  * `invalid_grant` from the refresh, and a revoked access token's 401
402
412
  * (`grant_revoked`) is returned as it is: either way the user is unlinked and
403
413
  * must link again. With no tokens stored it throws `not_linked`.
@@ -421,12 +431,22 @@ export function linkFetch(args) {
421
431
  return await call(await source.rotate(tokens), input, init);
422
432
  };
423
433
  }
434
+ /**
435
+ * What the grant holds now: its plans and API keys, whether each can serve,
436
+ * the models they serve, and the user's budget. It makes no provider call,
437
+ * so it is the cheap check before a long run, and what a connections list
438
+ * shows. A grant that is gone throws a LinkError whose `unlinked` is true.
439
+ */
440
+ export async function grant(args) {
441
+ const fetcher = "fetcher" in args ? args.fetcher : linkFetch(args);
442
+ return grantOf(await json(await fetcher("/v1/link/grant")));
443
+ }
424
444
  /**
425
445
  * What the grant's requests used, child tokens' included: only requests
426
446
  * carrying every given tag (X-Dari-Tags or a child token's tags), received
427
447
  * in [since, until), and with `groupByTag` also totalled per value of that
428
- * tag. Pass the `linkFetch` your app already uses as `fetcher` so this shares
429
- * its refresh; otherwise pass the client and token storage.
448
+ * tag. Takes the grant's `refreshToken` or token storage as `linkFetch`
449
+ * does, or the `linkFetch` your app already made as `fetcher`.
430
450
  */
431
451
  export async function usage(args) {
432
452
  const params = new URLSearchParams();
@@ -443,19 +463,43 @@ export async function usage(args) {
443
463
  const response = await fetcher(`/v1/link/usage${query ? `?${query}` : ""}`);
444
464
  return await json(response);
445
465
  }
446
- // One grant's tokens from storage: fresh ones, refreshed shortly before they
447
- // expire, and a rotation that concurrent callers share.
466
+ // The access tokens this process made from refresh tokens, by gateway,
467
+ // client, and refresh token, and each one's refresh in flight.
468
+ const held = new Map();
469
+ const refreshes = new Map();
470
+ // One grant's tokens: fresh ones, refreshed shortly before they expire, and
471
+ // a rotation that concurrent callers share.
448
472
  function tokenSource(args) {
449
473
  const now = args.now ?? Date.now;
474
+ // A refresh token that never rotates names its grant for the whole process.
475
+ const key = "refreshToken" in args ? `${args.gatewayUrl}\n${args.clientId}\n${args.refreshToken}` : null;
476
+ if (key !== null && !args.clientSecret) {
477
+ throw new LinkError("invalid_request", "Only a client with a clientSecret keeps one refresh token; a public client's rotates, so pass loadTokens and saveTokens.", 0);
478
+ }
450
479
  const load = async () => {
480
+ // No access token made yet: the first call refreshes.
481
+ if ("refreshToken" in args)
482
+ return held.get(key) ?? { accessToken: "", refreshToken: args.refreshToken, expiresAt: 0 };
451
483
  const stored = await args.loadTokens();
452
484
  if (stored === null)
453
485
  throw new LinkError("not_linked", "This user has not linked a Dari Link grant.", 0);
454
486
  return stored;
455
487
  };
488
+ const save = async (next) => {
489
+ if (!("refreshToken" in args))
490
+ return await args.saveTokens(next);
491
+ for (const [other, tokens] of held)
492
+ if (tokens.expiresAt <= now())
493
+ held.delete(other);
494
+ held.set(key, { accessToken: next.accessToken, refreshToken: next.refreshToken, expiresAt: next.expiresAt });
495
+ };
496
+ // One refresh at a time: per call site with storage, per process with a refresh token.
456
497
  let refreshing = null;
457
498
  const rotate = (stale) => {
458
- refreshing ??= (async () => {
499
+ const running = key === null ? refreshing : refreshes.get(key) ?? null;
500
+ if (running !== null)
501
+ return running;
502
+ const started = (async () => {
459
503
  try {
460
504
  // Another call or process may have refreshed since `stale` was read.
461
505
  const stored = await load();
@@ -463,7 +507,7 @@ function tokenSource(args) {
463
507
  return stored;
464
508
  try {
465
509
  const next = await refresh({ ...args, refreshToken: stored.refreshToken });
466
- await args.saveTokens(next);
510
+ await save(next);
467
511
  return next;
468
512
  }
469
513
  catch (error) {
@@ -475,10 +519,17 @@ function tokenSource(args) {
475
519
  }
476
520
  }
477
521
  finally {
478
- refreshing = null;
522
+ if (key === null)
523
+ refreshing = null;
524
+ else
525
+ refreshes.delete(key);
479
526
  }
480
527
  })();
481
- return refreshing;
528
+ if (key === null)
529
+ refreshing = started;
530
+ else
531
+ refreshes.set(key, started);
532
+ return started;
482
533
  };
483
534
  return {
484
535
  rotate,
@@ -509,10 +560,15 @@ function clientHeaders(args) {
509
560
  }
510
561
  function tokenSet(payload) {
511
562
  return {
563
+ ...grantOf(payload),
512
564
  accessToken: String(payload.access_token),
513
565
  refreshToken: String(payload.refresh_token),
514
566
  expiresAt: Date.now() + Number(payload.expires_in) * 1000,
515
- grantId: typeof payload.grant_id === "string" ? payload.grant_id : null,
567
+ };
568
+ }
569
+ function grantOf(payload) {
570
+ return {
571
+ grantId: String(payload.grant_id),
516
572
  scope: typeof payload.scope === "string" ? payload.scope : "route",
517
573
  budget: Array.isArray(payload.budget) ? payload.budget : [],
518
574
  state: payload.state === "budget_limit" ? "budget_limit" : "ready",
@@ -18,7 +18,7 @@ export function anthropicMessagesToInteraction(payload) {
18
18
  throw invalidRequest(unsupportedModelMessage(), "model");
19
19
  }
20
20
  const tools = anthropicTools(payload.tools);
21
- toolsByWireName(tools);
21
+ const declaredTools = toolsByWireName(tools);
22
22
  const toolChoice = anthropicToolChoice(payload.tool_choice);
23
23
  const maxOutputTokens = requiredPositiveInteger(payload.max_tokens, "max_tokens");
24
24
  const stream = optionalBoolean(payload.stream, "stream") ?? false;
@@ -27,7 +27,7 @@ export function anthropicMessagesToInteraction(payload) {
27
27
  sourceProtocol: "anthropic_messages",
28
28
  model,
29
29
  instructions: anthropicSystem(payload.system),
30
- items: anthropicItems(payload.messages),
30
+ items: anthropicItems(payload.messages, declaredTools),
31
31
  tools,
32
32
  toolChoice,
33
33
  parallelToolCalls: parallelToolCalls(payload.tool_choice),
@@ -45,7 +45,9 @@ export function anthropicMessagesToInteraction(payload) {
45
45
  ...(sessionId !== undefined ? { promptCacheKey: sessionId } : {}),
46
46
  };
47
47
  }
48
- function anthropicItems(value) {
48
+ // `declaredTools` resolves `tool_addition` references by name: the request's
49
+ // tools, then each tool an earlier `tool_addition` defined.
50
+ function anthropicItems(value, declaredTools) {
49
51
  if (!Array.isArray(value) || value.length === 0) {
50
52
  throw invalidRequest("messages must be a non-empty array.", "messages");
51
53
  }
@@ -58,11 +60,11 @@ function anthropicItems(value) {
58
60
  if (role !== "system" && role !== "user" && role !== "assistant") {
59
61
  throw invalidRequest(`Unsupported Anthropic message role '${role}'.`, `messages.${messageIndex}.role`);
60
62
  }
61
- appendAnthropicMessage(items, role, rawMessage.content, messageIndex);
63
+ appendAnthropicMessage(items, role, rawMessage.content, messageIndex, declaredTools);
62
64
  }
63
65
  return items;
64
66
  }
65
- function appendAnthropicMessage(items, role, value, messageIndex) {
67
+ function appendAnthropicMessage(items, role, value, messageIndex, declaredTools) {
66
68
  if (typeof value === "string") {
67
69
  items.push({
68
70
  type: "message",
@@ -242,17 +244,36 @@ function appendAnthropicMessage(items, role, value, messageIndex) {
242
244
  if (type === "tool_addition") {
243
245
  if (role !== "system")
244
246
  throw invalidRequest("tool_addition blocks require the system role.", param);
245
- const tool = isRecord(rawBlock.tool) ? rawBlock.tool : undefined;
246
- if (tool?.type !== "tool_definition") {
247
- throw invalidRequest(`${param}.tool must be a tool_definition.`, `${param}.tool`);
248
- }
249
- toolsAdded.push(anthropicTool(tool.definition, `${param}.tool.definition`));
247
+ toolsAdded.push(anthropicToolAddition(rawBlock.tool, `${param}.tool`, declaredTools));
250
248
  continue;
251
249
  }
252
250
  throw new HttpError(400, `Anthropic content block type '${type}' is not supported.`, "unsupported_content_block", param);
253
251
  }
254
252
  flushMessage();
255
253
  }
254
+ /* A `tool_addition` carries the tool by value (`tool_definition`) or names a
255
+ tool already declared (`tool_reference`), which Claude Code sends for a
256
+ deferred tool it loads mid-session. A referenced tool is added by value,
257
+ no longer deferred, so every provider path sees its full definition. */
258
+ function anthropicToolAddition(value, param, declaredTools) {
259
+ if (!isRecord(value))
260
+ throw invalidRequest(`${param} must be an object.`, param);
261
+ const type = requiredString(value.type, `${param}.type`);
262
+ if (type === "tool_definition") {
263
+ const tool = anthropicTool(value.definition, `${param}.definition`);
264
+ if (tool.kind !== "hosted" && tool.kind !== "server_tool")
265
+ declaredTools.set(tool.name, tool);
266
+ return tool;
267
+ }
268
+ if (type === "tool_reference") {
269
+ const name = requiredString(value.name, `${param}.name`);
270
+ const tool = declaredTools.get(name);
271
+ if (tool === undefined)
272
+ throw invalidRequest(`${param} references undeclared tool '${name}'.`, `${param}.name`);
273
+ return tool.kind === "function" ? { ...tool, deferLoading: undefined } : tool;
274
+ }
275
+ throw new HttpError(400, `Anthropic tool_addition tool type '${type}' is not supported.`, "unsupported_content_block", `${param}.type`);
276
+ }
256
277
  /* PDFs stay native documents; they route only to models that read PDFs.
257
278
  Text and content documents become ordinary parts so every model can read
258
279
  them. Title and context travel as a leading text part. Citations are not
@@ -19,6 +19,22 @@ export type StubGatewayOptions = {
19
19
  gatewayKey?: string;
20
20
  port?: number;
21
21
  allowHttpRedirectHosts?: string[];
22
+ redirectUri?: string;
23
+ };
24
+ /** A server app on the stub gateway: the settings an app's Dari Link calls take. */
25
+ export type StubLinkApp = {
26
+ gatewayUrl: string;
27
+ clientId: string;
28
+ clientSecret: string;
29
+ redirectUri: string;
30
+ };
31
+ export type StubConnectOptions = {
32
+ credentialIds?: string[];
33
+ deny?: boolean;
34
+ clients?: string[];
35
+ plans?: string[];
36
+ keyProviders?: string[];
37
+ grantId?: string;
22
38
  };
23
39
  /** What the approval page handed the app: a `web_message` post, or a redirect's query. */
24
40
  export type StubLinkMessage = {
@@ -46,6 +62,12 @@ export type StubGateway = {
46
62
  credentialIds?: string[];
47
63
  deny?: boolean;
48
64
  }): Promise<StubLinkMessage>;
65
+ app: StubLinkApp;
66
+ connect(options?: StubConnectOptions): Promise<{
67
+ code: string;
68
+ codeVerifier: string;
69
+ state: string;
70
+ }>;
49
71
  setState(state: StubState): void;
50
72
  stop(): Promise<void>;
51
73
  };
@@ -7,18 +7,28 @@
7
7
  * ```ts
8
8
  * import { startStubGateway } from "@mupt-ai/dari-gateway/self_host/stub_gateway";
9
9
  * const gateway = await startStubGateway({ plans: ["openai_codex"] });
10
- * // gateway.baseUrl, gateway.gatewayKey, gateway.planIds, gateway.calls; await gateway.stop();
10
+ * // Your app's Dari Link settings in the test: gateway.app.
11
+ * // The user clicks Connect with Dari and approves:
12
+ * const { code, codeVerifier } = await gateway.connect();
13
+ * // Send them to your server as your page does; then gateway.calls; await gateway.stop();
11
14
  * ```
12
15
  *
13
16
  * From any other test runner, as a process (`dari-gateway-stub`, see
14
17
  * stub_main.ts): it prints one JSON line with the same fields and serves the
15
18
  * recorded calls at `GET <controlUrl>/served`.
16
19
  *
17
- * Approval without a browser: `gateway.approve(authorizeUrl)` (or `POST
18
- * <controlUrl>/approve` with `{"url"}`) opens the approval page as the user
19
- * who connected the stand-in plans, ticks every plan the app can use (or
20
- * `credentialIds`), approves (or denies with `deny`), and returns what the
21
- * page hands the app:
20
+ * `gateway.app` is a server app registered on the gateway (a confidential
21
+ * client: `gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
22
+ * `gateway.connect()` (or `POST <controlUrl>/connect`) is its user approving
23
+ * it: it resolves with what `DariLink.open` hands your page, `{code,
24
+ * codeVerifier, state}`, or rejects with the `LinkError` it would (`deny`).
25
+ * `clients`, `plans`, `keyProviders`, and `grantId` are `DariLink.open`'s.
26
+ *
27
+ * To drive an approval for an app you registered yourself:
28
+ * `gateway.approve(authorizeUrl)` (or `POST <controlUrl>/approve` with
29
+ * `{"url"}`) opens the approval page as the user who connected the stand-in
30
+ * plans, ticks every plan the app can use (or `credentialIds`), approves (or
31
+ * denies with `deny`), and returns what the page hands the app:
22
32
  * `{message, targetOrigin}`, the `web_message` post or the redirect's query.
23
33
  * Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
24
34
  *
@@ -50,6 +60,7 @@ import { tmpdir } from "node:os";
50
60
  import { join } from "node:path";
51
61
  import { fileURLToPath } from "node:url";
52
62
  import { zstdDecompressSync } from "node:zlib";
63
+ import { authorizeUrl, LinkError } from "../link/client.js";
53
64
  import { linkUserCookie } from "../link/endpoints.js";
54
65
  import { SqliteLinkStore } from "../link/sqlite_store.js";
55
66
  import { secretBoxFromEnv } from "./secret_box.js";
@@ -68,6 +79,9 @@ export async function startStubGateway(options = {}) {
68
79
  let approve = async () => {
69
80
  throw new Error("The gateway is not up yet.");
70
81
  };
82
+ let connect = async () => {
83
+ throw new Error("The gateway is not up yet.");
84
+ };
71
85
  const provider = Bun.serve({
72
86
  port: 0,
73
87
  hostname: "127.0.0.1",
@@ -81,6 +95,24 @@ export async function startStubGateway(options = {}) {
81
95
  state = (await request.json());
82
96
  return Response.json({ state });
83
97
  }
98
+ if (pathname === "/connect" && request.method === "POST") {
99
+ // No body is the user sharing everything the app can use.
100
+ const body = ((await request.json().catch(() => null)) ?? {});
101
+ try {
102
+ const result = await connect({
103
+ ...(body.credential_ids ? { credentialIds: body.credential_ids } : {}),
104
+ ...(body.deny ? { deny: true } : {}),
105
+ ...(body.clients ? { clients: body.clients } : {}),
106
+ ...(body.plans ? { plans: body.plans } : {}),
107
+ ...(body.key_providers ? { keyProviders: body.key_providers } : {}),
108
+ ...(body.grant_id ? { grantId: body.grant_id } : {}),
109
+ });
110
+ return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
111
+ }
112
+ catch (error) {
113
+ return Response.json({ error: error instanceof LinkError ? error.code : String(error) }, { status: 400 });
114
+ }
115
+ }
84
116
  if (pathname === "/approve" && request.method === "POST") {
85
117
  const body = (await request.json());
86
118
  try {
@@ -206,6 +238,32 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
206
238
  messages.push(result);
207
239
  return result;
208
240
  };
241
+ const registered = await fetch(`${baseUrl}/v1/link/apps`, {
242
+ method: "POST",
243
+ headers: { authorization: `Bearer ${gatewayKey}`, "content-type": "application/json" },
244
+ body: JSON.stringify({
245
+ name: "Stub App",
246
+ redirect_uris: [options.redirectUri ?? "https://app.test/dari/callback"],
247
+ confidential: true,
248
+ }),
249
+ });
250
+ if (!registered.ok)
251
+ throw new Error(`The stub app was not registered:\n${await registered.text()}`);
252
+ const { client_id: clientId, client_secret: clientSecret } = (await registered.json());
253
+ const app = {
254
+ gatewayUrl: baseUrl,
255
+ clientId,
256
+ clientSecret,
257
+ redirectUri: options.redirectUri ?? "https://app.test/dari/callback",
258
+ };
259
+ connect = async ({ credentialIds, deny, ...request } = {}) => {
260
+ const { url, codeVerifier, state } = await authorizeUrl({ ...app, ...request, responseMode: "web_message" });
261
+ const { message } = await approve(url, { ...(credentialIds ? { credentialIds } : {}), ...(deny ? { deny } : {}) });
262
+ if (message.code === undefined) {
263
+ throw new LinkError(message.error ?? "invalid_request", message.error_description ?? "Dari Link was not approved.", 0);
264
+ }
265
+ return { code: message.code, codeVerifier, state };
266
+ };
209
267
  return {
210
268
  baseUrl,
211
269
  gatewayKey,
@@ -219,6 +277,8 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
219
277
  dbPath,
220
278
  messages,
221
279
  approve: (url, approveOptions) => approve(url, approveOptions),
280
+ app,
281
+ connect: (connectOptions) => connect(connectOptions),
222
282
  setState: (next) => {
223
283
  state = next;
224
284
  },
@@ -7,10 +7,14 @@
7
7
  * ```
8
8
  *
9
9
  * It prints one JSON line, `{"baseUrl", "gatewayKey", "planIds", "keyIds",
10
- * "userCookie", "controlUrl"}`, then serves until it is killed. The plans are the approval
11
- * page's user's: `userCookie` is the `Cookie` header that opens the page as them. `GET <controlUrl>/served`
10
+ * "userCookie", "controlUrl", "app"}`, then serves until it is killed. The plans are the approval
11
+ * page's user's: `userCookie` is the `Cookie` header that opens the page as them. `app` is a server
12
+ * app registered on the gateway (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
13
+ * `POST <controlUrl>/connect` (with `{"credential_ids"?, "deny"?, "clients"?, "plans"?,
14
+ * "key_providers"?, "grant_id"?}`, all optional) is its user approving it: it answers
15
+ * `{"code", "code_verifier", "state"}`, what Connect with Dari hands your page. `GET <controlUrl>/served`
12
16
  * answers `{"calls": [...]}`: every provider call so far, with its path,
13
- * model, thinking, and client headers. `POST <controlUrl>/approve` with
17
+ * model, thinking, and client headers. For an app you registered yourself, `POST <controlUrl>/approve` with
14
18
  * `{"url": <authorize URL>, "credential_ids"?, "deny"?}` goes through the
15
19
  * approval page and answers `{"message", "target_origin"}`, which `GET
16
20
  * <controlUrl>/messages` lists; `POST <controlUrl>/state` with `{"limited"?,
@@ -19,6 +23,7 @@
19
23
  * `openai_codex` and `anthropic_claude_code`), `--keys` (comma-separated
20
24
  * `anthropic`, `openai`, and `openrouter`: an API key of the plans' user for each), `--models` (the default
21
25
  * router's models), `--key` (the gateway key), `--port` (the gateway's port),
26
+ * `--redirect-uri` (the redirect URI `app` is registered with),
22
27
  * and `--allow-http-redirect-host` (repeatable: a host apps may register http
23
28
  * redirect URIs on, such as `*.example.ts.net`).
24
29
  */
@@ -45,6 +50,7 @@ if (port !== undefined && !/^\d+$/.test(port)) {
45
50
  console.error("--port takes a port number.");
46
51
  process.exit(2);
47
52
  }
53
+ const redirectUri = option("redirect-uri");
48
54
  const httpHosts = process.argv.flatMap((arg, index) => arg === "--allow-http-redirect-host" ? [process.argv[index + 1] ?? ""] : []);
49
55
  const gateway = await startStubGateway({
50
56
  ...(plans ? { plans: plans } : {}),
@@ -52,6 +58,7 @@ const gateway = await startStubGateway({
52
58
  ...(models ? { models } : {}),
53
59
  ...(gatewayKey ? { gatewayKey } : {}),
54
60
  ...(port ? { port: Number(port) } : {}),
61
+ ...(redirectUri ? { redirectUri } : {}),
55
62
  ...(httpHosts.length > 0 ? { allowHttpRedirectHosts: httpHosts } : {}),
56
63
  });
57
64
  console.log(JSON.stringify({
@@ -61,6 +68,7 @@ console.log(JSON.stringify({
61
68
  keyIds: gateway.keyIds,
62
69
  userCookie: gateway.userCookie,
63
70
  controlUrl: gateway.controlUrl,
71
+ app: gateway.app,
64
72
  }));
65
73
  for (const signal of ["SIGINT", "SIGTERM"]) {
66
74
  process.on(signal, () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.327",
3
+ "version": "1.0.328",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.327",
55
+ "@mupt-ai/dari-router": "1.0.328",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {