@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,239 @@
1
+ import { hostname } from "node:os";
2
+
3
+ import { isReasoningEffort, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
4
+ import { anthropicToken, bearerToken } from "../http/auth.js";
5
+ import { errorResponse, HttpError } from "../http/errors.js";
6
+ import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
7
+ import type { GatewayPlatform } from "../platform/platform.js";
8
+ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
9
+ import { explicitModelId } from "../protocol/input/router_model.js";
10
+ import { parseGatewayConfig, type RouterConfig } from "./config.js";
11
+ import type { HostedSync } from "./hosted_sync.js";
12
+ import { createSelfHostedPlatform } from "./platform.js";
13
+ import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
14
+
15
+ /**
16
+ * A self-hosted gateway connected to hosted Dari (the Dari CLI runs one for
17
+ * plans kept "on this computer"): it serves a turn on the user's own plans
18
+ * when one serves the model, and otherwise hands the whole request to hosted
19
+ * Dari with the user's Dari key, so agents see one router either way.
20
+ *
21
+ * - Routers are the user's hosted routers, by id (`/<router id>/v1/...`, or
22
+ * the default router at `/v1/...`): each serves the hosted router's models
23
+ * that a local plan serves, chosen by the hosted Auto Router API.
24
+ * - A request no local plan can serve (none connected or every one held, or
25
+ * a model they do not serve) goes to hosted, as does every other path the
26
+ * gateway does not manage itself, such as model lists and commit reports.
27
+ * - The plans and served requests sync to hosted (hosted_sync.ts), which
28
+ * shows them in Accounts and Activity; private plans neither serve nor sync.
29
+ * Dari Link and Activity are hosted's, not served here.
30
+ */
31
+ export type HostedConnection = {
32
+ // The hosted routing service, e.g. https://routing.dari.dev.
33
+ url: string;
34
+ // A Dari API key that acts for the user.
35
+ apiKey: string;
36
+ // This gateway, as hosted Dari tells the user's gateways apart.
37
+ gatewayId: string;
38
+ gatewayName: string;
39
+ };
40
+
41
+ /**
42
+ * The connection `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY` set up, or null
43
+ * when neither is set. A connected gateway needs `DARI_GATEWAY_ID` and
44
+ * `DARI_GATEWAY_ENCRYPTION_KEY`; `DARI_GATEWAY_NAME` defaults to the host name.
45
+ */
46
+ export function hostedConnectionFromEnv(env: Record<string, string | undefined>): HostedConnection | null {
47
+ const url = env.DARI_HOSTED_URL?.trim().replace(/\/+$/, "");
48
+ const apiKey = env.DARI_HOSTED_API_KEY?.trim();
49
+ if (!url && !apiKey) return null;
50
+ if (!url || !apiKey) throw new Error("Set both DARI_HOSTED_URL and DARI_HOSTED_API_KEY to connect to hosted Dari.");
51
+ const gatewayId = env.DARI_GATEWAY_ID?.trim();
52
+ if (!gatewayId) throw new Error("A gateway connected to hosted Dari needs DARI_GATEWAY_ID.");
53
+ if (!env.DARI_GATEWAY_ENCRYPTION_KEY?.trim()) {
54
+ throw new Error("A gateway connected to hosted Dari needs DARI_GATEWAY_ENCRYPTION_KEY to encrypt its plans' tokens.");
55
+ }
56
+ return { url, apiKey, gatewayId, gatewayName: env.DARI_GATEWAY_NAME?.trim() || hostname() };
57
+ }
58
+
59
+ type SelfHostedPlatformDeps = Parameters<typeof createSelfHostedPlatform>[0];
60
+
61
+ /** The self-hosted platform on hosted routers, reporting requests to hosted Dari. */
62
+ export function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
63
+ hosted: HostedConnection;
64
+ sync: HostedSync;
65
+ }): GatewayPlatform {
66
+ const platform = createSelfHostedPlatform(deps);
67
+ const hostedRouter = hostedRouters(deps.hosted, deps.fetch as typeof fetch);
68
+ return {
69
+ ...platform,
70
+ async resolveRouter(request) {
71
+ const router = await hostedRouter(request.routerId);
72
+ return await resolveSelfHostedRouter({
73
+ ...deps,
74
+ config: { ...deps.config, routers: { [request.routerId]: router } },
75
+ prefixHits: (args) => deps.prefixes.hits(args),
76
+ }, request);
77
+ },
78
+ recordRequest(record) {
79
+ console.info("routing request", JSON.stringify(record.summary));
80
+ try {
81
+ deps.sync.enqueue(record.row);
82
+ } catch (error) {
83
+ console.error("hosted Activity queue failed", error instanceof Error ? error.message : String(error));
84
+ }
85
+ },
86
+ link: undefined,
87
+ activity: undefined,
88
+ };
89
+ }
90
+
91
+ const ROUTER_CACHE_MS = 60_000;
92
+
93
+ /**
94
+ * A hosted router as this gateway serves it: its models, read from hosted's
95
+ * model list (cached for a minute), on the user's plans only.
96
+ */
97
+ function hostedRouters(hosted: HostedConnection, fetchImpl: typeof fetch) {
98
+ const cache = new Map<string, { router: RouterConfig; readAt: number }>();
99
+ return async (routerId: string): Promise<RouterConfig> => {
100
+ const cached = cache.get(routerId);
101
+ if (cached !== undefined && Date.now() - cached.readAt < ROUTER_CACHE_MS) return cached.router;
102
+ let router: RouterConfig;
103
+ try {
104
+ router = await readHostedRouter(hosted, fetchImpl, routerId);
105
+ } catch (error) {
106
+ if (cached !== undefined) return cached.router;
107
+ console.error("hosted router read failed", error instanceof Error ? error.message : String(error));
108
+ // A 424 hands the request to hosted, which reports its own error.
109
+ throw new HttpError(424, `Router ${routerId} could not be read from hosted Dari.`, "hosted_router_unavailable");
110
+ }
111
+ cache.set(routerId, { router, readAt: Date.now() });
112
+ return router;
113
+ };
114
+ }
115
+
116
+ async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetch, routerId: string): Promise<RouterConfig> {
117
+ const prefix = routerId === DEFAULT_ROUTER_ALIAS ? "" : `/${encodeURIComponent(routerId)}`;
118
+ const response = await fetchImpl(`${hosted.url}${prefix}/v1/models`, {
119
+ headers: { authorization: `Bearer ${hosted.apiKey}` },
120
+ signal: AbortSignal.timeout(30_000),
121
+ });
122
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
123
+ const catalog = await response.json() as {
124
+ remote_compaction?: string;
125
+ models?: Array<{ slug?: string; supported_reasoning_levels?: Array<{ effort?: string }> }>;
126
+ };
127
+ const models = (catalog.models ?? []).flatMap((entry) => {
128
+ // `dari/routing` is the router itself, not one of its models.
129
+ const id = explicitModelId(entry.slug);
130
+ if (id === null) return [];
131
+ const thinking = entry.supported_reasoning_levels
132
+ ?.map((level) => level.effort === "none" ? "off" : level.effort)
133
+ .filter((level): level is ReasoningEffort => isReasoningEffort(level));
134
+ return [thinking?.length ? { id, thinking } : { id }];
135
+ });
136
+ if (models.length === 0) throw new Error("it lists no models");
137
+ return parseGatewayConfig({
138
+ routers: {
139
+ [routerId]: { models, subscriptions: true, nativeCompaction: catalog.remote_compaction === "v2" },
140
+ },
141
+ }).routers[routerId]!;
142
+ }
143
+
144
+ // The routed calls a local plan may serve; anything else the gateway does
145
+ // not manage goes to hosted.
146
+ const ROUTED_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages)$/;
147
+
148
+ /**
149
+ * Serve a connected gateway's routed surface: `gateway` (the gateway's own
150
+ * handler on the connected platform) first, and hosted Dari for a request it
151
+ * cannot serve on a local plan. Health checks stay local; every request
152
+ * forwarded must carry a gateway key.
153
+ */
154
+ export function connectedHandler(deps: {
155
+ gateway: (request: Request) => Promise<Response>;
156
+ gatewayKeys: readonly string[];
157
+ hosted: HostedConnection;
158
+ sync: HostedSync;
159
+ fetch: typeof fetch;
160
+ }): (request: Request) => Promise<Response> {
161
+ return async (request) => {
162
+ const { pathname } = new URL(request.url);
163
+ if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
164
+ return await deps.gateway(request);
165
+ }
166
+ // Claude Code reads errors in Anthropic's shape, as the gateway answers them.
167
+ const fail = MESSAGES_CALL.test(pathname) ? anthropicErrorResponse : errorResponse;
168
+ try {
169
+ const anthropic = !request.headers.has("authorization") && request.headers.has("x-api-key");
170
+ const key = anthropic ? anthropicToken(request.headers) : bearerToken(request.headers);
171
+ if (gatewayKeyIndex(deps.gatewayKeys, key) === null) {
172
+ throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
173
+ }
174
+ } catch (error) {
175
+ return fail(error);
176
+ }
177
+ const body = request.method === "GET" || request.method === "HEAD" ? null : await request.arrayBuffer();
178
+ if (request.method === "POST" && ROUTED_CALL.test(pathname)) {
179
+ const local = await deps.gateway(new Request(request.url, {
180
+ method: request.method,
181
+ headers: request.headers,
182
+ body,
183
+ signal: request.signal,
184
+ }));
185
+ if (!(await servedElsewhere(local))) return local;
186
+ await local.body?.cancel();
187
+ // Hosted logs the request it serves; the local attempt is not one.
188
+ const requestId = local.headers.get("x-request-id");
189
+ if (requestId !== null) deps.sync.discard(requestId);
190
+ }
191
+ return await forward(request, body, deps, fail);
192
+ };
193
+ }
194
+
195
+ const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
196
+
197
+ /**
198
+ * Whether a local response means no local plan could serve the request: none
199
+ * serves the router's models or the one asked for (424, or the explicit
200
+ * model's 400), or every one is at its limit (429).
201
+ */
202
+ async function servedElsewhere(response: Response): Promise<boolean> {
203
+ if (response.status === 424 || response.status === 429) return true;
204
+ if (response.status !== 400) return false;
205
+ const text = await response.clone().text();
206
+ return text.includes("model_not_enabled") || text.includes("is not enabled on this router");
207
+ }
208
+
209
+ // The request as the client sent it, on hosted Dari with the user's key.
210
+ async function forward(
211
+ request: Request,
212
+ body: ArrayBuffer | null,
213
+ deps: { hosted: HostedConnection; fetch: typeof fetch },
214
+ fail: (error: unknown) => Response,
215
+ ): Promise<Response> {
216
+ const url = new URL(request.url);
217
+ const headers = new Headers(request.headers);
218
+ for (const name of ["host", "authorization", "x-api-key", "content-length", "connection", "accept-encoding"]) {
219
+ headers.delete(name);
220
+ }
221
+ headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
222
+ let response: Response;
223
+ try {
224
+ response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
225
+ method: request.method,
226
+ headers,
227
+ body,
228
+ redirect: "manual",
229
+ signal: request.signal,
230
+ });
231
+ } catch {
232
+ return fail(new HttpError(502, "Hosted Dari could not be reached.", "hosted_unreachable"));
233
+ }
234
+ // The body arrives decoded; its length and encoding no longer apply.
235
+ const responseHeaders = new Headers(response.headers);
236
+ responseHeaders.delete("content-encoding");
237
+ responseHeaders.delete("content-length");
238
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders });
239
+ }
@@ -0,0 +1,285 @@
1
+ import type { Database } from "bun:sqlite";
2
+
3
+ import type { HostedConnection } from "./connected.js";
4
+ import {
5
+ activeModelHolds,
6
+ isHeld,
7
+ SUBSCRIPTION_PROVIDERS,
8
+ type ConnectedAccount,
9
+ type SubscriptionCredential,
10
+ type SubscriptionProvider,
11
+ type SubscriptionStore,
12
+ } from "./subscriptions/index.js";
13
+
14
+ // Hosted Dari's per-call limit, and a size that stays well under its body cap.
15
+ const MAX_BATCH_ROWS = 16;
16
+ const MAX_BATCH_BYTES = 8 * 1024 * 1024;
17
+ // A row past this sheds its request and response bodies, as hosted ingest does.
18
+ const MAX_ROW_BYTES = 4 * 1024 * 1024;
19
+ const PLANS_DEBOUNCE_MS = 1_000;
20
+ // Usage and last use change on every turn; they reach hosted at most this often.
21
+ const USAGE_INTERVAL_MS = 60_000;
22
+ // Plans are reported at least this often, so hosted can tell a computer that
23
+ // is gone (its plans stop counting as connected after a day) from a quiet one.
24
+ const HEARTBEAT_MS = 60 * 60_000;
25
+ const RETRY_BASE_MS = 5_000;
26
+ const RETRY_MAX_MS = 15 * 60_000;
27
+ // Queued rows wait at least this long, so a request handed on to hosted can
28
+ // take its own row back out first (`discard`).
29
+ const DRAIN_INTERVAL_MS = 2_000;
30
+ const SETTLE_MS = 1_000;
31
+
32
+ type OutboxRow = { id: number; row_json: string };
33
+
34
+ /**
35
+ * What a gateway connected to hosted Dari tells it: its plans (metadata, never
36
+ * tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
37
+ * requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
38
+ * a moment after a plan changes and at most once a minute for usage; request
39
+ * rows wait in a SQLite outbox, sent in batches with backoff until hosted
40
+ * takes them. Private plans are never reported.
41
+ */
42
+ export class HostedSync {
43
+ private snapshotTimer: ReturnType<typeof setTimeout> | null = null;
44
+ private snapshotDueAt = Infinity;
45
+ private snapshotFailures = 0;
46
+ // Snapshots go one at a time, so an older one never lands after a newer one.
47
+ private snapshots: Promise<void> = Promise.resolve();
48
+ private lastSnapshotAt = 0;
49
+ private drainTimer: ReturnType<typeof setInterval> | null = null;
50
+ private draining: Promise<void> | null = null;
51
+ private drainFailures = 0;
52
+ private drainPausedUntil = 0;
53
+
54
+ constructor(
55
+ private readonly db: Database,
56
+ private readonly subscriptions: SubscriptionStore,
57
+ private readonly hosted: HostedConnection,
58
+ private readonly fetch: typeof globalThis.fetch,
59
+ private readonly now: () => number = Date.now,
60
+ ) {
61
+ db.run(`CREATE TABLE IF NOT EXISTS hosted_request_outbox (
62
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
63
+ row_json TEXT NOT NULL,
64
+ queued_at INTEGER NOT NULL
65
+ )`);
66
+ }
67
+
68
+ /** Report the plans now and send waiting requests, then keep at it. */
69
+ start(): void {
70
+ this.scheduleSnapshot(0);
71
+ this.drainTimer = setInterval(() => void this.drain(), DRAIN_INTERVAL_MS);
72
+ this.drainTimer.unref?.();
73
+ void this.drain();
74
+ }
75
+
76
+ stop(): void {
77
+ if (this.snapshotTimer !== null) clearTimeout(this.snapshotTimer);
78
+ if (this.drainTimer !== null) clearInterval(this.drainTimer);
79
+ this.snapshotTimer = null;
80
+ this.drainTimer = null;
81
+ }
82
+
83
+ /** A plan was connected, removed, renamed, moved, held, or released. */
84
+ plansChanged(): void {
85
+ this.scheduleSnapshot(PLANS_DEBOUNCE_MS);
86
+ }
87
+
88
+ /** A plan reported usage or served a turn. */
89
+ usageChanged(): void {
90
+ this.scheduleSnapshot(Math.max(PLANS_DEBOUNCE_MS, this.lastSnapshotAt + USAGE_INTERVAL_MS - this.now()));
91
+ }
92
+
93
+ /** Queue a served request's log row for hosted Activity. */
94
+ enqueue(row: Record<string, unknown>): void {
95
+ let json = JSON.stringify(row);
96
+ if (json.length > MAX_ROW_BYTES) {
97
+ json = JSON.stringify({
98
+ ...row,
99
+ client_request_json: null,
100
+ client_request_format: null,
101
+ client_response_json: null,
102
+ });
103
+ }
104
+ this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
105
+ }
106
+
107
+ /** Drop a queued request's row: hosted served that request itself and logs its own. */
108
+ discard(requestId: string): void {
109
+ this.db.run("DELETE FROM hosted_request_outbox WHERE json_extract(row_json, '$.request_id') = ?", [requestId]);
110
+ }
111
+
112
+ /** The plans hosted Dari shows for this gateway. */
113
+ snapshot(): Record<string, unknown> {
114
+ const now = new Date(this.now());
115
+ return {
116
+ gateway_id: this.hosted.gatewayId,
117
+ gateway_name: this.hosted.gatewayName,
118
+ subscriptions: this.subscriptions.list().filter((plan) => !plan.private).map((plan) => planReport(plan, now)),
119
+ };
120
+ }
121
+
122
+ // Keeps the earliest of the snapshots asked for.
123
+ private scheduleSnapshot(delayMs: number): void {
124
+ const dueAt = this.now() + delayMs;
125
+ if (this.snapshotTimer !== null && this.snapshotDueAt <= dueAt) return;
126
+ if (this.snapshotTimer !== null) clearTimeout(this.snapshotTimer);
127
+ this.snapshotDueAt = dueAt;
128
+ this.snapshotTimer = setTimeout(() => {
129
+ this.snapshotTimer = null;
130
+ this.snapshotDueAt = Infinity;
131
+ this.snapshots = this.snapshots.then(() => this.putSnapshot());
132
+ }, delayMs);
133
+ this.snapshotTimer.unref?.();
134
+ }
135
+
136
+ private async putSnapshot(): Promise<void> {
137
+ this.lastSnapshotAt = this.now();
138
+ try {
139
+ const response = await this.call("PUT", "/v1/gateway/subscriptions", this.snapshot());
140
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
141
+ this.snapshotFailures = 0;
142
+ this.scheduleSnapshot(HEARTBEAT_MS);
143
+ } catch (error) {
144
+ this.snapshotFailures += 1;
145
+ console.error("hosted plan sync failed", error instanceof Error ? error.message : String(error));
146
+ this.scheduleSnapshot(backoff(this.snapshotFailures));
147
+ }
148
+ }
149
+
150
+ /** Send the queued request rows a batch at a time, unless hosted failed lately. */
151
+ drain(): Promise<void> {
152
+ this.draining ??= this.drainDue().finally(() => {
153
+ this.draining = null;
154
+ });
155
+ return this.draining;
156
+ }
157
+
158
+ private async drainDue(): Promise<void> {
159
+ while (this.now() >= this.drainPausedUntil) {
160
+ const due = this.db
161
+ .query<OutboxRow, [number, number]>(
162
+ "SELECT id, row_json FROM hosted_request_outbox WHERE queued_at <= ? ORDER BY id LIMIT ?",
163
+ )
164
+ // A row waits a moment, so a request handed on to hosted is discarded before it is sent.
165
+ .all(this.now() - SETTLE_MS, MAX_BATCH_ROWS);
166
+ const batch: OutboxRow[] = [];
167
+ let bytes = 0;
168
+ for (const row of due) {
169
+ if (batch.length > 0 && bytes + row.row_json.length > MAX_BATCH_BYTES) break;
170
+ batch.push(row);
171
+ bytes += row.row_json.length;
172
+ }
173
+ if (batch.length === 0) return;
174
+ // Rows are stored as JSON already; spliced in, they are not parsed again.
175
+ const body = `{"gateway_id":${JSON.stringify(this.hosted.gatewayId)},"requests":[${
176
+ batch.map((row) => `{"row":${row.row_json}}`).join(",")
177
+ }]}`;
178
+ let status: number;
179
+ try {
180
+ const response = await this.call("POST", "/v1/gateway/requests", body);
181
+ status = response.status;
182
+ if (response.ok) {
183
+ const result = await response.json() as { rejected?: Array<{ request_id: string | null; error: string }> };
184
+ if (result.rejected?.length) console.error("hosted Activity refused requests", JSON.stringify(result.rejected));
185
+ } else {
186
+ console.error("hosted Activity sync failed", `HTTP ${status}: ${(await response.text()).slice(0, 300)}`);
187
+ }
188
+ } catch (error) {
189
+ status = 0;
190
+ console.error("hosted Activity sync failed", error instanceof Error ? error.message : String(error));
191
+ }
192
+ // Taken, or refused for good (a malformed or oversized batch): sent.
193
+ if ((status >= 200 && status < 300) || status === 400 || status === 413) {
194
+ this.db.run(`DELETE FROM hosted_request_outbox WHERE id IN (${batch.map(() => "?").join(",")})`, batch.map((row) => row.id));
195
+ this.drainFailures = 0;
196
+ continue;
197
+ }
198
+ // Anything else may pass later: the rows wait, and so does every send.
199
+ this.drainFailures += 1;
200
+ this.drainPausedUntil = this.now() + backoff(this.drainFailures);
201
+ }
202
+ }
203
+
204
+ private call(method: string, path: string, body: unknown): Promise<Response> {
205
+ return this.fetch(`${this.hosted.url}${path}`, {
206
+ method,
207
+ headers: { authorization: `Bearer ${this.hosted.apiKey}`, "content-type": "application/json" },
208
+ body: typeof body === "string" ? body : JSON.stringify(body),
209
+ signal: AbortSignal.timeout(60_000),
210
+ });
211
+ }
212
+ }
213
+
214
+ /**
215
+ * The user's plans hosted Dari holds on other computers and on Dari, for the
216
+ * check before a sign-in connects an account: `GET /v1/gateway/accounts`
217
+ * returns each one's provider, account identity, and where it lives, never a token.
218
+ */
219
+ export async function readHostedAccounts(
220
+ hosted: HostedConnection,
221
+ fetchImpl: typeof globalThis.fetch,
222
+ ): Promise<ConnectedAccount[]> {
223
+ const response = await fetchImpl(
224
+ `${hosted.url}/v1/gateway/accounts?gateway_id=${encodeURIComponent(hosted.gatewayId)}`,
225
+ {
226
+ headers: { authorization: `Bearer ${hosted.apiKey}` },
227
+ signal: AbortSignal.timeout(30_000),
228
+ },
229
+ );
230
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
231
+ const body = await response.json() as { accounts?: unknown };
232
+ if (!Array.isArray(body.accounts)) throw new Error("hosted accounts response has no accounts list");
233
+ return body.accounts.map((entry: Record<string, unknown>) => {
234
+ if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider as SubscriptionProvider)) {
235
+ throw new Error(`hosted accounts response names an unknown provider ${JSON.stringify(entry.provider)}`);
236
+ }
237
+ const dari = entry.where === "dari";
238
+ return {
239
+ provider: entry.provider as SubscriptionProvider,
240
+ accountId: typeof entry.account_id === "string" ? entry.account_id : null,
241
+ accountEmail: typeof entry.account_email === "string" ? entry.account_email : null,
242
+ place: dari ? "dari" : "other_computer",
243
+ name: typeof entry.name === "string" ? entry.name : null,
244
+ gatewayName: typeof entry.gateway_name === "string" ? entry.gateway_name : null,
245
+ };
246
+ });
247
+ }
248
+
249
+ function backoff(failures: number): number {
250
+ return Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, failures - 1));
251
+ }
252
+
253
+ // One plan as `PUT /v1/gateway/subscriptions` takes it. Usage uses the keys
254
+ // and formats hosted subscriptions keep in their metadata.
255
+ function planReport(plan: SubscriptionCredential, now: Date): Record<string, unknown> {
256
+ const held = isHeld(plan, now);
257
+ const usage = plan.usage;
258
+ return {
259
+ local_id: plan.id,
260
+ provider: plan.provider,
261
+ label: plan.label,
262
+ account_email: plan.accountEmail,
263
+ account_id: plan.accountId,
264
+ plan: null,
265
+ connected_at: plan.createdAt.toISOString(),
266
+ last_used_at: plan.lastUsedAt?.toISOString() ?? null,
267
+ unavailable_until: held ? plan.unavailableUntil!.toISOString() : null,
268
+ unavailable_reason: held ? plan.unavailableReason : null,
269
+ model_holds: Object.fromEntries(activeModelHolds(plan, now).map((hold) => [
270
+ hold.model,
271
+ { until: hold.until.toISOString(), reason: hold.reason },
272
+ ])),
273
+ usage: usage === null ? {} : {
274
+ usage_utilization: usage.utilization.toFixed(4),
275
+ usage_resets_at: usage.resetsAt.toISOString(),
276
+ usage_windows: JSON.stringify(usage.windows.map((window) => ({
277
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
278
+ minutes: window.minutes,
279
+ utilization: Math.round(window.utilization * 10_000) / 10_000,
280
+ resets_at: window.resetsAt.toISOString(),
281
+ }))),
282
+ usage_observed_at: usage.observedAt.toISOString(),
283
+ },
284
+ };
285
+ }
@@ -11,6 +11,8 @@ import { createAutoRoutingSelectorBackend } from "../strategies/auto_routing_sel
11
11
  import { createPrioritySelectorBackend } from "../strategies/priority_selector.js";
