@mupt-ai/dari-gateway 1.0.367 → 1.0.369

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +4 -3
  2. package/dist/link/client.d.ts +3 -1
  3. package/dist/link/client.js +4 -1
  4. package/dist/link/endpoints.js +33 -5
  5. package/dist/link/self_hosted.js +0 -1
  6. package/dist/platform/platform.d.ts +2 -0
  7. package/dist/platform/routing_contract.d.ts +1 -0
  8. package/dist/platform/routing_contract.js +4 -0
  9. package/dist/protocol/input/chat_completions.js +9 -13
  10. package/dist/protocol/input/chat_completions_validation.js +2 -7
  11. package/dist/protocol/input/openai_responses.js +3 -3
  12. package/dist/protocol/output/anthropic_messages.d.ts +1 -0
  13. package/dist/protocol/output/anthropic_messages.js +1 -1
  14. package/dist/protocol/output/anthropic_messages_output.d.ts +1 -1
  15. package/dist/protocol/output/anthropic_messages_output.js +3 -1
  16. package/dist/protocol/output/anthropic_messages_stream.d.ts +1 -0
  17. package/dist/protocol/output/anthropic_messages_stream.js +1 -1
  18. package/dist/protocol/output/chat_completions.d.ts +2 -0
  19. package/dist/protocol/output/chat_completions.js +5 -3
  20. package/dist/protocol/output/openai_responses.d.ts +1 -0
  21. package/dist/protocol/output/openai_responses.js +1 -1
  22. package/dist/protocol/output/openai_responses_output.d.ts +1 -1
  23. package/dist/protocol/output/openai_responses_output.js +3 -1
  24. package/dist/protocol/output/openai_responses_stream.d.ts +1 -0
  25. package/dist/protocol/output/openai_responses_stream.js +1 -1
  26. package/dist/providers/execution.js +2 -0
  27. package/dist/providers/provider_call.d.ts +1 -0
  28. package/dist/providers/provider_call.js +2 -0
  29. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  30. package/dist/runtime/prepare_routed_completion.js +4 -0
  31. package/dist/runtime/routed_completion.js +2 -0
  32. package/dist/runtime/routed_protocol.d.ts +2 -0
  33. package/dist/self_host/connected.d.ts +7 -3
  34. package/dist/self_host/connected.js +9 -10
  35. package/dist/self_host/hosted_sync.js +1 -1
  36. package/dist/self_host/main.d.ts +3 -2
  37. package/dist/self_host/main.js +16 -6
  38. package/dist/self_host/private_mode.d.ts +16 -0
  39. package/dist/self_host/private_mode.js +35 -0
  40. package/dist/self_host/resolve.js +5 -2
  41. package/dist/self_host/stub_gateway.d.ts +1 -0
  42. package/dist/self_host/stub_gateway.js +7 -6
  43. package/dist/self_host/stub_main.js +1 -1
  44. package/dist/self_host/subscriptions/http.js +2 -17
  45. package/dist/self_host/subscriptions/store.d.ts +7 -6
  46. package/dist/self_host/subscriptions/store.js +15 -27
  47. package/dist/telemetry/report.js +1 -0
  48. package/dist/types.d.ts +1 -0
  49. package/package.json +2 -2
  50. package/src/link/client.ts +7 -1
  51. package/src/link/endpoints.ts +38 -5
  52. package/src/link/self_hosted.ts +0 -1
  53. package/src/platform/platform.ts +6 -0
  54. package/src/platform/routing_contract.ts +5 -0
  55. package/src/protocol/input/chat_completions.ts +8 -18
  56. package/src/protocol/input/chat_completions_validation.ts +2 -9
  57. package/src/protocol/input/openai_responses.ts +3 -8
  58. package/src/protocol/output/anthropic_messages.ts +2 -1
  59. package/src/protocol/output/anthropic_messages_output.ts +4 -1
  60. package/src/protocol/output/anthropic_messages_stream.ts +2 -1
  61. package/src/protocol/output/chat_completions.ts +7 -3
  62. package/src/protocol/output/openai_responses.ts +2 -1
  63. package/src/protocol/output/openai_responses_output.ts +4 -1
  64. package/src/protocol/output/openai_responses_stream.ts +2 -1
  65. package/src/providers/execution.ts +2 -0
  66. package/src/providers/provider_call.ts +5 -0
  67. package/src/runtime/prepare_routed_completion.ts +4 -0
  68. package/src/runtime/routed_completion.ts +2 -0
  69. package/src/runtime/routed_protocol.ts +2 -0
  70. package/src/self_host/connected.ts +16 -12
  71. package/src/self_host/hosted_sync.ts +1 -1
  72. package/src/self_host/main.ts +14 -6
  73. package/src/self_host/private_mode.ts +41 -0
  74. package/src/self_host/resolve.ts +4 -2
  75. package/src/self_host/stub_gateway.ts +12 -7
  76. package/src/self_host/stub_main.ts +1 -1
  77. package/src/self_host/subscriptions/http.ts +2 -15
  78. package/src/self_host/subscriptions/store.ts +15 -34
  79. package/src/telemetry/report.ts +1 -0
  80. package/src/types.ts +3 -0
