@mupt-ai/dari-gateway 1.0.360 → 1.0.362

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 (41) hide show
  1. package/dist/ingress/client_harness.d.ts +6 -0
  2. package/dist/ingress/client_harness.js +17 -1
  3. package/dist/ingress/models.js +0 -3
  4. package/dist/models/runtime_overrides.js +5 -0
  5. package/dist/platform/platform.d.ts +2 -1
  6. package/dist/platform/routing_contract.d.ts +1 -1
  7. package/dist/platform/routing_contract.js +3 -3
  8. package/dist/providers/pi.js +10 -2
  9. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  10. package/dist/runtime/prepare_routed_completion.js +1 -0
  11. package/dist/runtime/routed_completion.js +2 -0
  12. package/dist/self_host/connected.d.ts +29 -16
  13. package/dist/self_host/connected.js +64 -68
  14. package/dist/self_host/hosted_sync.d.ts +0 -2
  15. package/dist/self_host/hosted_sync.js +2 -10
  16. package/dist/self_host/main.d.ts +2 -2
  17. package/dist/self_host/main.js +10 -9
  18. package/dist/self_host/resolve.d.ts +7 -4
  19. package/dist/self_host/resolve.js +72 -18
  20. package/dist/self_host/subscriptions/http.js +13 -3
  21. package/dist/self_host/subscriptions/store.d.ts +3 -15
  22. package/dist/self_host/subscriptions/store.js +11 -27
  23. package/dist/telemetry/report.js +4 -0
  24. package/dist/types.d.ts +1 -0
  25. package/package.json +2 -2
  26. package/src/ingress/client_harness.ts +18 -1
  27. package/src/ingress/models.ts +0 -3
  28. package/src/models/runtime_overrides.ts +4 -0
  29. package/src/platform/platform.ts +5 -4
  30. package/src/platform/routing_contract.ts +3 -3
  31. package/src/providers/pi.ts +10 -2
  32. package/src/runtime/prepare_routed_completion.ts +2 -0
  33. package/src/runtime/routed_completion.ts +2 -0
  34. package/src/self_host/connected.ts +102 -82
  35. package/src/self_host/hosted_sync.ts +2 -13
  36. package/src/self_host/main.ts +10 -9
  37. package/src/self_host/resolve.ts +75 -19
  38. package/src/self_host/subscriptions/http.ts +12 -3
  39. package/src/self_host/subscriptions/store.ts +11 -25
  40. package/src/telemetry/report.ts +3 -0
  41. package/src/types.ts +2 -0
@@ -1,12 +1,12 @@
1
1
  import { hostname } from "node:os";
2
2
 