12
12
  import type { SelectorBackend } from "../strategies/routing.js";
13
13
  import { ActivityStore } from "./activity_store.js";
14
+ import { connectedHandler, createConnectedPlatform, hostedConnectionFromEnv } from "./connected.js";
15
+ import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
14
16
  import { createSelfHostedPlatform } from "./platform.js";
15
17
  import { checkProviderKey } from "../providers/key_check.js";
16
18
  import { CANONICAL_MODELS } from "../models/canonical.js";
@@ -36,10 +38,15 @@ import {
36
38
  } from "./router_specs.js";
37
39
  import { SessionPinStore } from "./session_pin_store.js";
38
40
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
41
+ import { providerBaseUrls } from "./subscriptions/resets.js";
42
+ import { refreshStaleUsage } from "./subscriptions/usage.js";
39
43
 
40
44
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
41
45
  // The models Dari serves, which the Dari CLI's model picker offers.
42
46
  const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
47
+ // How often a connected gateway reads idle plans' usage, so hosted Dari's
48
+ // meters move without a request here.
49
+ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
43
50
 
44
51
  /**
45
52
  * Start a self-hosted Dari Gateway from environment variables:
@@ -66,8 +73,14 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
66
73
  * Auto Routing; without it, `dari/routing` serves the first listed model.
67
74
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
68
75
  * image sets 0.0.0.0), and each provider's standard API key variable.
76
+ * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
77
+ * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
78
+ * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
79
+ * its own plans, hands hosted every request they cannot serve, and syncs its
80
+ * plans and requests there; Dari Link and Activity are hosted's.
69
81
  */
