@mupt-ai/dari-gateway 1.0.329 → 1.0.331
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/README.md +38 -8
- package/dari-gateway.example.yaml +4 -0
- package/dist/activity/conversations.js +4 -2
- package/dist/activity/core.js +52 -28
- package/dist/activity/people.js +20 -17
- package/dist/link/assets.js +2 -0
- package/dist/link/key_providers.js +1 -0
- package/dist/models/canonical.d.ts +12 -0
- package/dist/models/canonical.js +10 -0
- package/dist/models/canonical_models.json +69 -0
- package/dist/models/catalog.js +1 -0
- package/dist/models/provider_defaults.js +2 -0
- package/dist/models/provider_models.json +114 -0
- package/dist/models/runtime_overrides.js +13 -0
- package/dist/protocol/output/anthropic_messages_output.js +3 -1
- package/dist/protocol/output/anthropic_messages_stream.js +14 -0
- package/dist/providers/model_capabilities.d.ts +1 -0
- package/dist/providers/model_capabilities.js +5 -1
- package/dist/providers/pi.js +2 -0
- package/dist/providers/pi_context.js +35 -2
- package/dist/providers/pi_options.js +50 -0
- package/dist/providers/pi_output.js +21 -3
- package/dist/self_host/config.d.ts +46 -4
- package/dist/self_host/config.js +165 -54
- package/dist/self_host/main.d.ts +7 -3
- package/dist/self_host/main.js +40 -17
- package/dist/self_host/platform.d.ts +4 -3
- package/dist/self_host/platform.js +6 -4
- package/dist/self_host/resolve.d.ts +2 -0
- package/dist/self_host/resolve.js +23 -10
- package/dist/self_host/router_models.d.ts +5 -2
- package/dist/self_host/router_models.js +10 -5
- package/dist/self_host/router_specs.d.ts +64 -0
- package/dist/self_host/router_specs.js +194 -0
- package/dist/telemetry/requests/interaction_observability.js +1 -0
- package/package.json +3 -3
- package/src/activity/conversations.ts +4 -2
- package/src/activity/core.ts +52 -28
- package/src/activity/people.ts +20 -18
- package/src/link/assets.ts +2 -0
- package/src/link/key_providers.ts +1 -0
- package/src/models/canonical.ts +22 -0
- package/src/models/canonical_models.json +69 -0
- package/src/models/catalog.ts +1 -0
- package/src/models/provider_defaults.ts +2 -0
- package/src/models/provider_models.json +114 -0
- package/src/models/runtime_overrides.ts +13 -0
- package/src/protocol/output/anthropic_messages_output.ts +5 -1
- package/src/protocol/output/anthropic_messages_stream.ts +16 -0
- package/src/providers/model_capabilities.ts +6 -1
- package/src/providers/pi.ts +1 -0
- package/src/providers/pi_context.ts +34 -3
- package/src/providers/pi_options.ts +51 -1
- package/src/providers/pi_output.ts +21 -3
- package/src/self_host/config.ts +217 -60
- package/src/self_host/main.ts +47 -18
- package/src/self_host/platform.ts +6 -4
- package/src/self_host/resolve.ts +24 -9
- package/src/self_host/router_models.ts +16 -6
- package/src/self_host/router_specs.ts +236 -0
- package/src/telemetry/requests/interaction_observability.ts +1 -0
package/src/self_host/config.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isReasoningEffort,
|
|
3
3
|
isRecord,
|
|
4
|
+
providerForModel,
|
|
4
5
|
type ReasoningEffort,
|
|
5
6
|
} from "@mupt-ai/dari-router/policy-engine";
|
|
6
7
|
|
|
7
8
|
import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
|
|
9
|
+
import { otherModelProviders, providerModel } from "../models/canonical.js";
|
|
8
10
|
import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } from "../types.js";
|
|
9
11
|
|
|
10
12
|
/**
|
|
@@ -15,16 +17,16 @@ import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } f
|
|
|
15
17
|
* default:
|
|
16
18
|
* models:
|
|
17
19
|
* - anthropic/claude-sonnet-5-5
|
|
18
|
-
* - id: openai/gpt-6.
|
|
20
|
+
* - id: openai/gpt-6.2-sol
|
|
19
21
|
* thinking: [medium, high]
|
|
20
22
|
* agentModels: # optional: a coding agent's own list
|
|
21
23
|
* codex:
|
|
22
|
-
* - openai/gpt-6.
|
|
24
|
+
* - openai/gpt-6.2-sol
|
|
23
25
|
* subscriptions: true # serve with connected Claude Code / ChatGPT plans
|
|
24
26
|
* sessionPinning: false # route each session and subagent once, then keep its model
|
|
25
27
|
* roleModels: # optional: serve an agent role one model, without routing
|
|
26
28
|
* main: anthropic/claude-fable-5-2
|
|
27
|
-
* subagent: openai/gpt-6.
|
|
29
|
+
* subagent: openai/gpt-6.2-sol
|
|
28
30
|
* rolePrompts: # optional: append to an agent role's system prompt
|
|
29
31
|
* main: Delegate codebase exploration to subagents.
|
|
30
32
|
* nativeCompaction: false # let Codex compact server-side with the provider's native compaction
|
|
@@ -43,7 +45,8 @@ import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } f
|
|
|
43
45
|
* provider API keys from each provider's standard environment variable, and
|
|
44
46
|
* personal subscriptions from the gateway database. Model lists saved through
|
|
45
47
|
* the gateway's API (`dari gateway models`) live in the database too, and are
|
|
46
|
-
* served in place of this file's.
|
|
48
|
+
* served in place of this file's. So do router specs (parseRouterSpec), each a
|
|
49
|
+
* whole router, which are served in place of this file's router of their id.
|
|
47
50
|
*/
|
|
48
51
|
export type GatewayConfig = {
|
|
49
52
|
routers: Record<string, RouterConfig>;
|
|
@@ -92,9 +95,17 @@ export type RouterModelConfig = {
|
|
|
92
95
|
// Thinking levels the router offers; absent offers every level the model
|
|
93
96
|
// supports.
|
|
94
97
|
thinking?: ReasoningEffort[];
|
|
98
|
+
// The provider that serves the model when not the one its id names, such as
|
|
99
|
+
// `opencode-go` for `deepseek-ai/DeepSeek-V4.1-Flash-1017`.
|
|
100
|
+
provider?: string;
|
|
95
101
|
};
|
|
96
102
|
|
|
97
|
-
|
|
103
|
+
/** The provider that serves a router's model, whose credential it needs. */
|
|
104
|
+
export function modelProvider(model: RouterModelConfig): string {
|
|
105
|
+
return model.provider ?? providerForModel(model.id);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
98
109
|
const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*$/;
|
|
99
110
|
const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
|
|
100
111
|
|
|
@@ -109,7 +120,7 @@ export const DEFAULT_GATEWAY_CONFIG: GatewayConfig = parseGatewayConfig({
|
|
|
109
120
|
"anthropic/claude-opus-5-5",
|
|
110
121
|
"anthropic/claude-fable-5-2",
|
|
111
122
|
"anthropic/claude-haiku-5-5",
|
|
112
|
-
"openai/gpt-6.
|
|
123
|
+
"openai/gpt-6.2-sol",
|
|
113
124
|
"openai/gpt-6.1-terra",
|
|
114
125
|
],
|
|
115
126
|
},
|
|
@@ -206,26 +217,14 @@ export function allRouterModels(router: RouterConfig): RouterModelConfig[] {
|
|
|
206
217
|
|
|
207
218
|
function parseRouter(id: string, raw: unknown): RouterConfig {
|
|
208
219
|
if (!isRecord(raw)) throw new Error(`Router "${id}" needs a non-empty \`models\` list.`);
|
|
209
|
-
const agentModels
|
|
210
|
-
if (raw.agentModels !== undefined) {
|
|
211
|
-
if (!isRecord(raw.agentModels)) {
|
|
212
|
-
throw new Error(`routers.${id}.agentModels must map coding agents to model lists.`);
|
|
213
|
-
}
|
|
214
|
-
for (const [agent, models] of Object.entries(raw.agentModels)) {
|
|
215
|
-
if (!CLIENT_HARNESSES.includes(agent)) {
|
|
216
|
-
throw new Error(
|
|
217
|
-
`Router "${id}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`,
|
|
218
|
-
);
|
|
219
|
-
}
|
|
220
|
-
agentModels[agent as ClientHarness] = parseRouterModels(id, `agentModels.${agent}`, models);
|
|
221
|
-
}
|
|
222
|
-
}
|
|
220
|
+
const agentModels = parseAgentModels(id, `routers.${id}.agentModels`, raw.agentModels);
|
|
223
221
|
const models = parseRouterModels(id, "models", raw.models);
|
|
224
222
|
return {
|
|
225
223
|
models,
|
|
226
224
|
agentModels,
|
|
227
|
-
roleModels:
|
|
228
|
-
|
|
225
|
+
roleModels: parseRoleMap(`routers.${id}.roleModels`, raw.roleModels, (field, model) =>
|
|
226
|
+
roleModel(field, model, [models, ...Object.values(agentModels)].flat())),
|
|
227
|
+
rolePrompts: parseRoleMap(`routers.${id}.rolePrompts`, raw.rolePrompts, rolePrompt),
|
|
229
228
|
retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
|
|
230
229
|
subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
|
|
231
230
|
sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
|
|
@@ -234,44 +233,55 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
|
|
|
234
233
|
};
|
|
235
234
|
}
|
|
236
235
|
|
|
236
|
+
function parseAgentModels(routerId: string, field: string, raw: unknown): RouterConfig["agentModels"] {
|
|
237
|
+
const agentModels: RouterConfig["agentModels"] = {};
|
|
238
|
+
if (raw == null) return agentModels;
|
|
239
|
+
if (!isRecord(raw)) throw new Error(`${field} must map coding agents to model lists.`);
|
|
240
|
+
for (const [agent, models] of Object.entries(raw)) {
|
|
241
|
+
if (!CLIENT_HARNESSES.includes(agent)) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
`Router "${routerId}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
agentModels[agent as ClientHarness] = parseRouterModels(routerId, `${field}.${agent}`, models);
|
|
247
|
+
}
|
|
248
|
+
return agentModels;
|
|
249
|
+
}
|
|
250
|
+
|
|
237
251
|
const ROUTER_ROLES: readonly RouterRole[] = ["main", "subagent"];
|
|
238
252
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
253
|
+
// A map of main and subagent to values `read` checks, leaving out nulls.
|
|
254
|
+
function parseRoleMap(
|
|
255
|
+
field: string,
|
|
256
|
+
raw: unknown,
|
|
257
|
+
read: (field: string, value: unknown) => string,
|
|
258
|
+
): Partial<Record<RouterRole, string>> {
|
|
259
|
+
if (raw == null) return {};
|
|
260
|
+
if (!isRecord(raw)) throw new Error(`${field} must map main and subagent.`);
|
|
261
|
+
const roles: Partial<Record<RouterRole, string>> = {};
|
|
262
|
+
for (const [role, value] of Object.entries(raw)) {
|
|
244
263
|
if (!(ROUTER_ROLES as readonly string[]).includes(role)) {
|
|
245
|
-
throw new Error(
|
|
264
|
+
throw new Error(`${field} has an unknown role "${role}"; use main or subagent.`);
|
|
246
265
|
}
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
266
|
+
if (value !== null) roles[role as RouterRole] = read(`${field}.${role}`, value);
|
|
267
|
+
}
|
|
268
|
+
return roles;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function roleModel(field: string, model: unknown, models: readonly RouterModelConfig[]): string {
|
|
272
|
+
if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
|
|
273
|
+
throw new Error(`${field} must be one of the router's models.`);
|
|
252
274
|
}
|
|
253
|
-
return
|
|
275
|
+
return model;
|
|
254
276
|
}
|
|
255
277
|
|
|
256
278
|
export const ROLE_PROMPT_MAX_LENGTH = 4000;
|
|
257
279
|
|
|
258
|
-
function
|
|
259
|
-
if (
|
|
260
|
-
|
|
261
|
-
const rolePrompts: RouterRolePrompts = {};
|
|
262
|
-
for (const [role, prompt] of Object.entries(raw)) {
|
|
263
|
-
if (!(ROUTER_ROLES as readonly string[]).includes(role)) {
|
|
264
|
-
throw new Error(`routers.${routerId}.rolePrompts has an unknown role "${role}"; use main or subagent.`);
|
|
265
|
-
}
|
|
266
|
-
if (prompt === null) continue;
|
|
267
|
-
if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
|
|
268
|
-
throw new Error(
|
|
269
|
-
`routers.${routerId}.rolePrompts.${role} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`,
|
|
270
|
-
);
|
|
271
|
-
}
|
|
272
|
-
rolePrompts[role as RouterRole] = prompt.trim();
|
|
280
|
+
function rolePrompt(field: string, prompt: unknown): string {
|
|
281
|
+
if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
|
|
282
|
+
throw new Error(`${field} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`);
|
|
273
283
|
}
|
|
274
|
-
return
|
|
284
|
+
return prompt.trim();
|
|
275
285
|
}
|
|
276
286
|
|
|
277
287
|
/** Read one model list of a router, naming `field` in what it rejects. */
|
|
@@ -295,17 +305,30 @@ function parseModel(routerId: string, raw: unknown): RouterModelConfig {
|
|
|
295
305
|
`Router "${routerId}" has an invalid model; use a canonical "provider/model" id.`,
|
|
296
306
|
);
|
|
297
307
|
}
|
|
298
|
-
|
|
299
|
-
if (
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
308
|
+
const model: RouterModelConfig = { id: entry.id };
|
|
309
|
+
if (entry.thinking != null) {
|
|
310
|
+
if (
|
|
311
|
+
!Array.isArray(entry.thinking) ||
|
|
312
|
+
entry.thinking.length === 0 ||
|
|
313
|
+
!entry.thinking.every(isReasoningEffort)
|
|
314
|
+
) {
|
|
315
|
+
throw new Error(
|
|
316
|
+
`Model ${entry.id} on router "${routerId}" has invalid thinking levels; use off, minimal, low, medium, high, xhigh, or max.`,
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
model.thinking = [...new Set(entry.thinking)];
|
|
320
|
+
}
|
|
321
|
+
if (entry.provider != null && entry.provider !== providerForModel(entry.id)) {
|
|
322
|
+
if (typeof entry.provider !== "string" || providerModel(entry.id, entry.provider) === undefined) {
|
|
323
|
+
const others = otherModelProviders(entry.id);
|
|
324
|
+
throw new Error(
|
|
325
|
+
`Model ${entry.id} on router "${routerId}" cannot be served by provider ${String(entry.provider)} on a self-hosted gateway; `
|
|
326
|
+
+ `${others.length > 0 ? `use ${others.join(" or ")}, or ` : ""}leave out \`provider\` to use ${providerForModel(entry.id)}.`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
model.provider = entry.provider;
|
|
307
330
|
}
|
|
308
|
-
return
|
|
331
|
+
return model;
|
|
309
332
|
}
|
|
310
333
|
|
|
311
334
|
function optionalBoolean(value: unknown, field: string): boolean | undefined {
|
|
@@ -321,3 +344,137 @@ function optionalRetries(value: unknown, field: string): number | undefined {
|
|
|
321
344
|
}
|
|
322
345
|
return value;
|
|
323
346
|
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* A router spec: a whole router as one document, the same one hosted Dari
|
|
350
|
+
* applies (`dari router apply`), with no credentials:
|
|
351
|
+
*
|
|
352
|
+
* ```yaml
|
|
353
|
+
* name: Opus 5.5 + DeepSeek Subagents
|
|
354
|
+
* models:
|
|
355
|
+
* - anthropic/claude-opus-5-5
|
|
356
|
+
* - id: deepseek-ai/DeepSeek-V4.1-Flash-1017
|
|
357
|
+
* thinking: [high]
|
|
358
|
+
* provider: opencode-go # served by this provider, not the one its id names
|
|
359
|
+
* roles:
|
|
360
|
+
* main: { model: anthropic/claude-opus-5-5 }
|
|
361
|
+
* subagent: { model: deepseek-ai/DeepSeek-V4.1-Flash-1017, prompt: Be brief. }
|
|
362
|
+
* routing: { session_pinning: false, retries: 1 }
|
|
363
|
+
* payment: { allow: [subscription, key, credits] }
|
|
364
|
+
* native_compaction: false
|
|
365
|
+
* agents: { codex: [openai/gpt-6.1-sol] }
|
|
366
|
+
* ```
|
|
367
|
+
*
|
|
368
|
+
* The gateway pays with connected subscriptions when `payment.allow` lists
|
|
369
|
+
* `subscription`, and otherwise with provider API keys; it has no credits.
|
|
370
|
+
* `hosted` settings and a model's `fast` apply only on hosted Dari, and are
|
|
371
|
+
* accepted and left unused; `routing.rules` runs only there and is refused.
|
|
372
|
+
*/
|
|
373
|
+
export type RouterSpec = { name: string; router: RouterConfig };
|
|
374
|
+
|
|
375
|
+
const SPEC_FIELDS = ["name", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
|
|
376
|
+
const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast"];
|
|
377
|
+
const PAYMENT_KINDS = ["subscription", "key", "credits"];
|
|
378
|
+
const SPEC_NAME_MAX_LENGTH = 120;
|
|
379
|
+
|
|
380
|
+
/** Read a router spec's YAML (or JSON) text; YAML 1.2, so `off` stays a thinking level. */
|
|
381
|
+
export function parseRouterSpecText(text: string): unknown {
|
|
382
|
+
try {
|
|
383
|
+
return Bun.YAML.parse(text);
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw new Error(`The router spec is not valid YAML: ${error instanceof Error ? error.message : String(error)}`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Check a router spec and read it as the router `id` serves it. */
|
|
390
|
+
export function parseRouterSpec(id: string, raw: unknown): RouterSpec {
|
|
391
|
+
const spec = specMap("The router spec", raw, SPEC_FIELDS);
|
|
392
|
+
if (typeof spec.name !== "string" || !spec.name.trim() || spec.name.length > SPEC_NAME_MAX_LENGTH) {
|
|
393
|
+
throw new Error(`name must be text of at most ${SPEC_NAME_MAX_LENGTH} characters.`);
|
|
394
|
+
}
|
|
395
|
+
if (Array.isArray(spec.models)) {
|
|
396
|
+
for (const [index, model] of spec.models.entries()) {
|
|
397
|
+
if (!isRecord(model)) continue;
|
|
398
|
+
specMap(`models[${index}]`, model, SPEC_MODEL_FIELDS);
|
|
399
|
+
optionalBoolean(model.fast ?? undefined, `models[${index}].fast`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const models = parseRouterModels(id, "models", spec.models);
|
|
403
|
+
const agentModels = parseAgentModels(id, "agents", spec.agents);
|
|
404
|
+
const roles = specMap("roles", spec.roles, ROUTER_ROLES);
|
|
405
|
+
const roleSpecs = Object.fromEntries(
|
|
406
|
+
ROUTER_ROLES.map((role) => [role, specMap(`roles.${role}`, roles[role], ["model", "prompt"])]),
|
|
407
|
+
);
|
|
408
|
+
const roleValues = (key: string) =>
|
|
409
|
+
Object.fromEntries(ROUTER_ROLES.map((role) => [role, roleSpecs[role]![key] ?? null]));
|
|
410
|
+
const routing = specMap("routing", spec.routing, ["session_pinning", "retries", "rules"]);
|
|
411
|
+
if (routing.rules != null && (!Array.isArray(routing.rules) || routing.rules.length > 0)) {
|
|
412
|
+
throw new Error("routing.rules runs only on hosted Dari; remove it to serve this router on a self-hosted gateway.");
|
|
413
|
+
}
|
|
414
|
+
const payment = specMap("payment", spec.payment, ["allow"]);
|
|
415
|
+
const allow = payment.allow ?? PAYMENT_KINDS;
|
|
416
|
+
if (!Array.isArray(allow) || !allow.every((kind) => PAYMENT_KINDS.includes(kind))) {
|
|
417
|
+
throw new Error(`payment.allow must list ${PAYMENT_KINDS.join(", ")}.`);
|
|
418
|
+
}
|
|
419
|
+
if (allow.length === 0) throw new Error("payment.allow needs at least one way to pay.");
|
|
420
|
+
if (spec.hosted != null && !isRecord(spec.hosted)) throw new Error("hosted must be a map.");
|
|
421
|
+
return {
|
|
422
|
+
name: spec.name.trim(),
|
|
423
|
+
router: {
|
|
424
|
+
models,
|
|
425
|
+
agentModels,
|
|
426
|
+
roleModels: parseRoleMap("roles", roleValues("model"), (field, model) =>
|
|
427
|
+
roleModel(`${field}.model`, model, [models, ...Object.values(agentModels)].flat())),
|
|
428
|
+
rolePrompts: parseRoleMap("roles", roleValues("prompt"), (field, prompt) => rolePrompt(`${field}.prompt`, prompt)),
|
|
429
|
+
retries: optionalRetries(routing.retries ?? undefined, "routing.retries") ?? 1,
|
|
430
|
+
subscriptions: allow.includes("subscription"),
|
|
431
|
+
sessionPinning: optionalBoolean(routing.session_pinning ?? undefined, "routing.session_pinning") ?? false,
|
|
432
|
+
nativeCompaction: optionalBoolean(spec.native_compaction ?? undefined, "native_compaction") ?? false,
|
|
433
|
+
zdr: false,
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** The spec of a router, such as one from the config file. */
|
|
439
|
+
export function routerSpecFor(name: string, router: RouterConfig): Record<string, unknown> {
|
|
440
|
+
const roles = Object.fromEntries(ROUTER_ROLES.flatMap((role) => {
|
|
441
|
+
const model = router.roleModels[role];
|
|
442
|
+
const prompt = router.rolePrompts[role];
|
|
443
|
+
if (model == null && prompt == null) return [];
|
|
444
|
+
return [[role, { ...(model == null ? {} : { model }), ...(prompt == null ? {} : { prompt }) }]];
|
|
445
|
+
}));
|
|
446
|
+
const agents = Object.entries(router.agentModels);
|
|
447
|
+
return {
|
|
448
|
+
name,
|
|
449
|
+
models: router.models.map(specModel),
|
|
450
|
+
...(Object.keys(roles).length > 0 ? { roles } : {}),
|
|
451
|
+
routing: { session_pinning: router.sessionPinning, retries: router.retries },
|
|
452
|
+
// The gateway pays with plans and API keys; it has no credits.
|
|
453
|
+
payment: { allow: router.subscriptions ? ["subscription", "key"] : ["key"] },
|
|
454
|
+
native_compaction: router.nativeCompaction,
|
|
455
|
+
...(agents.length > 0
|
|
456
|
+
? { agents: Object.fromEntries(agents.map(([agent, models]) => [agent, models!.map(specModel)])) }
|
|
457
|
+
: {}),
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** A spec as YAML text. */
|
|
462
|
+
export function routerSpecYaml(spec: unknown): string {
|
|
463
|
+
// Bun writes "key: " before a nested value; strings never span lines.
|
|
464
|
+
return `${Bun.YAML.stringify(spec, null, 2).replace(/: $/gm, ":")}\n`;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function specModel(model: RouterModelConfig): string | Record<string, unknown> {
|
|
468
|
+
return model.thinking === undefined && model.provider === undefined ? model.id : { ...model };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// A spec section as a map, refusing fields the spec does not have; absent is empty.
|
|
472
|
+
function specMap(field: string, raw: unknown, fields: readonly string[]): Record<string, unknown> {
|
|
473
|
+
if (raw == null) return {};
|
|
474
|
+
if (!isRecord(raw)) throw new Error(`${field} must be a map.`);
|
|
475
|
+
const unknown = Object.keys(raw).filter((key) => !fields.includes(key));
|
|
476
|
+
if (unknown.length > 0) {
|
|
477
|
+
throw new Error(`${field} has unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")}; use ${fields.join(", ")}.`);
|
|
478
|
+
}
|
|
479
|
+
return raw;
|
|
480
|
+
}
|
package/src/self_host/main.ts
CHANGED
|
@@ -12,10 +12,9 @@ import { createPrioritySelectorBackend } from "../strategies/priority_selector.j
|
|
|
12
12
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
13
13
|
import { ActivityStore } from "./activity_store.js";
|
|
14
14
|
import { createSelfHostedPlatform } from "./platform.js";
|
|
15
|
-
import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
|
|
16
15
|
import { checkProviderKey } from "../providers/key_check.js";
|
|
17
16
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
18
|
-
import { allRouterModels, loadGatewayConfig, type GatewayConfig, type RouterConfig } from "./config.js";
|
|
17
|
+
import { allRouterModels, loadGatewayConfig, modelProvider, type GatewayConfig, type RouterConfig } from "./config.js";
|
|
19
18
|
import {
|
|
20
19
|
configuredProviderApiKey,
|
|
21
20
|
gatewayKeyIndex,
|
|
@@ -26,6 +25,15 @@ import { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
|
26
25
|
import { secretBoxFromEnv } from "./secret_box.js";
|
|
27
26
|
import { PrefixStore } from "./prefix_store.js";
|
|
28
27
|
import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
|
|
28
|
+
import {
|
|
29
|
+
handleRouterSpecsRequest,
|
|
30
|
+
loadRouterSpecDirectory,
|
|
31
|
+
ROUTERS_ROUTE,
|
|
32
|
+
RouterSpecStore,
|
|
33
|
+
servedRouter,
|
|
34
|
+
servedRouterIds,
|
|
35
|
+
type ServedRouters,
|
|
36
|
+
} from "./router_specs.js";
|
|
29
37
|
import { SessionPinStore } from "./session_pin_store.js";
|
|
30
38
|
import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
|
|
31
39
|
|
|
@@ -39,10 +47,14 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
|
|
|
39
47
|
* - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
|
|
40
48
|
* - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
|
|
41
49
|
* serves when present, and otherwise the default router.
|
|
50
|
+
* - `DARI_GATEWAY_ROUTERS_DIR`: a directory of router specs, read at startup:
|
|
51
|
+
* each `<id>.yaml` (or `.yml`) is router `<id>`, served in place of a
|
|
52
|
+
* config file router of that id. Specs saved through `PUT /v1/routers/<id>`
|
|
53
|
+
* are served in place of both.
|
|
42
54
|
* - `DARI_GATEWAY_DB`: SQLite database for subscriptions, Dari Link grants,
|
|
43
|
-
* saved model lists, prefix-cache state, and Activity:
|
|
44
|
-
* row and, outside ZDR routers, its request and response
|
|
45
|
-
* `dari-gateway.db`). It holds subscription tokens.
|
|
55
|
+
* saved model lists and router specs, prefix-cache state, and Activity:
|
|
56
|
+
* each request's log row and, outside ZDR routers, its request and response
|
|
57
|
+
* bodies (default `dari-gateway.db`). It holds subscription tokens.
|
|
46
58
|
* - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
|
|
47
59
|
* keys in the database (`openssl rand -base64 32`; see secret_box.ts for
|
|
48
60
|
* rotation). Unset, they are stored as they are, and the Dari Link approval
|
|
@@ -64,6 +76,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
64
76
|
throw new Error("Set DARI_GATEWAY_KEYS to the comma-separated keys clients authenticate with.");
|
|
65
77
|
}
|
|
66
78
|
const config = await loadGatewayConfig(env.DARI_GATEWAY_CONFIG?.trim() || undefined);
|
|
79
|
+
const routersDir = env.DARI_GATEWAY_ROUTERS_DIR?.trim();
|
|
80
|
+
const specFiles = routersDir ? await loadRouterSpecDirectory(routersDir) : undefined;
|
|
67
81
|
const databasePath = env.DARI_GATEWAY_DB ?? "dari-gateway.db";
|
|
68
82
|
const created = databasePath !== ":memory:" && !existsSync(databasePath);
|
|
69
83
|
const db = new Database(databasePath, { create: true });
|
|
@@ -79,13 +93,17 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
79
93
|
const prefixes = new PrefixStore(db);
|
|
80
94
|
const sessionPins = new SessionPinStore(db);
|
|
81
95
|
const routerModels = new RouterModelStore(db);
|
|
96
|
+
const routerSpecs = new RouterSpecStore(db, specFiles);
|
|
97
|
+
const routers: ServedRouters = { config, routerModels, routerSpecs };
|
|
82
98
|
const links = new SqliteLinkStore(db, secrets);
|
|
83
99
|
const activity = new ActivityStore(db);
|
|
84
|
-
|
|
100
|
+
// Activity lists the routers served, so it follows each saved spec.
|
|
101
|
+
const syncActivityRouters = () => activity.syncDirectory(
|
|
85
102
|
SELF_HOSTED_ORGANIZATION_ID,
|
|
86
|
-
|
|
103
|
+
servedRouterIds(routers).map((id) => ({ id, zdr: servedRouter(routers, id)!.zdr })),
|
|
87
104
|
gatewayKeys.length,
|
|
88
105
|
);
|
|
106
|
+
syncActivityRouters();
|
|
89
107
|
// Pi's provider auth reads each provider's standard key variable, such as
|
|
90
108
|
// OPENAI_API_KEY, from this environment only.
|
|
91
109
|
const piModels = builtinModels({
|
|
@@ -98,6 +116,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
98
116
|
activity,
|
|
99
117
|
config,
|
|
100
118
|
routerModels,
|
|
119
|
+
routerSpecs,
|
|
101
120
|
gatewayKeys,
|
|
102
121
|
subscriptions,
|
|
103
122
|
links,
|
|
@@ -110,9 +129,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
110
129
|
});
|
|
111
130
|
// A model without a credential is dropped at request time, so a missing key
|
|
112
131
|
// would otherwise surface only as a 424 on the first request.
|
|
113
|
-
const
|
|
114
|
-
.map(([routerId, router]) => [routerId, routerModels.served(routerId, router)] as const);
|
|
115
|
-
for (const [routerId, router] of routers) {
|
|
132
|
+
const warnWithoutCredentials = async (routerId: string, router: RouterConfig) => {
|
|
116
133
|
const missing = await providersWithoutCredentials({ config, subscriptions, providerApiKey, env }, router);
|
|
117
134
|
if (missing.length > 0) {
|
|
118
135
|
console.warn(
|
|
@@ -120,9 +137,17 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
120
137
|
JSON.stringify({ router: routerId, providers: missing }),
|
|
121
138
|
);
|
|
122
139
|
}
|
|
123
|
-
}
|
|
124
|
-
|
|
140
|
+
};
|
|
141
|
+
const served = servedRouterIds(routers).map((routerId) => [routerId, servedRouter(routers, routerId)!] as const);
|
|
142
|
+
for (const [routerId, router] of served) await warnWithoutCredentials(routerId, router);
|
|
143
|
+
await checkConfiguredProviderKeys(config, served.map(([, router]) => router), (provider) =>
|
|
125
144
|
configuredProviderApiKey({ config, providerApiKey, env }, provider));
|
|
145
|
+
// A saved or removed spec changes what is served at once.
|
|
146
|
+
const routersChanged = (routerId: string) => {
|
|
147
|
+
syncActivityRouters();
|
|
148
|
+
const router = servedRouter(routers, routerId);
|
|
149
|
+
if (router !== undefined) void warnWithoutCredentials(routerId, router);
|
|
150
|
+
};
|
|
126
151
|
const selectorBackend: SelectorBackend = autoRoutingKey
|
|
127
152
|
? createAutoRoutingSelectorBackend({
|
|
128
153
|
apiKey: autoRoutingKey,
|
|
@@ -131,14 +156,15 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
131
156
|
: createPrioritySelectorBackend();
|
|
132
157
|
const gateway = createRequestHandler({ platform, selectorBackend });
|
|
133
158
|
|
|
134
|
-
// Subscriptions
|
|
135
|
-
// other path is the gateway's own.
|
|
159
|
+
// Subscriptions, model lists, and router specs are managed with any gateway
|
|
160
|
+
// key; every other path is the gateway's own.
|
|
136
161
|
const handler = async (request: Request): Promise<Response> => {
|
|
137
162
|
const { pathname } = new URL(request.url);
|
|
138
163
|
const manages = pathname === SUBSCRIPTION_ROUTES
|
|
139
164
|
|| pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
|
|
140
165
|
|| pathname === CANONICAL_MODELS_ROUTE
|
|
141
|
-
|| ROUTER_MODELS_ROUTE.test(pathname)
|
|
166
|
+
|| ROUTER_MODELS_ROUTE.test(pathname)
|
|
167
|
+
|| ROUTERS_ROUTE.test(pathname);
|
|
142
168
|
if (!manages) return await gateway(request);
|
|
143
169
|
try {
|
|
144
170
|
if (gatewayKeyIndex(gatewayKeys, bearerToken(request.headers)) === null) {
|
|
@@ -151,7 +177,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
151
177
|
return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
|
|
152
178
|
}
|
|
153
179
|
return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
|
|
154
|
-
?? (await handleRouterModelsRequest(request,
|
|
180
|
+
?? (await handleRouterModelsRequest(request, routers))
|
|
181
|
+
?? (await handleRouterSpecsRequest(request, { ...routers, changed: routersChanged }))
|
|
155
182
|
?? errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
156
183
|
};
|
|
157
184
|
|
|
@@ -165,9 +192,11 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
|
|
|
165
192
|
hostname,
|
|
166
193
|
// The bound port, so PORT=0 reports the port the OS assigned.
|
|
167
194
|
port: server.port,
|
|
168
|
-
routers:
|
|
195
|
+
routers: servedRouterIds(routers),
|
|
169
196
|
// These serve lists saved with `dari gateway models`, not the config file's.
|
|
170
197
|
saved_model_lists: routerModels.routersWithSavedLists(),
|
|
198
|
+
// These serve router specs saved through the API.
|
|
199
|
+
saved_routers: routerSpecs.savedIds(),
|
|
171
200
|
auto_routing: autoRoutingKey ? "dari" : "priority",
|
|
172
201
|
}),
|
|
173
202
|
);
|
|
@@ -184,7 +213,7 @@ async function checkConfiguredProviderKeys(
|
|
|
184
213
|
providerApiKey: (provider: string) => Promise<string | undefined>,
|
|
185
214
|
): Promise<void> {
|
|
186
215
|
const providers = new Set(
|
|
187
|
-
routers.flatMap((router) => allRouterModels(router).map(
|
|
216
|
+
routers.flatMap((router) => allRouterModels(router).map(modelProvider)),
|
|
188
217
|
);
|
|
189
218
|
const checks = await Promise.all([...providers].map(async (provider) => {
|
|
190
219
|
const endpoint = config.providers[provider];
|
|
@@ -6,6 +6,7 @@ import type { GatewayPlatform } from "../platform/platform.js";
|
|
|
6
6
|
import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
|
|
7
7
|
import { SELF_HOSTED_BLOB_BUCKET, type ActivityStore } from "./activity_store.js";
|
|
8
8
|
import type { PrefixStore } from "./prefix_store.js";
|
|
9
|
+
import { servedRouter } from "./router_specs.js";
|
|
9
10
|
import type { SessionPinStore } from "./session_pin_store.js";
|
|
10
11
|
import {
|
|
11
12
|
gatewayKeyIndex,
|
|
@@ -17,9 +18,10 @@ import { type SubscriptionStore } from "./subscriptions/index.js";
|
|
|
17
18
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
|
-
* The self-hosted platform: routers from the config file
|
|
21
|
-
* Dari Link grants, prefix-cache state, session pins, and
|
|
22
|
-
* gateway's SQLite database, and one content-free log line
|
|
21
|
+
* The self-hosted platform: routers from the config file and router specs,
|
|
22
|
+
* subscriptions, Dari Link grants, prefix-cache state, session pins, and
|
|
23
|
+
* Activity in the gateway's SQLite database, and one content-free log line
|
|
24
|
+
* per request.
|
|
23
25
|
*/
|
|
24
26
|
export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "prefixHits"> & {
|
|
25
27
|
activity: ActivityStore;
|
|
@@ -37,7 +39,7 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
|
|
|
37
39
|
deps.prefixes.write(write);
|
|
38
40
|
},
|
|
39
41
|
writePendingLease: async (write) => {
|
|
40
|
-
deps.prefixes.writePendingLease(write, deps
|
|
42
|
+
deps.prefixes.writePendingLease(write, servedRouter(deps, write.router_id)?.zdr ?? false);
|
|
41
43
|
},
|
|
42
44
|
readSessionPin: async (key) => deps.sessionPins.read(key),
|
|
43
45
|
writeSessionPin: async (write) => {
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -11,13 +11,14 @@ import { HttpError } from "../http/errors.js";
|
|
|
11
11
|
import type { ResolveRouterRequest } from "../platform/platform.js";
|
|
12
12
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
13
13
|
import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
14
|
-
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
14
|
+
import { CANONICAL_MODELS, providerModel } from "../models/canonical.js";
|
|
15
15
|
import { gatewayFor } from "../models/gateways.js";
|
|
16
16
|
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
17
17
|
import { registeredModelPrice } from "../providers/pi.js";
|
|
18
18
|
import type { LinkUnavailable, ProviderCredential as SuppliedProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
|
|
19
19
|
import {
|
|
20
20
|
allRouterModels,
|
|
21
|
+
modelProvider,
|
|
21
22
|
routerModelsFor,
|
|
22
23
|
type GatewayConfig,
|
|
23
24
|
type RouterConfig,
|
|
@@ -27,6 +28,7 @@ import type { ActiveLinkGrant } from "../link/grants.js";
|
|
|
27
28
|
import type { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
28
29
|
import { linkTokenGrant } from "../link/service.js";
|
|
29
30
|
import type { RouterModelStore } from "./router_models.js";
|
|
31
|
+
import { servedRouter, type RouterSpecStore } from "./router_specs.js";
|
|
30
32
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
31
33
|
import {
|
|
32
34
|
activeModelHolds,
|
|
@@ -46,6 +48,8 @@ export type SelfHostedResolverDeps = {
|
|
|
46
48
|
config: GatewayConfig;
|
|
47
49
|
// Model lists saved through the API, served in place of the config's.
|
|
48
50
|
routerModels: RouterModelStore;
|
|
51
|
+
// Router specs, each served in place of the config's router of its id.
|
|
52
|
+
routerSpecs: RouterSpecStore;
|
|
49
53
|
gatewayKeys: readonly string[];
|
|
50
54
|
subscriptions: SubscriptionStore;
|
|
51
55
|
links: SqliteLinkStore;
|
|
@@ -94,11 +98,10 @@ export async function resolveSelfHostedRouter(
|
|
|
94
98
|
if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
|
|
95
99
|
throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
|
|
96
100
|
}
|
|
97
|
-
const
|
|
98
|
-
if (
|
|
101
|
+
const router = servedRouter(deps, request.routerId);
|
|
102
|
+
if (router === undefined) {
|
|
99
103
|
throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
|
|
100
104
|
}
|
|
101
|
-
const router = deps.routerModels.served(request.routerId, configured);
|
|
102
105
|
|
|
103
106
|
const routed = routerModelsFor(router, request.clientHarness);
|
|
104
107
|
const granted = grant === null
|
|
@@ -113,7 +116,7 @@ export async function resolveSelfHostedRouter(
|
|
|
113
116
|
const servable = grant === null ? undefined : new Set(grant.credentialIds);
|
|
114
117
|
const credentials = new Map<string, ProviderCredential | null>();
|
|
115
118
|
const exhausted = new Set<SubscriptionProvider>();
|
|
116
|
-
for (const provider of new Set(listed.map(
|
|
119
|
+
for (const provider of new Set(listed.map(modelProvider))) {
|
|
117
120
|
// A grant uses the subscriptions its user chose, whatever the router allows.
|
|
118
121
|
const subscription = router.subscriptions || grant !== null
|
|
119
122
|
? subscriptionProviderFor(provider, request.clientHarness)
|
|
@@ -158,7 +161,7 @@ export async function resolveSelfHostedRouter(
|
|
|
158
161
|
);
|
|
159
162
|
const models = [];
|
|
160
163
|
for (const model of listed) {
|
|
161
|
-
const credential = credentials.get(
|
|
164
|
+
const credential = credentials.get(modelProvider(model));
|
|
162
165
|
if (credential == null) continue;
|
|
163
166
|
const plan = credential.subscription;
|
|
164
167
|
const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
|
|
@@ -259,12 +262,24 @@ export async function resolveSelfHostedRouter(
|
|
|
259
262
|
resolved.provider_key_sources![provider] = "user";
|
|
260
263
|
}
|
|
261
264
|
for (const model of models) {
|
|
262
|
-
const
|
|
265
|
+
const provider = modelProvider(model);
|
|
266
|
+
// A model another provider serves runs as that provider's own model.
|
|
267
|
+
const served = model.provider === undefined ? undefined : providerModel(model.id, provider);
|
|
268
|
+
const price = served === undefined
|
|
269
|
+
? registeredModelPrice(model.id)
|
|
270
|
+
: registeredModelPrice(`${provider}/${served.native_model_id}`);
|
|
263
271
|
if (price !== null) resolved.model_prices![model.id] = price;
|
|
264
|
-
const provider = providerForModel(model.id);
|
|
265
272
|
const endpoint = deps.config.providers[provider];
|
|
266
273
|
if (credentials.get(provider)?.subscription?.provider === "openai_codex") {
|
|
267
274
|
resolved.model_configs![model.id] = codexModelConfig(model.id, price, deps.config.providers["openai-codex"]?.baseUrl);
|
|
275
|
+
} else if (served !== undefined) {
|
|
276
|
+
resolved.model_configs![model.id] = {
|
|
277
|
+
provider,
|
|
278
|
+
native_model_id: served.native_model_id,
|
|
279
|
+
api: endpoint?.api ?? served.api,
|
|
280
|
+
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
281
|
+
cost: price ?? { input: 0, output: 0 },
|
|
282
|
+
};
|
|
268
283
|
} else if (endpoint !== undefined) {
|
|
269
284
|
resolved.model_configs![model.id] = {
|
|
270
285
|
provider,
|
|
@@ -379,7 +394,7 @@ export async function providersWithoutCredentials(
|
|
|
379
394
|
router: RouterConfig,
|
|
380
395
|
): Promise<string[]> {
|
|
381
396
|
const missing: string[] = [];
|
|
382
|
-
for (const provider of new Set(allRouterModels(router).map(
|
|
397
|
+
for (const provider of new Set(allRouterModels(router).map(modelProvider))) {
|
|
383
398
|
const plans = router.subscriptions
|
|
384
399
|
? [subscriptionProviderFor(provider, "claude_code"), subscriptionProviderFor(provider, "muse_code")]
|
|
385
400
|
: [];
|