@@ -1,6 +1,7 @@
1
1
  import type { GatewayPlatform } from "../platform/platform.js";
2
2
  import { type RouterConfig } from "./config.js";
3
3
  import type { HostedSync } from "./hosted_sync.js";
4
+ import type { PrivateMode } from "./private_mode.js";
4
5
  import { createSelfHostedPlatform } from "./platform.js";
5
6
  /**
6
7
  * A self-hosted gateway connected to hosted Dari (the Dari CLI runs one for
@@ -18,9 +19,11 @@ import { createSelfHostedPlatform } from "./platform.js";
18
19
  * reports, goes to hosted with the user's Dari key.
19
20
  * - The requests served here sync to hosted Activity (hosted_sync.ts), each
20
21
  * 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.
22
+ * computer. Requests hosted Dari served are hosted's to log. Dari Link and
23
+ * Activity are hosted's, not served here.
24
+ * - In private mode (private_mode.ts) every request is private
25
+ * (PRIVATE_HEADER): none syncs, and hosted Dari keeps only what billing
26
+ * needs of those it serves.
24
27
  */
25
28
  export type HostedConnection = {
26
29
  url: string;
@@ -60,6 +63,7 @@ export declare function connectedHandler(deps: {
60
63
  gatewayKeys: readonly string[];
61
64
  hosted: HostedConnection;
62
65
  hostedRouter: HostedRouters;
66
+ privateMode: PrivateMode;
63
67
  fetch: typeof fetch;
64
68
  }): (request: Request) => Promise<Response>;
65
69
  export {};
@@ -2,7 +2,7 @@ import { hostname } from "node:os";
2
2
  import { anthropicToken, bearerToken } from "../http/auth.js";
3
3
  import { errorResponse, HttpError } from "../http/errors.js";
4
4
  import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
5
- import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
5
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
6
6
  import { parseGatewayConfig } from "./config.js";
7
7
  import { createSelfHostedPlatform } from "./platform.js";
8
8
  import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
@@ -41,16 +41,10 @@ export function createConnectedPlatform(deps) {
41
41
  },
42
42
  recordRequest(record) {
43
43
  console.info("routing request", JSON.stringify(record.summary));
44
- // Hosted Dari logs the requests it served itself.
45
- if (record.summary.selected_provider === HOSTED_DARI_PROVIDER)
44
+ // Hosted Dari logs the requests it served itself, and private ones
45
+ // stay on this computer.
46
+ if (record.summary.selected_provider === HOSTED_DARI_PROVIDER || record.private)
46
47
  return;
47
- // A private plan's requests stay on this computer, as the plan does; so
48
- // does one whose plan is gone, since it may have been private.
49
- if (record.subscriptionCredentialId !== undefined) {
50
- const plan = deps.subscriptions.get(record.subscriptionCredentialId);
51
- if (plan === null || plan.private)
52
- return;
53
- }
54
48
  try {
55
49
  deps.sync.enqueue(record.row);
56
50
  }
@@ -122,6 +116,11 @@ const LOCAL_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messa
122
116
  */
123
117
  export function connectedHandler(deps) {
124
118
  return async (request) => {
119
+ if (deps.privateMode.on) {
120
+ const headers = new Headers(request.headers);
121
+ headers.set(PRIVATE_HEADER, "true");
122
+ request = new Request(request, { headers });
123
+ }
125
124
  const { pathname } = new URL(request.url);
126
125
  if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
127
126
  return await deps.gateway(request);
@@ -82,7 +82,7 @@ export class HostedSync {
82
82
  const onDari = await readHostedAccounts(this.hosted, this.fetch);
83
83
  this.accountsFailures = 0;
84
84
  for (const plan of this.subscriptions.list()) {
85
- if (plan.owner !== null || plan.private || plan.accountId === null)
85
+ if (plan.owner !== null || plan.accountId === null)
86
86
  continue;
87
87
  const moved = onDari.some((account) => account.provider === plan.provider
88
88
  && account.accountId === plan.accountId
@@ -27,8 +27,9 @@
27
27
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
28
28
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
29
29
  * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
30
- * its own plans and then on hosted Dari, and syncs its plans and requests
31
- * there; Dari Link and Activity are hosted's.
30
+ * its own plans and then on hosted Dari, and syncs its requests there unless
31
+ * private mode is on (`/v1/gateway/private`); Dari Link and Activity are
32
+ * hosted's.
32
33
  */
33
34
  export declare function startSelfHostedGateway(env?: Record<string, string>): Promise<{
34
35
  server: import("../http/http2_server.js").Http2RoutingServer | Bun.Server<undefined>;
@@ -21,6 +21,7 @@ import { secretBoxFromEnv } from "./secret_box.js";
21
21
  import { PrefixStore } from "./prefix_store.js";
22
22
  import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
23
23
  import { handleRouterSpecsRequest, loadRouterSpecDirectory, ROUTERS_ROUTE, RouterSpecStore, servedRouter, servedRouterIds, } from "./router_specs.js";
24
+ import { handlePrivateModeRequest, PRIVATE_MODE_ROUTE, PrivateMode } from "./private_mode.js";
24
25
  import { SessionPinStore } from "./session_pin_store.js";
25
26
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
26
27
  import { providerBaseUrls } from "./subscriptions/resets.js";
@@ -28,8 +29,8 @@ import { refreshStaleUsage } from "./subscriptions/usage.js";
28
29
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
29
30
  // The models Dari serves, which the Dari CLI's model picker offers.
30
31
  const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
31
- // How often a connected gateway reads idle plans' usage, so hosted Dari's
32
- // meters move without a request here.
32
+ // How often a connected gateway reads idle plans' usage, so their meters move
33
+ // without a request here.
33
34
  const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
34
35
  /**
35
36
  * Start a self-hosted Dari Gateway from environment variables:
@@ -59,8 +60,9 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
59
60
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
60
61
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
61
62
  * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
62
- * its own plans and then on hosted Dari, and syncs its plans and requests
63
- * there; Dari Link and Activity are hosted's.
63
+ * its own plans and then on hosted Dari, and syncs its requests there unless
64
+ * private mode is on (`/v1/gateway/private`); Dari Link and Activity are
65
+ * hosted's.
64
66
  */
65
67
  export async function startSelfHostedGateway(env = process.env) {
66
68
  const hosted = hostedConnectionFromEnv(env);
@@ -85,6 +87,11 @@ export async function startSelfHostedGateway(env = process.env) {
85
87
  console.warn("dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them");
86
88
  }
87
89
  const subscriptions = new SubscriptionStore(db, secrets);
90
+ const privateMode = new PrivateMode(db);
91
+ // Plans marked private before private mode kept their requests out of
92
+ // Activity; the gateway now keeps all of them out instead.
93
+ if (subscriptions.clearLegacyPrivate())
94
+ privateMode.set(true);
88
95
  const prefixes = new PrefixStore(db);
89
96
  const sessionPins = new SessionPinStore(db);
90
97
  const routerModels = new RouterModelStore(db);
@@ -156,7 +163,7 @@ export async function startSelfHostedGateway(env = process.env) {
156
163
  const routed = createRequestHandler({ platform, selectorBackend });
157
164
  const gateway = hosted === null || sync === null || hostedRouter === null
158
165
  ? routed
159
- : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, fetch });
166
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, privateMode, fetch });
160
167
  // Subscriptions, model lists, and router specs are managed with any gateway
161
168
  // key; every other path is the gateway's own.
162
169
  const handler = async (request) => {
@@ -165,7 +172,8 @@ export async function startSelfHostedGateway(env = process.env) {
165
172
  || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
166
173
  || pathname === CANONICAL_MODELS_ROUTE
167
174
  || ROUTER_MODELS_ROUTE.test(pathname)
168
- || ROUTERS_ROUTE.test(pathname);
175
+ || ROUTERS_ROUTE.test(pathname)
176
+ || pathname === PRIVATE_MODE_ROUTE;
169
177
  if (!manages)
170
178
  return await gateway(request);
171
179
  try {
@@ -176,6 +184,8 @@ export async function startSelfHostedGateway(env = process.env) {
176
184
  catch (error) {
177
185
  return errorResponse(error);
178
186
  }
187
+ if (pathname === PRIVATE_MODE_ROUTE)
188
+ return await handlePrivateModeRequest(request, privateMode).catch(errorResponse);
179
189
  if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
180
190
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
181
191
  }
@@ -0,0 +1,16 @@
1
+ import type { Database } from "bun:sqlite";
2
+ /** `GET` reads private mode and `PUT {"private": true|false}` sets it. */
3
+ export declare const PRIVATE_MODE_ROUTE = "/v1/gateway/private";
4
+ /**
5
+ * Private mode of a gateway connected to hosted Dari, kept in its database:
6
+ * on, none of its requests reach Activity, whichever plan or Dari serves them.
7
+ * It sends none to hosted Activity, and asks hosted Dari to keep only what
8
+ * billing needs of each it serves (PRIVATE_HEADER).
9
+ */
10
+ export declare class PrivateMode {
11
+ private readonly db;
12
+ constructor(db: Database);
13
+ get on(): boolean;
14
+ set(on: boolean): void;
15
+ }
16
+ export declare function handlePrivateModeRequest(request: Request, mode: PrivateMode): Promise<Response>;
@@ -0,0 +1,35 @@
1
+ import { HttpError } from "../http/errors.js";
2
+ import { parseJsonRequest } from "../ingress/json.js";
3
+ /** `GET` reads private mode and `PUT {"private": true|false}` sets it. */
4
+ export const PRIVATE_MODE_ROUTE = "/v1/gateway/private";
5
+ /**
6
+ * Private mode of a gateway connected to hosted Dari, kept in its database:
7
+ * on, none of its requests reach Activity, whichever plan or Dari serves them.
8
+ * It sends none to hosted Activity, and asks hosted Dari to keep only what
9
+ * billing needs of each it serves (PRIVATE_HEADER).
10
+ */
11
+ export class PrivateMode {
12
+ db;
13
+ constructor(db) {
14
+ this.db = db;
15
+ db.run("CREATE TABLE IF NOT EXISTS gateway_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
16
+ }
17
+ get on() {
18
+ return this.db.query("SELECT value FROM gateway_settings WHERE key = 'private'").get()?.value === "1";
19
+ }
20
+ set(on) {
21
+ this.db.run("INSERT INTO gateway_settings (key, value) VALUES ('private', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", [on ? "1" : "0"]);
22
+ }
23
+ }
24
+ export async function handlePrivateModeRequest(request, mode) {
25
+ if (request.method === "PUT") {
26
+ const body = await parseJsonRequest(request);
27
+ if (typeof body.private !== "boolean")
28
+ throw new HttpError(400, "private must be true or false.", "invalid_request_error");
29
+ mode.set(body.private);
30
+ }
31
+ else if (request.method !== "GET") {
32
+ throw new HttpError(405, "Use GET or PUT.", "method_not_allowed");
33
+ }
34
+ return Response.json({ private: mode.on }, { headers: { "Cache-Control": "no-store" } });
35
+ }
@@ -1,7 +1,7 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
3
3
  import { HttpError } from "../http/errors.js";
4
- import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
4
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
5
5
  import { explicitModelSlug } from "../protocol/input/router_model.js";
6
6
  import { CLIENT_HARNESS_HEADER } from "../ingress/client_harness.js";
7
7
  import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
@@ -382,7 +382,8 @@ function candidateConfig(deps, modelId, candidate) {
382
382
  * called for `dari/model/<id>` with the user's Dari key, in Anthropic's API
383
383
  * for Anthropic's models and OpenAI's Responses API for the rest, with the
384
384
  * client's own identifying headers and the coding agent it named, so hosted
385
- * sees the same client. Hosted Dari bills and logs what it serves.
385
+ * sees the same client. Hosted Dari bills and logs what it serves; a private
386
+ * request asks it to keep only what billing needs.
386
387
  */
387
388
  function hostedCandidate(hosted, request, modelId) {
388
389
  let routerUrl = hosted.url;
@@ -398,6 +399,8 @@ function hostedCandidate(hosted, request, modelId) {
398
399
  const headers = { ...request.clientHeaders };
399
400
  if (request.clientHarness !== undefined)
400
401
  headers[CLIENT_HARNESS_HEADER] = request.clientHarness;
402
+ if (request.private === true)
403
+ headers[PRIVATE_HEADER] = "true";
401
404
  return {
402
405
  provider: HOSTED_DARI_PROVIDER,
403
406
  key: hosted.apiKey,
@@ -34,6 +34,7 @@ export type StubConnectOptions = {
34
34
  clients?: string[];
35
35
  plans?: string[];
36
36
  keyProviders?: string[];
37
+ allowPooling?: boolean;
37
38
  grantId?: string;
38
39
  };
39
40
  /** What the approval page handed the app: a `web_message` post, or a redirect's query. */
@@ -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, ticks every plan the app can use (or `credentialIds`), approves (or
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: tick the plans,
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 usable = [...choose.matchAll(/name="credential_id" value="([^"]+)"/g)].map((match) => match[1]);
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 ?? usable).map((id) => ["credential_id", id]),
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
@@ -12,7 +12,7 @@ import { refreshStaleUsage } from "./usage.js";
12
12
  const BASE = "/v1/organizations/current/credentials";
13
13
  // Subscription names are env-var-style, which keeps other credential routes
14
14
  // such as `provider-credentials/...` out of these matches.
15
- const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
15
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/resets|\/resets\/[^/]+\/use)?$/;
16
16
  class HttpError extends Error {
17
17
  status;
18
18
  constructor(status, message) {
@@ -70,14 +70,6 @@ export async function handleSubscriptionRequest(request, deps) {
70
70
  }
71
71
  return json(200, summary(deps.store, found(renamed, name), now));
72
72
  }
73
- if (action === "/private" && request.method === "PUT") {
74
- // Private plans stay off hosted Dari: a connected gateway neither
75
- // serves nor reports them.
76
- const body = await readBody(request);
77
- if (typeof body.private !== "boolean")
78
- throw new HttpError(400, "private must be true or false.");
79
- return json(200, summary(deps.store, found(deps.store.setPrivate(name, body.private, now), name), now));
80
- }
81
73
  if (action === "/mark-available" && request.method === "POST") {
82
74
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
83
75
  }
@@ -135,10 +127,6 @@ async function startSession(deps, body, now) {
135
127
  if (credentialName !== null && reconnecting?.provider !== provider) {
136
128
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(credentialName)}.`);
137
129
  }
138
- // A reconnected plan stays where it was unless the caller says otherwise.
139
- const isPrivate = body.private ?? reconnecting?.private ?? false;
140
- if (typeof isPrivate !== "boolean")
141
- throw new HttpError(400, "private must be true or false.");
142
130
  // `dari accounts subscription connect` names the hosted plan it moves here.
143
131
  const movingFrom = body.moving_from ?? null;
144
132
  if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
@@ -150,7 +138,6 @@ async function startSession(deps, body, now) {
150
138
  flow: authorization.flow,
151
139
  credentialName,
152
140
  owner: null,
153
- private: isPrivate,
154
141
  movingFrom,
155
142
  expiresAt: authorization.expiresAt,
156
143
  }, now);
@@ -196,7 +183,7 @@ async function completeSession(deps, body, now) {
196
183
  console.error("hosted account check failed", error instanceof Error ? error.message : String(error));
197
184
  }
198
185
  }
199
- const stored = deps.store.connect(tokens, session.credentialName, now, null, session.private, elsewhere);
186
+ const stored = deps.store.connect(tokens, session.credentialName, now, null, elsewhere);
200
187
  if (stored === null) {
201
188
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(session.credentialName)}.`);
202
189
  }
@@ -286,8 +273,6 @@ function credentialBody(credential, active, now) {
286
273
  // subscription here belongs to the gateway's one user.
287
274
  credential_scope: "user",
288
275
  oauth_provider: credential.provider,
289
- // Kept off hosted Dari (`dari accounts subscription connect --on private`).
290
- private: credential.private,
291
276
  created_at: credential.createdAt.toISOString(),
292
277
  last_used_at: credential.lastUsedAt?.toISOString() ?? null,
293
278
  unavailable_until: held ? credential.unavailableUntil.toISOString() : null,
@@ -37,7 +37,6 @@ export type SubscriptionCredential = {
37
37
  accountEmail: string | null;
38
38
  accountId: string | null;
39
39
  owner: string | null;
40
- private: boolean;
41
40
  accessToken: string;
42
41
  refreshToken: string;
43
42
  expiresAt: Date;
@@ -63,7 +62,6 @@ export type PendingOAuthSession = {
63
62
  flow: Record<string, string>;
64
63
  credentialName: string | null;
65
64
  owner: string | null;
66
- private: boolean;
67
65
  movingFrom: string | null;
68
66
  expiresAt: Date;
69
67
  };
@@ -86,7 +84,7 @@ export type AccountRef = {
86
84
  * other computers. `name` is the plan's handle.
87
85
  */
88
86
  export type ConnectedAccount = AccountRef & {
89
- place: "dari" | "this_computer" | "private";
87
+ place: "dari" | "this_computer";
90
88
  name: string | null;
91
89
  connectedAt?: Date;
92
90
  };
@@ -149,15 +147,18 @@ export declare class SubscriptionStore {
149
147
  * null is the gateway owner), or `elsewhere` (the owner's plans on hosted
150
148
  * Dari and other computers) holds it.
151
149
  */
152
- connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null, isPrivate?: boolean, elsewhere?: ConnectedAccount[]): SubscriptionCredential | null;
150
+ connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null, elsewhere?: ConnectedAccount[]): SubscriptionCredential | null;
153
151
  private refuseSecondCopy;
154
152
  /** Persist refreshed tokens. Keeps the stored account id when the refresh carries none. */
155
153
  updateTokens(id: string, tokens: OAuthTokens, now?: Date): void;
156
154
  touch(id: string, now?: Date): void;
157
155
  /** An empty label clears it. Null when the subscription is not connected. */
158
156
  rename(name: string, label: string | null, now?: Date): SubscriptionCredential | null;
159
- /** Make the gateway owner's subscription private, or not. Null when it is not connected. */
160
- setPrivate(name: string, isPrivate: boolean, now?: Date): SubscriptionCredential | null;
157
+ /**
158
+ * Clear the marks of plans connected as private, before private mode
159
+ * replaced them; true when any was marked.
160
+ */
161
+ clearLegacyPrivate(): boolean;
161
162
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
162
163
  disconnect(name: string, owner?: string | null): SubscriptionCredential | null;
163
164
  /**
@@ -40,7 +40,6 @@ const PROVIDER_LABELS = {
40
40
  const PLACE_NAMES = {
41
41
  dari: "on Dari",
42
42
  this_computer: "on This Computer",
43
- private: "Private on This Computer",
44
43
  };
45
44
  function connectedAccountMessage(account) {
46
45
  const asName = account.name === null ? "" : ` as ${account.name}`;
@@ -63,7 +62,7 @@ const ADDED_COLUMNS = {
63
62
  usage_windows: "TEXT",
64
63
  model_holds: "TEXT",
65
64
  owner: "TEXT",
66
- private: "INTEGER",
65
+ private: "INTEGER", // read once, by clearLegacyPrivate
67
66
  auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
68
67
  };
69
68
  export class SubscriptionStore {
@@ -115,12 +114,11 @@ export class SubscriptionStore {
115
114
  flow_json TEXT NOT NULL,
116
115
  credential_name TEXT,
117
116
  owner TEXT,
118
- private INTEGER,
119
117
  moving_from TEXT,
120
118
  expires_at INTEGER NOT NULL
121
119
  )`);
122
120
  const sessionColumns = new Set(db.query("PRAGMA table_info(subscription_oauth_sessions)").all().map((column) => column.name));
123
- for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"], ["moving_from", "TEXT"]]) {
121
+ for (const [column, type] of [["owner", "TEXT"], ["moving_from", "TEXT"]]) {
124
122
  if (!sessionColumns.has(column))
125
123
  db.run(`ALTER TABLE subscription_oauth_sessions ADD COLUMN ${column} ${type}`);
126
124
  }
@@ -281,7 +279,7 @@ export class SubscriptionStore {
281
279
  * null is the gateway owner), or `elsewhere` (the owner's plans on hosted
282
280
  * Dari and other computers) holds it.
283
281
  */
284
- connect(tokens, reconnectName, now = new Date(), owner = null, isPrivate = false, elsewhere = []) {
282
+ connect(tokens, reconnectName, now = new Date(), owner = null, elsewhere = []) {
285
283
  const connected = this.db.transaction(() => {
286
284
  const existing = reconnectName !== null ? this.getByName(reconnectName, owner ?? null) : null;
287
285
  if (reconnectName !== null && existing?.provider !== tokens.provider)
@@ -297,7 +295,7 @@ export class SubscriptionStore {
297
295
  this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
298
296
  account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
299
297
  usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, model_holds = ?,
300
- private = ?, updated_at = ?
298
+ updated_at = ?
301
299
  WHERE id = ?`, [
302
300
  this.seal(tokens.accessToken, tokenPlace(existing.id, "access_token")),
303
301
  this.seal(tokens.refreshToken, tokenPlace(existing.id, "refresh_token")),
@@ -311,7 +309,6 @@ export class SubscriptionStore {
311
309
  usage?.observedAt.getTime() ?? null,
312
310
  usage === null ? null : windowsJson(usage),
313
311
  sameAccount ? modelHoldsJson(existing.modelHolds) : null,
314
- isPrivate ? 1 : 0,
315
312
  now.getTime(),
316
313
  existing.id,
317
314
  ]);
@@ -325,16 +322,15 @@ export class SubscriptionStore {
325
322
  const position = this.db
326
323
  .query("SELECT COALESCE(MAX(position), 0) + 1 AS next FROM subscription_credentials")
327
324
  .get().next;
328
- this.db.run(`INSERT INTO subscription_credentials (id, provider, name, account_email, account_id, owner, private,
325
+ this.db.run(`INSERT INTO subscription_credentials (id, provider, name, account_email, account_id, owner,
329
326
  access_token, refresh_token, expires_at, position, created_at, updated_at)
330
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
327
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
331
328
  id,
332
329
  tokens.provider,
333
330
  this.freeName(BASE_NAMES[tokens.provider]),
334
331
  tokens.accountEmail,
335
332
  tokens.accountId,
336
333
  owner,
337
- isPrivate ? 1 : 0,
338
334
  this.seal(tokens.accessToken, tokenPlace(id, "access_token")),
339
335
  this.seal(tokens.refreshToken, tokenPlace(id, "refresh_token")),
340
336
  tokens.expiresAt.getTime(),
@@ -355,7 +351,7 @@ export class SubscriptionStore {
355
351
  provider: local.provider,
356
352
  accountId: local.accountId,
357
353
  accountEmail: local.accountEmail,
358
- place: local.private ? "private" : "this_computer",
354
+ place: "this_computer",
359
355
  name: local.name,
360
356
  }));
361
357
  }
@@ -394,17 +390,12 @@ export class SubscriptionStore {
394
390
  ]);
395
391
  return this.get(credential.id);
396
392
  }
397
- /** Make the gateway owner's subscription private, or not. Null when it is not connected. */
398
- setPrivate(name, isPrivate, now = new Date()) {
399
- const credential = this.getByName(name);
400
- if (credential === null)
401
- return null;
402
- this.db.run("UPDATE subscription_credentials SET private = ?, updated_at = ? WHERE id = ?", [
403
- isPrivate ? 1 : 0,
404
- now.getTime(),
405
- credential.id,
406
- ]);
407
- return this.get(credential.id);
393
+ /**
394
+ * Clear the marks of plans connected as private, before private mode
395
+ * replaced them; true when any was marked.
396
+ */
397
+ clearLegacyPrivate() {
398
+ return this.db.run("UPDATE subscription_credentials SET private = NULL WHERE private = 1").changes > 0;
408
399
  }
409
400
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
410
401
  disconnect(name, owner = null) {
@@ -462,14 +453,13 @@ export class SubscriptionStore {
462
453
  createSession(session, now = new Date()) {
463
454
  const token = randomBytes(32).toString("base64url");
464
455
  this.db.run("DELETE FROM subscription_oauth_sessions WHERE expires_at <= ?", [now.getTime()]);
465
- this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, moving_from, expires_at)
466
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
456
+ this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, moving_from, expires_at)
457
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
467
458
  token,
468
459
  session.provider,
469
460
  this.seal(JSON.stringify(session.flow), flowPlace(token)),
470
461
  session.credentialName,
471
462
  session.owner,
472
- session.private ? 1 : 0,
473
463
  session.movingFrom,
474
464
  session.expiresAt.getTime(),
475
465
  ]);
@@ -488,7 +478,6 @@ export class SubscriptionStore {
488
478
  flow: JSON.parse(this.open(row.flow_json, flowPlace(row.token))),
489
479
  credentialName: row.credential_name,
490
480
  owner: row.owner,
491
- private: row.private === 1,
492
481
  movingFrom: row.moving_from,
493
482
  expiresAt: new Date(row.expires_at),
494
483
  };
@@ -589,7 +578,6 @@ function credentialFromRow(row) {
589
578
  accountEmail: row.account_email,
590
579
  accountId: row.account_id,
591
580
  owner: row.owner,
592
- private: row.private === 1,
593
581
  accessToken: row.access_token,
594
582
  refreshToken: row.refresh_token,
595
583
  expiresAt: new Date(row.expires_at),
@@ -457,6 +457,7 @@ export class RequestReporter {
457
457
  gatewayPlatform().recordRequest({
458
458
  ...(link === undefined ? {} : { link }),
459
459
  ...(subscriptionCredentialId === undefined ? {} : { subscriptionCredentialId }),
460
+ private: a.credentials.private === true,
460
461
  router: requestRecordRouter(a.credentials),
461
462
  candidates: a.candidates.map(({ model, reasoningEffort }) => ({ model, reasoningEffort })),
462
463
  ...(a.sessionPinKey === undefined ? {} : { sessionPinKey: a.sessionPinKey }),
package/dist/types.d.ts CHANGED
@@ -108,6 +108,7 @@ export type ResolvedRouter = {
108
108
  }> | null;
109
109
  link_tags?: Record<string, string> | null;
110
110
  zdr?: boolean;
111
+ private?: boolean;
111
112
  allow_long_context?: boolean;
112
113
  speculative_routing?: boolean;
113
114
  session_pinning?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.367",
3
+ "version": "1.0.369",
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.367",
55
+ "@mupt-ai/dari-router": "1.0.369",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -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. `grantId` (update mode)
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]] : []),