@mupt-ai/dari-gateway 1.0.330 → 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.
Files changed (61) hide show
  1. package/README.md +38 -8
  2. package/dari-gateway.example.yaml +4 -0
  3. package/dist/activity/conversations.js +4 -2
  4. package/dist/activity/core.js +52 -28
  5. package/dist/activity/people.js +20 -17
  6. package/dist/link/assets.js +2 -0
  7. package/dist/link/key_providers.js +1 -0
  8. package/dist/models/canonical.d.ts +12 -0
  9. package/dist/models/canonical.js +10 -0
  10. package/dist/models/canonical_models.json +69 -0
  11. package/dist/models/catalog.js +1 -0
  12. package/dist/models/provider_defaults.js +2 -0
  13. package/dist/models/provider_models.json +114 -0
  14. package/dist/models/runtime_overrides.js +13 -0
  15. package/dist/protocol/output/anthropic_messages_output.js +3 -1
  16. package/dist/protocol/output/anthropic_messages_stream.js +14 -0
  17. package/dist/providers/model_capabilities.d.ts +1 -0
  18. package/dist/providers/model_capabilities.js +5 -1
  19. package/dist/providers/pi.js +2 -0
  20. package/dist/providers/pi_context.js +35 -2
  21. package/dist/providers/pi_options.js +50 -0
  22. package/dist/providers/pi_output.js +21 -3
  23. package/dist/self_host/config.d.ts +46 -4
  24. package/dist/self_host/config.js +165 -54
  25. package/dist/self_host/main.d.ts +7 -3
  26. package/dist/self_host/main.js +40 -17
  27. package/dist/self_host/platform.d.ts +4 -3
  28. package/dist/self_host/platform.js +6 -4
  29. package/dist/self_host/resolve.d.ts +2 -0
  30. package/dist/self_host/resolve.js +23 -10
  31. package/dist/self_host/router_models.d.ts +5 -2
  32. package/dist/self_host/router_models.js +10 -5
  33. package/dist/self_host/router_specs.d.ts +64 -0
  34. package/dist/self_host/router_specs.js +194 -0
  35. package/dist/telemetry/requests/interaction_observability.js +1 -0
  36. package/package.json +3 -3
  37. package/src/activity/conversations.ts +4 -2
  38. package/src/activity/core.ts +52 -28
  39. package/src/activity/people.ts +20 -18
  40. package/src/link/assets.ts +2 -0
  41. package/src/link/key_providers.ts +1 -0
  42. package/src/models/canonical.ts +22 -0
  43. package/src/models/canonical_models.json +69 -0
  44. package/src/models/catalog.ts +1 -0
  45. package/src/models/provider_defaults.ts +2 -0
  46. package/src/models/provider_models.json +114 -0
  47. package/src/models/runtime_overrides.ts +13 -0
  48. package/src/protocol/output/anthropic_messages_output.ts +5 -1
  49. package/src/protocol/output/anthropic_messages_stream.ts +16 -0
  50. package/src/providers/model_capabilities.ts +6 -1
  51. package/src/providers/pi.ts +1 -0
  52. package/src/providers/pi_context.ts +34 -3
  53. package/src/providers/pi_options.ts +51 -1
  54. package/src/providers/pi_output.ts +21 -3
  55. package/src/self_host/config.ts +217 -60
  56. package/src/self_host/main.ts +47 -18
  57. package/src/self_host/platform.ts +6 -4
  58. package/src/self_host/resolve.ts +24 -9
  59. package/src/self_host/router_models.ts +16 -6
  60. package/src/self_host/router_specs.ts +236 -0
  61. package/src/telemetry/requests/interaction_observability.ts +1 -0
