@mupt-ai/dari-gateway 1.0.354 → 1.0.355

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 (75) hide show
  1. package/README.md +5 -5
  2. package/dist/link/assets.js +0 -3
  3. package/dist/link/client.d.ts +2 -2
  4. package/dist/link/client.js +2 -2
  5. package/dist/link/endpoints.js +31 -8
  6. package/dist/link/errors.js +0 -1
  7. package/dist/link/self_hosted.js +11 -3
  8. package/dist/link/service.d.ts +3 -1
  9. package/dist/link/service.js +1 -0
  10. package/dist/models/catalog.js +0 -1
  11. package/dist/models/provider_defaults.js +0 -5
  12. package/dist/models/provider_models.json +0 -182
  13. package/dist/models/subscriptions.js +0 -1
  14. package/dist/platform/platform.d.ts +11 -0
  15. package/dist/providers/codex_usage.d.ts +6 -0
  16. package/dist/providers/codex_usage.js +2 -1
  17. package/dist/providers/execution.js +0 -3
  18. package/dist/providers/provider_call.js +1 -5
  19. package/dist/providers/subscription_limits.d.ts +1 -1
  20. package/dist/providers/subscription_limits.js +1 -4
  21. package/dist/providers/subscription_resets.d.ts +53 -0
  22. package/dist/providers/subscription_resets.js +184 -0
  23. package/dist/self_host/connected.d.ts +51 -0
  24. package/dist/self_host/connected.js +197 -0
  25. package/dist/self_host/hosted_sync.d.ts +53 -0
  26. package/dist/self_host/hosted_sync.js +261 -0
  27. package/dist/self_host/main.d.ts +5 -0
  28. package/dist/self_host/main.js +58 -10
  29. package/dist/self_host/platform.js +15 -2
  30. package/dist/self_host/resolve.js +0 -1
  31. package/dist/self_host/subscriptions/http.d.ts +4 -1
  32. package/dist/self_host/subscriptions/http.js +83 -11
  33. package/dist/self_host/subscriptions/index.d.ts +3 -3
  34. package/dist/self_host/subscriptions/index.js +3 -3
  35. package/dist/self_host/subscriptions/oauth.d.ts +3 -4
  36. package/dist/self_host/subscriptions/oauth.js +9 -76
  37. package/dist/self_host/subscriptions/resets.d.ts +41 -0
  38. package/dist/self_host/subscriptions/resets.js +235 -0
  39. package/dist/self_host/subscriptions/store.d.ts +61 -8
  40. package/dist/self_host/subscriptions/store.js +151 -26
  41. package/dist/self_host/subscriptions/usage.d.ts +3 -1
  42. package/dist/self_host/subscriptions/usage.js +12 -7
  43. package/dist/types.d.ts +1 -1
  44. package/package.json +2 -2
  45. package/src/link/assets.ts +0 -3
  46. package/src/link/client.ts +5 -3
  47. package/src/link/endpoints.ts +35 -7
  48. package/src/link/errors.ts +0 -1
  49. package/src/link/self_hosted.ts +9 -3
  50. package/src/link/service.ts +4 -0
  51. package/src/models/catalog.ts +0 -1
  52. package/src/models/provider_defaults.ts +0 -5
  53. package/src/models/provider_models.json +0 -182
  54. package/src/models/subscriptions.ts +0 -1
  55. package/src/platform/platform.ts +9 -0
  56. package/src/providers/codex_usage.ts +2 -1
  57. package/src/providers/execution.ts +0 -3
  58. package/src/providers/provider_call.ts +1 -5
  59. package/src/providers/subscription_limits.ts +1 -3
  60. package/src/providers/subscription_resets.ts +256 -0
  61. package/src/self_host/connected.ts +239 -0
  62. package/src/self_host/hosted_sync.ts +285 -0
  63. package/src/self_host/main.ts +55 -9
  64. package/src/self_host/platform.ts +13 -1
  65. package/src/self_host/resolve.ts +0 -1
  66. package/src/self_host/subscriptions/http.ts +85 -10
  67. package/src/self_host/subscriptions/index.ts +5 -2
  68. package/src/self_host/subscriptions/oauth.ts +8 -91
  69. package/src/self_host/subscriptions/resets.ts +254 -0
  70. package/src/self_host/subscriptions/store.ts +185 -27
  71. package/src/self_host/subscriptions/usage.ts +13 -7
  72. package/src/types.ts +0 -3
  73. package/dist/providers/github_copilot.d.ts +0 -8
  74. package/dist/providers/github_copilot.js +0 -21
  75. package/src/providers/github_copilot.ts +0 -24
