@mupt-ai/dari-gateway 1.0.359 → 1.0.361
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ingress/client_harness.d.ts +6 -0
- package/dist/ingress/client_harness.js +17 -1
- package/dist/ingress/models.js +0 -3
- package/dist/models/runtime_overrides.js +5 -0
- package/dist/platform/platform.d.ts +2 -1
- package/dist/platform/routing_contract.d.ts +1 -1
- package/dist/platform/routing_contract.js +3 -3
- package/dist/providers/pi.js +10 -2
- package/dist/runtime/prepare_routed_completion.d.ts +1 -0
- package/dist/runtime/prepare_routed_completion.js +1 -0
- package/dist/runtime/routed_completion.js +2 -0
- package/dist/self_host/config.d.ts +2 -0
- package/dist/self_host/config.js +14 -0
- package/dist/self_host/connected.d.ts +29 -16
- package/dist/self_host/connected.js +64 -68
- package/dist/self_host/hosted_sync.d.ts +0 -2
- package/dist/self_host/hosted_sync.js +2 -10
- package/dist/self_host/main.d.ts +2 -2
- package/dist/self_host/main.js +12 -9
- package/dist/self_host/resolve.d.ts +7 -4
- package/dist/self_host/resolve.js +78 -18
- package/dist/self_host/subscriptions/http.js +1 -1
- package/dist/self_host/subscriptions/store.d.ts +3 -15
- package/dist/self_host/subscriptions/store.js +4 -16
- package/dist/telemetry/report.js +4 -0
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/ingress/client_harness.ts +18 -1
- package/src/ingress/models.ts +0 -3
- package/src/models/runtime_overrides.ts +4 -0
- package/src/platform/platform.ts +5 -4
- package/src/platform/routing_contract.ts +3 -3
- package/src/providers/pi.ts +10 -2
- package/src/runtime/prepare_routed_completion.ts +2 -0
- package/src/runtime/routed_completion.ts +2 -0
- package/src/self_host/config.ts +15 -0
- package/src/self_host/connected.ts +102 -82
- package/src/self_host/hosted_sync.ts +2 -13
- package/src/self_host/main.ts +11 -9
- package/src/self_host/resolve.ts +81 -19
- package/src/self_host/subscriptions/http.ts +1 -1
- package/src/self_host/subscriptions/store.ts +3 -14
- package/src/telemetry/report.ts +3 -0
- package/src/types.ts +2 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { hostname } from "node:os";
|
|
2
2
|
|
|
3
|
-
import {
|
|
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,
|
|
9
|
-
import {
|
|
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
|
-
*
|
|
18
|
-
*
|
|
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/...`)
|
|
23
|
-
*
|
|
24
|
-
* - A
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
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
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
|
125
|
-
|
|
126
|
-
|
|
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]: {
|
|
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
|
|
146
|
-
//
|
|
147
|
-
const
|
|
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
|
|
151
|
-
* handler on the connected platform)
|
|
152
|
-
*
|
|
153
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
|
211
|
+
return await deps.gateway(request);
|
|
193
212
|
};
|
|
194
213
|
}
|
|
195
214
|
|
|
196
215
|
const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
|
|
197
216
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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
|
-
|
|
224
|
-
|
|
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
|
|
162
|
-
|
|
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) {
|
package/src/self_host/main.ts
CHANGED
|
@@ -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
|
|
80
|
-
*
|
|
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
|
-
|
|
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,
|
|
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.
|
|
@@ -234,6 +235,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
234
235
|
...(hosted === null ? {} : { connected: { hosted_url: hosted.url, gateway_id: hosted.gatewayId } }),
|
|
235
236
|
}),
|
|
236
237
|
);
|
|
238
|
+
if (env.DARI_SESSION_PORT_FILE) await Bun.write(env.DARI_SESSION_PORT_FILE, String(server.port));
|
|
237
239
|
sync?.start();
|
|
238
240
|
const idleUsage = sync === null ? null : setInterval(() => {
|
|
239
241
|
void refreshStaleUsage(subscriptions, { fetch, baseUrls });
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -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,
|
|
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
|
-
*
|
|
93
|
-
*
|
|
94
|
-
* list on the router is served that
|
|
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
|
-
|
|
230
|
-
key
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
|
389
|
-
// provider that serves another maker's model as
|
|
390
|
-
// endpoint, or (undefined) the model's own
|
|
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") {
|
|
@@ -400,9 +423,14 @@ function candidateConfig(
|
|
|
400
423
|
}
|
|
401
424
|
const served = providerModel(modelId, provider);
|
|
402
425
|
const endpoint = deps.config.providers[provider];
|
|
426
|
+
const limits = {
|
|
427
|
+
...(endpoint?.contextWindow !== undefined ? { context_window: endpoint.contextWindow } : {}),
|
|
428
|
+
...(endpoint?.maxOutputTokens !== undefined ? { max_output_tokens: endpoint.maxOutputTokens } : {}),
|
|
429
|
+
};
|
|
403
430
|
if (served !== undefined) {
|
|
404
431
|
return {
|
|
405
432
|
provider,
|
|
433
|
+
...limits,
|
|
406
434
|
native_model_id: served.native_model_id,
|
|
407
435
|
api: endpoint?.api ?? served.api,
|
|
408
436
|
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
@@ -412,6 +440,7 @@ function candidateConfig(
|
|
|
412
440
|
if (endpoint === undefined) return undefined;
|
|
413
441
|
return {
|
|
414
442
|
provider,
|
|
443
|
+
...limits,
|
|
415
444
|
native_model_id: nativeModelId(modelId),
|
|
416
445
|
api: endpoint.api,
|
|
417
446
|
base_url: endpoint.baseUrl,
|
|
@@ -419,6 +448,39 @@ function candidateConfig(
|
|
|
419
448
|
};
|
|
420
449
|
}
|
|
421
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
|
+
|
|
422
484
|
// A fallback names its endpoint even on the model's own provider, as the
|
|
423
485
|
// catalog has it; undefined when the catalog has none.
|
|
424
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(
|
|
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
|
};
|
|
@@ -210,15 +210,9 @@ export class SubscriptionStore {
|
|
|
210
210
|
*/
|
|
211
211
|
onChange: ((change: "plans" | "usage") => void) | undefined;
|
|
212
212
|
|
|
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
213
|
constructor(
|
|
219
214
|
private readonly db: Database,
|
|
220
215
|
private readonly box: SecretBox | null = null,
|
|
221
|
-
private readonly options: { privatePlansServe?: boolean } = {},
|
|
222
216
|
) {
|
|
223
217
|
db.run(`CREATE TABLE IF NOT EXISTS subscription_credentials (
|
|
224
218
|
id TEXT PRIMARY KEY,
|
|
@@ -330,14 +324,9 @@ export class SubscriptionStore {
|
|
|
330
324
|
});
|
|
331
325
|
}
|
|
332
326
|
|
|
333
|
-
/**
|
|
334
|
-
|
|
335
|
-
|
|
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));
|
|
327
|
+
/** The gateway owner's subscriptions, grouped by provider, in connection order. */
|
|
328
|
+
list(provider?: SubscriptionProvider): SubscriptionCredential[] {
|
|
329
|
+
return this.every(provider).filter((credential) => credential.owner === null);
|
|
341
330
|
}
|
|
342
331
|
|
|
343
332
|
/** The subscriptions a Dari Link user connected. */
|
package/src/telemetry/report.ts
CHANGED
|
@@ -638,8 +638,11 @@ export class RequestReporter {
|
|
|
638
638
|
}),
|
|
639
639
|
};
|
|
640
640
|
|
|
641
|
+
let subscriptionCredentialId: string | undefined;
|
|
642
|
+
if (keySource === "subscription") subscriptionCredentialId = outcome.providerExecution?.subscriptionCredentialId;
|
|
641
643
|
gatewayPlatform().recordRequest({
|
|
642
644
|
...(link === undefined ? {} : { link }),
|
|
645
|
+
...(subscriptionCredentialId === undefined ? {} : { subscriptionCredentialId }),
|
|
643
646
|
router: requestRecordRouter(a.credentials),
|
|
644
647
|
candidates: a.candidates.map(({ model, reasoningEffort }) => ({ model, reasoningEffort })),
|
|
645
648
|
...(a.sessionPinKey === undefined ? {} : { sessionPinKey: a.sessionPinKey }),
|
package/src/types.ts
CHANGED
|
@@ -119,6 +119,8 @@ export type ResolvedRouterModelConfig = {
|
|
|
119
119
|
native_model_id: string;
|
|
120
120
|
api: string;
|
|
121
121
|
base_url?: string | null;
|
|
122
|
+
// Sent with every call to the endpoint.
|
|
123
|
+
headers?: Record<string, string>;
|
|
122
124
|
context_window?: number | null;
|
|
123
125
|
standard_context_limit?: number | null;
|
|
124
126
|
allow_long_context?: boolean;
|