@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.
Files changed (127) hide show
  1. package/README.md +279 -2
  2. package/dist/context/provider_prompt_accounting.js +7 -0
  3. package/dist/context/routing_context.js +4 -1
  4. package/dist/http/handler.d.ts +2 -1
  5. package/dist/http/handler.js +12 -2
  6. package/dist/ingress/anthropic_messages.js +15 -3
  7. package/dist/ingress/chat_completions.js +6 -1
  8. package/dist/ingress/codex.js +2 -2
  9. package/dist/ingress/link.d.ts +24 -0
  10. package/dist/ingress/link.js +1519 -0
  11. package/dist/ingress/link_assets.d.ts +14 -0
  12. package/dist/ingress/link_assets.js +49 -0
  13. package/dist/ingress/link_font.d.ts +1 -0
  14. package/dist/ingress/link_font.js +6 -0
  15. package/dist/ingress/models.js +46 -2
  16. package/dist/interaction/types.d.ts +1 -0
  17. package/dist/link_client.d.ts +386 -0
  18. package/dist/link_client.js +579 -0
  19. package/dist/models/gateways.d.ts +2 -0
  20. package/dist/models/gateways.js +2 -0
  21. package/dist/models/link_errors.d.ts +30 -0
  22. package/dist/models/link_errors.js +120 -0
  23. package/dist/models/subscriptions.d.ts +8 -1
  24. package/dist/models/subscriptions.js +13 -2
  25. package/dist/platform/platform.d.ts +303 -1
  26. package/dist/protocol/input/router_model.d.ts +4 -0
  27. package/dist/protocol/input/router_model.js +31 -1
  28. package/dist/providers/execution.js +31 -5
  29. package/dist/providers/pi_options.js +57 -1
  30. package/dist/providers/provider_call.d.ts +4 -0
  31. package/dist/providers/provider_call.js +9 -2
  32. package/dist/providers/response_capture.d.ts +4 -1
  33. package/dist/providers/response_capture.js +81 -2
  34. package/dist/providers/stream_finalization.d.ts +1 -0
  35. package/dist/providers/subscription_limits.d.ts +15 -0
  36. package/dist/providers/subscription_limits.js +45 -0
  37. package/dist/runtime/explicit_model.js +16 -4
  38. package/dist/runtime/harness_identity/extract.js +20 -36
  39. package/dist/runtime/link_budget.d.ts +27 -0
  40. package/dist/runtime/link_budget.js +62 -0
  41. package/dist/runtime/link_grant_access.d.ts +7 -0
  42. package/dist/runtime/link_grant_access.js +99 -0
  43. package/dist/runtime/link_in_flight.d.ts +4 -0
  44. package/dist/runtime/link_in_flight.js +43 -0
  45. package/dist/runtime/prepare_routed_completion.js +5 -1
  46. package/dist/runtime/routed_runtime.js +8 -0
  47. package/dist/runtime/runtime_reporter.d.ts +1 -0
  48. package/dist/runtime/runtime_reporter.js +1 -0
  49. package/dist/self_host/config.d.ts +9 -0
  50. package/dist/self_host/config.js +11 -1
  51. package/dist/self_host/link_store.d.ts +167 -0
  52. package/dist/self_host/link_store.js +564 -0
  53. package/dist/self_host/main.d.ts +10 -3
  54. package/dist/self_host/main.js +19 -4
  55. package/dist/self_host/platform.d.ts +2 -2
  56. package/dist/self_host/platform.js +284 -10
  57. package/dist/self_host/resolve.d.ts +8 -0
  58. package/dist/self_host/resolve.js +146 -15
  59. package/dist/self_host/secret_box.d.ts +23 -0
  60. package/dist/self_host/secret_box.js +105 -0
  61. package/dist/self_host/stub_gateway.d.ts +60 -0
  62. package/dist/self_host/stub_gateway.js +397 -0
  63. package/dist/self_host/stub_main.d.ts +2 -0
  64. package/dist/self_host/stub_main.js +69 -0
  65. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  66. package/dist/self_host/subscription_test_gateway.js +25 -91
  67. package/dist/self_host/subscriptions/access.d.ts +5 -0
  68. package/dist/self_host/subscriptions/access.js +5 -1
  69. package/dist/self_host/subscriptions/http.js +8 -1
  70. package/dist/self_host/subscriptions/index.d.ts +5 -2
  71. package/dist/self_host/subscriptions/index.js +5 -2
  72. package/dist/self_host/subscriptions/store.d.ts +41 -16
  73. package/dist/self_host/subscriptions/store.js +136 -32
  74. package/dist/self_host/subscriptions/usage.d.ts +7 -0
  75. package/dist/self_host/subscriptions/usage.js +52 -0
  76. package/dist/telemetry/report.js +18 -0
  77. package/dist/types.d.ts +18 -0
  78. package/package.json +4 -3
  79. package/src/context/provider_prompt_accounting.ts +7 -0
  80. package/src/context/routing_context.ts +3 -1
  81. package/src/http/handler.ts +14 -2
  82. package/src/ingress/anthropic_messages.ts +19 -4
  83. package/src/ingress/chat_completions.ts +6 -1
  84. package/src/ingress/codex.ts +2 -2
  85. package/src/ingress/link.ts +1731 -0
  86. package/src/ingress/link_assets.ts +56 -0
  87. package/src/ingress/link_font.ts +9 -0
  88. package/src/ingress/models.ts +48 -2
  89. package/src/interaction/types.ts +4 -0
  90. package/src/link_client.ts +796 -0
  91. package/src/models/gateways.ts +3 -0
  92. package/src/models/link_errors.ts +157 -0
  93. package/src/models/subscriptions.ts +15 -1
  94. package/src/platform/platform.ts +330 -1
  95. package/src/protocol/input/router_model.ts +36 -1
  96. package/src/providers/execution.ts +31 -4
  97. package/src/providers/pi_options.ts +57 -1
  98. package/src/providers/provider_call.ts +20 -2
  99. package/src/providers/response_capture.ts +88 -2
  100. package/src/providers/stream_finalization.ts +1 -0
  101. package/src/providers/subscription_limits.ts +53 -0
  102. package/src/runtime/explicit_model.ts +21 -8
  103. package/src/runtime/harness_identity/extract.ts +21 -60
  104. package/src/runtime/link_budget.ts +75 -0
  105. package/src/runtime/link_grant_access.ts +116 -0
  106. package/src/runtime/link_in_flight.ts +46 -0
  107. package/src/runtime/prepare_routed_completion.ts +6 -1
  108. package/src/runtime/routed_runtime.ts +8 -0
  109. package/src/runtime/runtime_reporter.ts +3 -0
  110. package/src/self_host/config.ts +24 -1
  111. package/src/self_host/link_store.ts +782 -0
  112. package/src/self_host/main.ts +21 -4
  113. package/src/self_host/platform.ts +305 -11
  114. package/src/self_host/resolve.ts +172 -15
  115. package/src/self_host/secret_box.ts +112 -0
  116. package/src/self_host/stub_gateway.ts +497 -0
  117. package/src/self_host/stub_main.ts +72 -0
  118. package/src/self_host/subscription_test_gateway.ts +26 -95
  119. package/src/self_host/subscriptions/access.ts +10 -1
  120. package/src/self_host/subscriptions/http.ts +9 -1
  121. package/src/self_host/subscriptions/index.ts +6 -0
  122. package/src/self_host/subscriptions/store.ts +167 -36
  123. package/src/self_host/subscriptions/usage.ts +64 -0
  124. package/src/telemetry/report.ts +17 -1
  125. package/src/types.ts +26 -0
  126. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  127. package/dist/self_host/subscriptions/test_support.js +0 -34