@@ -0,0 +1,261 @@
1
+ import { activeModelHolds, isHeld, SUBSCRIPTION_PROVIDERS, } from "./subscriptions/index.js";
2
+ // Hosted Dari's per-call limit, and a size that stays well under its body cap.
3
+ const MAX_BATCH_ROWS = 16;
4
+ const MAX_BATCH_BYTES = 8 * 1024 * 1024;
5
+ // A row past this sheds its request and response bodies, as hosted ingest does.
6
+ const MAX_ROW_BYTES = 4 * 1024 * 1024;
7
+ const PLANS_DEBOUNCE_MS = 1_000;
8
+ // Usage and last use change on every turn; they reach hosted at most this often.
9
+ const USAGE_INTERVAL_MS = 60_000;
10
+ // Plans are reported at least this often, so hosted can tell a computer that
11
+ // is gone (its plans stop counting as connected after a day) from a quiet one.
12
+ const HEARTBEAT_MS = 60 * 60_000;
13
+ const RETRY_BASE_MS = 5_000;
14
+ const RETRY_MAX_MS = 15 * 60_000;
15
+ // Queued rows wait at least this long, so a request handed on to hosted can
16
+ // take its own row back out first (`discard`).
17
+ const DRAIN_INTERVAL_MS = 2_000;
18
+ const SETTLE_MS = 1_000;
19
+ /**
20
+ * What a gateway connected to hosted Dari tells it: its plans (metadata, never
21
+ * tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
22
+ * requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
23
+ * a moment after a plan changes and at most once a minute for usage; request
24
+ * rows wait in a SQLite outbox, sent in batches with backoff until hosted
25
+ * takes them. Private plans are never reported.
26
+ */
27
+ export class HostedSync {
28
+ db;
29
+ subscriptions;
30
+ hosted;
31
+ fetch;
32
+ now;
33
+ snapshotTimer = null;
34
+ snapshotDueAt = Infinity;
35
+ snapshotFailures = 0;
36
+ // Snapshots go one at a time, so an older one never lands after a newer one.
37
+ snapshots = Promise.resolve();
38
+ lastSnapshotAt = 0;
39
+ drainTimer = null;
40
+ draining = null;
41
+ drainFailures = 0;
42
+ drainPausedUntil = 0;
43
+ constructor(db, subscriptions, hosted, fetch, now = Date.now) {
44
+ this.db = db;
45
+ this.subscriptions = subscriptions;
46
+ this.hosted = hosted;
47
+ this.fetch = fetch;
48
+ this.now = now;
49
+ db.run(`CREATE TABLE IF NOT EXISTS hosted_request_outbox (
50
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ row_json TEXT NOT NULL,
52
+ queued_at INTEGER NOT NULL
53
+ )`);
54
+ }
55
+ /** Report the plans now and send waiting requests, then keep at it. */
56
+ start() {
57
+ this.scheduleSnapshot(0);
58
+ this.drainTimer = setInterval(() => void this.drain(), DRAIN_INTERVAL_MS);
59
+ this.drainTimer.unref?.();
60
+ void this.drain();
61
+ }
62
+ stop() {
63
+ if (this.snapshotTimer !== null)
64
+ clearTimeout(this.snapshotTimer);
65
+ if (this.drainTimer !== null)
66
+ clearInterval(this.drainTimer);
67
+ this.snapshotTimer = null;
68
+ this.drainTimer = null;
69
+ }
70
+ /** A plan was connected, removed, renamed, moved, held, or released. */
71
+ plansChanged() {
72
+ this.scheduleSnapshot(PLANS_DEBOUNCE_MS);
73
+ }
74
+ /** A plan reported usage or served a turn. */
75
+ usageChanged() {
76
+ this.scheduleSnapshot(Math.max(PLANS_DEBOUNCE_MS, this.lastSnapshotAt + USAGE_INTERVAL_MS - this.now()));
77
+ }
78
+ /** Queue a served request's log row for hosted Activity. */
79
+ enqueue(row) {
80
+ let json = JSON.stringify(row);
81
+ if (json.length > MAX_ROW_BYTES) {
82
+ json = JSON.stringify({
83
+ ...row,
84
+ client_request_json: null,
85
+ client_request_format: null,
86
+ client_response_json: null,
87
+ });
88
+ }
89
+ this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
90
+ }
91
+ /** Drop a queued request's row: hosted served that request itself and logs its own. */
92
+ discard(requestId) {
93
+ this.db.run("DELETE FROM hosted_request_outbox WHERE json_extract(row_json, '$.request_id') = ?", [requestId]);
94
+ }
95
+ /** The plans hosted Dari shows for this gateway. */
96
+ snapshot() {
97
+ const now = new Date(this.now());
98
+ return {
99
+ gateway_id: this.hosted.gatewayId,
100
+ gateway_name: this.hosted.gatewayName,
101
+ subscriptions: this.subscriptions.list().filter((plan) => !plan.private).map((plan) => planReport(plan, now)),
102
+ };
103
+ }
104
+ // Keeps the earliest of the snapshots asked for.
105
+ scheduleSnapshot(delayMs) {
106
+ const dueAt = this.now() + delayMs;
107
+ if (this.snapshotTimer !== null && this.snapshotDueAt <= dueAt)
108
+ return;
109
+ if (this.snapshotTimer !== null)
110
+ clearTimeout(this.snapshotTimer);
111
+ this.snapshotDueAt = dueAt;
112
+ this.snapshotTimer = setTimeout(() => {
113
+ this.snapshotTimer = null;
114
+ this.snapshotDueAt = Infinity;
115
+ this.snapshots = this.snapshots.then(() => this.putSnapshot());
116
+ }, delayMs);
117
+ this.snapshotTimer.unref?.();
118
+ }
119
+ async putSnapshot() {
120
+ this.lastSnapshotAt = this.now();
121
+ try {
122
+ const response = await this.call("PUT", "/v1/gateway/subscriptions", this.snapshot());
123
+ if (!response.ok)
124
+ throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
125
+ this.snapshotFailures = 0;
126
+ this.scheduleSnapshot(HEARTBEAT_MS);
127
+ }
128
+ catch (error) {
129
+ this.snapshotFailures += 1;
130
+ console.error("hosted plan sync failed", error instanceof Error ? error.message : String(error));
131
+ this.scheduleSnapshot(backoff(this.snapshotFailures));
132
+ }
133
+ }
134
+ /** Send the queued request rows a batch at a time, unless hosted failed lately. */
135
+ drain() {
136
+ this.draining ??= this.drainDue().finally(() => {
137
+ this.draining = null;
138
+ });
139
+ return this.draining;
140
+ }
141
+ async drainDue() {
142
+ while (this.now() >= this.drainPausedUntil) {
143
+ const due = this.db
144
+ .query("SELECT id, row_json FROM hosted_request_outbox WHERE queued_at <= ? ORDER BY id LIMIT ?")
145
+ // A row waits a moment, so a request handed on to hosted is discarded before it is sent.
146
+ .all(this.now() - SETTLE_MS, MAX_BATCH_ROWS);
147
+ const batch = [];
148
+ let bytes = 0;
149
+ for (const row of due) {
150
+ if (batch.length > 0 && bytes + row.row_json.length > MAX_BATCH_BYTES)
151
+ break;
152
+ batch.push(row);
153
+ bytes += row.row_json.length;
154
+ }
155
+ if (batch.length === 0)
156
+ return;
157
+ // Rows are stored as JSON already; spliced in, they are not parsed again.
158
+ const body = `{"gateway_id":${JSON.stringify(this.hosted.gatewayId)},"requests":[${batch.map((row) => `{"row":${row.row_json}}`).join(",")}]}`;
159
+ let status;
160
+ try {
161
+ const response = await this.call("POST", "/v1/gateway/requests", body);
162
+ status = response.status;
163
+ if (response.ok) {
164
+ const result = await response.json();
165
+ if (result.rejected?.length)
166
+ console.error("hosted Activity refused requests", JSON.stringify(result.rejected));
167
+ }
168
+ else {
169
+ console.error("hosted Activity sync failed", `HTTP ${status}: ${(await response.text()).slice(0, 300)}`);
170
+ }
171
+ }
172
+ catch (error) {
173
+ status = 0;
174
+ console.error("hosted Activity sync failed", error instanceof Error ? error.message : String(error));
175
+ }
176
+ // Taken, or refused for good (a malformed or oversized batch): sent.
177
+ if ((status >= 200 && status < 300) || status === 400 || status === 413) {
178
+ this.db.run(`DELETE FROM hosted_request_outbox WHERE id IN (${batch.map(() => "?").join(",")})`, batch.map((row) => row.id));
179
+ this.drainFailures = 0;
180
+ continue;
181
+ }
182
+ // Anything else may pass later: the rows wait, and so does every send.
183
+ this.drainFailures += 1;
184
+ this.drainPausedUntil = this.now() + backoff(this.drainFailures);
185
+ }
186
+ }
187
+ call(method, path, body) {
188
+ return this.fetch(`${this.hosted.url}${path}`, {
189
+ method,
190
+ headers: { authorization: `Bearer ${this.hosted.apiKey}`, "content-type": "application/json" },
191
+ body: typeof body === "string" ? body : JSON.stringify(body),
192
+ signal: AbortSignal.timeout(60_000),
193
+ });
194
+ }
195
+ }
196
+ /**
197
+ * The user's plans hosted Dari holds on other computers and on Dari, for the
198
+ * check before a sign-in connects an account: `GET /v1/gateway/accounts`
199
+ * returns each one's provider, account identity, and where it lives, never a token.
200
+ */
201
+ export async function readHostedAccounts(hosted, fetchImpl) {
202
+ const response = await fetchImpl(`${hosted.url}/v1/gateway/accounts?gateway_id=${encodeURIComponent(hosted.gatewayId)}`, {
203
+ headers: { authorization: `Bearer ${hosted.apiKey}` },
204
+ signal: AbortSignal.timeout(30_000),
205
+ });
206
+ if (!response.ok)
207
+ throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
208
+ const body = await response.json();
209
+ if (!Array.isArray(body.accounts))
210
+ throw new Error("hosted accounts response has no accounts list");
211
+ return body.accounts.map((entry) => {
212
+ if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider)) {
213
+ throw new Error(`hosted accounts response names an unknown provider ${JSON.stringify(entry.provider)}`);
214
+ }
215
+ const dari = entry.where === "dari";
216
+ return {
217
+ provider: entry.provider,
218
+ accountId: typeof entry.account_id === "string" ? entry.account_id : null,
219
+ accountEmail: typeof entry.account_email === "string" ? entry.account_email : null,
220
+ place: dari ? "dari" : "other_computer",
221
+ name: typeof entry.name === "string" ? entry.name : null,
222
+ gatewayName: typeof entry.gateway_name === "string" ? entry.gateway_name : null,
223
+ };
224
+ });
225
+ }
226
+ function backoff(failures) {
227
+ return Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, failures - 1));
228
+ }
229
+ // One plan as `PUT /v1/gateway/subscriptions` takes it. Usage uses the keys
230
+ // and formats hosted subscriptions keep in their metadata.
231
+ function planReport(plan, now) {
232
+ const held = isHeld(plan, now);
233
+ const usage = plan.usage;
234
+ return {
235
+ local_id: plan.id,
236
+ provider: plan.provider,
237
+ label: plan.label,
238
+ account_email: plan.accountEmail,
239
+ account_id: plan.accountId,
240
+ plan: null,
241
+ connected_at: plan.createdAt.toISOString(),
242
+ last_used_at: plan.lastUsedAt?.toISOString() ?? null,
243
+ unavailable_until: held ? plan.unavailableUntil.toISOString() : null,
244
+ unavailable_reason: held ? plan.unavailableReason : null,
245
+ model_holds: Object.fromEntries(activeModelHolds(plan, now).map((hold) => [
246
+ hold.model,
247
+ { until: hold.until.toISOString(), reason: hold.reason },
248
+ ])),
249
+ usage: usage === null ? {} : {
250
+ usage_utilization: usage.utilization.toFixed(4),
251
+ usage_resets_at: usage.resetsAt.toISOString(),
252
+ usage_windows: JSON.stringify(usage.windows.map((window) => ({
253
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
254
+ minutes: window.minutes,
255
+ utilization: Math.round(window.utilization * 10_000) / 10_000,
256
+ resets_at: window.resetsAt.toISOString(),
257
+ }))),
258
+ usage_observed_at: usage.observedAt.toISOString(),
259
+ },
260
+ };
261
+ }
@@ -24,6 +24,11 @@
24
24
  * Auto Routing; without it, `dari/routing` serves the first listed model.