70
82
  export async function startSelfHostedGateway(env: Record<string, string> = process.env as Record<string, string>) {
83
+ const hosted = hostedConnectionFromEnv(env);
71
84
  const gatewayKeys = (env.DARI_GATEWAY_KEYS ?? "")
72
85
  .split(",")
73
86
  .map((key) => key.trim())
@@ -89,7 +102,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
89
102
  "dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them",
90
103
  );
91
104
  }
92
- const subscriptions = new SubscriptionStore(db, secrets);
105
+ // Private plans stay off hosted Dari, so a connected gateway never serves them.
106
+ const subscriptions = new SubscriptionStore(db, secrets, { privatePlansServe: hosted === null });
93
107
  const prefixes = new PrefixStore(db);
94
108
  const sessionPins = new SessionPinStore(db);
95
109
  const routerModels = new RouterModelStore(db);
@@ -111,8 +125,13 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
111
125
  });
112
126
 
113
127
  const providerApiKey = async (provider: string) => (await piModels.getAuth(provider))?.auth.apiKey;
114
- const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
115
- const platform = createSelfHostedPlatform({
128
+ const autoRoutingKey = hosted?.apiKey ?? env.DARI_AUTO_ROUTING_API_KEY?.trim();
129
+ const sync = hosted === null ? null : new HostedSync(db, subscriptions, hosted, fetch);
130
+ const baseUrls = providerBaseUrls(config.providers);
131
+ if (sync !== null) {
132
+ subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
133
+ }
134
+ const platformDeps = {
116
135
  activity,
117
136
  config,
118
137
  routerModels,
@@ -126,7 +145,10 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
126
145
  autoRouting: Boolean(autoRoutingKey),
127
146
  env,
128
147
  fetch,
129
- });
148
+ };
149
+ const platform = hosted === null || sync === null
150
+ ? createSelfHostedPlatform(platformDeps)
151
+ : createConnectedPlatform({ ...platformDeps, hosted, sync });
130
152
  // A model without a credential is dropped at request time, so a missing key
