@mupt-ai/dari-gateway 1.0.366 → 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/activity/conversation_detail.js +8 -0
- package/dist/link/client.d.ts +3 -1
- package/dist/link/client.js +4 -1
- package/dist/link/endpoints.js +38 -30
- package/dist/link/service.d.ts +1 -3
- package/dist/link/service.js +0 -1
- package/dist/platform/platform.d.ts +1 -11
- package/dist/protocol/input/anthropic_messages.js +3 -4
- 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/providers/execution.js +1 -0
- package/dist/providers/provider_call.d.ts +1 -0
- package/dist/providers/provider_call.js +1 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/connected.d.ts +5 -4
- package/dist/self_host/hosted_sync.d.ts +14 -23
- package/dist/self_host/hosted_sync.js +56 -120
- package/dist/self_host/main.js +0 -3
- package/dist/self_host/platform.js +2 -0
- package/dist/self_host/resolve.js +2 -1
- 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/dist/self_host/subscriptions/index.d.ts +1 -1
- package/dist/self_host/subscriptions/index.js +1 -1
- package/dist/self_host/subscriptions/store.d.ts +8 -6
- package/dist/self_host/subscriptions/store.js +8 -16
- package/dist/telemetry/report.js +8 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +8 -0
- package/src/link/client.ts +7 -1
- package/src/link/endpoints.ts +42 -34
- package/src/link/service.ts +0 -4
- package/src/platform/platform.ts +2 -9
- package/src/protocol/input/anthropic_messages.ts +3 -9
- 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/providers/execution.ts +1 -0
- package/src/providers/provider_call.ts +3 -0
- package/src/runtime/runtime_reporter.ts +3 -1
- package/src/self_host/connected.ts +5 -4
- package/src/self_host/hosted_sync.ts +51 -121
- package/src/self_host/main.ts +0 -3
- package/src/self_host/platform.ts +2 -1
- package/src/self_host/resolve.ts +2 -0
- package/src/self_host/stub_gateway.ts +12 -7
- package/src/self_host/stub_main.ts +1 -1
- package/src/self_host/subscriptions/index.ts +1 -0
- package/src/self_host/subscriptions/store.ts +14 -18
- package/src/telemetry/report.ts +8 -1
- package/src/types.ts +3 -0
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
|
|
|
@@ -30,6 +30,13 @@ function agentContext(record) {
|
|
|
30
30
|
agentType: readOptionalString(value.agentType),
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
+
/** The name of the plan that served the request, when one did. */
|
|
34
|
+
function subscriptionAccount(record) {
|
|
35
|
+
const metadata = record.requestMetadata;
|
|
36
|
+
if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))
|
|
37
|
+
return null;
|
|
38
|
+
return readOptionalString(metadata.subscription_account);
|
|
39
|
+
}
|
|
33
40
|
function routePath(records) {
|
|
34
41
|
const path = [];
|
|
35
42
|
for (const record of records) {
|
|
@@ -187,6 +194,7 @@ function conversationStep(record, organizationId, currentRouterZdr, skillEvents)
|
|
|
187
194
|
selected_model: record.selectedModel,
|
|
188
195
|
selected_reasoning_effort: effort,
|
|
189
196
|
selected_provider: record.selectedProvider,
|
|
197
|
+
subscription_account: subscriptionAccount(record),
|
|
190
198
|
provider_input_tokens: record.providerInputTokens,
|
|
191
199
|
provider_cache_read_tokens: record.providerCacheReadTokens,
|
|
192
200
|
provider_cache_write_tokens: record.providerCacheWriteTokens,
|
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
|
}
|
|
@@ -1183,28 +1189,9 @@ async function homePage(approval, authorize, session) {
|
|
|
1183
1189
|
if (session === null)
|
|
1184
1190
|
return introPage(approval, authorize);
|
|
1185
1191
|
const subscriptions = await approval.subscriptions(session.subject);
|
|
1186
|
-
const onComputers = await plansOnComputersNote(approval, authorize, session.subject, subscriptions);
|
|
1187
1192
|
return shareable(authorize, subscriptions).length > 0
|
|
1188
|
-
? choosePage(authorize, session, subscriptions, current
|
|
1189
|
-
: introPage(approval, authorize
|
|
1190
|
-
}
|
|
1191
|
-
// Where the user keeps a plan the app could use on one of their computers,
|
|
1192
|
-
// for each kind they have no plan of here: apps reach only the platform's.
|
|
1193
|
-
async function plansOnComputersNote(approval, authorize, subject, subscriptions) {
|
|
1194
|
-
if (approval.plansOnComputers === undefined)
|
|
1195
|
-
return "";
|
|
1196
|
-
const here = new Set(subscriptions.map((subscription) => subscription.provider));
|
|
1197
|
-
const usable = new Set(connectKinds(approval, authorize));
|
|
1198
|
-
const computers = new Map();
|
|
1199
|
-
for (const plan of await approval.plansOnComputers(subject)) {
|
|
1200
|
-
if (here.has(plan.provider) || !usable.has(plan.provider))
|
|
1201
|
-
continue;
|
|
1202
|
-
const names = computers.get(plan.provider) ?? [];
|
|
1203
|
-
if (!names.includes(plan.computer))
|
|
1204
|
-
names.push(plan.computer);
|
|
1205
|
-
computers.set(plan.provider, names);
|
|
1206
|
-
}
|
|
1207
|
-
return [...computers].map(([kind, names]) => `<p class="hint">Your ${KINDS[kind].name} plan is on ${escapeHtml(names.join(" and "))}. Apps can only use plans on Dari.</p>`).join("\n");
|
|
1193
|
+
? choosePage(authorize, session, subscriptions, current)
|
|
1194
|
+
: introPage(approval, authorize);
|
|
1208
1195
|
}
|
|
1209
1196
|
// In update mode, the grant being changed. A grant this browser's user does
|
|
1210
1197
|
// not hold (another browser, cleared cookies) starts a new connection instead,
|
|
@@ -1307,6 +1294,11 @@ async function authorizeSubmit(link, request, form) {
|
|
|
1307
1294
|
if (!credentialIds.every((id) => usable.has(id))) {
|
|
1308
1295
|
return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
|
|
1309
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
|
+
}
|
|
1310
1302
|
const limits = limitsFromForm(form, credentialIds);
|
|
1311
1303
|
if (limits === null)
|
|
1312
1304
|
return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
|
|
@@ -1689,7 +1681,7 @@ const KINDS = {
|
|
|
1689
1681
|
vercel_token_pass: { name: "Vercel Token Pass", plan: "Token Pass", at: "Vercel", pastedKey: true },
|
|
1690
1682
|
};
|
|
1691
1683
|
// The first page a new user sees: what connecting means, and one button.
|
|
1692
|
-
function introPage(approval, authorize
|
|
1684
|
+
function introPage(approval, authorize) {
|
|
1693
1685
|
const app = escapeHtml(authorize.app.name);
|
|
1694
1686
|
const kinds = connectKinds(approval, authorize);
|
|
1695
1687
|
const keys = keyProviders(approval, authorize);
|
|
@@ -1707,7 +1699,7 @@ function introPage(approval, authorize, onComputers = "") {
|
|
|
1707
1699
|
<ul class="points">
|
|
1708
1700
|
<li>${ICONS.zap}<div><strong>Connect In Seconds</strong><p>${kinds.length > 0 ? `Use what you already pay for: ${escapeHtml(ways)}.` : "Add the API key you already have."}</p></div></li>
|
|
1709
1701
|
<li>${ICONS.shield}<div><strong>You Stay In Control</strong><p>${app} can only send model requests on what you share. It sees each shared plan's account email, never a key or your other plans, and you can disconnect it any time.</p></div></li>
|
|
1710
|
-
</ul
|
|
1702
|
+
</ul>`,
|
|
1711
1703
|
footer: `<button class="btn primary" type="submit" name="decision" value="select">Continue</button>`,
|
|
1712
1704
|
});
|
|
1713
1705
|
}
|
|
@@ -1791,11 +1783,16 @@ function providerPage(authorize, connect, error) {
|
|
|
1791
1783
|
});
|
|
1792
1784
|
}
|
|
1793
1785
|
// The user's plans and keys, ticked: one button shares them with the app.
|
|
1794
|
-
function choosePage(authorize, session, subscriptions, current, error
|
|
1786
|
+
function choosePage(authorize, session, subscriptions, current, error) {
|
|
1795
1787
|
const app = escapeHtml(authorize.app.name);
|
|
1796
1788
|
const plans = shareable(authorize, subscriptions);
|
|
1797
|
-
// A new connection starts with every plan ticked; an update, with the plans
|
|
1798
|
-
|
|
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));
|
|
1799
1796
|
return pane(authorize, {
|
|
1800
1797
|
title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
|
|
1801
1798
|
step: "choose_plans",
|
|
@@ -1805,7 +1802,6 @@ function choosePage(authorize, session, subscriptions, current, error, onCompute
|
|
|
1805
1802
|
<!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
|
|
1806
1803
|
<button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
|
|
1807
1804
|
${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
|
|
1808
|
-
${onComputers}
|
|
1809
1805
|
<details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
|
|
1810
1806
|
${plans.map((plan) => {
|
|
1811
1807
|
const set = current?.limits.find((limit) => limit.credentialId === plan.id);
|
|
@@ -1818,8 +1814,14 @@ ${plans.map((plan) => {
|
|
|
1818
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>`,
|
|
1819
1815
|
});
|
|
1820
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
|
+
}
|
|
1821
1821
|
function planOption(authorize, subscription, ticked) {
|
|
1822
|
-
|
|
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" : ""}>`;
|
|
1823
1825
|
if (subscription.apiKeyProvider !== undefined) {
|
|
1824
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>`;
|
|
1825
1827
|
}
|
|
@@ -1862,6 +1864,7 @@ function authorizeFields(authorize) {
|
|
|
1862
1864
|
...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
|
|
1863
1865
|
...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
|
|
1864
1866
|
...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
|
|
1867
|
+
...(authorize.allowPooling ? { allow_pooling: "true" } : {}),
|
|
1865
1868
|
...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
|
|
1866
1869
|
...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
|
|
1867
1870
|
};
|
|
@@ -1898,6 +1901,11 @@ function page(title, body, options = {}) {
|
|
|
1898
1901
|
const button = event.submitter;
|
|
1899
1902
|
if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
|
|
1900
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;
|
|
1901
1909
|
});</script>`;
|
|
1902
1910
|
options = { ...options, scriptNonce: busyNonce };
|
|
1903
1911
|
if (options.event !== undefined) {
|
package/dist/link/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkLimit, LinkPlanAdded,
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkLimit, LinkPlanAdded, LinkPlatform, LinkSignIn, LinkSubscription } from "../platform/platform.js";
|
|
2
2
|
import type { SubscriptionKind } from "../types.js";
|
|
3
3
|
import { type BudgetUse } from "./budget.js";
|
|
4
4
|
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo, type LinkTokenIssue } from "./grants.js";
|
|
@@ -95,8 +95,6 @@ export type LinkUsers = {
|
|
|
95
95
|
completeThrough(grantId: string): string | null;
|
|
96
96
|
/** A user's plans and API keys, oldest first. */
|
|
97
97
|
plans(subject: string): Promise<LinkSubscription[]>;
|
|
98
|
-
/** See `LinkApprovalPage.plansOnComputers`. */
|
|
99
|
-
plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
|
|
100
98
|
/** The plans and API keys with these ids, whoever added them. */
|
|
101
99
|
plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
|
|
102
100
|
/** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
|
package/dist/link/service.js
CHANGED
|
@@ -81,7 +81,6 @@ export function linkPlatform(store, users) {
|
|
|
81
81
|
connectable: users.connectable,
|
|
82
82
|
keyProviders: users.keyProviders,
|
|
83
83
|
subscriptions: (subject) => users.plans(subject),
|
|
84
|
-
...(users.plansOnComputers === undefined ? {} : { plansOnComputers: users.plansOnComputers }),
|
|
85
84
|
async addKey(subject, provider, apiKey) {
|
|
86
85
|
if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
|
|
87
86
|
throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
|
|
@@ -255,12 +255,6 @@ export type LinkApprovalPage = {
|
|
|
255
255
|
addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
|
|
256
256
|
/** The plans this user connected and the API keys they added, which an approval chooses among. */
|
|
257
257
|
subscriptions(subject: string): Promise<LinkSubscription[]>;
|
|
258
|
-
/**
|
|
259
|
-
* The user's plans that live on one of their computers rather than on the
|
|
260
|
-
* platform, which apps cannot use; the page says where each is. Absent on
|
|
261
|
-
* a platform where every plan is its own.
|
|
262
|
-
*/
|
|
263
|
-
plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
|
|
264
258
|
/** Start the provider's sign-in for a plan of this kind. */
|
|
265
259
|
startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
|
|
266
260
|
/**
|
|
@@ -313,11 +307,6 @@ export type LinkSignIn = {
|
|
|
313
307
|
issuedAt: number;
|
|
314
308
|
} | null>;
|
|
315
309
|
};
|
|
316
|
-
/** A plan kept on one of the user's computers: its kind and the computer's name. */
|
|
317
|
-
export type LinkPlanOnComputer = {
|
|
318
|
-
provider: SubscriptionKind;
|
|
319
|
-
computer: string;
|
|
320
|
-
};
|
|
321
310
|
/** A plan or API key the user added, and who they are now. */
|
|
322
311
|
export type LinkPlanAdded = {
|
|
323
312
|
subject: string;
|
|
@@ -550,6 +539,7 @@ export type NextSubscriptionRequest = {
|
|
|
550
539
|
};
|
|
551
540
|
export type NextSubscription = {
|
|
552
541
|
credentialId: string;
|
|
542
|
+
account?: string;
|
|
553
543
|
apiKey: string;
|
|
554
544
|
};
|
|
555
545
|
export type SubscriptionUsageReport = {
|
|
@@ -352,12 +352,11 @@ function anthropicImage(value, param) {
|
|
|
352
352
|
}
|
|
353
353
|
function anthropicReasoningItem(block, type, param) {
|
|
354
354
|
const encoded = requiredString(type === "thinking" ? block.signature : block.data, `${param}.${type === "thinking" ? "signature" : "data"}`);
|
|
355
|
+
// A conversation begun on Anthropic directly carries raw signatures. They
|
|
356
|
+
// name no provider or model, so they cannot be replayed; the turn keeps its
|
|
357
|
+
// readable thinking and the conversation continues.
|
|
355
358
|
const continuation = decodeUntrustedProviderContinuationState(encoded);
|
|
356
359
|
const portable = continuation ? null : decodeUntrustedPortableReasoningState(encoded);
|
|
357
|
-
if (!continuation && !portable) {
|
|
358
|
-
const field = type === "thinking" ? "signature" : "data";
|
|
359
|
-
throw new HttpError(400, `${param}.${field} must be a Dari reasoning-state envelope; raw provider state has no recoverable provider/model provenance.`, "invalid_provider_continuation_state", `${param}.${field}`);
|
|
360
|
-
}
|
|
361
360
|
const thinking = type === "thinking" ? requiredStringAllowEmpty(block.thinking, `${param}.thinking`) : "";
|
|
362
361
|
const reasoning = {
|
|
363
362
|
type: "reasoning",
|
|
@@ -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"),
|
|
@@ -27,6 +27,7 @@ export type ProviderExecution = ProviderCallConfig & {
|
|
|
27
27
|
providerKeySource: ProviderKeySource;
|
|
28
28
|
subscriptionUserId?: string;
|
|
29
29
|
subscriptionCredentialId?: string;
|
|
30
|
+
subscriptionAccount?: string;
|
|
30
31
|
subscriptionLinkGrantId?: string;
|
|
31
32
|
subscriptionSources?: Source[];
|
|
32
33
|
subscriptionResetMinHours?: number;
|
|
@@ -62,6 +62,7 @@ export function prepareProviderExecution(args) {
|
|
|
62
62
|
...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
|
|
63
63
|
}
|
|
64
64
|
: {}),
|
|
65
|
+
...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
|
|
65
66
|
thinkingLevel,
|
|
66
67
|
usageContext: usageContextFor({
|
|
67
68
|
billable: args.billable,
|
|
@@ -8,6 +8,7 @@ export type ReportedProviderExecution = {
|
|
|
8
8
|
providerKeySource: ProviderKeySource;
|
|
9
9
|
thinkingLevel?: string;
|
|
10
10
|
subscriptionCredentialId?: string;
|
|
11
|
+
subscriptionAccount?: string;
|
|
11
12
|
};
|
|
12
13
|
export declare function reportedExecution(execution: ReportedProviderExecution): ReportedProviderExecution;
|
|
13
14
|
export type ReportableProviderOutcome = {
|
|
@@ -7,6 +7,7 @@ export function reportedExecution(execution) {
|
|
|
7
7
|
...(execution.subscriptionCredentialId === undefined
|
|
8
8
|
? {}
|
|
9
9
|
: { subscriptionCredentialId: execution.subscriptionCredentialId }),
|
|
10
|
+
...(execution.subscriptionAccount === undefined ? {} : { subscriptionAccount: execution.subscriptionAccount }),
|
|
10
11
|
};
|
|
11
12
|
}
|
|
12
13
|
export function createExperimentRoutedRuntimeReporter() {
|
|
@@ -16,10 +16,11 @@ import { createSelfHostedPlatform } from "./platform.js";
|
|
|
16
16
|
* Dari key (resolve.ts).
|
|
17
17
|
* - Every other path the gateway does not manage itself, such as commit
|
|
18
18
|
* reports, goes to hosted with the user's Dari key.
|
|
19
|
-
* - The
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* hosted's to log. Dari Link and Activity are hosted's, not
|
|
19
|
+
* - The requests served here sync to hosted Activity (hosted_sync.ts), each
|
|
20
|
+
* naming the plan that served it. The plans themselves never leave this
|
|
21
|
+
* computer. A private plan's requests do not sync either; requests hosted
|
|
22
|
+
* Dari served are hosted's to log. Dari Link and Activity are hosted's, not
|
|
23
|
+
* served here.
|
|
23
24
|
*/
|
|
24
25
|
export type HostedConnection = {
|
|
25
26
|
url: string;
|
|
@@ -2,12 +2,12 @@ import type { Database } from "bun:sqlite";
|
|
|
2
2
|
import type { HostedConnection } from "./connected.js";
|
|
3
3
|
import { type ConnectedAccount, type SubscriptionStore } from "./subscriptions/index.js";
|
|
4
4
|
/**
|
|
5
|
-
* What a gateway connected to hosted Dari tells it:
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
5
|
+
* What a gateway connected to hosted Dari tells it: the requests it served,
|
|
6
|
+
* for Activity, `POST /v1/gateway/requests`. Rows wait in a SQLite outbox,
|
|
7
|
+
* sent in batches with backoff until hosted takes them. Requests a private
|
|
8
|
+
* plan served are never queued. This computer's plans themselves never leave
|
|
9
|
+
* it; it only reads the accounts on Dari (`GET /v1/gateway/accounts`), to drop
|
|
10
|
+
* a plan whose account was since connected there.
|
|
11
11
|
*/
|
|
12
12
|
export declare class HostedSync {
|
|
13
13
|
private readonly db;
|
|
@@ -15,30 +15,20 @@ export declare class HostedSync {
|
|
|
15
15
|
private readonly hosted;
|
|
16
16
|
private readonly fetch;
|
|
17
17
|
private readonly now;
|
|
18
|
-
private
|
|
19
|
-
private
|
|
20
|
-
private snapshotFailures;
|
|
21
|
-
private snapshots;
|
|
22
|
-
private lastSnapshotAt;
|
|
18
|
+
private accountsTimer;
|
|
19
|
+
private accountsFailures;
|
|
23
20
|
private drainTimer;
|
|
24
21
|
private draining;
|
|
25
22
|
private drainFailures;
|
|
26
23
|
private drainPausedUntil;
|
|
27
24
|
constructor(db: Database, subscriptions: SubscriptionStore, hosted: HostedConnection, fetch: typeof globalThis.fetch, now?: () => number);
|
|
28
|
-
/**
|
|
25
|
+
/** Check the accounts on Dari and send waiting requests now, then keep at it. */
|
|
29
26
|
start(): void;
|
|
30
27
|
stop(): void;
|
|
31
|
-
/** A plan was connected, removed, renamed, moved, held, or released. */
|
|
32
|
-
plansChanged(): void;
|
|
33
|
-
/** A plan reported usage or served a turn. */
|
|
34
|
-
usageChanged(): void;
|
|
35
28
|
/** Queue a served request's log row for hosted Activity. */
|
|
36
29
|
enqueue(row: Record<string, unknown>): void;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
private scheduleSnapshot;
|
|
40
|
-
private putSnapshot;
|
|
41
|
-
private dropPlansOnDari;
|
|
30
|
+
private scheduleAccountsCheck;
|
|
31
|
+
private checkAccounts;
|
|
42
32
|
/** Send the queued request rows a batch at a time, unless hosted failed lately. */
|
|
43
33
|
drain(): Promise<void>;
|
|
44
34
|
private drainDue;
|
|
@@ -46,8 +36,9 @@ export declare class HostedSync {
|
|
|
46
36
|
}
|
|
47
37
|
/**
|
|
48
38
|
* The user's plans on hosted Dari, for the check before a sign-in connects an
|
|
49
|
-
* account
|
|
50
|
-
*
|
|
39
|
+
* account and for dropping a plan here that moved there: `GET
|
|
40
|
+
* /v1/gateway/accounts` returns each one's provider, account identity, name,
|
|
41
|
+
* and when it was connected, never a token. Other computers may hold the same
|
|
51
42
|
* account, so only Dari's plans count.
|
|
52
43
|
*/
|
|
53
44
|
export declare function readHostedAccounts(hosted: HostedConnection, fetchImpl: typeof globalThis.fetch): Promise<ConnectedAccount[]>;
|