@mupt-ai/dari-gateway 1.0.367 → 1.0.368
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 +4 -3
- package/dist/link/client.d.ts +3 -1
- package/dist/link/client.js +4 -1
- package/dist/link/endpoints.js +33 -5
- package/dist/protocol/input/chat_completions.js +9 -13
- package/dist/protocol/input/chat_completions_validation.js +2 -7
- package/dist/protocol/input/openai_responses.js +3 -3
- package/dist/self_host/stub_gateway.d.ts +1 -0
- package/dist/self_host/stub_gateway.js +7 -6
- package/dist/self_host/stub_main.js +1 -1
- package/package.json +2 -2
- package/src/link/client.ts +7 -1
- package/src/link/endpoints.ts +38 -5
- package/src/protocol/input/chat_completions.ts +8 -18
- package/src/protocol/input/chat_completions_validation.ts +2 -9
- package/src/protocol/input/openai_responses.ts +3 -8
- package/src/self_host/stub_gateway.ts +12 -7
- package/src/self_host/stub_main.ts +1 -1
package/README.md
CHANGED
|
@@ -157,7 +157,7 @@ Dari Link lets another app send one user's model requests through the gateway on
|
|
|
157
157
|
|
|
158
158
|
**Which plans serve which apps.** A ChatGPT plan (`openai_codex`) serves any app, including a plain OpenAI `chat/completions` or Responses client, through the Codex backend. A Claude Pro/Max/Ultra plan (`anthropic_claude_code`) serves only Claude Code itself, and a Muse Code plan only Muse Code; the gateway never presents another app as those clients. An OpenCode Go plan (`opencode_go`) serves any app its `opencode-go` models, and Grok (`xai_grok`) and Vercel Token Pass (`vercel_token_pass`, a pasted Token Pass key that serves Vercel AI Gateway's featured models) plans serve any app theirs. So an app that calls the API itself needs the user to grant one of those plans, or an API key. The approval page offers only what the app can use: a Claude or Muse plan appears when the app runs Claude Code or Muse Code itself and says so with `client` on the authorize request.
|
|
159
159
|
|
|
160
|
-
**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
|
|
160
|
+
**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 one per provider with an app, or several when the app passes `allow_pooling=true`.
|
|
161
161
|
|
|
162
162
|
**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.
|
|
163
163
|
|
|
@@ -222,6 +222,7 @@ The gateway refuses a model the grant cannot serve, a plan at its limit, a spent
|
|
|
222
222
|
- `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.
|
|
223
223
|
- `plans`: the plan kinds to offer, such as `plans=openai_codex`; the page lists only those.
|
|
224
224
|
- `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.
|
|
225
|
+
- `allow_pooling=true` (`allowPooling` in the client): the user may share several accounts of one provider, such as two ChatGPT plans, which Dari pools. By default they share at most one per plan kind or API key provider: the page ticks the first of each, ticking another unticks it, and an approval with two is refused.
|
|
225
226
|
- `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.
|
|
226
227
|
- `grant_id`: update mode (above).
|
|
227
228
|
|
|
@@ -318,7 +319,7 @@ A sandbox given a child token needs to reach only the gateway's host (for hosted
|
|
|
318
319
|
|
|
319
320
|
Error text replaces anything shaped like an `sk-` key with `sk-…`, and responses replace the serving plan's own credential wherever it appears.
|
|
320
321
|
|
|
321
|
-
**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.
|
|
322
|
+
**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`, `keyProviders`, `purposes`, `allowPooling`, and `grantId`). Every call takes `clientSecret` for a confidential client.
|
|
322
323
|
|
|
323
324
|
`linkFetch`, `grant`, `childToken`, and `usage` take one grant's tokens in either of two ways:
|
|
324
325
|
|
|
@@ -409,7 +410,7 @@ A child token is simpler still when the agent runs somewhere you control: give t
|
|
|
409
410
|
|
|
410
411
|
**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.
|
|
411
412
|
|
|
412
|
-
**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`.
|
|
413
|
+
**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?, allowPooling?, grantId? })` is its user approving it (sharing what the page ticks unless `credentialIds`): 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`.
|
|
413
414
|
|
|
414
415
|
## Embed
|
|
415
416
|
|
package/dist/link/client.d.ts
CHANGED
|
@@ -147,7 +147,8 @@ export declare function registerClient(args: Gateway & {
|
|
|
147
147
|
* `clients` names the clients the app runs, such as `claude_code`, so the
|
|
148
148
|
* user can grant plans that serve only those. `plans` limits the page to
|
|
149
149
|
* those plan kinds, such as `openai_codex`, or `"supported"`. `purposes` says what the app does
|
|
150
|
-
* with each audience's plans, shown beside them.
|
|
150
|
+
* with each audience's plans, shown beside them. The user shares at most one
|
|
151
|
+
* account per provider unless `allowPooling`. `grantId` (update mode)
|
|
151
152
|
* opens the page on that existing grant: the user changes its plans in place,
|
|
152
153
|
* its id and tokens stay, and the new code redeems for more tokens of it.
|
|
153
154
|
*/
|
|
@@ -183,6 +184,7 @@ export type AuthorizeOptions = {
|
|
|
183
184
|
claude_code?: string;
|
|
184
185
|
muse_code?: string;
|
|
185
186
|
};
|
|
187
|
+
allowPooling?: boolean;
|
|
186
188
|
grantId?: string;
|
|
187
189
|
responseMode?: "query" | "web_message";
|
|
188
190
|
};
|
package/dist/link/client.js
CHANGED
|
@@ -102,7 +102,8 @@ export async function registerClient(args) {
|
|
|
102
102
|
* `clients` names the clients the app runs, such as `claude_code`, so the
|
|
103
103
|
* user can grant plans that serve only those. `plans` limits the page to
|
|
104
104
|
* those plan kinds, such as `openai_codex`, or `"supported"`. `purposes` says what the app does
|
|
105
|
-
* with each audience's plans, shown beside them.
|
|
105
|
+
* with each audience's plans, shown beside them. The user shares at most one
|
|
106
|
+
* account per provider unless `allowPooling`. `grantId` (update mode)
|
|
106
107
|
* opens the page on that existing grant: the user changes its plans in place,
|
|
107
108
|
* its id and tokens stay, and the new code redeems for more tokens of it.
|
|
108
109
|
*/
|
|
@@ -128,6 +129,7 @@ export async function createLinkToken(args) {
|
|
|
128
129
|
...(args.clients?.length ? { client: args.clients } : {}),
|
|
129
130
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders } : {}),
|
|
130
131
|
...(args.purposes ? { purposes: args.purposes } : {}),
|
|
132
|
+
...(args.allowPooling ? { allow_pooling: true } : {}),
|
|
131
133
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
132
134
|
}),
|
|
133
135
|
});
|
|
@@ -159,6 +161,7 @@ function authorizationUrl(args) {
|
|
|
159
161
|
...(args.clients?.length ? { client: args.clients.join(" ") } : {}),
|
|
160
162
|
...(args.plans?.length ? { plans: [args.plans].flat().join(" ") } : {}),
|
|
161
163
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders.join(" ") } : {}),
|
|
164
|
+
...(args.allowPooling ? { allow_pooling: "true" } : {}),
|
|
162
165
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
163
166
|
...Object.fromEntries(Object.entries(args.purposes ?? {}).flatMap(([audience, purpose]) => purpose ? [[`purpose_${audience}`, purpose]] : [])),
|
|
164
167
|
}).toString();
|
package/dist/link/endpoints.js
CHANGED
|
@@ -1000,8 +1000,8 @@ function oauthError(error, description, status = 400, headers = {}, errorCode) {
|
|
|
1000
1000
|
* secret alone: no state or PKCE for the app to keep. JSON body:
|
|
1001
1001
|
* `client_id`, `secret` (or HTTP Basic), and optionally `redirect_uri` (one
|
|
1002
1002
|
* the app registered; default its first), `plans`, `client`, `key_providers`
|
|
1003
|
-
* (arrays), `purposes` ({ any_app, claude_code, muse_code }),
|
|
1004
|
-
* for update mode.
|
|
1003
|
+
* (arrays), `purposes` ({ any_app, claude_code, muse_code }), `allow_pooling`
|
|
1004
|
+
* (true), and `grant_id` for update mode.
|
|
1005
1005
|
*/
|
|
1006
1006
|
async function createLinkToken(link, request) {
|
|
1007
1007
|
let body;
|
|
@@ -1027,6 +1027,7 @@ async function createLinkToken(link, request) {
|
|
|
1027
1027
|
...(list("plans") ? { plans: list("plans") } : {}),
|
|
1028
1028
|
...(list("client") ? { client: list("client") } : {}),
|
|
1029
1029
|
...(list("key_providers") ? { key_providers: list("key_providers") } : {}),
|
|
1030
|
+
...(body.allow_pooling === true ? { allow_pooling: "true" } : {}),
|
|
1030
1031
|
...(typeof body.grant_id === "string" ? { grant_id: body.grant_id } : {}),
|
|
1031
1032
|
...Object.fromEntries(PLAN_AUDIENCES.flatMap((audience) => typeof purposes[audience] === "string" ? [[`purpose_${audience}`, purposes[audience]]] : [])),
|
|
1032
1033
|
};
|
|
@@ -1140,6 +1141,10 @@ async function authorizeRequest(link, params) {
|
|
|
1140
1141
|
if (purpose)
|
|
1141
1142
|
purposes[audience] = purpose.slice(0, MAX_PURPOSE_CHARS);
|
|
1142
1143
|
}
|
|
1144
|
+
const allowPooling = params.get("allow_pooling");
|
|
1145
|
+
if (allowPooling !== null && allowPooling !== "true" && allowPooling !== "false") {
|
|
1146
|
+
return badRequest("allow_pooling is true or false.");
|
|
1147
|
+
}
|
|
1143
1148
|
const grantId = params.get("grant_id");
|
|
1144
1149
|
if (grantId !== null && !GRANT_ID.test(grantId)) {
|
|
1145
1150
|
return badRequest("grant_id names one of the user's grants for this app.");
|
|
@@ -1154,6 +1159,7 @@ async function authorizeRequest(link, params) {
|
|
|
1154
1159
|
plans: plans.length === 0 ? null : plans,
|
|
1155
1160
|
keyProviders: keyProviders.length === 0 ? null : keyProviders,
|
|
1156
1161
|
purposes,
|
|
1162
|
+
allowPooling: allowPooling === "true",
|
|
1157
1163
|
grantId,
|
|
1158
1164
|
};
|
|
1159
1165
|
}
|
|
@@ -1288,6 +1294,11 @@ async function authorizeSubmit(link, request, form) {
|
|
|
1288
1294
|
if (!credentialIds.every((id) => usable.has(id))) {
|
|
1289
1295
|
return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
|
|
1290
1296
|
}
|
|
1297
|
+
const pooled = authorize.allowPooling ? undefined : subscriptions.find((subscription, index) => credentialIds.includes(subscription.id)
|
|
1298
|
+
&& subscriptions.slice(0, index).some((other) => credentialIds.includes(other.id) && pool(other) === pool(subscription)));
|
|
1299
|
+
if (pooled !== undefined) {
|
|
1300
|
+
return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} uses one account per provider: choose one ${planName(pooled)}${pooled.apiKeyProvider === undefined ? " account" : ""}.`);
|
|
1301
|
+
}
|
|
1291
1302
|
const limits = limitsFromForm(form, credentialIds);
|
|
1292
1303
|
if (limits === null)
|
|
1293
1304
|
return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
|
|
@@ -1775,8 +1786,13 @@ function providerPage(authorize, connect, error) {
|
|
|
1775
1786
|
function choosePage(authorize, session, subscriptions, current, error) {
|
|
1776
1787
|
const app = escapeHtml(authorize.app.name);
|
|
1777
1788
|
const plans = shareable(authorize, subscriptions);
|
|
1778
|
-
// A new connection starts with every plan ticked; an update, with the plans
|
|
1779
|
-
|
|
1789
|
+
// A new connection starts with every plan ticked; an update, with the plans
|
|
1790
|
+
// it shares now. Without pooling, only the first of each provider's, so an
|
|
1791
|
+
// update of a grant made with pooling saves as it opens.
|
|
1792
|
+
const candidates = plans.filter((plan) => current === null || current.credentialIds.includes(plan.id));
|
|
1793
|
+
const ticked = new Set(candidates
|
|
1794
|
+
.filter((plan, index) => authorize.allowPooling || !candidates.slice(0, index).some((other) => pool(other) === pool(plan)))
|
|
1795
|
+
.map((plan) => plan.id));
|
|
1780
1796
|
return pane(authorize, {
|
|
1781
1797
|
title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
|
|
1782
1798
|
step: "choose_plans",
|
|
@@ -1798,8 +1814,14 @@ ${plans.map((plan) => {
|
|
|
1798
1814
|
<p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit or yours.</p>`,
|
|
1799
1815
|
});
|
|
1800
1816
|
}
|
|
1817
|
+
// Plans and keys of one pool: one kind of plan, or one provider's API keys.
|
|
1818
|
+
function pool(subscription) {
|
|
1819
|
+
return subscription.apiKeyProvider === undefined ? subscription.provider : `api_key:${subscription.apiKeyProvider}`;
|
|
1820
|
+
}
|
|
1801
1821
|
function planOption(authorize, subscription, ticked) {
|
|
1802
|
-
|
|
1822
|
+
// Without pooling, ticking one of a pool unticks the rest (see `page`).
|
|
1823
|
+
const pooled = authorize.allowPooling ? "" : ` data-pool="${escapeHtml(pool(subscription))}"`;
|
|
1824
|
+
const box = `<input type="checkbox"${pooled} name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
|
|
1803
1825
|
if (subscription.apiKeyProvider !== undefined) {
|
|
1804
1826
|
return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key · ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
|
|
1805
1827
|
}
|
|
@@ -1842,6 +1864,7 @@ function authorizeFields(authorize) {
|
|
|
1842
1864
|
...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
|
|
1843
1865
|
...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
|
|
1844
1866
|
...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
|
|
1867
|
+
...(authorize.allowPooling ? { allow_pooling: "true" } : {}),
|
|
1845
1868
|
...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
|
|
1846
1869
|
...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
|
|
1847
1870
|
};
|
|
@@ -1878,6 +1901,11 @@ function page(title, body, options = {}) {
|
|
|
1878
1901
|
const button = event.submitter;
|
|
1879
1902
|
if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
|
|
1880
1903
|
setTimeout(() => { button.disabled = true; button.setAttribute("aria-busy", "true"); button.prepend(Object.assign(document.createElement("span"), { className: "spin" })); });
|
|
1904
|
+
});
|
|
1905
|
+
document.addEventListener("change", (event) => {
|
|
1906
|
+
const box = event.target;
|
|
1907
|
+
if (!(box instanceof HTMLInputElement) || !box.checked || !box.dataset.pool) return;
|
|
1908
|
+
for (const other of box.form?.querySelectorAll("input[data-pool]") ?? []) if (other !== box && other.dataset.pool === box.dataset.pool) other.checked = false;
|
|
1881
1909
|
});</script>`;
|
|
1882
1910
|
options = { ...options, scriptNonce: busyNonce };
|
|
1883
1911
|
if (options.event !== undefined) {
|
|
@@ -25,7 +25,7 @@ export function internalChatCompletionsToInteraction(request) {
|
|
|
25
25
|
});
|
|
26
26
|
continue;
|
|
27
27
|
}
|
|
28
|
-
const reasoningItems = chatReasoningItems(message
|
|
28
|
+
const reasoningItems = chatReasoningItems(message);
|
|
29
29
|
items.push(...reasoningItems);
|
|
30
30
|
items.push({
|
|
31
31
|
type: "message",
|
|
@@ -129,19 +129,19 @@ function hostedToolCallStatus(value, param) {
|
|
|
129
129
|
}
|
|
130
130
|
throw new HttpError(400, `${param} is not supported.`, "invalid_request_error", param);
|
|
131
131
|
}
|
|
132
|
-
function chatReasoningItems(message
|
|
132
|
+
function chatReasoningItems(message) {
|
|
133
133
|
if (message.role !== "assistant")
|
|
134
134
|
return [];
|
|
135
135
|
const readable = [message.reasoning_content, message.reasoning, message.reasoning_text]
|
|
136
136
|
.find((value) => typeof value === "string" && value.length > 0);
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
137
|
+
// A conversation begun on another provider carries that provider's reasoning
|
|
138
|
+
// details. They name no provider or model, so they cannot be replayed; the
|
|
139
|
+
// turn keeps its readable reasoning and the conversation continues.
|
|
140
|
+
const continuations = (message.reasoning_details ?? []).flatMap((detail) => {
|
|
141
|
+
if (detail.type !== "reasoning.encrypted" || typeof detail.data !== "string")
|
|
142
|
+
return [];
|
|
141
143
|
const continuation = decodeUntrustedProviderContinuationState(detail.data);
|
|
142
|
-
|
|
143
|
-
throw invalidChatContinuation(messageIndex, detailIndex);
|
|
144
|
-
return continuation;
|
|
144
|
+
return continuation ? [continuation] : [];
|
|
145
145
|
});
|
|
146
146
|
if (continuations.length === 0) {
|
|
147
147
|
return readable
|
|
@@ -156,10 +156,6 @@ function chatReasoningItems(message, messageIndex) {
|
|
|
156
156
|
continuation,
|
|
157
157
|
}));
|
|
158
158
|
}
|
|
159
|
-
function invalidChatContinuation(messageIndex, detailIndex) {
|
|
160
|
-
const param = `messages.${messageIndex}.reasoning_details.${detailIndex}.data`;
|
|
161
|
-
return new HttpError(400, `${param} must be a Dari provider continuation envelope; raw provider state has no recoverable provider/model provenance.`, "invalid_provider_continuation_state", param);
|
|
162
|
-
}
|
|
163
159
|
function contentShape(content) {
|
|
164
160
|
if (content === undefined)
|
|
165
161
|
return "absent";
|
|
@@ -69,13 +69,8 @@ function validateMessageReasoning(message, messageIndex) {
|
|
|
69
69
|
throw new HttpError(400, `messages[${messageIndex}].reasoning_details must be an array on an assistant message.`, "invalid_request_error", `messages.${messageIndex}.reasoning_details`);
|
|
70
70
|
}
|
|
71
71
|
for (const [detailIndex, detail] of message.reasoning_details.entries()) {
|
|
72
|
-
if (!isRecord(detail)
|
|
73
|
-
|
|
74
|
-
typeof detail.id !== "string" ||
|
|
75
|
-
!detail.id ||
|
|
76
|
-
typeof detail.data !== "string" ||
|
|
77
|
-
!detail.data) {
|
|
78
|
-
throw new HttpError(400, `messages[${messageIndex}].reasoning_details[${detailIndex}] is not a supported encrypted reasoning detail.`, "invalid_request_error", `messages.${messageIndex}.reasoning_details.${detailIndex}`);
|
|
72
|
+
if (!isRecord(detail)) {
|
|
73
|
+
throw new HttpError(400, `messages[${messageIndex}].reasoning_details[${detailIndex}] must be an object.`, "invalid_request_error", `messages.${messageIndex}.reasoning_details.${detailIndex}`);
|
|
79
74
|
}
|
|
80
75
|
}
|
|
81
76
|
}
|
|
@@ -307,11 +307,11 @@ function clientTurnId(value) {
|
|
|
307
307
|
: {};
|
|
308
308
|
}
|
|
309
309
|
function reasoningItem(value) {
|
|
310
|
+
// A conversation begun on OpenAI directly carries raw ciphertext. It names
|
|
311
|
+
// no provider or model, so it cannot be replayed; the item keeps its
|
|
312
|
+
// readable summary and the conversation continues.
|
|
310
313
|
const encoded = optionalString(value.encrypted_content, "input.reasoning.encrypted_content");
|
|
311
314
|
const continuation = encoded ? decodeUntrustedProviderContinuationState(encoded) : null;
|
|
312
|
-
if (encoded && !continuation) {
|
|
313
|
-
throw new HttpError(400, "input.reasoning.encrypted_content must be a Dari provider continuation envelope; raw provider ciphertext has no recoverable provider/model provenance.", "invalid_provider_continuation_state", "input.reasoning.encrypted_content");
|
|
314
|
-
}
|
|
315
315
|
return {
|
|
316
316
|
type: "reasoning",
|
|
317
317
|
id: optionalString(value.id, "input.reasoning.id"),
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
* `gateway.connect()` (or `POST <controlUrl>/connect`) is its user approving
|
|
23
23
|
* it: it resolves with what `DariLink.open` hands your page, `{code,
|
|
24
24
|
* codeVerifier, state}`, or rejects with the `LinkError` it would (`deny`).
|
|
25
|
-
* `clients`, `plans`, `keyProviders`, and `grantId` are `DariLink.open`'s.
|
|
25
|
+
* `clients`, `plans`, `keyProviders`, `allowPooling`, and `grantId` are `DariLink.open`'s.
|
|
26
26
|
*
|
|
27
27
|
* To drive an approval for an app you registered yourself:
|
|
28
28
|
* `gateway.approve(authorizeUrl)` (or `POST <controlUrl>/approve` with
|
|
29
29
|
* `{"url"}`) opens the approval page as the user who connected the stand-in
|
|
30
|
-
* plans,
|
|
30
|
+
* plans, keeps the plans the page ticks (or ticks `credentialIds`), approves (or
|
|
31
31
|
* denies with `deny`), and returns what the page hands the app:
|
|
32
32
|
* `{message, targetOrigin}`, the `web_message` post or the redirect's query.
|
|
33
33
|
* Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
|
|
@@ -123,6 +123,7 @@ export async function startStubGateway(options = {}) {
|
|
|
123
123
|
...(body.clients ? { clients: body.clients } : {}),
|
|
124
124
|
...(body.plans ? { plans: body.plans } : {}),
|
|
125
125
|
...(body.key_providers ? { keyProviders: body.key_providers } : {}),
|
|
126
|
+
...(body.allow_pooling ? { allowPooling: true } : {}),
|
|
126
127
|
...(body.grant_id ? { grantId: body.grant_id } : {}),
|
|
127
128
|
});
|
|
128
129
|
return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
|
|
@@ -336,8 +337,8 @@ ${keys.filter((key) => key === "openrouter").map((key) => ` ${key}:\n baseUr
|
|
|
336
337
|
},
|
|
337
338
|
};
|
|
338
339
|
}
|
|
339
|
-
// The approval page as the plans' user goes through it:
|
|
340
|
-
// approve or deny; then what the page hands the app.
|
|
340
|
+
// The approval page as the plans' user goes through it: keep the plans it
|
|
341
|
+
// ticks (or tick the given ones), approve or deny; then what the page hands the app.
|
|
341
342
|
async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
342
343
|
const url = new URL(authorizeUrl);
|
|
343
344
|
const page = `${baseUrl}${url.pathname}${url.search}`;
|
|
@@ -348,7 +349,7 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
348
349
|
throw new Error("The approval page offers this app nothing to approve: none of the stub user's plans or keys serves it. "
|
|
349
350
|
+ 'A Claude Code plan serves only an app that asks for clients: ["claude_code"].');
|
|
350
351
|
}
|
|
351
|
-
const
|
|
352
|
+
const ticked = [...choose.matchAll(/name="credential_id" value="([^"]+)"[^>]* checked>/g)].map((match) => match[1]);
|
|
352
353
|
const decided = await fetch(`${baseUrl}${url.pathname}`, {
|
|
353
354
|
method: "POST",
|
|
354
355
|
redirect: "manual",
|
|
@@ -357,7 +358,7 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
357
358
|
...params,
|
|
358
359
|
["csrf", csrf],
|
|
359
360
|
["decision", options.deny ? "deny" : "approve"],
|
|
360
|
-
...(options.credentialIds ??
|
|
361
|
+
...(options.credentialIds ?? ticked).map((id) => ["credential_id", id]),
|
|
361
362
|
]),
|
|
362
363
|
});
|
|
363
364
|
const location = decided.headers.get("location");
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* page's user's: `userCookie` is the `Cookie` header that opens the page as them. `app` is a server
|
|
12
12
|
* app registered on the gateway (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
|
|
13
13
|
* `POST <controlUrl>/connect` (with `{"credential_ids"?, "deny"?, "clients"?, "plans"?,
|
|
14
|
-
* "key_providers"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
14
|
+
* "key_providers"?, "allow_pooling"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
15
15
|
* `{"code", "code_verifier", "state"}`, what Connect with Dari hands your page. `GET <controlUrl>/served`
|
|
16
16
|
* answers `{"calls": [...]}`: every provider call so far, with its path,
|
|
17
17
|
* model, thinking, and client headers. For an app you registered yourself, `POST <controlUrl>/approve` with
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.368",
|
|
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.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.368",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
package/src/link/client.ts
CHANGED
|
@@ -182,7 +182,8 @@ export async function registerClient(
|
|
|
182
182
|
* `clients` names the clients the app runs, such as `claude_code`, so the
|
|
183
183
|
* user can grant plans that serve only those. `plans` limits the page to
|
|
184
184
|
* those plan kinds, such as `openai_codex`, or `"supported"`. `purposes` says what the app does
|
|
185
|
-
* with each audience's plans, shown beside them.
|
|
185
|
+
* with each audience's plans, shown beside them. The user shares at most one
|
|
186
|
+
* account per provider unless `allowPooling`. `grantId` (update mode)
|
|
186
187
|
* opens the page on that existing grant: the user changes its plans in place,
|
|
187
188
|
* its id and tokens stay, and the new code redeems for more tokens of it.
|
|
188
189
|
*/
|
|
@@ -213,6 +214,7 @@ export async function createLinkToken(
|
|
|
213
214
|
...(args.clients?.length ? { client: args.clients } : {}),
|
|
214
215
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders } : {}),
|
|
215
216
|
...(args.purposes ? { purposes: args.purposes } : {}),
|
|
217
|
+
...(args.allowPooling ? { allow_pooling: true } : {}),
|
|
216
218
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
217
219
|
}),
|
|
218
220
|
});
|
|
@@ -233,6 +235,9 @@ export type AuthorizeOptions = {
|
|
|
233
235
|
// ["anthropic", "openrouter"]; omit to offer every one.
|
|
234
236
|
keyProviders?: string[];
|
|
235
237
|
purposes?: { any_app?: string; claude_code?: string; muse_code?: string };
|
|
238
|
+
// Let the user share several accounts of one provider, such as two Claude
|
|
239
|
+
// plans, which Dari pools; by default they share at most one per provider.
|
|
240
|
+
allowPooling?: boolean;
|
|
236
241
|
grantId?: string;
|
|
237
242
|
// `web_message` posts the result to the window that opened the page.
|
|
238
243
|
responseMode?: "query" | "web_message";
|
|
@@ -264,6 +269,7 @@ function authorizationUrl(args: AuthorizeOptions & { codeChallenge: string; stat
|
|
|
264
269
|
...(args.clients?.length ? { client: args.clients.join(" ") } : {}),
|
|
265
270
|
...(args.plans?.length ? { plans: [args.plans].flat().join(" ") } : {}),
|
|
266
271
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders.join(" ") } : {}),
|
|
272
|
+
...(args.allowPooling ? { allow_pooling: "true" } : {}),
|
|
267
273
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
268
274
|
...Object.fromEntries(
|
|
269
275
|
Object.entries(args.purposes ?? {}).flatMap(([audience, purpose]) => purpose ? [[`purpose_${audience}`, purpose]] : []),
|
package/src/link/endpoints.ts
CHANGED
|
@@ -1118,8 +1118,8 @@ function oauthError(
|
|
|
1118
1118
|
* secret alone: no state or PKCE for the app to keep. JSON body:
|
|
1119
1119
|
* `client_id`, `secret` (or HTTP Basic), and optionally `redirect_uri` (one
|
|
1120
1120
|
* the app registered; default its first), `plans`, `client`, `key_providers`
|
|
1121
|
-
* (arrays), `purposes` ({ any_app, claude_code, muse_code }),
|
|
1122
|
-
* for update mode.
|
|
1121
|
+
* (arrays), `purposes` ({ any_app, claude_code, muse_code }), `allow_pooling`
|
|
1122
|
+
* (true), and `grant_id` for update mode.
|
|
1123
1123
|
*/
|
|
1124
1124
|
async function createLinkToken(link: LinkPlatform, request: Request): Promise<Response> {
|
|
1125
1125
|
let body: Record<string, unknown>;
|
|
@@ -1143,6 +1143,7 @@ async function createLinkToken(link: LinkPlatform, request: Request): Promise<Re
|
|
|
1143
1143
|
...(list("plans") ? { plans: list("plans") } : {}),
|
|
1144
1144
|
...(list("client") ? { client: list("client") } : {}),
|
|
1145
1145
|
...(list("key_providers") ? { key_providers: list("key_providers") } : {}),
|
|
1146
|
+
...(body.allow_pooling === true ? { allow_pooling: "true" } : {}),
|
|
1146
1147
|
...(typeof body.grant_id === "string" ? { grant_id: body.grant_id } : {}),
|
|
1147
1148
|
...Object.fromEntries(PLAN_AUDIENCES.flatMap((audience) =>
|
|
1148
1149
|
typeof purposes[audience] === "string" ? [[`purpose_${audience}`, purposes[audience] as string]] : []
|
|
@@ -1210,6 +1211,9 @@ type AuthorizeRequest = {
|
|
|
1210
1211
|
keyProviders: string[] | null;
|
|
1211
1212
|
// What the app says it does with each audience's plans, shown beside them.
|
|
1212
1213
|
purposes: Partial<Record<PlanAudience, string>>;
|
|
1214
|
+
// Whether the user may share several accounts of one provider, which Dari
|
|
1215
|
+
// then pools; by default one per provider.
|
|
1216
|
+
allowPooling: boolean;
|
|
1213
1217
|
// Update mode: the user's grant for this app whose plans to change in place.
|
|
1214
1218
|
grantId: string | null;
|
|
1215
1219
|
};
|
|
@@ -1282,6 +1286,10 @@ async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Pr
|
|
|
1282
1286
|
const purpose = params.get(`purpose_${audience}`)?.trim();
|
|
1283
1287
|
if (purpose) purposes[audience] = purpose.slice(0, MAX_PURPOSE_CHARS);
|
|
1284
1288
|
}
|
|
1289
|
+
const allowPooling = params.get("allow_pooling");
|
|
1290
|
+
if (allowPooling !== null && allowPooling !== "true" && allowPooling !== "false") {
|
|
1291
|
+
return badRequest("allow_pooling is true or false.");
|
|
1292
|
+
}
|
|
1285
1293
|
const grantId = params.get("grant_id");
|
|
1286
1294
|
if (grantId !== null && !GRANT_ID.test(grantId)) {
|
|
1287
1295
|
return badRequest("grant_id names one of the user's grants for this app.");
|
|
@@ -1296,6 +1304,7 @@ async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Pr
|
|
|
1296
1304
|
plans: plans.length === 0 ? null : plans as OfferKind[],
|
|
1297
1305
|
keyProviders: keyProviders.length === 0 ? null : keyProviders,
|
|
1298
1306
|
purposes,
|
|
1307
|
+
allowPooling: allowPooling === "true",
|
|
1299
1308
|
grantId,
|
|
1300
1309
|
};
|
|
1301
1310
|
}
|
|
@@ -1428,6 +1437,12 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
|
|
|
1428
1437
|
if (!credentialIds.every((id) => usable.has(id))) {
|
|
1429
1438
|
return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
|
|
1430
1439
|
}
|
|
1440
|
+
const pooled = authorize.allowPooling ? undefined : subscriptions.find((subscription, index) =>
|
|
1441
|
+
credentialIds.includes(subscription.id)
|
|
1442
|
+
&& subscriptions.slice(0, index).some((other) => credentialIds.includes(other.id) && pool(other) === pool(subscription)));
|
|
1443
|
+
if (pooled !== undefined) {
|
|
1444
|
+
return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} uses one account per provider: choose one ${planName(pooled)}${pooled.apiKeyProvider === undefined ? " account" : ""}.`);
|
|
1445
|
+
}
|
|
1431
1446
|
const limits = limitsFromForm(form, credentialIds);
|
|
1432
1447
|
if (limits === null) return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
|
|
1433
1448
|
try {
|
|
@@ -1986,8 +2001,13 @@ function choosePage(
|
|
|
1986
2001
|
): Response {
|
|
1987
2002
|
const app = escapeHtml(authorize.app.name);
|
|
1988
2003
|
const plans = shareable(authorize, subscriptions);
|
|
1989
|
-
// A new connection starts with every plan ticked; an update, with the plans
|
|
1990
|
-
|
|
2004
|
+
// A new connection starts with every plan ticked; an update, with the plans
|
|
2005
|
+
// it shares now. Without pooling, only the first of each provider's, so an
|
|
2006
|
+
// update of a grant made with pooling saves as it opens.
|
|
2007
|
+
const candidates = plans.filter((plan) => current === null || current.credentialIds.includes(plan.id));
|
|
2008
|
+
const ticked = new Set(candidates
|
|
2009
|
+
.filter((plan, index) => authorize.allowPooling || !candidates.slice(0, index).some((other) => pool(other) === pool(plan)))
|
|
2010
|
+
.map((plan) => plan.id));
|
|
1991
2011
|
return pane(authorize, {
|
|
1992
2012
|
title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
|
|
1993
2013
|
step: "choose_plans",
|
|
@@ -2010,8 +2030,15 @@ ${plans.map((plan) => {
|
|
|
2010
2030
|
});
|
|
2011
2031
|
}
|
|
2012
2032
|
|
|
2033
|
+
// Plans and keys of one pool: one kind of plan, or one provider's API keys.
|
|
2034
|
+
function pool(subscription: LinkSubscription): string {
|
|
2035
|
+
return subscription.apiKeyProvider === undefined ? subscription.provider : `api_key:${subscription.apiKeyProvider}`;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2013
2038
|
function planOption(authorize: AuthorizeRequest, subscription: LinkSubscription, ticked: boolean): string {
|
|
2014
|
-
|
|
2039
|
+
// Without pooling, ticking one of a pool unticks the rest (see `page`).
|
|
2040
|
+
const pooled = authorize.allowPooling ? "" : ` data-pool="${escapeHtml(pool(subscription))}"`;
|
|
2041
|
+
const box = `<input type="checkbox"${pooled} name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
|
|
2015
2042
|
if (subscription.apiKeyProvider !== undefined) {
|
|
2016
2043
|
return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key · ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
|
|
2017
2044
|
}
|
|
@@ -2056,6 +2083,7 @@ function authorizeFields(authorize: AuthorizeRequest): Record<string, string> {
|
|
|
2056
2083
|
...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
|
|
2057
2084
|
...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
|
|
2058
2085
|
...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
|
|
2086
|
+
...(authorize.allowPooling ? { allow_pooling: "true" } : {}),
|
|
2059
2087
|
...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
|
|
2060
2088
|
...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
|
|
2061
2089
|
};
|
|
@@ -2116,6 +2144,11 @@ function page(
|
|
|
2116
2144
|
const button = event.submitter;
|
|
2117
2145
|
if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
|
|
2118
2146
|
setTimeout(() => { button.disabled = true; button.setAttribute("aria-busy", "true"); button.prepend(Object.assign(document.createElement("span"), { className: "spin" })); });
|
|
2147
|
+
});
|
|
2148
|
+
document.addEventListener("change", (event) => {
|
|
2149
|
+
const box = event.target;
|
|
2150
|
+
if (!(box instanceof HTMLInputElement) || !box.checked || !box.dataset.pool) return;
|
|
2151
|
+
for (const other of box.form?.querySelectorAll("input[data-pool]") ?? []) if (other !== box && other.dataset.pool === box.dataset.pool) other.checked = false;
|
|
2119
2152
|
});</script>`;
|
|
2120
2153
|
options = { ...options, scriptNonce: busyNonce };
|
|
2121
2154
|
if (options.event !== undefined) {
|
|
@@ -43,7 +43,7 @@ export function internalChatCompletionsToInteraction(request: ChatCompletionRequ
|
|
|
43
43
|
continue;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
const reasoningItems = chatReasoningItems(message
|
|
46
|
+
const reasoningItems = chatReasoningItems(message);
|
|
47
47
|
items.push(...reasoningItems);
|
|
48
48
|
items.push({
|
|
49
49
|
type: "message",
|
|
@@ -171,17 +171,17 @@ function hostedToolCallStatus(
|
|
|
171
171
|
throw new HttpError(400, `${param} is not supported.`, "invalid_request_error", param);
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
function chatReasoningItems(message: ChatMessage
|
|
174
|
+
function chatReasoningItems(message: ChatMessage): InteractionItem[] {
|
|
175
175
|
if (message.role !== "assistant") return [];
|
|
176
176
|
const readable = [message.reasoning_content, message.reasoning, message.reasoning_text]
|
|
177
177
|
.find((value) => typeof value === "string" && value.length > 0);
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
178
|
+
// A conversation begun on another provider carries that provider's reasoning
|
|
179
|
+
// details. They name no provider or model, so they cannot be replayed; the
|
|
180
|
+
// turn keeps its readable reasoning and the conversation continues.
|
|
181
|
+
const continuations = (message.reasoning_details ?? []).flatMap((detail) => {
|
|
182
|
+
if (detail.type !== "reasoning.encrypted" || typeof detail.data !== "string") return [];
|
|
182
183
|
const continuation = decodeUntrustedProviderContinuationState(detail.data);
|
|
183
|
-
|
|
184
|
-
return continuation;
|
|
184
|
+
return continuation ? [continuation] : [];
|
|
185
185
|
});
|
|
186
186
|
if (continuations.length === 0) {
|
|
187
187
|
return readable
|
|
@@ -197,16 +197,6 @@ function chatReasoningItems(message: ChatMessage, messageIndex: number): Interac
|
|
|
197
197
|
}));
|
|
198
198
|
}
|
|
199
199
|
|
|
200
|
-
function invalidChatContinuation(messageIndex: number, detailIndex: number): HttpError {
|
|
201
|
-
const param = `messages.${messageIndex}.reasoning_details.${detailIndex}.data`;
|
|
202
|
-
return new HttpError(
|
|
203
|
-
400,
|
|
204
|
-
`${param} must be a Dari provider continuation envelope; raw provider state has no recoverable provider/model provenance.`,
|
|
205
|
-
"invalid_provider_continuation_state",
|
|
206
|
-
param,
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
200
|
function contentShape(content: ChatMessage["content"]): InteractionMessage["contentShape"] {
|
|
211
201
|
if (content === undefined) return "absent";
|
|
212
202
|
if (content === null) return "null";
|
|
@@ -83,17 +83,10 @@ function validateMessageReasoning(message: Record<string, unknown>, messageIndex
|
|
|
83
83
|
);
|
|
84
84
|
}
|
|
85
85
|
for (const [detailIndex, detail] of message.reasoning_details.entries()) {
|
|
86
|
-
if (
|
|
87
|
-
!isRecord(detail) ||
|
|
88
|
-
detail.type !== "reasoning.encrypted" ||
|
|
89
|
-
typeof detail.id !== "string" ||
|
|
90
|
-
!detail.id ||
|
|
91
|
-
typeof detail.data !== "string" ||
|
|
92
|
-
!detail.data
|
|
93
|
-
) {
|
|
86
|
+
if (!isRecord(detail)) {
|
|
94
87
|
throw new HttpError(
|
|
95
88
|
400,
|
|
96
|
-
`messages[${messageIndex}].reasoning_details[${detailIndex}]
|
|
89
|
+
`messages[${messageIndex}].reasoning_details[${detailIndex}] must be an object.`,
|
|
97
90
|
"invalid_request_error",
|
|
98
91
|
`messages.${messageIndex}.reasoning_details.${detailIndex}`
|
|
99
92
|
);
|
|
@@ -383,16 +383,11 @@ function clientTurnId(
|
|
|
383
383
|
}
|
|
384
384
|
|
|
385
385
|
function reasoningItem(value: Record<string, unknown>): InteractionItem {
|
|
386
|
+
// A conversation begun on OpenAI directly carries raw ciphertext. It names
|
|
387
|
+
// no provider or model, so it cannot be replayed; the item keeps its
|
|
388
|
+
// readable summary and the conversation continues.
|
|
386
389
|
const encoded = optionalString(value.encrypted_content, "input.reasoning.encrypted_content");
|
|
387
390
|
const continuation = encoded ? decodeUntrustedProviderContinuationState(encoded) : null;
|
|
388
|
-
if (encoded && !continuation) {
|
|
389
|
-
throw new HttpError(
|
|
390
|
-
400,
|
|
391
|
-
"input.reasoning.encrypted_content must be a Dari provider continuation envelope; raw provider ciphertext has no recoverable provider/model provenance.",
|
|
392
|
-
"invalid_provider_continuation_state",
|
|
393
|
-
"input.reasoning.encrypted_content"
|
|
394
|
-
);
|
|
395
|
-
}
|
|
396
391
|
return {
|
|
397
392
|
type: "reasoning",
|
|
398
393
|
id: optionalString(value.id, "input.reasoning.id"),
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
* `gateway.connect()` (or `POST <controlUrl>/connect`) is its user approving
|
|
23
23
|
* it: it resolves with what `DariLink.open` hands your page, `{code,
|
|
24
24
|
* codeVerifier, state}`, or rejects with the `LinkError` it would (`deny`).
|
|
25
|
-
* `clients`, `plans`, `keyProviders`, and `grantId` are `DariLink.open`'s.
|
|
25
|
+
* `clients`, `plans`, `keyProviders`, `allowPooling`, and `grantId` are `DariLink.open`'s.
|
|
26
26
|
*
|
|
27
27
|
* To drive an approval for an app you registered yourself:
|
|
28
28
|
* `gateway.approve(authorizeUrl)` (or `POST <controlUrl>/approve` with
|
|
29
29
|
* `{"url"}`) opens the approval page as the user who connected the stand-in
|
|
30
|
-
* plans,
|
|
30
|
+
* plans, keeps the plans the page ticks (or ticks `credentialIds`), approves (or
|
|
31
31
|
* denies with `deny`), and returns what the page hands the app:
|
|
32
32
|
* `{message, targetOrigin}`, the `web_message` post or the redirect's query.
|
|
33
33
|
* Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
|
|
@@ -121,13 +121,16 @@ export type StubGatewayOptions = {
|
|
|
121
121
|
export type StubLinkApp = { gatewayUrl: string; clientId: string; clientSecret: string; redirectUri: string };
|
|
122
122
|
|
|
123
123
|
export type StubConnectOptions = {
|
|
124
|
-
// The plans and keys the user shares. Default:
|
|
124
|
+
// The plans and keys the user shares. Default: those the page ticks, every
|
|
125
|
+
// one the app can use (one per provider without `allowPooling`), or in
|
|
126
|
+
// update mode the ones the grant shares now.
|
|
125
127
|
credentialIds?: string[];
|
|
126
128
|
deny?: boolean;
|
|
127
129
|
// As `DariLink.open` takes them.
|
|
128
130
|
clients?: string[];
|
|
129
131
|
plans?: string[];
|
|
130
132
|
keyProviders?: string[];
|
|
133
|
+
allowPooling?: boolean;
|
|
131
134
|
grantId?: string;
|
|
132
135
|
};
|
|
133
136
|
|
|
@@ -227,6 +230,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
|
|
|
227
230
|
clients?: string[];
|
|
228
231
|
plans?: string[];
|
|
229
232
|
key_providers?: string[];
|
|
233
|
+
allow_pooling?: boolean;
|
|
230
234
|
grant_id?: string;
|
|
231
235
|
};
|
|
232
236
|
try {
|
|
@@ -236,6 +240,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
|
|
|
236
240
|
...(body.clients ? { clients: body.clients } : {}),
|
|
237
241
|
...(body.plans ? { plans: body.plans } : {}),
|
|
238
242
|
...(body.key_providers ? { keyProviders: body.key_providers } : {}),
|
|
243
|
+
...(body.allow_pooling ? { allowPooling: true } : {}),
|
|
239
244
|
...(body.grant_id ? { grantId: body.grant_id } : {}),
|
|
240
245
|
});
|
|
241
246
|
return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
|
|
@@ -445,8 +450,8 @@ ${keys.filter((key) => key === "openrouter").map((key) => ` ${key}:\n baseUr
|
|
|
445
450
|
};
|
|
446
451
|
}
|
|
447
452
|
|
|
448
|
-
// The approval page as the plans' user goes through it:
|
|
449
|
-
// approve or deny; then what the page hands the app.
|
|
453
|
+
// The approval page as the plans' user goes through it: keep the plans it
|
|
454
|
+
// ticks (or tick the given ones), approve or deny; then what the page hands the app.
|
|
450
455
|
async function driveApproval(
|
|
451
456
|
baseUrl: string,
|
|
452
457
|
cookie: string,
|
|
@@ -464,7 +469,7 @@ async function driveApproval(
|
|
|
464
469
|
+ 'A Claude Code plan serves only an app that asks for clients: ["claude_code"].',
|
|
465
470
|
);
|
|
466
471
|
}
|
|
467
|
-
const
|
|
472
|
+
const ticked = [...choose.matchAll(/name="credential_id" value="([^"]+)"[^>]* checked>/g)].map((match) => match[1]!);
|
|
468
473
|
const decided = await fetch(`${baseUrl}${url.pathname}`, {
|
|
469
474
|
method: "POST",
|
|
470
475
|
redirect: "manual",
|
|
@@ -473,7 +478,7 @@ async function driveApproval(
|
|
|
473
478
|
...params,
|
|
474
479
|
["csrf", csrf],
|
|
475
480
|
["decision", options.deny ? "deny" : "approve"],
|
|
476
|
-
...(options.credentialIds ??
|
|
481
|
+
...(options.credentialIds ?? ticked).map((id) => ["credential_id", id]),
|
|
477
482
|
]),
|
|
478
483
|
});
|
|
479
484
|
const location = decided.headers.get("location");
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* page's user's: `userCookie` is the `Cookie` header that opens the page as them. `app` is a server
|
|
12
12
|
* app registered on the gateway (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
|
|
13
13
|
* `POST <controlUrl>/connect` (with `{"credential_ids"?, "deny"?, "clients"?, "plans"?,
|
|
14
|
-
* "key_providers"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
14
|
+
* "key_providers"?, "allow_pooling"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
15
15
|
* `{"code", "code_verifier", "state"}`, what Connect with Dari hands your page. `GET <controlUrl>/served`
|
|
16
16
|
* answers `{"calls": [...]}`: every provider call so far, with its path,
|
|
17
17
|
* model, thinking, and client headers. For an app you registered yourself, `POST <controlUrl>/approve` with
|