131
153
  // would otherwise surface only as a 424 on the first request.
132
154
  const warnWithoutCredentials = async (routerId: string, router: RouterConfig) => {
@@ -139,7 +161,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
139
161
  }
140
162
  };
141
163
  const served = servedRouterIds(routers).map((routerId) => [routerId, servedRouter(routers, routerId)!] as const);
142
- for (const [routerId, router] of served) await warnWithoutCredentials(routerId, router);
164
+ // A connected gateway serves hosted routers, not these.
165
+ if (hosted === null) for (const [routerId, router] of served) await warnWithoutCredentials(routerId, router);
143
166
  await checkConfiguredProviderKeys(config, served.map(([, router]) => router), (provider) =>
144
167
  configuredProviderApiKey({ config, providerApiKey, env }, provider));
145
168
  // A saved or removed spec changes what is served at once.
@@ -151,10 +174,15 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
151
174
  const selectorBackend: SelectorBackend = autoRoutingKey
152
175
  ? createAutoRoutingSelectorBackend({
153
176
  apiKey: autoRoutingKey,
154
- ...(env.DARI_AUTO_ROUTING_URL ? { endpoint: env.DARI_AUTO_ROUTING_URL } : {}),
177
+ ...(hosted !== null
178
+ ? { endpoint: `${hosted.url}/v1/auto-router` }
179
+ : env.DARI_AUTO_ROUTING_URL ? { endpoint: env.DARI_AUTO_ROUTING_URL } : {}),
155
180
  })