3
- import { isReasoningEffort, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
3
+ import type { ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
4
4
  import { anthropicToken, bearerToken } from "../http/auth.js";
5
5
  import { errorResponse, HttpError } from "../http/errors.js";
6
6
  import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
7
7
  import type { GatewayPlatform } from "../platform/platform.js";
8
- import { DEFAULT_ROUTER_ALIAS, GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
9
- import { explicitModelId } from "../protocol/input/router_model.js";
8
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
9
+ import type { Source } from "../models/sources.js";
10
10
  import { parseGatewayConfig, type RouterConfig } from "./config.js";
11
11
  import type { HostedSync } from "./hosted_sync.js";
12
12
  import { createSelfHostedPlatform } from "./platform.js";
@@ -14,19 +14,22 @@ import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
14
14
 
15
15
  /**
16
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.
17
+ * every launch signed in to Dari): it serves every routed call itself, on the
18
+ * user's plans on this computer first and then on hosted Dari as a provider.
20
19
  *
21
20
  * - 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.
21
+ * the default router at `/v1/...`), read from hosted Dari: every model, each
22
+ * with its sources (models/sources.ts), chosen by the hosted Auto Router API.
23
+ * - A model's plans on this computer serve it first. Whatever comes next that
24
+ * only Dari can serve (its own plans, the router's key, managed credits) is
25
+ * one candidate: hosted Dari, called for `dari/model/<id>` with the user's
26
+ * Dari key (resolve.ts).
27
+ * - Every other path the gateway does not manage itself, such as commit
28
+ * reports, goes to hosted with the user's Dari key.
29
+ * - The plans and the requests served here sync to hosted (hosted_sync.ts),
30
+ * which shows them in Accounts and Activity. Private plans serve, but
31
+ * neither they nor their requests sync; requests hosted Dari served are
32
+ * hosted's to log. Dari Link and Activity are hosted's, not served here.
30
33
  */
31
34
  export type HostedConnection = {
32
35
  // The hosted routing service, e.g. https://routing.dari.dev.
@@ -62,13 +65,13 @@ type SelfHostedPlatformDeps = Parameters<typeof createSelfHostedPlatform>[0];
62
65
  export function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
63
66
  hosted: HostedConnection;
64
67
  sync: HostedSync;
68
+ hostedRouter: HostedRouters;
65
69
  }): GatewayPlatform {
66
70
  const platform = createSelfHostedPlatform(deps);
67
- const hostedRouter = hostedRouters(deps.hosted, deps.fetch as typeof fetch);
68
71
  return {
69
72
  ...platform,
70
73
  async resolveRouter(request) {
71
- const router = await hostedRouter(request.routerId);
74
+ const router = (await deps.hostedRouter(request.routerId)).config;
72
75
  return await resolveSelfHostedRouter({
73
76
  ...deps,
74
77
  config: { ...deps.config, routers: { [request.routerId]: router } },
@@ -77,6 +80,14 @@ export function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
77
80
  },
78
81
  recordRequest(record) {
79
82
  console.info("routing request", JSON.stringify(record.summary));
83
+ // Hosted Dari logs the requests it served itself.
84
+ if (record.summary.selected_provider === HOSTED_DARI_PROVIDER) return;
85
+ // A private plan's requests stay on this computer, as the plan does; so
86
+ // does one whose plan is gone, since it may have been private.
87
+ if (record.subscriptionCredentialId !== undefined) {
88
+ const plan = deps.subscriptions.get(record.subscriptionCredentialId);
89
+ if (plan === null || plan.private) return;
90
+ }
80
91
  try {
81
92
  deps.sync.enqueue(record.row);
82
93
  } catch (error) {
@@ -90,73 +101,89 @@ export function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
90
101
 
91
102
  const ROUTER_CACHE_MS = 60_000;
92
103
 
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> => {
104
+ /** A hosted router as this gateway serves it, read from hosted Dari (cached for a minute). */
105
+ /** A hosted router as this gateway serves it, and whether it uses custom rules. */
106
+ export type HostedRouterState = { config: RouterConfig; customRules: boolean };
107
+ export type HostedRouters = (routerId: string) => Promise<HostedRouterState>;
108
+
109
+ export function hostedRouters(hosted: HostedConnection, fetchImpl: typeof fetch): HostedRouters {
110
+ const cache = new Map<string, { router: HostedRouterState; readAt: number }>();
111
+ return async (routerId: string): Promise<HostedRouterState> => {
100
112
  const cached = cache.get(routerId);
101
113
  if (cached !== undefined && Date.now() - cached.readAt < ROUTER_CACHE_MS) return cached.router;
102
- let router: RouterConfig;
114
+ let router: HostedRouterState;
103
115
  try {
104
116
  router = await readHostedRouter(hosted, fetchImpl, routerId);
105
117
  } catch (error) {
106
118
  if (cached !== undefined) return cached.router;
107
119
  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");
120
+ throw new HttpError(502, `Router ${routerId} could not be read from hosted Dari.`, "hosted_router_unavailable");
110
121
  }
111
122
  cache.set(routerId, { router, readAt: Date.now() });
112
123
  return router;
113
124
  };
114
125
  }
115
126
 
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
- // Lists the models this gateway's plans serve, though hosted holds none.
120
- headers: { authorization: `Bearer ${hosted.apiKey}`, [GATEWAY_ID_HEADER]: hosted.gatewayId },
127
+ /**
128
+ * What hosted Dari says of a router (`GET /v1/gateway/routers/<id>`, or
129
+ * `/v1/gateway/router` for the default): its every model, with the thinking
130
+ * levels it offers and its sources, its reset threshold, and whether Codex may
131
+ * compact natively.
132
+ */
133
+ type HostedRouter = {
134
+ models: Array<{ id: string; thinking: ReasoningEffort[] | null; sources: Source[] }>;
135
+ reset_min_hours: number;
136
+ native_compaction: boolean;
137
+ zdr: boolean;
138
+ session_pinning: boolean;
139
+ retries: number;
140
+ role_models: Record<string, string | null>;
141
+ role_prompts: Record<string, string | null>;
142
+ custom_rules: boolean;
143
+ };
144
+
145
+ async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetch, routerId: string): Promise<HostedRouterState> {
146
+ let path = `/v1/gateway/routers/${encodeURIComponent(routerId)}`;
147
+ if (routerId === DEFAULT_ROUTER_ALIAS) path = "/v1/gateway/router";
148
+ const response = await fetchImpl(`${hosted.url}${path}`, {
149
+ headers: { authorization: `Bearer ${hosted.apiKey}` },
121
150
  signal: AbortSignal.timeout(30_000),
122
151
  });
123
152
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
124
- const catalog = await response.json() as {
125
- remote_compaction?: string;
126
- models?: Array<{ slug?: string; supported_reasoning_levels?: Array<{ effort?: string }> }>;
127
- };
128
- const models = (catalog.models ?? []).flatMap((entry) => {
129
- // `dari/routing` is the router itself, not one of its models.
130
- const id = explicitModelId(entry.slug);
131
- if (id === null) return [];
132
- const thinking = entry.supported_reasoning_levels
133
- ?.map((level) => level.effort === "none" ? "off" : level.effort)
134
- .filter((level): level is ReasoningEffort => isReasoningEffort(level));
135
- return [thinking?.length ? { id, thinking } : { id }];
136
- });
137
- if (models.length === 0) throw new Error("it lists no models");
138
- return parseGatewayConfig({
153
+ const router = await response.json() as HostedRouter;
154
+ // A model's null thinking offers every level it supports.
155
+ const config = parseGatewayConfig({
139
156
  routers: {
140
- [routerId]: { models, nativeCompaction: catalog.remote_compaction === "v2" },
157
+ [routerId]: {
158
+ models: router.models,
159
+ resetMinHours: router.reset_min_hours,
160
+ nativeCompaction: router.native_compaction,
161
+ zdr: router.zdr,
162
+ sessionPinning: router.session_pinning,
163
+ retries: router.retries,
164
+ roleModels: router.role_models,
165
+ rolePrompts: router.role_prompts,
166
+ },
141
167
  },
142
168
  }).routers[routerId]!;
169
+ return { config, customRules: router.custom_rules === true };
143
170
  }
144
171
 
145
- // The routed calls a local plan may serve; anything else the gateway does
146
- // not manage goes to hosted.
147
- const ROUTED_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages)$/;
172
+ // The calls this gateway serves itself: routed calls and model lists. Every
173
+ // other path goes to hosted.
174
+ const LOCAL_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages|models)$/;
148
175
 
149
176
  /**
150
- * Serve a connected gateway's routed surface: `gateway` (the gateway's own
151
- * handler on the connected platform) first, and hosted Dari for a request it
152
- * cannot serve on a local plan. Health checks stay local; every request
153
- * forwarded must carry a gateway key.
177
+ * Serve a connected gateway: routed calls and model lists on `gateway` (the
178
+ * gateway's own handler on the connected platform), and every other path on
179
+ * hosted Dari with the user's Dari key. Health checks stay local; every other
180
+ * request must carry a gateway key.
154
181
  */
155
182
  export function connectedHandler(deps: {
156
183
  gateway: (request: Request) => Promise<Response>;
157
184
  gatewayKeys: readonly string[];
158
185
  hosted: HostedConnection;
159
- sync: HostedSync;
186
+ hostedRouter: HostedRouters;
160
187
  fetch: typeof fetch;
161
188
  }): (request: Request) => Promise<Response> {
162
189
  return async (request) => {
@@ -175,42 +202,35 @@ export function connectedHandler(deps: {
175
202
  } catch (error) {
176
203
  return fail(error);
177
204
  }
178
- const body = request.method === "GET" || request.method === "HEAD" ? null : await request.arrayBuffer();
179
- if (request.method === "POST" && ROUTED_CALL.test(pathname)) {
180
- const local = await deps.gateway(new Request(request.url, {
181
- method: request.method,
182
- headers: request.headers,
183
- body,
184
- signal: request.signal,
185
- }));
186
- if (!(await servedElsewhere(local))) return local;
187
- await local.body?.cancel();
188
- // Hosted logs the request it serves; the local attempt is not one.
189
- const requestId = local.headers.get("x-request-id");
190
- if (requestId !== null) deps.sync.discard(requestId);
205
+ if (!LOCAL_CALL.test(pathname)) return await forward(request, deps, fail);
206
+ // Custom routing rules run only on hosted Dari: it serves those routers'
207
+ // calls whole.
208
+ if (request.method === "POST" && await usesCustomRules(deps.hostedRouter, pathname)) {
209
+ return await forward(request, deps, fail);
191
210
  }
192
- return await forward(request, body, deps, fail);
211
+ return await deps.gateway(request);
193
212
  };
194
213
  }
195
214
 
196
215
  const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
197
216
 
198
- /**
199
- * Whether a local response means no local plan could serve the request: none
200
- * serves the router's models or the one asked for (424, or the explicit
201
- * model's 400), or every one is at its limit (429).
202
- */
203
- async function servedElsewhere(response: Response): Promise<boolean> {
204
- if (response.status === 424 || response.status === 429) return true;
205
- if (response.status !== 400) return false;
206
- const text = await response.clone().text();
207
- return text.includes("model_not_enabled") || text.includes("is not enabled on this router");
217
+ // Whether the router a routed call's path names uses custom rules. A router
218
+ // that cannot be read goes to hosted Dari too: it may use them, and only Dari
219
+ // can run them.
220
+ async function usesCustomRules(hostedRouter: HostedRouters, pathname: string): Promise<boolean> {
221
+ let routerId = DEFAULT_ROUTER_ALIAS;
222
+ const first = pathname.split("/")[1];
223
+ if (first !== undefined && first !== "v1" && !LOCAL_CALL.test(`/${first}`)) routerId = first;
224
+ try {
225
+ return (await hostedRouter(routerId)).customRules;
226
+ } catch {
227
+ return true;
228
+ }
208
229
  }
209
230
 
210
231
  // The request as the client sent it, on hosted Dari with the user's key.
211
232
  async function forward(
212
233
  request: Request,
213
- body: ArrayBuffer | null,
214
234
  deps: { hosted: HostedConnection; fetch: typeof fetch },
215
235
  fail: (error: unknown) => Response,
216
236
  ): Promise<Response> {
@@ -220,8 +240,8 @@ async function forward(
220
240
  headers.delete(name);
221
241
  }
222
242
  headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
223
- // An agent's model list includes the models this gateway's plans serve.
224
- headers.set(GATEWAY_ID_HEADER, deps.hosted.gatewayId);
243
+ let body: ArrayBuffer | null = null;
244
+ if (request.method !== "GET" && request.method !== "HEAD") body = await request.arrayBuffer();
225
245
  let response: Response;
226
246
  try {
227
247
  response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
@@ -24,10 +24,7 @@ const USAGE_INTERVAL_MS = 60_000;
24
24
  const HEARTBEAT_MS = 60 * 60_000;
25
25
  const RETRY_BASE_MS = 5_000;
26
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
27
  const DRAIN_INTERVAL_MS = 2_000;
30
- const SETTLE_MS = 1_000;
31
28
 
32
29
  type OutboxRow = { id: number; row_json: string };
33
30
 
@@ -104,11 +101,6 @@ export class HostedSync {
104
101
  this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
105
102
  }
106
103
 
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
104
  /** The plans hosted Dari shows for this gateway. */
113
105
  snapshot(): Record<string, unknown> {
114
106
  const now = new Date(this.now());
@@ -158,11 +150,8 @@ export class HostedSync {
158
150
  private async drainDue(): Promise<void> {
159
151
  while (this.now() >= this.drainPausedUntil) {
160
152
  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);
153
+ .query<OutboxRow, [number]>("SELECT id, row_json FROM hosted_request_outbox ORDER BY id LIMIT ?")
154
+ .all(MAX_BATCH_ROWS);
166
155
  const batch: OutboxRow[] = [];
167
156
  let bytes = 0;
168
157
  for (const row of due) {
@@ -11,7 +11,7 @@ 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";
14
+ import { connectedHandler, createConnectedPlatform, hostedConnectionFromEnv, hostedRouters } from "./connected.js";
15
15
  import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
16
16
  import { createSelfHostedPlatform } from "./platform.js";
17
17
  import { checkProviderKey } from "../providers/key_check.js";
@@ -76,8 +76,8 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
76
76
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
77
77
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
78
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.
79
+ * its own plans and then on hosted Dari, and syncs its plans and requests
80
+ * there; Dari Link and Activity are hosted's.
81
81
  */
82
82
  export async function startSelfHostedGateway(env: Record<string, string> = process.env as Record<string, string>) {
83
83
  const hosted = hostedConnectionFromEnv(env);
@@ -102,8 +102,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
102
102
  "dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them",
103
103
  );
104
104
  }
105
- // Private plans stay off hosted Dari, so a connected gateway never serves them.
106
- const subscriptions = new SubscriptionStore(db, secrets, { privatePlansServe: hosted === null });
105
+ const subscriptions = new SubscriptionStore(db, secrets);
107
106
  const prefixes = new PrefixStore(db);
108
107
  const sessionPins = new SessionPinStore(db);
109
108
  const routerModels = new RouterModelStore(db);
@@ -127,6 +126,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
127
126
  const providerApiKey = async (provider: string) => (await piModels.getAuth(provider))?.auth.apiKey;
128
127
  const autoRoutingKey = hosted?.apiKey ?? env.DARI_AUTO_ROUTING_API_KEY?.trim();
129
128
  const sync = hosted === null ? null : new HostedSync(db, subscriptions, hosted, fetch);
129
+ // The hosted router, read once a minute, for both serving and routing calls.
130
+ const hostedRouter = hosted === null ? null : hostedRouters(hosted, fetch);
130
131
  const baseUrls = providerBaseUrls(config.providers);
131
132
  if (sync !== null) {
132
133
  subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
@@ -146,9 +147,9 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
146
147
  env,
147
148
  fetch,
148
149
  };
149
- const platform = hosted === null || sync === null
150
+ const platform = hosted === null || sync === null || hostedRouter === null
150
151
  ? createSelfHostedPlatform(platformDeps)
151
- : createConnectedPlatform({ ...platformDeps, hosted, sync });
152
+ : createConnectedPlatform({ ...platformDeps, hosted, sync, hostedRouter });
152
153
  // A model without a credential is dropped at request time, so a missing key
153
154
  // would otherwise surface only as a 424 on the first request.
154
155
  const warnWithoutCredentials = async (routerId: string, router: RouterConfig) => {
@@ -180,9 +181,9 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
180
181
  })
181
182
  : createPrioritySelectorBackend();
182
183
  const routed = createRequestHandler({ platform, selectorBackend });
183
- const gateway = hosted === null || sync === null
184
+ const gateway = hosted === null || sync === null || hostedRouter === null
184
185
  ? routed
185
- : connectedHandler({ gateway: routed, gatewayKeys, hosted, sync, fetch });
186
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, fetch });
186
187
 
187
188
  // Subscriptions, model lists, and router specs are managed with any gateway
188
189
  // key; every other path is the gateway's own.
@@ -10,7 +10,9 @@ import {
10
10
  } from "@mupt-ai/dari-router/policy-engine";
11
11
  import { HttpError } from "../http/errors.js";
12
12
  import type { ResolveRouterRequest } from "../platform/platform.js";
13
- import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
13
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
14
+ import { explicitModelSlug } from "../protocol/input/router_model.js";
15
+ import { CLIENT_HARNESS_HEADER } from "../ingress/client_harness.js";
14
16
  import {
15
17
  codexModelConfig,
16
18
  modelSubscriptions,
@@ -37,6 +39,7 @@ import {
37
39
  type RouterModelConfig,
38
40
  } from "./config.js";
39
41
  import type { ActiveLinkGrant } from "../link/grants.js";
42
+ import type { HostedConnection } from "./connected.js";
40
43
  import type { SqliteLinkStore } from "../link/sqlite_store.js";
41
44
  import { linkSubscription } from "../link/self_hosted.js";
42
45
  import { linkTokenGrant } from "../link/service.js";
@@ -78,20 +81,25 @@ export type SelfHostedResolverDeps = {
78
81
  autoRouting: boolean;
79
82
  env: Record<string, string | undefined>;
80
83
  fetch: OAuthFetch;
84
+ // Set on a gateway connected to hosted Dari (connected.ts).
85
+ hosted?: HostedConnection;
81
86
  };
82
87
 
83
- // One way to serve a model: a connected plan, or its provider's API key.
88
+ // One way to serve a model: a connected plan, its provider's API key, or
89
+ // hosted Dari, with the user's Dari key and the endpoint that serves it.
84
90
  type Candidate =
85
91
  | { provider: string; plan: SubscriptionCredential }
86
- | { provider: string; key: string };
92
+ | { provider: string; key: string }
93
+ | { provider: string; key: string; config: ResolvedRouterModelConfig };
87
94
 
88
95
  /**
89
96
  * Resolve a configured router for one request. Each model is served by the
90
97
  * connected personal subscriptions that serve it, when the router allows them,
91
- * in plan order (see models/subscriptions.ts), then by its provider's API key:
92
- * the first available serves and the rest fail over within the request.
93
- * Models nothing can serve are left out. A coding agent with its own model
94
- * list on the router is served that list.
98
+ * in plan order (see models/subscriptions.ts), then by its provider's API key
99
+ * (on a connected gateway, by hosted Dari): the first available serves and
100
+ * the rest fail over within the request. Models nothing can serve are left
101
+ * out. A coding agent with its own model list on the router is served that
102
+ * list.
95
103
  *
96
104
  * A Dari Link token is served apart from any router, on its grant's plans and
97
105
  * API keys alone: `dari/routing` chooses among every catalog model they
@@ -226,15 +234,28 @@ export async function resolveSelfHostedRouter(
226
234
  },
227
235
  });
228
236
  }
229
- const candidates = await candidatesFor(sources, plans, {
230
- key: async () => {
231
- const key = await apiKey(base);
232
- if (key === undefined) return null;
233
- return { provider: base, key };
234
- },
235
- // A self-hosted gateway has no managed keys.
236
- managed: async () => null,
237
- });
237
+ let keyCandidate = async (): Promise<Candidate | null> => {
238
+ const key = await apiKey(base);
239
+ if (key === undefined) return null;
240
+ return { provider: base, key };
241
+ };
242
+ // A self-hosted gateway has no managed keys.
243
+ let managedCandidate = async (): Promise<Candidate | null> => null;
244
+ // On a gateway connected to hosted Dari, Dari serves what no plan on this
245
+ // computer does: its own plans after this computer's, the router's key,
246
+ // and managed credits.
247
+ const hosted = deps.hosted;
248
+ if (hosted !== undefined) {
249
+ const dari = async () => hostedCandidate(hosted, request, model.id);
250
+ plans.push({ servesClient: true, candidate: dari });
251
+ keyCandidate = dari;
252
+ managedCandidate = dari;
253
+ }
254
+ const candidates = await candidatesFor(sources, plans, { key: keyCandidate, managed: managedCandidate });
255
+ // Dari walks the model's sources itself from there, so its one candidate
256
+ // ends the list.
257
+ const dariAt = candidates.findIndex((candidate) => candidate.provider === HOSTED_DARI_PROVIDER);
258
+ if (dariAt !== -1) candidates.splice(dariAt + 1);
238
259
 
239
260
  if (candidates.length === 0) {
240
261
  for (const kind of heldKinds) exhausted.add(kind);
@@ -385,14 +406,16 @@ export function gatewayKeyIndex(keys: readonly string[], presented: string): num
385
406
  return null;
386
407
  }
387
408
 
388
- // How a candidate runs a model: a ChatGPT plan through the Codex backend, a
389
- // provider that serves another maker's model as its own model, a configured
390
- // endpoint, or (undefined) the model's own provider as the catalog has it.
409
+ // How a candidate runs a model: hosted Dari's endpoint, a ChatGPT plan
410
+ // through the Codex backend, a provider that serves another maker's model as
411
+ // its own model, a configured endpoint, or (undefined) the model's own
412
+ // provider as the catalog has it.
391
413
  function candidateConfig(
392
414
  deps: Pick<SelfHostedResolverDeps, "config">,
393
415
  modelId: string,
394
416
  candidate: Candidate,
395
417
  ): ResolvedRouterModelConfig | undefined {
418
+ if ("config" in candidate) return candidate.config;
396
419
  const { provider } = candidate;
397
420
  const price = priceFor(modelId, provider);
398
421
  if ("plan" in candidate && candidate.plan.provider === "openai_codex") {
@@ -425,6 +448,39 @@ function candidateConfig(
425
448
  };
426
449
  }
427
450
 
451
+ /**
452
+ * Hosted Dari as the provider of a model: the request's router on hosted Dari,
453
+ * called for `dari/model/<id>` with the user's Dari key, in Anthropic's API
454
+ * for Anthropic's models and OpenAI's Responses API for the rest, with the
455
+ * client's own identifying headers and the coding agent it named, so hosted
456
+ * sees the same client. Hosted Dari bills and logs what it serves.
457
+ */
458
+ function hostedCandidate(hosted: HostedConnection, request: ResolveRouterRequest, modelId: string): Candidate {
459
+ let routerUrl = hosted.url;
460
+ if (request.routerId !== DEFAULT_ROUTER_ALIAS) routerUrl = `${hosted.url}/${encodeURIComponent(request.routerId)}`;
461
+ let api = "openai-responses";
462
+ let baseUrl = `${routerUrl}/v1`;
463
+ // Anthropic's client adds /v1 itself.
464
+ if (providerForModel(modelId) === "anthropic") {
465
+ api = "anthropic-messages";
466
+ baseUrl = routerUrl;
467
+ }
468
+ const headers: Record<string, string> = { ...request.clientHeaders };
469
+ if (request.clientHarness !== undefined) headers[CLIENT_HARNESS_HEADER] = request.clientHarness;
470
+ return {
471
+ provider: HOSTED_DARI_PROVIDER,
472
+ key: hosted.apiKey,
473
+ config: {
474
+ provider: HOSTED_DARI_PROVIDER,
475
+ native_model_id: explicitModelSlug(modelId),
476
+ api,
477
+ base_url: baseUrl,
478
+ headers,
479
+ cost: registeredModelPrice(modelId) ?? { input: 0, output: 0 },
480
+ },
481
+ };
482
+ }
483
+
428
484
  // A fallback names its endpoint even on the model's own provider, as the
429
485
  // catalog has it; undefined when the catalog has none.
430
486
  function registryConfig(modelId: string, provider: string): ResolvedRouterModelConfig | undefined {
@@ -142,7 +142,7 @@ function listBody(store: SubscriptionStore, now: Date) {
142
142
  SUBSCRIPTION_PROVIDERS.map((provider) => store.activeCredential(provider, now)?.id),
143
143
  );
144
144
  return {
145
- credentials: store.list(undefined, true).map((credential) => credentialBody(credential, active.has(credential.id), now)),
145
+ credentials: store.list().map((credential) => credentialBody(credential, active.has(credential.id), now)),
146
146
  // Plan gating is hosted-only; a self-hosted gateway always allows routing.
147
147
  autorouting_allowed: true,
148
148
  };
@@ -164,7 +164,7 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
164
164
  // A reconnected plan stays where it was unless the caller says otherwise.
165
165
  const isPrivate = body.private ?? reconnecting?.private ?? false;
166
166
  if (typeof isPrivate !== "boolean") throw new HttpError(400, "private must be true or false.");
167
- // `dari accounts subscription move` names the hosted plan it moves here.
167
+ // `dari accounts subscription connect` names the hosted plan it moves here.
168
168
  const movingFrom = body.moving_from ?? null;
169
169
  if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
170
170
  throw new HttpError(400, "moving_from must be a non-empty string.");
@@ -297,13 +297,22 @@ function usageBody(credential: SubscriptionCredential, now: Date) {
297
297
  };
298
298
  }
299
299
 
300
+ function safeMetadata(credential: SubscriptionCredential): Record<string, string> {
301
+ const metadata: Record<string, string> = {};
302
+ if (credential.accountEmail !== null) metadata.account_email = credential.accountEmail;
303
+ if (credential.accountId !== null) metadata.account_id = credential.accountId;
304
+ return metadata;
305
+ }
306
+
300
307
  function credentialBody(credential: SubscriptionCredential, active: boolean, now: Date) {
301
308
  const held = isHeld(credential, now);
302
309
  return {
303
310
  id: credential.id,
304
311
  name: credential.name,
305
312
  label: credential.label,
306
- safe_metadata: credential.accountEmail === null ? {} : { account_email: credential.accountEmail },
313
+ // The account, as hosted Dari shows a plan's: its email and, where the
314
+ // provider names one, its account (a ChatGPT workspace).
315
+ safe_metadata: safeMetadata(credential),
307
316
  // Hosted organizations also hold organization-scoped secrets; every
308
317
  // subscription here belongs to the gateway's one user.
309
318
  credential_scope: "user",
@@ -130,18 +130,15 @@ const PROVIDER_LABELS: Record<SubscriptionProvider, string> = {
130
130
  vercel_token_pass: "Vercel Token Pass",
131
131
  };
132
132
 
133
+ const PLACE_NAMES: Record<ConnectedAccount["place"], string> = {
134
+ dari: "on Dari",
135
+ this_computer: "on This Computer",
136
+ private: "Private on This Computer",
137
+ };
138
+
133
139
  function connectedAccountMessage(account: ConnectedAccount): string {
134
- const label = PROVIDER_LABELS[account.provider];
135
- const handle = account.name ?? "NAME";
136
- const asName = account.name === null ? "" : ` as ${handle}`;
137
- switch (account.place) {
138
- case "dari":
139
- return `This ${label} account is already connected on Dari${asName}. Move it with \`dari accounts subscription move ${handle} --on computer\`, or disconnect it first.`;
140
- case "this_computer":
141
- return `This ${label} account is already connected on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\`, or disconnect it first.`;
142
- case "private":
143
- return `This ${label} account is already connected Private on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\` or \`--on computer\`, or disconnect it first.`;
144
- }
140
+ const asName = account.name === null ? "" : ` as ${account.name}`;
141
+ return `This ${PROVIDER_LABELS[account.provider]} account is already connected ${PLACE_NAMES[account.place]}${asName}. Run \`dari accounts subscription connect\` again and choose Move, or disconnect it first.`;
145
142
  }
146
143
 
147
144
  const BASE_NAMES: Record<SubscriptionProvider, string> = {
@@ -210,15 +207,9 @@ export class SubscriptionStore {
210
207
  */
211
208
  onChange: ((change: "plans" | "usage") => void) | undefined;
212
209
 
213
- /**
214
- * `privatePlansServe: false` (a gateway connected to hosted Dari) leaves
215
- * private plans out of routing and `list`; `list(provider, true)` still
216
- * shows them.
217
- */
218
210
  constructor(
219
211
  private readonly db: Database,
220
212
  private readonly box: SecretBox | null = null,
221
- private readonly options: { privatePlansServe?: boolean } = {},
222
213
  ) {
223
214
  db.run(`CREATE TABLE IF NOT EXISTS subscription_credentials (
224
215
  id TEXT PRIMARY KEY,
@@ -330,14 +321,9 @@ export class SubscriptionStore {
330
321
  });
331
322
  }
332
323
 
333
- /**
334
- * The gateway owner's subscriptions that serve, grouped by provider, in
335
- * connection order; with `includePrivate`, private ones too even where they
336
- * do not serve.
337
- */
338
- list(provider?: SubscriptionProvider, includePrivate = false): SubscriptionCredential[] {
339
- const privateShown = includePrivate || this.options.privatePlansServe !== false;
340
- return this.every(provider).filter((credential) => credential.owner === null && (privateShown || !credential.private));
324
+ /** The gateway owner's subscriptions, grouped by provider, in connection order. */
325
+ list(provider?: SubscriptionProvider): SubscriptionCredential[] {
326
+ return this.every(provider).filter((credential) => credential.owner === null);
341
327
  }
342
328
 
343
329
  /** The subscriptions a Dari Link user connected. */