@@ -0,0 +1,386 @@
1
+ /**
2
+ * A small Dari Link client for apps: register, send the user to approve,
3
+ * exchange the code, and call the gateway with tokens that refresh
4
+ * themselves. It uses only `fetch` and Web Crypto, so it runs in browsers,
5
+ * Node, Bun, and Deno.
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.
9
+ *
10
+ * ```ts
11
+ * import { DariLink } from "@mupt-ai/dari-gateway/link_client";
12
+ *
13
+ * button.onclick = async () => {
14
+ * const { code, codeVerifier } = await DariLink.open({ gatewayUrl, clientId, redirectUri });
15
+ * await fetch("/api/dari/exchange", { method: "POST", body: JSON.stringify({ code, codeVerifier }) });
16
+ * };
17
+ * ```
18
+ *
19
+ * Without a popup, send the user to the approval URL yourself:
20
+ *
21
+ * ```ts
22
+ * import { authorizeUrl, exchange, linkFetch } from "@mupt-ai/dari-gateway/link_client";
23
+ *
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", {
35
+ * method: "POST",
36
+ * headers: { "content-type": "application/json" },
37
+ * body: JSON.stringify({ model: "dari/routing", messages }),
38
+ * });
39
+ * ```
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.
48
+ */
49
+ export type LinkPlan = {
50
+ id: string;
51
+ kind: string;
52
+ title: string;
53
+ provider?: string;
54
+ model_prefix?: string;
55
+ plan: string;
56
+ label: string;
57
+ account_email: string | null;
58
+ serves: string;
59
+ unavailable_until: string | null;
60
+ usage: Array<{
61
+ window_minutes: number;
62
+ utilization: number;
63
+ resets_at: string;
64
+ }>;
65
+ state: "ready" | "plan_limit";
66
+ available_at: string | null;
67
+ models: LinkModel[];
68
+ };
69
+ export type LinkModel = {
70
+ id: string;
71
+ name: string;
72
+ };
73
+ export type LinkBudgetWindow = {
74
+ window_minutes: number;
75
+ max_tokens: number;
76
+ used_tokens: number;
77
+ resets_at: string | null;
78
+ };
79
+ export type LinkTokenSet = {
80
+ accessToken: string;
81
+ refreshToken: string;
82
+ expiresAt: number;
83
+ grantId: string | null;
84
+ scope: string;
85
+ budget: LinkBudgetWindow[];
86
+ state: "ready" | "budget_limit";
87
+ availableAt: string | null;
88
+ plans: LinkPlan[];
89
+ models: LinkModel[];
90
+ user: {
91
+ email: string | null;
92
+ name: string | null;
93
+ } | null;
94
+ manageUrl: string | null;
95
+ routes: boolean;
96
+ };
97
+ export type LinkChildToken = {
98
+ accessToken: string;
99
+ expiresAt: number;
100
+ models: Array<{
101
+ model: string;
102
+ thinking: string | null;
103
+ }>;
104
+ };
105
+ /**
106
+ * A refused Dari Link call. `code` is the most specific error code: an OAuth
107
+ * error such as `invalid_grant` (the grant is gone: the user must link
108
+ * again), `refresh_race`, or a gateway code such as `grant_revoked`. `detail`
109
+ * holds what came with it, such as `revoked_by` or `request_id`.
110
+ */
111
+ export declare class LinkError extends Error {
112
+ readonly code: string;
113
+ readonly status: number;
114
+ readonly detail: Record<string, unknown>;
115
+ constructor(code: string, message: string, status: number, detail?: Record<string, unknown>);
116
+ }
117
+ type Fetch = typeof fetch;
118
+ type Gateway = {
119
+ gatewayUrl: string;
120
+ fetch?: Fetch;
121
+ };
122
+ type Client = Gateway & {
123
+ clientId: string;
124
+ clientSecret?: string;
125
+ };
126
+ /**
127
+ * Register an app openly (RFC 7591). A public client gets a client id; with
128
+ * `confidential`, a server also gets its client secret, returned this once:
129
+ * keep it in your secret manager.
130
+ */
131
+ export declare function registerClient(args: Gateway & {
132
+ clientName: string;
133
+ redirectUris: string[];
134
+ confidential?: boolean;
135
+ }): Promise<{
136
+ clientId: string;
137
+ clientSecret?: string;
138
+ }>;
139
+ /**
140
+ * The approval URL to send the user to, with a fresh PKCE verifier and state.
141
+ * `clients` names the clients the app runs, such as `claude_code`, so the
142
+ * user can grant plans that serve only those. `plans` limits the page to
143
+ * those plan kinds, such as `openai_codex`. `purposes` says what the app does
144
+ * with each audience's plans, shown beside them. `grantId` (update mode)
145
+ * opens the page on that existing grant: the user changes its plans in place,
146
+ * its id and tokens stay, and the new code redeems for more tokens of it.
147
+ */
148
+ export declare function authorizeUrl(args: AuthorizeOptions): Promise<{
149
+ url: string;
150
+ codeVerifier: string;
151
+ state: string;
152
+ }>;
153
+ export type AuthorizeOptions = {
154
+ gatewayUrl: string;
155
+ clientId: string;
156
+ redirectUri: string;
157
+ state?: string;
158
+ clients?: string[];
159
+ plans?: string[];
160
+ keyProviders?: string[];
161
+ purposes?: {
162
+ any_app?: string;
163
+ claude_code?: string;
164
+ muse_code?: string;
165
+ };
166
+ grantId?: string;
167
+ responseMode?: "query" | "web_message";
168
+ };
169
+ /**
170
+ * A fresh PKCE pair and state, made on your server: keep `codeVerifier` (and
171
+ * `state`) with the user's session, and hand the browser only `codeChallenge`
172
+ * and `state` for `DariLink.open`. The verifier then never reaches the page,
173
+ * and the page needs no Web Crypto.
174
+ */
175
+ export declare function createAuthorization(state?: string): Promise<{
176
+ codeVerifier: string;
177
+ codeChallenge: string;
178
+ state: string;
179
+ }>;
180
+ type LinkPopup = {
181
+ closed: boolean;
182
+ close(): void;
183
+ location: {
184
+ href: string;
185
+ };
186
+ };
187
+ type LinkMessage = {
188
+ source: unknown;
189
+ origin: string;
190
+ data: unknown;
191
+ };
192
+ type LinkChannel = {
193
+ postMessage(data: unknown): void;
194
+ close(): void;
195
+ onmessage: ((event: {
196
+ data: unknown;
197
+ }) => void) | null;
198
+ };
199
+ export type LinkBrowser = {
200
+ open(url: string, target: string, features: string): LinkPopup | null;
201
+ addEventListener(type: "message", listener: (event: LinkMessage) => void): void;
202
+ removeEventListener(type: "message", listener: (event: LinkMessage) => void): void;
203
+ BroadcastChannel?: new (name: string) => LinkChannel;
204
+ location?: {
205
+ search: string;
206
+ };
207
+ close?(): void;
208
+ isSecureContext?: boolean;
209
+ screenX?: number;
210
+ screenY?: number;
211
+ outerWidth?: number;
212
+ outerHeight?: number;
213
+ };
214
+ /**
215
+ * The approval step the user reached in the popup: `sign_in`,
216
+ * `connect_subscription` (no plan to share yet), or `choose_plans`. A user who
217
+ * denies leaves at `denied`.
218
+ */
219
+ export type LinkStep = "sign_in" | "connect_subscription" | "choose_plans" | "denied";
220
+ /** Why the popup ended without a code, and the step the user left at (null before any). */
221
+ export type LinkExit = {
222
+ error: string;
223
+ step: LinkStep | null;
224
+ };
225
+ export type OpenLinkOptions = AuthorizeOptions & {
226
+ codeChallenge?: string;
227
+ fetch?: Fetch;
228
+ window?: LinkBrowser;
229
+ onEvent?: (step: LinkStep) => void;
230
+ onExit?: (exit: LinkExit) => void;
231
+ };
232
+ /**
233
+ * Open Dari's approval page in a popup and resolve with the code once the
234
+ * user approves. Call it from a click handler, so the browser allows the
235
+ * popup. Send `code` and `codeVerifier` to your server to `exchange`.
236
+ *
237
+ * The options may be a function returning them (a promise is fine): it is
238
+ * awaited only after the popup opens, so fetching a client id or state from
239
+ * your server first does not get the popup blocked.
240
+ *
241
+ * Rejects with a `LinkError`: `popup_blocked`, `popup_closed` when the user
242
+ * closes it, or the OAuth error the page returned, such as `access_denied`.
243
+ * The result is accepted only from the popup and from the gateway's approval
244
+ * origin, and only with the state this call made.
245
+ *
246
+ * A popup that signed the user in along the way can lose its link to this
247
+ * window; the approval then lands on your redirect URI inside the popup. Call
248
+ * `DariLink.callback()` on that page (or load `/v1/link/callback.js` there)
249
+ * and this call still resolves.
250
+ */
251
+ export declare function openLink(options: OpenLinkOptions | (() => OpenLinkOptions | Promise<OpenLinkOptions>), browserOverride?: LinkBrowser): Promise<{
252
+ code: string;
253
+ state: string;
254
+ codeVerifier: string | null;
255
+ }>;
256
+ /**
257
+ * On your redirect URI's page: hand an approval that arrived there in the
258
+ * popup to the window that called `DariLink.open`, and close the popup.
259
+ * Returns false when the page holds no Dari Link result.
260
+ */
261
+ export declare function completeLink(args?: {
262
+ window?: LinkBrowser;
263
+ }): boolean;
264
+ /** The Dari mark: a white turtle on a black disc, square, scalable. */
265
+ export declare const DARI_MARK_SVG: string;
266
+ type ButtonHost = {
267
+ innerHTML: string;
268
+ querySelector(selector: string): {
269
+ addEventListener(type: "click", listener: () => void): void;
270
+ } | null;
271
+ };
272
+ /**
273
+ * Render the standard "Connect with Dari" button into `container` and call
274
+ * `onClick` (which should call `DariLink.open`) when it is pressed. `dark`
275
+ * (the default) is for light pages: black button, white text; `light` is for
276
+ * dark pages. The button is 40px tall with the mark at 20px; see the README's
277
+ * button guidelines.
278
+ */
279
+ export declare function renderButton(container: ButtonHost, options: {
280
+ onClick: () => void;
281
+ theme?: "dark" | "light";
282
+ label?: string;
283
+ }): void;
284
+ /**
285
+ * `DariLink.open(...)` is the one call a "Connect with Dari" button makes;
286
+ * `DariLink.callback()` goes on the redirect URI's page; `DariLink.renderButton`
287
+ * draws the button.
288
+ */
289
+ export declare const DariLink: {
290
+ open: typeof openLink;
291
+ callback: typeof completeLink;
292
+ renderButton: typeof renderButton;
293
+ };
294
+ /** Redeem the code from the approval redirect for the grant's first tokens. */
295
+ export declare function exchange(args: Client & {
296
+ redirectUri: string;
297
+ code: string;
298
+ codeVerifier: string;
299
+ }): Promise<LinkTokenSet>;
300
+ /**
301
+ * A new access token. A public client's refresh token rotates: the one passed
302
+ * in stops working. A confidential client's stays the same.
303
+ */
304
+ export declare function refresh(args: Client & {
305
+ refreshToken: string;
306
+ }): Promise<LinkTokenSet>;
307
+ /**
308
+ * Mint a child token for a sandbox or worker, from the grant's access token
309
+ * or from your token storage (refreshed as `linkFetch` does): it serves only
310
+ * its models (each at one thinking level when pinned) for up to twelve
311
+ * hours, cannot refresh, mint, or read the grant, and dies with the grant.
312
+ */
313
+ export declare function childToken(args: Client & ({
314
+ accessToken: string;
315
+ } | TokenStorage) & {
316
+ models: Array<{
317
+ model: string;
318
+ thinking?: string;
319
+ }>;
320
+ expiresIn?: number;
321
+ tags?: Record<string, string>;
322
+ now?: () => number;
323
+ }): Promise<LinkChildToken>;
324
+ /** End the grant a token belongs to, as when the user disconnects in the app. */
325
+ export declare function revoke(args: Client & {
326
+ token: string;
327
+ }): Promise<void>;
328
+ /**
329
+ * A fetch for the gateway on one grant: paths resolve against `gatewayUrl`
330
+ * and the access token is attached. Your storage is the source of truth: the
331
+ * tokens are read with `loadTokens` on every call, refreshed shortly before
332
+ * they expire and once after a 401 for an expired token, and every new token
333
+ * set reaches `saveTokens` before use. Concurrent calls in a process share
334
+ * one refresh. A grant that is gone throws LinkError with code
335
+ * `invalid_grant` from the refresh, and a revoked access token's 401
336
+ * (`grant_revoked`) is returned as it is: either way the user is unlinked and
337
+ * must link again. With no tokens stored it throws `not_linked`.
338
+ */
339
+ export declare function linkFetch(args: Client & TokenStorage & {
340
+ now?: () => number;
341
+ }): (input: string, init?: RequestInit) => Promise<Response>;
342
+ export type LinkUsageTotals = {
343
+ requests: number;
344
+ errors: number;
345
+ input_tokens: number;
346
+ output_tokens: number;
347
+ cache_read_tokens: number;
348
+ cache_write_tokens: number;
349
+ };
350
+ export type LinkUsage = LinkUsageTotals & {
351
+ complete_through: string | null;
352
+ by_model: Array<LinkUsageTotals & {
353
+ model: string;
354
+ thinking: string | null;
355
+ }>;
356
+ by_tag?: Array<LinkUsageTotals & {
357
+ value: string | null;
358
+ }>;
359
+ };
360
+ /**
361
+ * What the grant's requests used, child tokens' included: only requests
362
+ * carrying every given tag (X-Dari-Tags or a child token's tags), received
363
+ * in [since, until), and with `groupByTag` also totalled per value of that
364
+ * tag. Pass the `linkFetch` your app already uses as `fetcher` so this shares
365
+ * its refresh; otherwise pass the client and token storage.
366
+ */
367
+ export declare function usage(args: ({
368
+ fetcher: (input: string, init?: RequestInit) => Promise<Response>;
369
+ } | (Client & TokenStorage & {
370
+ now?: () => number;
371
+ })) & {
372
+ tags?: Record<string, string>;
373
+ since?: Date;
374
+ until?: Date;
375
+ groupByTag?: string;
376
+ }): Promise<LinkUsage>;
377
+ /**
378
+ * Where an app keeps one grant's tokens. `loadTokens` returns null when the
379
+ * user has not linked (or unlinked): calls then throw LinkError `not_linked`
380
+ * without reaching the gateway.
381
+ */
382
+ export type TokenStorage = {
383
+ loadTokens: () => LinkTokenSet | null | Promise<LinkTokenSet | null>;
384
+ saveTokens: (tokens: LinkTokenSet) => void | Promise<void>;
385
+ };
386
+ export {};