156
181
  : createPrioritySelectorBackend();
157
- const gateway = createRequestHandler({ platform, selectorBackend });
182
+ const routed = createRequestHandler({ platform, selectorBackend });
183
+ const gateway = hosted === null || sync === null
184
+ ? routed
185
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, sync, fetch });
158
186
 
159
187
  // Subscriptions, model lists, and router specs are managed with any gateway
160
188
  // key; every other path is the gateway's own.
@@ -176,7 +204,12 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
176
204
  if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
177
205
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
178
206
  }
179
- return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
207
+ return (await handleSubscriptionRequest(request, {
208
+ store: subscriptions,
209
+ fetch,
210
+ baseUrls,
211
+ ...(hosted === null ? {} : { hostedAccounts: () => readHostedAccounts(hosted, fetch) }),
212
+ }))
180
213
  ?? (await handleRouterModelsRequest(request, routers))
181
214
  ?? (await handleRouterSpecsRequest(request, { ...routers, changed: routersChanged }))
182
215
  ?? errorResponse(new HttpError(404, "Not found", "not_found"));
@@ -198,9 +231,22 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
198
231
  // These serve router specs saved through the API.
199
232
  saved_routers: routerSpecs.savedIds(),
200
233
  auto_routing: autoRoutingKey ? "dari" : "priority",
234
+ ...(hosted === null ? {} : { connected: { hosted_url: hosted.url, gateway_id: hosted.gatewayId } }),
201
235
  }),
202
236
  );
203
- return { server, close: () => db.close() };
237
+ sync?.start();
238
+ const idleUsage = sync === null ? null : setInterval(() => {
239
+ void refreshStaleUsage(subscriptions, { fetch, baseUrls });
240
+ }, IDLE_USAGE_INTERVAL_MS);
241
+ idleUsage?.unref?.();
242
+ return {
243
+ server,
244
+ close: () => {
245
+ if (idleUsage !== null) clearInterval(idleUsage);
246
+ sync?.stop();
247
+ db.close();
248
+ },
249
+ };
204
250
  }
205
251
 
206
252
  /**