@@ -1,7 +1,12 @@
1
- import { isReasoningEffort, isRecord, } from "@mupt-ai/dari-router/policy-engine";
1
+ import { isReasoningEffort, isRecord, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
3
+ import { otherModelProviders, providerModel } from "../models/canonical.js";
3
4
  const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
4
- const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
5
+ /** The provider that serves a router's model, whose credential it needs. */
6
+ export function modelProvider(model) {
7
+ return model.provider ?? providerForModel(model.id);
8
+ }
9
+ export const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
5
10
  const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*$/;
6
11
  const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
7
12
  // Served when no config file is set or found. A model is served once its
@@ -15,7 +20,7 @@ export const DEFAULT_GATEWAY_CONFIG = parseGatewayConfig({
15
20
  "anthropic/claude-opus-5-5",
16
21
  "anthropic/claude-fable-5-2",
17
22
  "anthropic/claude-haiku-5-5",
18
- "openai/gpt-6.1-sol",
23
+ "openai/gpt-6.2-sol",
19
24
  "openai/gpt-6.1-terra",
20
25
  ],
21
26
  },
@@ -106,24 +111,13 @@ export function allRouterModels(router) {
106
111
  function parseRouter(id, raw) {
107
112
  if (!isRecord(raw))
108
113
  throw new Error(`Router "${id}" needs a non-empty \`models\` list.`);
109
- const agentModels = {};
110
- if (raw.agentModels !== undefined) {
111
- if (!isRecord(raw.agentModels)) {
112
- throw new Error(`routers.${id}.agentModels must map coding agents to model lists.`);
113
- }
114
- for (const [agent, models] of Object.entries(raw.agentModels)) {
115
- if (!CLIENT_HARNESSES.includes(agent)) {
116
- throw new Error(`Router "${id}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`);
117
- }
118
- agentModels[agent] = parseRouterModels(id, `agentModels.${agent}`, models);
119
- }
120
- }
114
+ const agentModels = parseAgentModels(id, `routers.${id}.agentModels`, raw.agentModels);
121
115
  const models = parseRouterModels(id, "models", raw.models);
122
116
  return {
123
117
  models,
124
118
  agentModels,
125
- roleModels: parseRoleModels(id, raw.roleModels, [models, ...Object.values(agentModels)].flat()),
126
- rolePrompts: parseRolePrompts(id, raw.rolePrompts),
119
+ roleModels: parseRoleMap(`routers.${id}.roleModels`, raw.roleModels, (field, model) => roleModel(field, model, [models, ...Object.values(agentModels)].flat())),
120
+ rolePrompts: parseRoleMap(`routers.${id}.rolePrompts`, raw.rolePrompts, rolePrompt),
127
121
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
128
122
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
129
123
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
@@ -131,45 +125,49 @@ function parseRouter(id, raw) {
131
125
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
132
126
  };
133
127
  }
134
- const ROUTER_ROLES = ["main", "subagent"];
135
- function parseRoleModels(routerId, raw, models) {
136
- if (raw === undefined)
137
- return {};
128
+ function parseAgentModels(routerId, field, raw) {
129
+ const agentModels = {};
130
+ if (raw == null)
131
+ return agentModels;
138
132
  if (!isRecord(raw))
139
- throw new Error(`routers.${routerId}.roleModels must map main and subagent to models.`);
140
- const roleModels = {};
141
- for (const [role, model] of Object.entries(raw)) {
142
- if (!ROUTER_ROLES.includes(role)) {
143
- throw new Error(`routers.${routerId}.roleModels has an unknown role "${role}"; use main or subagent.`);
144
- }
145
- if (model === null)
146
- continue;
147
- if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
148
- throw new Error(`routers.${routerId}.roleModels.${role} must be one of the router's models.`);
133
+ throw new Error(`${field} must map coding agents to model lists.`);
134
+ for (const [agent, models] of Object.entries(raw)) {
135
+ if (!CLIENT_HARNESSES.includes(agent)) {
136
+ throw new Error(`Router "${routerId}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`);
149
137
  }
150
- roleModels[role] = model;
138
+ agentModels[agent] = parseRouterModels(routerId, `${field}.${agent}`, models);
151
139
  }
152
- return roleModels;
140
+ return agentModels;
153
141
  }
154
- export const ROLE_PROMPT_MAX_LENGTH = 4000;
155
- function parseRolePrompts(routerId, raw) {
156
- if (raw === undefined)
142
+ const ROUTER_ROLES = ["main", "subagent"];
143
+ // A map of main and subagent to values `read` checks, leaving out nulls.
144
+ function parseRoleMap(field, raw, read) {
145
+ if (raw == null)
157
146
  return {};
158
147
  if (!isRecord(raw))
159
- throw new Error(`routers.${routerId}.rolePrompts must map main and subagent to text.`);
160
- const rolePrompts = {};
161
- for (const [role, prompt] of Object.entries(raw)) {
148
+ throw new Error(`${field} must map main and subagent.`);
149
+ const roles = {};
150
+ for (const [role, value] of Object.entries(raw)) {
162
151
  if (!ROUTER_ROLES.includes(role)) {
163
- throw new Error(`routers.${routerId}.rolePrompts has an unknown role "${role}"; use main or subagent.`);
164
- }
165
- if (prompt === null)
166
- continue;
167
- if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
168
- throw new Error(`routers.${routerId}.rolePrompts.${role} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`);
152
+ throw new Error(`${field} has an unknown role "${role}"; use main or subagent.`);
169
153
  }
170
- rolePrompts[role] = prompt.trim();
154
+ if (value !== null)
155
+ roles[role] = read(`${field}.${role}`, value);
171
156
  }
172
- return rolePrompts;
157
+ return roles;
158
+ }
159
+ function roleModel(field, model, models) {
160
+ if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
161
+ throw new Error(`${field} must be one of the router's models.`);
162
+ }
163
+ return model;
164
+ }
165
+ export const ROLE_PROMPT_MAX_LENGTH = 4000;
166
+ function rolePrompt(field, prompt) {
167
+ if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
168
+ throw new Error(`${field} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`);
169
+ }
170
+ return prompt.trim();
173
171
  }
174
172
  /** Read one model list of a router, naming `field` in what it rejects. */
175
173
  export function parseRouterModels(routerId, field, raw) {
@@ -190,14 +188,24 @@ function parseModel(routerId, raw) {
190
188
  if (!isRecord(entry) || typeof entry.id !== "string" || !MODEL_ID_PATTERN.test(entry.id)) {
191
189
  throw new Error(`Router "${routerId}" has an invalid model; use a canonical "provider/model" id.`);
192
190
  }
193
- if (entry.thinking === undefined)
194
- return { id: entry.id };
195
- if (!Array.isArray(entry.thinking) ||
196
- entry.thinking.length === 0 ||
197
- !entry.thinking.every(isReasoningEffort)) {
198
- throw new Error(`Model ${entry.id} on router "${routerId}" has invalid thinking levels; use off, minimal, low, medium, high, xhigh, or max.`);
191
+ const model = { id: entry.id };
192
+ if (entry.thinking != null) {
193
+ if (!Array.isArray(entry.thinking) ||
194
+ entry.thinking.length === 0 ||
195
+ !entry.thinking.every(isReasoningEffort)) {
196
+ throw new Error(`Model ${entry.id} on router "${routerId}" has invalid thinking levels; use off, minimal, low, medium, high, xhigh, or max.`);
197
+ }
198
+ model.thinking = [...new Set(entry.thinking)];
199
+ }
200
+ if (entry.provider != null && entry.provider !== providerForModel(entry.id)) {
201
+ if (typeof entry.provider !== "string" || providerModel(entry.id, entry.provider) === undefined) {
202
+ const others = otherModelProviders(entry.id);
203
+ throw new Error(`Model ${entry.id} on router "${routerId}" cannot be served by provider ${String(entry.provider)} on a self-hosted gateway; `
204
+ + `${others.length > 0 ? `use ${others.join(" or ")}, or ` : ""}leave out \`provider\` to use ${providerForModel(entry.id)}.`);
205
+ }
206
+ model.provider = entry.provider;
199
207
  }
200
- return { id: entry.id, thinking: [...new Set(entry.thinking)] };
208
+ return model;
201
209
  }
202
210
  function optionalBoolean(value, field) {
203
211
  if (value === undefined)
@@ -214,3 +222,106 @@ function optionalRetries(value, field) {
214
222
  }
215
223
  return value;
216
224
  }
225
+ const SPEC_FIELDS = ["name", "models", "roles", "routing", "payment", "native_compaction", "agents", "hosted"];
226
+ const SPEC_MODEL_FIELDS = ["id", "thinking", "provider", "fast"];
227
+ const PAYMENT_KINDS = ["subscription", "key", "credits"];
228
+ const SPEC_NAME_MAX_LENGTH = 120;
229
+ /** Read a router spec's YAML (or JSON) text; YAML 1.2, so `off` stays a thinking level. */
230
+ export function parseRouterSpecText(text) {
231
+ try {
232
+ return Bun.YAML.parse(text);
233
+ }
234
+ catch (error) {
235
+ throw new Error(`The router spec is not valid YAML: ${error instanceof Error ? error.message : String(error)}`);
236
+ }
237
+ }
238
+ /** Check a router spec and read it as the router `id` serves it. */
239
+ export function parseRouterSpec(id, raw) {
240
+ const spec = specMap("The router spec", raw, SPEC_FIELDS);
241
+ if (typeof spec.name !== "string" || !spec.name.trim() || spec.name.length > SPEC_NAME_MAX_LENGTH) {
242
+ throw new Error(`name must be text of at most ${SPEC_NAME_MAX_LENGTH} characters.`);
243
+ }
244
+ if (Array.isArray(spec.models)) {
245
+ for (const [index, model] of spec.models.entries()) {
246
+ if (!isRecord(model))
247
+ continue;
248
+ specMap(`models[${index}]`, model, SPEC_MODEL_FIELDS);
249
+ optionalBoolean(model.fast ?? undefined, `models[${index}].fast`);
250
+ }
251
+ }
252
+ const models = parseRouterModels(id, "models", spec.models);
253
+ const agentModels = parseAgentModels(id, "agents", spec.agents);
254
+ const roles = specMap("roles", spec.roles, ROUTER_ROLES);
255
+ const roleSpecs = Object.fromEntries(ROUTER_ROLES.map((role) => [role, specMap(`roles.${role}`, roles[role], ["model", "prompt"])]));
256
+ const roleValues = (key) => Object.fromEntries(ROUTER_ROLES.map((role) => [role, roleSpecs[role][key] ?? null]));
257
+ const routing = specMap("routing", spec.routing, ["session_pinning", "retries", "rules"]);
258
+ if (routing.rules != null && (!Array.isArray(routing.rules) || routing.rules.length > 0)) {
259
+ throw new Error("routing.rules runs only on hosted Dari; remove it to serve this router on a self-hosted gateway.");
260
+ }
261
+ const payment = specMap("payment", spec.payment, ["allow"]);
262
+ const allow = payment.allow ?? PAYMENT_KINDS;
263
+ if (!Array.isArray(allow) || !allow.every((kind) => PAYMENT_KINDS.includes(kind))) {
264
+ throw new Error(`payment.allow must list ${PAYMENT_KINDS.join(", ")}.`);
265
+ }
266
+ if (allow.length === 0)
267
+ throw new Error("payment.allow needs at least one way to pay.");
268
+ if (spec.hosted != null && !isRecord(spec.hosted))
269
+ throw new Error("hosted must be a map.");
270
+ return {
271
+ name: spec.name.trim(),
272
+ router: {
273
+ models,
274
+ agentModels,
275
+ roleModels: parseRoleMap("roles", roleValues("model"), (field, model) => roleModel(`${field}.model`, model, [models, ...Object.values(agentModels)].flat())),
276
+ rolePrompts: parseRoleMap("roles", roleValues("prompt"), (field, prompt) => rolePrompt(`${field}.prompt`, prompt)),
277
+ retries: optionalRetries(routing.retries ?? undefined, "routing.retries") ?? 1,
278
+ subscriptions: allow.includes("subscription"),
279
+ sessionPinning: optionalBoolean(routing.session_pinning ?? undefined, "routing.session_pinning") ?? false,
280
+ nativeCompaction: optionalBoolean(spec.native_compaction ?? undefined, "native_compaction") ?? false,
281
+ zdr: false,
282
+ },
283
+ };
284
+ }
285
+ /** The spec of a router, such as one from the config file. */
286
+ export function routerSpecFor(name, router) {
287
+ const roles = Object.fromEntries(ROUTER_ROLES.flatMap((role) => {
288
+ const model = router.roleModels[role];
289
+ const prompt = router.rolePrompts[role];
290
+ if (model == null && prompt == null)
291
+ return [];
292
+ return [[role, { ...(model == null ? {} : { model }), ...(prompt == null ? {} : { prompt }) }]];
293
+ }));
294
+ const agents = Object.entries(router.agentModels);
295
+ return {
296
+ name,
297
+ models: router.models.map(specModel),
298
+ ...(Object.keys(roles).length > 0 ? { roles } : {}),
299
+ routing: { session_pinning: router.sessionPinning, retries: router.retries },
300
+ // The gateway pays with plans and API keys; it has no credits.
301
+ payment: { allow: router.subscriptions ? ["subscription", "key"] : ["key"] },
302
+ native_compaction: router.nativeCompaction,
303
+ ...(agents.length > 0
304
+ ? { agents: Object.fromEntries(agents.map(([agent, models]) => [agent, models.map(specModel)])) }
305
+ : {}),
306
+ };
307
+ }
308
+ /** A spec as YAML text. */
309
+ export function routerSpecYaml(spec) {
310
+ // Bun writes "key: " before a nested value; strings never span lines.
311
+ return `${Bun.YAML.stringify(spec, null, 2).replace(/: $/gm, ":")}\n`;
312
+ }
313
+ function specModel(model) {
314
+ return model.thinking === undefined && model.provider === undefined ? model.id : { ...model };
315
+ }
316
+ // A spec section as a map, refusing fields the spec does not have; absent is empty.
317
+ function specMap(field, raw, fields) {
318
+ if (raw == null)
319
+ return {};
320
+ if (!isRecord(raw))
321
+ throw new Error(`${field} must be a map.`);
322
+ const unknown = Object.keys(raw).filter((key) => !fields.includes(key));
323
+ if (unknown.length > 0) {
324
+ throw new Error(`${field} has unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")}; use ${fields.join(", ")}.`);
325
+ }
326
+ return raw;
327
+ }
@@ -5,10 +5,14 @@
5
5
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
6
6
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
7
7
  * serves when present, and otherwise the default router.
8
+ * - `DARI_GATEWAY_ROUTERS_DIR`: a directory of router specs, read at startup:
9
+ * each `<id>.yaml` (or `.yml`) is router `<id>`, served in place of a
10
+ * config file router of that id. Specs saved through `PUT /v1/routers/<id>`
11
+ * are served in place of both.
8
12
  * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, Dari Link grants,
9
- * saved model lists, prefix-cache state, and Activity: each request's log
10
- * row and, outside ZDR routers, its request and response bodies (default
11
- * `dari-gateway.db`). It holds subscription tokens.
13
+ * saved model lists and router specs, prefix-cache state, and Activity:
14
+ * each request's log row and, outside ZDR routers, its request and response
15
+ * bodies (default `dari-gateway.db`). It holds subscription tokens.
12
16
  * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
13
17
  * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
14
18
  * rotation). Unset, they are stored as they are, and the Dari Link approval
@@ -10,15 +10,15 @@ import { createAutoRoutingSelectorBackend } from "../strategies/auto_routing_sel
10
10
  import { createPrioritySelectorBackend } from "../strategies/priority_selector.js";
11
11
  import { ActivityStore } from "./activity_store.js";
12
12
  import { createSelfHostedPlatform } from "./platform.js";
13
- import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
14
13
  import { checkProviderKey } from "../providers/key_check.js";
15
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
16
- import { allRouterModels, loadGatewayConfig } from "./config.js";
15
+ import { allRouterModels, loadGatewayConfig, modelProvider } from "./config.js";
17
16
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
18
17
  import { SqliteLinkStore } from "../link/sqlite_store.js";
19
18
  import { secretBoxFromEnv } from "./secret_box.js";
20
19
  import { PrefixStore } from "./prefix_store.js";
21
20
  import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
21
+ import { handleRouterSpecsRequest, loadRouterSpecDirectory, ROUTERS_ROUTE, RouterSpecStore, servedRouter, servedRouterIds, } from "./router_specs.js";
22
22
  import { SessionPinStore } from "./session_pin_store.js";
23
23
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
24
24
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
@@ -30,10 +30,14 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
30
30
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
31
31
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
32
32
  * serves when present, and otherwise the default router.
33
+ * - `DARI_GATEWAY_ROUTERS_DIR`: a directory of router specs, read at startup:
34
+ * each `<id>.yaml` (or `.yml`) is router `<id>`, served in place of a
35
+ * config file router of that id. Specs saved through `PUT /v1/routers/<id>`
36
+ * are served in place of both.
33
37
  * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, Dari Link grants,
34
- * saved model lists, prefix-cache state, and Activity: each request's log
35
- * row and, outside ZDR routers, its request and response bodies (default
36
- * `dari-gateway.db`). It holds subscription tokens.
38
+ * saved model lists and router specs, prefix-cache state, and Activity:
39
+ * each request's log row and, outside ZDR routers, its request and response
40
+ * bodies (default `dari-gateway.db`). It holds subscription tokens.
37
41
  * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
38
42
  * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
39
43
  * rotation). Unset, they are stored as they are, and the Dari Link approval
@@ -55,6 +59,8 @@ export async function startSelfHostedGateway(env = process.env) {
55
59
  throw new Error("Set DARI_GATEWAY_KEYS to the comma-separated keys clients authenticate with.");
56
60
  }
57
61
  const config = await loadGatewayConfig(env.DARI_GATEWAY_CONFIG?.trim() || undefined);
62
+ const routersDir = env.DARI_GATEWAY_ROUTERS_DIR?.trim();
63
+ const specFiles = routersDir ? await loadRouterSpecDirectory(routersDir) : undefined;
58
64
  const databasePath = env.DARI_GATEWAY_DB ?? "dari-gateway.db";
59
65
  const created = databasePath !== ":memory:" && !existsSync(databasePath);
60
66
  const db = new Database(databasePath, { create: true });
@@ -69,9 +75,13 @@ export async function startSelfHostedGateway(env = process.env) {
69
75
  const prefixes = new PrefixStore(db);
70
76
  const sessionPins = new SessionPinStore(db);
71
77
  const routerModels = new RouterModelStore(db);
78
+ const routerSpecs = new RouterSpecStore(db, specFiles);
79
+ const routers = { config, routerModels, routerSpecs };
72
80
  const links = new SqliteLinkStore(db, secrets);
73
81
  const activity = new ActivityStore(db);
74
- activity.syncDirectory(SELF_HOSTED_ORGANIZATION_ID, Object.entries(config.routers).map(([id, router]) => ({ id, zdr: router.zdr })), gatewayKeys.length);
82
+ // Activity lists the routers served, so it follows each saved spec.
83
+ const syncActivityRouters = () => activity.syncDirectory(SELF_HOSTED_ORGANIZATION_ID, servedRouterIds(routers).map((id) => ({ id, zdr: servedRouter(routers, id).zdr })), gatewayKeys.length);
84
+ syncActivityRouters();
75
85
  // Pi's provider auth reads each provider's standard key variable, such as
76
86
  // OPENAI_API_KEY, from this environment only.
77
87
  const piModels = builtinModels({
@@ -83,6 +93,7 @@ export async function startSelfHostedGateway(env = process.env) {
83
93
  activity,
84
94
  config,
85
95
  routerModels,
96
+ routerSpecs,
86
97
  gatewayKeys,
87
98
  subscriptions,
88
99
  links,
@@ -95,15 +106,23 @@ export async function startSelfHostedGateway(env = process.env) {
95
106
  });
96
107
  // A model without a credential is dropped at request time, so a missing key
97
108
  // would otherwise surface only as a 424 on the first request.
98
- const routers = Object.entries(config.routers)
99
- .map(([routerId, router]) => [routerId, routerModels.served(routerId, router)]);
100
- for (const [routerId, router] of routers) {
109
+ const warnWithoutCredentials = async (routerId, router) => {
101
110
  const missing = await providersWithoutCredentials({ config, subscriptions, providerApiKey, env }, router);
102
111
  if (missing.length > 0) {
103
112
  console.warn("dari-gateway router has providers without credentials; their models are not served", JSON.stringify({ router: routerId, providers: missing }));
104
113
  }
105
- }
106
- await checkConfiguredProviderKeys(config, routers.map(([, router]) => router), (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
114
+ };
115
+ const served = servedRouterIds(routers).map((routerId) => [routerId, servedRouter(routers, routerId)]);
116
+ for (const [routerId, router] of served)
117
+ await warnWithoutCredentials(routerId, router);
118
+ await checkConfiguredProviderKeys(config, served.map(([, router]) => router), (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
119
+ // A saved or removed spec changes what is served at once.
120
+ const routersChanged = (routerId) => {
121
+ syncActivityRouters();
122
+ const router = servedRouter(routers, routerId);
123
+ if (router !== undefined)
124
+ void warnWithoutCredentials(routerId, router);
125
+ };
107
126
  const selectorBackend = autoRoutingKey
108
127
  ? createAutoRoutingSelectorBackend({
109
128
  apiKey: autoRoutingKey,
@@ -111,14 +130,15 @@ export async function startSelfHostedGateway(env = process.env) {
111
130
  })
112
131
  : createPrioritySelectorBackend();
113
132
  const gateway = createRequestHandler({ platform, selectorBackend });
114
- // Subscriptions and model lists are managed with any gateway key; every
115
- // other path is the gateway's own.
133
+ // Subscriptions, model lists, and router specs are managed with any gateway
134
+ // key; every other path is the gateway's own.
116
135
  const handler = async (request) => {
117
136
  const { pathname } = new URL(request.url);
118
137
  const manages = pathname === SUBSCRIPTION_ROUTES
119
138
  || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
120
139
  || pathname === CANONICAL_MODELS_ROUTE
121
- || ROUTER_MODELS_ROUTE.test(pathname);
140
+ || ROUTER_MODELS_ROUTE.test(pathname)
141
+ || ROUTERS_ROUTE.test(pathname);
122
142
  if (!manages)
123
143
  return await gateway(request);
124
144
  try {
@@ -133,7 +153,8 @@ export async function startSelfHostedGateway(env = process.env) {
133
153
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
134
154
  }
135
155
  return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
136
- ?? (await handleRouterModelsRequest(request, { config, routerModels }))
156
+ ?? (await handleRouterModelsRequest(request, routers))
157
+ ?? (await handleRouterSpecsRequest(request, { ...routers, changed: routersChanged }))
137
158
  ?? errorResponse(new HttpError(404, "Not found", "not_found"));
138
159
  };
139
160
  const port = Number(env.PORT ?? "8080");
@@ -144,9 +165,11 @@ export async function startSelfHostedGateway(env = process.env) {
144
165
  hostname,
145
166
  // The bound port, so PORT=0 reports the port the OS assigned.
146
167
  port: server.port,
147
- routers: Object.keys(config.routers),
168
+ routers: servedRouterIds(routers),
148
169
  // These serve lists saved with `dari gateway models`, not the config file's.
149
170
  saved_model_lists: routerModels.routersWithSavedLists(),
171
+ // These serve router specs saved through the API.
172
+ saved_routers: routerSpecs.savedIds(),
150
173
  auto_routing: autoRoutingKey ? "dari" : "priority",
151
174
  }));
152
175
  return { server, close: () => db.close() };
@@ -156,7 +179,7 @@ export async function startSelfHostedGateway(env = process.env) {
156
179
  * provider rejects fails startup, and one no check could answer is reported.
157
180
  */
158
181
  async function checkConfiguredProviderKeys(config, routers, providerApiKey) {
159
- const providers = new Set(routers.flatMap((router) => allRouterModels(router).map((model) => providerForModel(model.id))));
182
+ const providers = new Set(routers.flatMap((router) => allRouterModels(router).map(modelProvider)));
160
183
  const checks = await Promise.all([...providers].map(async (provider) => {
161
184
  const endpoint = config.providers[provider];
162
185
  // Endpoints configured without a key variable take no key.
@@ -5,9 +5,10 @@ import type { SessionPinStore } from "./session_pin_store.js";
5
5
  import { type SelfHostedResolverDeps } from "./resolve.js";
6
6
  import { type SubscriptionStore } from "./subscriptions/index.js";
7
7
  /**
8
- * The self-hosted platform: routers from the config file, subscriptions,
9
- * Dari Link grants, prefix-cache state, session pins, and Activity in the
10
- * gateway's SQLite database, and one content-free log line per request.
8
+ * The self-hosted platform: routers from the config file and router specs,
9
+ * subscriptions, Dari Link grants, prefix-cache state, session pins, and
10
+ * Activity in the gateway's SQLite database, and one content-free log line
11
+ * per request.
11
12
  */
12
13
  export declare function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "prefixHits"> & {
13
14
  activity: ActivityStore;
@@ -4,12 +4,14 @@ import { errorCode } from "../http/errors.js";
4
4
  import { selfHostedLink } from "../link/self_hosted.js";
5
5
  import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
6
6
  import { SELF_HOSTED_BLOB_BUCKET } from "./activity_store.js";
7
+ import { servedRouter } from "./router_specs.js";
7
8
  import { gatewayKeyIndex, resolveSelfHostedRouter, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
8
9
  import { refreshedAccessToken } from "./subscriptions/access.js";
9
10
  /**
10
- * The self-hosted platform: routers from the config file, subscriptions,
11
- * Dari Link grants, prefix-cache state, session pins, and Activity in the
12
- * gateway's SQLite database, and one content-free log line per request.
11
+ * The self-hosted platform: routers from the config file and router specs,
12
+ * subscriptions, Dari Link grants, prefix-cache state, session pins, and
13
+ * Activity in the gateway's SQLite database, and one content-free log line
14
+ * per request.
13
15
  */
14
16
  export function createSelfHostedPlatform(deps) {
15
17
  const resolver = {
@@ -22,7 +24,7 @@ export function createSelfHostedPlatform(deps) {
22
24
  deps.prefixes.write(write);
23
25
  },
24
26
  writePendingLease: async (write) => {
25
- deps.prefixes.writePendingLease(write, deps.config.routers[write.router_id]?.zdr ?? false);
27
+ deps.prefixes.writePendingLease(write, servedRouter(deps, write.router_id)?.zdr ?? false);
26
28
  },
27
29
  readSessionPin: async (key) => deps.sessionPins.read(key),
28
30
  writeSessionPin: async (write) => {
@@ -4,12 +4,14 @@ import type { ResolvedRouter } from "../types.js";
4
4
  import { type GatewayConfig, type RouterConfig } from "./config.js";
5
5
  import type { SqliteLinkStore } from "../link/sqlite_store.js";
6
6
  import type { RouterModelStore } from "./router_models.js";
7
+ import { type RouterSpecStore } from "./router_specs.js";
7
8
  import { type OAuthFetch, type SubscriptionStore } from "./subscriptions/index.js";
8
9
  export declare const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
9
10
  export declare const SELF_HOSTED_USER_ID = "self-hosted";
10
11
  export type SelfHostedResolverDeps = {
11
12
  config: GatewayConfig;
12
13
  routerModels: RouterModelStore;
14
+ routerSpecs: RouterSpecStore;
13
15
  gatewayKeys: readonly string[];
14
16
  subscriptions: SubscriptionStore;
15
17
  links: SqliteLinkStore;
@@ -3,12 +3,13 @@ import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/da
3
3
  import { HttpError } from "../http/errors.js";
4
4
  import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
5
5
  import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
6
- import { CANONICAL_MODELS } from "../models/canonical.js";
6
+ import { CANONICAL_MODELS, providerModel } from "../models/canonical.js";
7
7
  import { gatewayFor } from "../models/gateways.js";
8
8
  import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
9
9
  import { registeredModelPrice } from "../providers/pi.js";
10
- import { allRouterModels, routerModelsFor, } from "./config.js";
10
+ import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
11
11
  import { linkTokenGrant } from "../link/service.js";
12
+ import { servedRouter } from "./router_specs.js";
12
13
  import { refreshedAccessToken } from "./subscriptions/access.js";
13
14
  import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
14
15
  // A self-hosted gateway is one tenant; these stand in for the hosted
@@ -37,11 +38,10 @@ export async function resolveSelfHostedRouter(deps, request) {
37
38
  if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
38
39
  throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
39
40
  }
40
- const configured = deps.config.routers[request.routerId];
41
- if (configured === undefined) {
41
+ const router = servedRouter(deps, request.routerId);
42
+ if (router === undefined) {
42
43
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
43
44
  }
44
- const router = deps.routerModels.served(request.routerId, configured);
45
45
  const routed = routerModelsFor(router, request.clientHarness);
46
46
  const granted = grant === null
47
47
  ? []
@@ -53,7 +53,7 @@ export async function resolveSelfHostedRouter(deps, request) {
53
53
  const servable = grant === null ? undefined : new Set(grant.credentialIds);
54
54
  const credentials = new Map();
55
55
  const exhausted = new Set();
56
- for (const provider of new Set(listed.map((model) => providerForModel(model.id)))) {
56
+ for (const provider of new Set(listed.map(modelProvider))) {
57
57
  // A grant uses the subscriptions its user chose, whatever the router allows.
58
58
  const subscription = router.subscriptions || grant !== null
59
59
  ? subscriptionProviderFor(provider, request.clientHarness)
@@ -93,7 +93,7 @@ export async function resolveSelfHostedRouter(deps, request) {
93
93
  : providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider), request.clientHarness, now);
94
94
  const models = [];
95
95
  for (const model of listed) {
96
- const credential = credentials.get(providerForModel(model.id));
96
+ const credential = credentials.get(modelProvider(model));
97
97
  if (credential == null)
98
98
  continue;
99
99
  const plan = credential.subscription;
@@ -194,14 +194,27 @@ export async function resolveSelfHostedRouter(deps, request) {
194
194
  resolved.provider_key_sources[provider] = "user";
195
195
  }
196
196
  for (const model of models) {
197
- const price = registeredModelPrice(model.id);
197
+ const provider = modelProvider(model);
198
+ // A model another provider serves runs as that provider's own model.
199
+ const served = model.provider === undefined ? undefined : providerModel(model.id, provider);
200
+ const price = served === undefined
201
+ ? registeredModelPrice(model.id)
202
+ : registeredModelPrice(`${provider}/${served.native_model_id}`);
198
203
  if (price !== null)
199
204
  resolved.model_prices[model.id] = price;
200
- const provider = providerForModel(model.id);
201
205
  const endpoint = deps.config.providers[provider];
202
206
  if (credentials.get(provider)?.subscription?.provider === "openai_codex") {
203
207
  resolved.model_configs[model.id] = codexModelConfig(model.id, price, deps.config.providers["openai-codex"]?.baseUrl);
204
208
  }
209
+ else if (served !== undefined) {
210
+ resolved.model_configs[model.id] = {
211
+ provider,
212
+ native_model_id: served.native_model_id,
213
+ api: endpoint?.api ?? served.api,
214
+ base_url: endpoint?.baseUrl ?? served.base_url,
215
+ cost: price ?? { input: 0, output: 0 },
216
+ };
217
+ }
205
218
  else if (endpoint !== undefined) {
206
219
  resolved.model_configs[model.id] = {
207
220
  provider,
@@ -297,7 +310,7 @@ const SUBSCRIPTION_PLAN_NAMES = {
297
310
  */
298
311
  export async function providersWithoutCredentials(deps, router) {
299
312
  const missing = [];
300
- for (const provider of new Set(allRouterModels(router).map((model) => providerForModel(model.id)))) {
313
+ for (const provider of new Set(allRouterModels(router).map(modelProvider))) {
301
314
  const plans = router.subscriptions
302
315
  ? [subscriptionProviderFor(provider, "claude_code"), subscriptionProviderFor(provider, "muse_code")]
303
316
  : [];
@@ -7,6 +7,7 @@
7
7
  import type { Database } from "bun:sqlite";
8
8
  import type { ClientHarness } from "../types.js";
9
9
  import { type GatewayConfig, type RouterConfig, type RouterModelConfig } from "./config.js";
10
+ import type { RouterSpecStore } from "./router_specs.js";
10
11
  export declare class RouterModelStore {
11
12
  private readonly db;
12
13
  constructor(db: Database);
@@ -32,10 +33,12 @@ export declare const ROUTER_MODELS_ROUTE: RegExp;
32
33
  * - `PUT` and `DELETE /v1/router/models/<agent>` do the same for one coding
33
34
  * agent's list.
34
35
  *
35
- * Each answers with the lists as served after the change. Returns null for
36
- * any other path.
36
+ * Each answers with the lists as served after the change. A router served
37
+ * from a spec has its spec's lists, which change with the spec. Returns null
38
+ * for any other path.
37
39
  */
38
40
  export declare function handleRouterModelsRequest(request: Request, deps: {
39
41
  config: GatewayConfig;
40
42
  routerModels: RouterModelStore;
43
+ routerSpecs: RouterSpecStore;
41
44
  }): Promise<Response | null>;