25
25
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
26
26
  * image sets 0.0.0.0), and each provider's standard API key variable.
27
+ * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
28
+ * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
29
+ * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
30
+ * its own plans, hands hosted every request they cannot serve, and syncs its
31
+ * plans and requests there; Dari Link and Activity are hosted's.
27
32
  */
28
33
  export declare function startSelfHostedGateway(env?: Record<string, string>): Promise<{
29
34
  server: import("../http/http2_server.js").Http2RoutingServer | Bun.Server<undefined>;
@@ -9,6 +9,8 @@ import { installShutdownHandlers, startServer } from "../http/serve.js";
9
9
  import { createAutoRoutingSelectorBackend } from "../strategies/auto_routing_selector.js";
10
10
  import { createPrioritySelectorBackend } from "../strategies/priority_selector.js";
11
11
  import { ActivityStore } from "./activity_store.js";
12
+ import { connectedHandler, createConnectedPlatform, hostedConnectionFromEnv } from "./connected.js";
13
+ import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
12
14
  import { createSelfHostedPlatform } from "./platform.js";
13
15
  import { checkProviderKey } from "../providers/key_check.js";
14
16
  import { CANONICAL_MODELS } from "../models/canonical.js";
@@ -21,9 +23,14 @@ import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from
21
23
  import { handleRouterSpecsRequest, loadRouterSpecDirectory, ROUTERS_ROUTE, RouterSpecStore, servedRouter, servedRouterIds, } from "./router_specs.js";
22
24
  import { SessionPinStore } from "./session_pin_store.js";
23
25
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
26
+ import { providerBaseUrls } from "./subscriptions/resets.js";
27
+ import { refreshStaleUsage } from "./subscriptions/usage.js";
24
28
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
25
29
  // The models Dari serves, which the Dari CLI's model picker offers.
26
30
  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.
33
+ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
27
34
  /**
28
35
  * Start a self-hosted Dari Gateway from environment variables:
29
36
  *
@@ -49,8 +56,14 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
49
56
  * Auto Routing; without it, `dari/routing` serves the first listed model.
50
57
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
51
58
  * image sets 0.0.0.0), and each provider's standard API key variable.
59
+ * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
60
+ * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
61
+ * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
62
+ * its own plans, hands hosted every request they cannot serve, and syncs its
63
+ * plans and requests there; Dari Link and Activity are hosted's.
52
64
  */
53
65
  export async function startSelfHostedGateway(env = process.env) {
66
+ const hosted = hostedConnectionFromEnv(env);
54
67
  const gatewayKeys = (env.DARI_GATEWAY_KEYS ?? "")
55
68
  .split(",")
56
69
  .map((key) => key.trim())
@@ -71,7 +84,8 @@ export async function startSelfHostedGateway(env = process.env) {
71
84
  if (secrets === null) {
72
85
  console.warn("dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them");
73
86
  }
74
- const subscriptions = new SubscriptionStore(db, secrets);
87
+ // Private plans stay off hosted Dari, so a connected gateway never serves them.
88
+ const subscriptions = new SubscriptionStore(db, secrets, { privatePlansServe: hosted === null });
75
89
  const prefixes = new PrefixStore(db);
76
90
  const sessionPins = new SessionPinStore(db);
77
91
  const routerModels = new RouterModelStore(db);
@@ -88,8 +102,13 @@ export async function startSelfHostedGateway(env = process.env) {
88
102
  authContext: { env: async (name) => env[name], fileExists: async () => false },
89
103
  });
90
104
  const providerApiKey = async (provider) => (await piModels.getAuth(provider))?.auth.apiKey;
91
- const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
92
- const platform = createSelfHostedPlatform({
105
+ const autoRoutingKey = hosted?.apiKey ?? env.DARI_AUTO_ROUTING_API_KEY?.trim();
106
+ const sync = hosted === null ? null : new HostedSync(db, subscriptions, hosted, fetch);
107
+ const baseUrls = providerBaseUrls(config.providers);
108
+ if (sync !== null) {
109
+ subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
110
+ }
111
+ const platformDeps = {
93
112
  activity,
94
113
  config,
95
114
  routerModels,
@@ -103,7 +122,10 @@ export async function startSelfHostedGateway(env = process.env) {
103
122
  autoRouting: Boolean(autoRoutingKey),
104
123
  env,
105
124
  fetch,
106
- });
125
+ };
126
+ const platform = hosted === null || sync === null
127
+ ? createSelfHostedPlatform(platformDeps)
128
+ : createConnectedPlatform({ ...platformDeps, hosted, sync });
107
129
  // A model without a credential is dropped at request time, so a missing key
108
130
  // would otherwise surface only as a 424 on the first request.
109
131
  const warnWithoutCredentials = async (routerId, router) => {
@@ -113,8 +135,10 @@ export async function startSelfHostedGateway(env = process.env) {
113
135
  }
114
136
  };
115
137
  const served = servedRouterIds(routers).map((routerId) => [routerId, servedRouter(routers, routerId)]);
116
- for (const [routerId, router] of served)
117
- await warnWithoutCredentials(routerId, router);
138
+ // A connected gateway serves hosted routers, not these.
139
+ if (hosted === null)
140
+ for (const [routerId, router] of served)
141
+ await warnWithoutCredentials(routerId, router);
118
142
  await checkConfiguredProviderKeys(config, served.map(([, router]) => router), (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
119
143
  // A saved or removed spec changes what is served at once.
120
144
  const routersChanged = (routerId) => {
@@ -126,10 +150,15 @@ export async function startSelfHostedGateway(env = process.env) {
126
150
  const selectorBackend = autoRoutingKey
127
151
  ? createAutoRoutingSelectorBackend({
128
152
  apiKey: autoRoutingKey,
129
- ...(env.DARI_AUTO_ROUTING_URL ? { endpoint: env.DARI_AUTO_ROUTING_URL } : {}),
153
+ ...(hosted !== null
154
+ ? { endpoint: `${hosted.url}/v1/auto-router` }
155
+ : env.DARI_AUTO_ROUTING_URL ? { endpoint: env.DARI_AUTO_ROUTING_URL } : {}),
130
156
  })
131
157
  : createPrioritySelectorBackend();
132
- const gateway = createRequestHandler({ platform, selectorBackend });
158
+ const routed = createRequestHandler({ platform, selectorBackend });
159
+ const gateway = hosted === null || sync === null
160
+ ? routed
161
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, sync, fetch });
133
162
  // Subscriptions, model lists, and router specs are managed with any gateway
134
163
  // key; every other path is the gateway's own.
135
164
  const handler = async (request) => {
@@ -152,7 +181,12 @@ export async function startSelfHostedGateway(env = process.env) {
152
181
  if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
153
182
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
154
183
  }
155
- return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
184
+ return (await handleSubscriptionRequest(request, {
185
+ store: subscriptions,
186
+ fetch,
187
+ baseUrls,
188
+ ...(hosted === null ? {} : { hostedAccounts: () => readHostedAccounts(hosted, fetch) }),
189
+ }))
156
190
  ?? (await handleRouterModelsRequest(request, routers))
157
191
  ?? (await handleRouterSpecsRequest(request, { ...routers, changed: routersChanged }))
158
192
  ?? errorResponse(new HttpError(404, "Not found", "not_found"));
@@ -171,8 +205,22 @@ export async function startSelfHostedGateway(env = process.env) {
171
205
  // These serve router specs saved through the API.
172
206
  saved_routers: routerSpecs.savedIds(),
173
207
  auto_routing: autoRoutingKey ? "dari" : "priority",
208
+ ...(hosted === null ? {} : { connected: { hosted_url: hosted.url, gateway_id: hosted.gatewayId } }),
174
209
  }));
175
- return { server, close: () => db.close() };
210
+ sync?.start();
211
+ const idleUsage = sync === null ? null : setInterval(() => {
212
+ void refreshStaleUsage(subscriptions, { fetch, baseUrls });
213
+ }, IDLE_USAGE_INTERVAL_MS);
214
+ idleUsage?.unref?.();
215
+ return {
216
+ server,
217
+ close: () => {
218
+ if (idleUsage !== null)
219
+ clearInterval(idleUsage);
220
+ sync?.stop();
221
+ db.close();
222
+ },
223
+ };
176
224
  }
177
225
  /**
178
226
  * Check each provider API key the routers use before serving: a key its
@@ -7,6 +7,7 @@ import { SELF_HOSTED_BLOB_BUCKET } from "./activity_store.js";
7
7
  import { servedRouter } from "./router_specs.js";
8
8
  import { gatewayKeyIndex, resolveSelfHostedRouter, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
9
9
  import { refreshedAccessToken } from "./subscriptions/access.js";
10
+ import { hasBankedResets, providerBaseUrls, recoverHeldPlans } from "./subscriptions/resets.js";
10
11
  /**
11
12
  * The self-hosted platform: routers from the config file and router specs,
12
13
  * subscriptions, Dari Link grants, prefix-cache state, session pins, and
@@ -55,8 +56,20 @@ export function createSelfHostedPlatform(deps) {
55
56
  return deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
56
57
  }
57
58
  const another = deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason);
58
- if (linkGrantId === undefined)
59
- return another;
59
+ if (linkGrantId === undefined) {
60
+ // The owner's plans may come back early: from the provider's own
61
+ // report, or by spending a banked reset (resets.ts).
62
+ const held = deps.subscriptions.get(credentialId);
63
+ if (held === null || held.owner !== null || !hasBankedResets(held))
64
+ return another;
65
+ if (held.provider === "anthropic_claude_code" && another)
66
+ return another;
67
+ return await recoverHeldPlans({
68
+ store: deps.subscriptions,
69
+ fetch: deps.fetch,
70
+ baseUrls: providerBaseUrls(deps.config.providers),
71
+ }, held);
72
+ }
60
73
  // A grant's retry may use only its own subscriptions.
61
74
  const provider = deps.subscriptions.get(credentialId)?.provider;
62
75
  return provider !== undefined && deps.subscriptions.activeCredential(provider, new Date(), deps.links.credentialIds(linkGrantId)) !== null;
@@ -363,7 +363,6 @@ const SUBSCRIPTION_PLAN_NAMES = {
363
363
  openai_codex: "ChatGPT",
364
364
  meta_muse: "Muse Code",
365
365
  opencode_go: "OpenCode Go",
366
- github_copilot: "GitHub Copilot",
367
366
  xai_grok: "Grok",
368
367
  vercel_token_pass: "Vercel Token Pass",
369
368
  };
@@ -5,11 +5,14 @@
5
5
  * every subscription. Errors are `{"detail": "..."}`, which the CLI prints.
6
6
  */
7
7
  import { type OAuthFetch } from "./oauth.js";
8
- import { type SubscriptionStore } from "./store.js";
8
+ import { type ConnectedAccount, type SubscriptionStore } from "./store.js";
9
+ import { type ProviderBaseUrls } from "./resets.js";
9
10
  export type SubscriptionHttpDeps = {
10
11
  store: SubscriptionStore;
11
12
  fetch: OAuthFetch;
13
+ baseUrls?: ProviderBaseUrls;
12
14
  now?: () => Date;
15
+ hostedAccounts?: () => Promise<ConnectedAccount[]>;
13
16
  };
14
17
  /** Handle a subscription route, or return null when the request is not one. */
15
18
  export declare function handleSubscriptionRequest(request: Request, deps: SubscriptionHttpDeps): Promise<Response | null>;
@@ -6,12 +6,13 @@
6
6
  */
7
7
  import { SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, startOAuth, } from "./oauth.js";
8
8
  import { canonicalModelName } from "../../models/canonical.js";
9
- import { activeModelHolds, currentUsage, isHeld, } from "./store.js";
9
+ import { activeModelHolds, currentUsage, isHeld, sameConnectedAccount, SubscriptionAccountConnectedError, } from "./store.js";
10
+ import { hasBankedResets, listResets, useReset } from "./resets.js";
10
11
  import { refreshStaleUsage } from "./usage.js";
11
12
  const BASE = "/v1/organizations/current/credentials";
12
13
  // Subscription names are env-var-style, which keeps other credential routes
13
14
  // such as `provider-credentials/...` out of these matches.
14
- const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset)?$/;
15
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/auto-reset|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
15
16
  class HttpError extends Error {
16
17
  status;
17
18
  constructor(status, message) {
@@ -28,9 +29,9 @@ export async function handleSubscriptionRequest(request, deps) {
28
29
  const now = deps.now?.() ?? new Date();
29
30
  try {
30
31
  if (path === "" && request.method === "GET") {
31
- // OpenCode Go reports usage only when asked.
32
+ // Plans whose usage is read only when asked, or idle since their last response.
32
33
  if (url.searchParams.get("refresh_usage") === "true") {
33
- await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
34
+ await refreshStaleUsage(deps.store, { fetch: deps.fetch, now, ...(deps.baseUrls ? { baseUrls: deps.baseUrls } : {}) });
34
35
  }
35
36
  return json(200, listBody(deps.store, now));
36
37
  }
@@ -69,17 +70,50 @@ export async function handleSubscriptionRequest(request, deps) {
69
70
  }
70
71
  return json(200, summary(deps.store, found(renamed, name), now));
71
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
+ }
72
81
  if (action === "/mark-available" && request.method === "POST") {
73
82
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
74
83
  }
75
- if (action === "/auto-reset" && request.method === "POST") {
76
- throw new HttpError(400, "Spending banked limit resets is not supported by this gateway.");
84
+ if (action === "/auto-reset" && request.method === "PUT") {
85
+ const body = await readBody(request);
86
+ if (typeof body.enabled !== "boolean")
87
+ throw new HttpError(400, "enabled must be true or false.");
88
+ const credential = resettable(found(deps.store.getByName(name), name));
89
+ return json(200, summary(deps.store, found(deps.store.setAutoRedeemResets(credential.name, body.enabled, now), name), now));
90
+ }
91
+ if (action === "/resets" && request.method === "GET") {
92
+ const credential = resettable(found(deps.store.getByName(name), name));
93
+ const resets = await fromProvider(() => listResets({ ...deps, now }, credential));
94
+ return json(200, {
95
+ resets: resets.map((reset) => ({
96
+ id: reset.id,
97
+ label: reset.label,
98
+ expires_at: reset.expiresAt?.toISOString() ?? null,
99
+ usable: reset.usable,
100
+ })),
101
+ // Always read live here; hosted Dari may show an earlier list.
102
+ read_at: null,
103
+ });
104
+ }
105
+ if (action?.startsWith("/resets/") && request.method === "POST") {
106
+ const credential = resettable(found(deps.store.getByName(name), name));
107
+ const resetId = decodeURIComponent(action.slice("/resets/".length, -"/use".length));
108
+ return json(200, { result: await fromProvider(() => useReset({ ...deps, now }, credential, resetId)) });
77
109
  }
78
110
  return null;
79
111
  }
80
112
  catch (error) {
81
113
  if (error instanceof HttpError)
82
114
  return json(error.status, { detail: error.message });
115
+ if (error instanceof SubscriptionAccountConnectedError)
116
+ return json(409, { detail: error.message });
83
117
  if (error instanceof SubscriptionOAuthInputError)
84
118
  return json(400, { detail: error.message });
85
119
  if (error instanceof SubscriptionOAuthProviderError)
@@ -90,7 +124,7 @@ export async function handleSubscriptionRequest(request, deps) {
90
124
  function listBody(store, now) {
91
125
  const active = new Set(SUBSCRIPTION_PROVIDERS.map((provider) => store.activeCredential(provider, now)?.id));
92
126
  return {
93
- credentials: store.list().map((credential) => credentialBody(credential, active.has(credential.id), now)),
127
+ credentials: store.list(undefined, true).map((credential) => credentialBody(credential, active.has(credential.id), now)),
94
128
  // Plan gating is hosted-only; a self-hosted gateway always allows routing.
95
129
  autorouting_allowed: true,
96
130
  };
@@ -104,15 +138,21 @@ async function startSession(deps, body, now) {
104
138
  if (credentialName !== null && (typeof credentialName !== "string" || !credentialName.trim())) {
105
139
  throw new HttpError(400, "credential_name must be a non-empty string.");
106
140
  }
107
- if (credentialName !== null && deps.store.getByName(credentialName)?.provider !== provider) {
141
+ const reconnecting = credentialName === null ? null : deps.store.getByName(credentialName);
142
+ if (credentialName !== null && reconnecting?.provider !== provider) {
108
143
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(credentialName)}.`);
109
144
  }
145
+ // A reconnected plan stays where it was unless the caller says otherwise.
146
+ const isPrivate = body.private ?? reconnecting?.private ?? false;
147
+ if (typeof isPrivate !== "boolean")
148
+ throw new HttpError(400, "private must be true or false.");
110
149
  const authorization = await startOAuth(provider, { fetch: deps.fetch, now });
111
150
  const session = deps.store.createSession({
112
151
  provider: provider,
113
152
  flow: authorization.flow,
114
153
  credentialName,
115
154
  owner: null,
155
+ private: isPrivate,
116
156
  expiresAt: authorization.expiresAt,
117
157
  }, now);
118
158
  return {
@@ -142,7 +182,22 @@ async function completeSession(deps, body, now) {
142
182
  now,
143
183
  });
144
184
  deps.store.deleteSession(token);
145
- const stored = deps.store.connect(tokens, session.credentialName, now);
185
+ // Reconnecting a plan to the account it already holds needs no check, so it
186
+ // works even when hosted Dari cannot be read.
187
+ const target = session.credentialName === null ? null : deps.store.getByName(session.credentialName);
188
+ const reconnectsSameAccount = target !== null && sameConnectedAccount(target, tokens);
189
+ let elsewhere = [];
190
+ if (deps.hostedAccounts !== undefined && !reconnectsSameAccount) {
191
+ try {
192
+ elsewhere = await deps.hostedAccounts();
193
+ }
194
+ catch (error) {
195
+ // The provider code is spent: keep the sign-in, checked against this
196
+ // gateway's own plans only, rather than make the user start over.
197
+ console.error("hosted account check failed", error instanceof Error ? error.message : String(error));
198
+ }
199
+ }
200
+ const stored = deps.store.connect(tokens, session.credentialName, now, null, session.private, elsewhere);
146
201
  if (stored === null) {
147
202
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(session.credentialName)}.`);
148
203
  }
@@ -222,6 +277,8 @@ function credentialBody(credential, active, now) {
222
277
  // subscription here belongs to the gateway's one user.
223
278
  credential_scope: "user",
224
279
  oauth_provider: credential.provider,
280
+ // Kept off hosted Dari (`dari accounts subscription connect --on private`).
281
+ private: credential.private,
225
282
  created_at: credential.createdAt.toISOString(),
226
283
  last_used_at: credential.lastUsedAt?.toISOString() ?? null,
227
284
  unavailable_until: held ? credential.unavailableUntil.toISOString() : null,
@@ -237,10 +294,25 @@ function credentialBody(credential, active, now) {
237
294
  // The share of its tightest window the plan last reported used, and
238
295
  // every window as shown; null when it reports none and is not held.
239
296
  usage: usageBody(credential, now),
240
- // Spending banked limit resets is hosted-only.
241
- auto_redeem_resets: false,
297
+ auto_redeem_resets: credential.autoRedeemResets,
242
298
  };
243
299
  }
300
+ function resettable(credential) {
301
+ if (!hasBankedResets(credential))
302
+ throw new HttpError(400, "Only ChatGPT and Claude Code plans have banked resets.");
303
+ return credential;
304
+ }
305
+ // A provider that fails to answer is a bad gateway, as on hosted Dari.
306
+ async function fromProvider(call) {
307
+ try {
308
+ return await call();
309
+ }
310
+ catch (error) {
311
+ if (error instanceof HttpError)
312
+ throw error;
313
+ throw new HttpError(502, error instanceof Error ? error.message : String(error));
314
+ }
315
+ }
244
316
  function found(credential, name) {
245
317
  if (credential === null)
246
318
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(name)}.`);
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code,
3
- * ChatGPT, Muse Code, OpenCode Go, GitHub Copilot, and Grok plans
3
+ * ChatGPT, Muse Code, OpenCode Go, and Grok plans
4
4
  * connected over OAuth, and Vercel Token Pass keys, used in place of API keys.
5
5
  *
6
6
  * - `oauth.ts`: the providers' OAuth protocols (Claude Code PKCE with a
@@ -26,5 +26,5 @@
26
26
  */
27
27
  export { freshAccessToken } from "./access.js";
28
28
  export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
29
- export { CODEX_APPROVAL_PENDING, GITHUB_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
30
- export { SubscriptionStore, activeModelHolds, currentUsage, isHeld, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
29
+ export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
30
+ export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, sameConnectedAccount, type AccountRef, type ConnectedAccount, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";