@mupt-ai/dari-gateway 1.0.302 → 1.0.303

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.
@@ -0,0 +1,120 @@
1
+ import { errorResponse, HttpError } from "../http/errors.js";
2
+ import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
3
+ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
4
+ import { DEFAULT_GATEWAY_CONFIG, parseRouterModels, } from "./config.js";
5
+ // A router's own list is saved under no agent.
6
+ const ROUTER_LIST = "";
7
+ export class RouterModelStore {
8
+ db;
9
+ constructor(db) {
10
+ this.db = db;
11
+ db.run(`CREATE TABLE IF NOT EXISTS router_models (
12
+ router_id TEXT NOT NULL,
13
+ agent TEXT NOT NULL,
14
+ models TEXT NOT NULL,
15
+ PRIMARY KEY (router_id, agent)
16
+ )`);
17
+ }
18
+ /** The router as served: each saved list in place of its config's. */
19
+ served(routerId, router) {
20
+ const rows = this.db
21
+ .query("SELECT agent, models FROM router_models WHERE router_id = ?")
22
+ .all(routerId);
23
+ if (rows.length === 0)
24
+ return router;
25
+ const served = { ...router, agentModels: { ...router.agentModels } };
26
+ for (const row of rows) {
27
+ const models = JSON.parse(row.models);
28
+ if (row.agent === ROUTER_LIST)
29
+ served.models = models;
30
+ else
31
+ served.agentModels[row.agent] = models;
32
+ }
33
+ return served;
34
+ }
35
+ /** The routers with a saved list. */
36
+ routersWithSavedLists() {
37
+ return this.db
38
+ .query("SELECT DISTINCT router_id FROM router_models ORDER BY router_id")
39
+ .all()
40
+ .map((row) => row.router_id);
41
+ }
42
+ /** Whether the router's own list is a saved one. */
43
+ hasRouterList(routerId) {
44
+ return this.db
45
+ .query("SELECT 1 FROM router_models WHERE router_id = ? AND agent = ?")
46
+ .get(routerId, ROUTER_LIST) !== null;
47
+ }
48
+ /** Save the router's own list, or one coding agent's. */
49
+ save(routerId, agent, models) {
50
+ this.db
51
+ .query(`INSERT INTO router_models (router_id, agent, models) VALUES (?, ?, ?)
52
+ ON CONFLICT (router_id, agent) DO UPDATE SET models = excluded.models`)
53
+ .run(routerId, agent ?? ROUTER_LIST, JSON.stringify(models));
54
+ }
55
+ /** Forget a saved list, so the config's is served again. */
56
+ remove(routerId, agent) {
57
+ this.db
58
+ .query("DELETE FROM router_models WHERE router_id = ? AND agent = ?")
59
+ .run(routerId, agent ?? ROUTER_LIST);
60
+ }
61
+ }
62
+ /** `/v1/router/models` for the default router, `/<router>/v1/router/models` for another; a coding agent's list is one segment below. */
63
+ export const ROUTER_MODELS_ROUTE = /^(?:\/([^/]+))?\/v1\/router\/models(?:\/([^/]+))?$/;
64
+ /**
65
+ * Serve a router's model lists. The caller authenticates the gateway key.
66
+ *
67
+ * - `GET /v1/router/models` returns the lists as served.
68
+ * - `PUT /v1/router/models` with `{ "models": [...] }` saves the router's own
69
+ * list, and `DELETE` goes back to the config file's.
70
+ * - `PUT` and `DELETE /v1/router/models/<agent>` do the same for one coding
71
+ * agent's list.
72
+ *
73
+ * Each answers with the lists as served after the change. Returns null for
74
+ * any other path.
75
+ */
76
+ export async function handleRouterModelsRequest(request, deps) {
77
+ const route = ROUTER_MODELS_ROUTE.exec(new URL(request.url).pathname);
78
+ if (route === null)
79
+ return null;
80
+ try {
81
+ const routerId = route[1] ?? DEFAULT_ROUTER_ALIAS;
82
+ const configured = deps.config.routers[routerId];
83
+ if (configured === undefined) {
84
+ throw new HttpError(404, `Router ${routerId} is not configured on this gateway.`, "router_not_found");
85
+ }
86
+ const agent = route[2];
87
+ if (agent !== undefined && !CLIENT_HARNESSES.includes(agent)) {
88
+ throw new HttpError(404, `Unknown coding agent '${agent}'; use ${CLIENT_HARNESSES.join(", ")}.`, "coding_agent_not_found");
89
+ }
90
+ if (request.method === "PUT") {
91
+ deps.routerModels.save(routerId, agent, await requestedModels(request, routerId));
92
+ }
93
+ else if (request.method === "DELETE") {
94
+ deps.routerModels.remove(routerId, agent);
95
+ }
96
+ else if (request.method !== "GET" || agent !== undefined) {
97
+ throw new HttpError(405, "Method not allowed.", "method_not_allowed");
98
+ }
99
+ const served = deps.routerModels.served(routerId, configured);
100
+ return Response.json({
101
+ models: served.models,
102
+ agent_models: served.agentModels,
103
+ // False while the router serves the gateway's built-in default
104
+ // models, which nobody chose.
105
+ chosen: deps.config !== DEFAULT_GATEWAY_CONFIG || deps.routerModels.hasRouterList(routerId),
106
+ }, { headers: { "Cache-Control": "no-store" } });
107
+ }
108
+ catch (error) {
109
+ return errorResponse(error);
110
+ }
111
+ }
112
+ async function requestedModels(request, routerId) {
113
+ const body = await request.json().catch(() => null);
114
+ try {
115
+ return parseRouterModels(routerId, "models", body?.models);
116
+ }
117
+ catch (error) {
118
+ throw new HttpError(400, error instanceof Error ? error.message : String(error), "invalid_request_error", "models");
119
+ }
120
+ }
package/dist/types.d.ts CHANGED
@@ -44,7 +44,7 @@ export type PublicEvalCatalogCard = Omit<RouterEval, "scores"> & {
44
44
  export type ServedDecision = RoutingDecision & {
45
45
  sessionPinned?: boolean;
46
46
  };
47
- export type ClientHarness = "claude_code" | "muse_code";
47
+ export type ClientHarness = "claude_code" | "codex" | "muse_code" | "opencode" | "pi" | "openclaw" | "hermes";
48
48
  export type ResolvedRouterModelConfig = {
49
49
  provider: string;
50
50
  native_model_id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.302",
3
+ "version": "1.0.303",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.302",
54
+ "@mupt-ai/dari-router": "1.0.303",
55
55
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
56
56
  },
57
57
  "devDependencies": {
@@ -9,6 +9,7 @@ import { explicitModelId } from "../protocol/input/router_model.js";
9
9
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
10
10
  import type { SelectorBackend } from "../strategies/routing.js";
11
11
  import { claudeCodeRequestContext } from "./claude_code/request_context.js";
12
+ import { claimedClientHarness } from "./client_harness.js";
12
13
  import {
13
14
  claudeCodeConversationIdentity,
14
15
  } from "../runtime/harness_identity/index.js";
@@ -61,7 +62,7 @@ export async function handleAnthropicMessages(
61
62
  streamBody: anthropicMessagesSseStream,
62
63
  errorResponse: anthropicErrorResponse,
63
64
  selectorBackend,
64
- clientHarness: isClaudeCode ? "claude_code" : undefined,
65
+ clientHarness: isClaudeCode ? "claude_code" : claimedClientHarness(request.headers),
65
66
  harnessConversationIdentity: isClaudeCode
66
67
  ? claudeCodeConversationIdentity(
67
68
  request.headers,
@@ -11,6 +11,8 @@ import {
11
11
  openCodeRequestContext,
12
12
  piRequestContext,
13
13
  } from "../runtime/harness_identity/index.js";
14
+ import type { ClientHarness } from "../types.js";
15
+ import { claimedClientHarness } from "./client_harness.js";
14
16
  import { parseJsonRequest } from "./json.js";
15
17
  import { museCodeClientId } from "./muse_code.js";
16
18
 
@@ -23,8 +25,16 @@ export async function handleChatCompletions(
23
25
  const apiKey = bearerToken(request.headers);
24
26
  const payload = await parseJsonRequest<ChatCompletionRequest>(request);
25
27
  const interaction = chatCompletionsToInteraction({ ...payload, source_protocol: "openai_chat" });
26
- const agentContext = piRequestContext(request.headers) ?? openCodeRequestContext(request.headers);
28
+ const piContext = piRequestContext(request.headers);
29
+ const openCodeContext = openCodeRequestContext(request.headers);
30
+ const agentContext = piContext ?? openCodeContext;
27
31
  const museClientId = museCodeClientId(request.headers);
32
+ // OpenClaw and Hermes send nothing of their own that tells them apart,
33
+ // so the Dari CLI sets them up to name themselves.
34
+ const clientHarness: ClientHarness | undefined = museClientId !== undefined ? "muse_code"
35
+ : piContext !== undefined ? "pi"
36
+ : openCodeContext !== undefined ? "opencode"
37
+ : claimedClientHarness(request.headers);
28
38
  return await handleRoutedCompletion({
29
39
  request,
30
40
  routerId,
@@ -38,7 +48,7 @@ export async function handleChatCompletions(
38
48
  streamBody: chatCompletionsSseStream,
39
49
  errorResponse,
40
50
  selectorBackend,
41
- clientHarness: museClientId === undefined ? undefined : "muse_code",
51
+ clientHarness,
42
52
  harnessConversationIdentity: chatCompletionsConversationIdentity(
43
53
  request.headers,
44
54
  payload.prompt_cache_key,
@@ -0,0 +1,32 @@
1
+ import type { ClientHarness } from "../types.js";
2
+
3
+ const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
4
+
5
+ export const CLIENT_HARNESSES: readonly string[] = [
6
+ "claude_code",
7
+ "codex",
8
+ "muse_code",
9
+ "opencode",
10
+ "pi",
11
+ "openclaw",
12
+ "hermes",
13
+ ] satisfies ClientHarness[];
14
+
15
+ /**
16
+ * The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
17
+ * model list. The header is a claim, not proof.
18
+ */
19
+ export function namedClientHarness(headers: Headers): ClientHarness | undefined {
20
+ const value = headers.get(CLIENT_HARNESS_HEADER)?.trim();
21
+ return value !== undefined && CLIENT_HARNESSES.includes(value) ? (value as ClientHarness) : undefined;
22
+ }
23
+
24
+ /**
25
+ * The coding agent a request with none of an agent's own headers claims to
26
+ * come from. A Claude Code or Muse Code plan serves only that agent, so a
27
+ * claim never names those two.
28
+ */
29
+ export function claimedClientHarness(headers: Headers): ClientHarness | undefined {
30
+ const named = namedClientHarness(headers);
31
+ return named === "claude_code" || named === "muse_code" ? undefined : named;
32
+ }
@@ -5,6 +5,7 @@ import { captureRequestError } from "../observability/errors.js";
5
5
  import { openAIResponsesResponse } from "../protocol/output/openai_responses.js";
6
6
  import { openAIResponsesSseStream } from "../protocol/output/openai_responses_stream.js";
7
7
  import { openAIResponsesToInteraction } from "../protocol/input/openai_responses.js";
8
+ import { claimedClientHarness } from "./client_harness.js";
8
9
  import { parseJsonRequest } from "./json.js";
9
10
  import { museCodeClientId } from "./muse_code.js";
10
11
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
@@ -56,7 +57,10 @@ export async function handleResponses(
56
57
  streamBody: openAIResponsesSseStream,
57
58
  errorResponse,
58
59
  selectorBackend,
59
- clientHarness: museClientId === undefined ? undefined : "muse_code",
60
+ clientHarness: museClientId !== undefined ? "muse_code"
61
+ // Codex describes every request in its turn metadata.
62
+ : agentContext !== undefined ? "codex"
63
+ : claimedClientHarness(request.headers),
60
64
  harnessConversationIdentity,
61
65
  });
62
66
  } catch (error) {
@@ -14,8 +14,8 @@ import { listModelCatalog } from "../models/catalog.js";
14
14
  import { modelSupportsImageInput } from "../providers/model_capabilities.js";
15
15
  import { modelMetadataLookup } from "../providers/pi.js";
16
16
  import { resolveRouter } from "../strategies/routing.js";
17
- import type { ClientHarness } from "../types.js";
18
17
  import { anthropicModelsResponse } from "./anthropic_models.js";
18
+ import { namedClientHarness } from "./client_harness.js";
19
19
  import { codexModelsResponse } from "./codex_models.js";
20
20
 
21
21
  export async function handleModels(request: Request, routerId: string): Promise<Response> {
@@ -29,7 +29,9 @@ export async function handleModels(request: Request, routerId: string): Promise<
29
29
  const apiKey = anthropicClient ? anthropicToken(request.headers) : bearerToken(request.headers);
30
30
  // Resolution authenticates the key and confirms the router exists even
31
31
  // when the response body (Anthropic shape) does not depend on it.
32
- const clientHarness = listedClientHarness(request.headers);
32
+ // A model list is for the agent the Dari CLI names: it changes only what
33
+ // is listed, and each request is still recognized by its own headers.
34
+ const clientHarness = namedClientHarness(request.headers);
33
35
  const router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
34
36
  const query = new URL(request.url).searchParams;
35
37
  if (query.get("detail") === "1") {
@@ -67,14 +69,3 @@ export async function handleModels(request: Request, routerId: string): Promise<
67
69
  return response;
68
70
  }
69
71
  }
70
-
71
- // The Dari CLI names the agent a model list is for, so subscriptions that
72
- // serve only that agent (a Claude Code or Muse Code plan) count toward the
73
- // list as they will for its requests. It changes only what is listed: each
74
- // request is still recognized by its own headers.
75
- const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
76
-
77
- function listedClientHarness(headers: Headers): ClientHarness | undefined {
78
- const value = headers.get(CLIENT_HARNESS_HEADER)?.trim();
79
- return value === "claude_code" || value === "muse_code" ? value : undefined;
80
- }
@@ -4,6 +4,9 @@ import {
4
4
  type ReasoningEffort,
5
5
  } from "@mupt-ai/dari-router/policy-engine";
6
6
 
7
+ import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
8
+ import type { ClientHarness } from "../types.js";
9
+
7
10
  /**
8
11
  * The self-hosted gateway's configuration file (YAML or JSON):
9
12
  *
@@ -14,6 +17,9 @@ import {
14
17
  * - anthropic/claude-sonnet-5-5
15
18
  * - id: openai/gpt-6.1-sol
16
19
  * thinking: [medium, high]
20
+ * agentModels: # optional: a coding agent's own list
21
+ * codex:
22
+ * - openai/gpt-6.1-sol
17
23
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
18
24
  * sessionPinning: false # route each session and subagent once, then keep its model
19
25
  * providers: # optional: OpenAI-compatible or self-run endpoints
@@ -24,7 +30,9 @@ import {
24
30
  *
25
31
  * Secrets never live here: gateway keys come from `DARI_GATEWAY_KEYS`,
26
32
  * provider API keys from each provider's standard environment variable, and
27
- * personal subscriptions from the gateway database.
33
+ * personal subscriptions from the gateway database. Model lists saved through
34
+ * the gateway's API (`dari gateway models`) live in the database too, and are
35
+ * served in place of this file's.
28
36
  */
29
37
  export type GatewayConfig = {
30
38
  routers: Record<string, RouterConfig>;
@@ -44,6 +52,8 @@ export type ProviderEndpointConfig = {
44
52
 
45
53
  export type RouterConfig = {
46
54
  models: RouterModelConfig[];
55
+ // A coding agent's own models, served to it in place of `models`.
56
+ agentModels: Partial<Record<ClientHarness, RouterModelConfig[]>>;
47
57
  retries: number;
48
58
  subscriptions: boolean;
49
59
  sessionPinning: boolean;
@@ -149,18 +159,35 @@ function parseProvider(id: string, raw: unknown): ProviderEndpointConfig {
149
159
  };
150
160
  }
151
161
 
162
+ /** The models a router serves a client: its coding agent's own list, else the router's. */
163
+ export function routerModelsFor(router: RouterConfig, clientHarness?: ClientHarness): RouterModelConfig[] {
164
+ return (clientHarness === undefined ? undefined : router.agentModels[clientHarness]) ?? router.models;
165
+ }
166
+
167
+ /** Every model a router can serve, to any client. */
168
+ export function allRouterModels(router: RouterConfig): RouterModelConfig[] {
169
+ return [router.models, ...Object.values(router.agentModels)].flat();
170
+ }
171
+
152
172
  function parseRouter(id: string, raw: unknown): RouterConfig {
153
- if (!isRecord(raw) || !Array.isArray(raw.models) || raw.models.length === 0) {
154
- throw new Error(`Router "${id}" needs a non-empty \`models\` list.`);
155
- }
156
- const models = raw.models.map((model) => parseModel(id, model));
157
- const seen = new Set<string>();
158
- for (const model of models) {
159
- if (seen.has(model.id)) throw new Error(`Router "${id}" lists ${model.id} twice.`);
160
- seen.add(model.id);
173
+ if (!isRecord(raw)) throw new Error(`Router "${id}" needs a non-empty \`models\` list.`);
174
+ const agentModels: RouterConfig["agentModels"] = {};
175
+ if (raw.agentModels !== undefined) {
176
+ if (!isRecord(raw.agentModels)) {
177
+ throw new Error(`routers.${id}.agentModels must map coding agents to model lists.`);
178
+ }
179
+ for (const [agent, models] of Object.entries(raw.agentModels)) {
180
+ if (!CLIENT_HARNESSES.includes(agent)) {
181
+ throw new Error(
182
+ `Router "${id}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`,
183
+ );
184
+ }
185
+ agentModels[agent as ClientHarness] = parseRouterModels(id, `agentModels.${agent}`, models);
186
+ }
161
187
  }
162
188
  return {
163
- models,
189
+ models: parseRouterModels(id, "models", raw.models),
190
+ agentModels,
164
191
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
165
192
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
166
193
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
@@ -168,6 +195,20 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
168
195
  };
169
196
  }
170
197
 
198
+ /** Read one model list of a router, naming `field` in what it rejects. */
199
+ export function parseRouterModels(routerId: string, field: string, raw: unknown): RouterModelConfig[] {
200
+ if (!Array.isArray(raw) || raw.length === 0) {
201
+ throw new Error(`Router "${routerId}" needs a non-empty \`${field}\` list.`);
202
+ }
203
+ const models = raw.map((model) => parseModel(routerId, model));
204
+ const seen = new Set<string>();
205
+ for (const model of models) {
206
+ if (seen.has(model.id)) throw new Error(`Router "${routerId}" lists ${model.id} twice in \`${field}\`.`);
207
+ seen.add(model.id);
208
+ }
209
+ return models;
210
+ }
211
+
171
212
  function parseModel(routerId: string, raw: unknown): RouterModelConfig {
172
213
  const entry = typeof raw === "string" ? { id: raw } : raw;
173
214
  if (!isRecord(entry) || typeof entry.id !== "string" || !MODEL_ID_PATTERN.test(entry.id)) {
@@ -14,13 +14,16 @@ import { createSelfHostedPlatform } from "./platform.js";
14
14
  import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
15
15
  import { checkProviderKey } from "../providers/key_check.js";
16
16
  import { CANONICAL_MODELS } from "../models/canonical.js";
17
- import { DEFAULT_GATEWAY_CONFIG, loadGatewayConfig, type GatewayConfig } from "./config.js";
17
+ import { allRouterModels, loadGatewayConfig, type GatewayConfig, type RouterConfig } from "./config.js";
18
18
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
19
19
  import { PrefixStore } from "./prefix_store.js";
20
+ import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
20
21
  import { SessionPinStore } from "./session_pin_store.js";
21
22
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
22
23
 
23
24
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
25
+ // The models Dari serves, which the Dari CLI's model picker offers.
26
+ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
24
27
 
25
28
  /**
26
29
  * Start a self-hosted Dari Gateway from environment variables:
@@ -28,8 +31,9 @@ const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
28
31
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
29
32
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
30
33
  * serves when present, and otherwise the default router.
31
- * - `DARI_GATEWAY_DB`: SQLite database for subscriptions and prefix-cache
32
- * state (default `dari-gateway.db`). It holds subscription tokens.
34
+ * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, saved model lists,
35
+ * and prefix-cache state (default `dari-gateway.db`). It holds subscription
36
+ * tokens.
33
37
  * - `DARI_AUTO_ROUTING_API_KEY`: choose among a router's models with Dari
34
38
  * Auto Routing; without it, `dari/routing` serves the first listed model.
35
39
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
@@ -52,6 +56,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
52
56
  const subscriptions = new SubscriptionStore(db);
53
57
  const prefixes = new PrefixStore(db);
54
58
  const sessionPins = new SessionPinStore(db);
59
+ const routerModels = new RouterModelStore(db);
55
60
  // Pi's provider auth reads each provider's standard key variable, such as
56
61
  // OPENAI_API_KEY, from this environment only.
57
62
  const piModels = builtinModels({
@@ -62,6 +67,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
62
67
  const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
63
68
  const platform = createSelfHostedPlatform({
64
69
  config,
70
+ routerModels,
65
71
  gatewayKeys,
66
72
  subscriptions,
67
73
  prefixes,
@@ -73,7 +79,9 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
73
79
  });
74
80
  // A model without a credential is dropped at request time, so a missing key
75
81
  // would otherwise surface only as a 424 on the first request.
76
- for (const [routerId, router] of Object.entries(config.routers)) {
82
+ const routers = Object.entries(config.routers)
83
+ .map(([routerId, router]) => [routerId, routerModels.served(routerId, router)] as const);
84
+ for (const [routerId, router] of routers) {
77
85
  const missing = await providersWithoutCredentials({ config, subscriptions, providerApiKey, env }, router);
78
86
  if (missing.length > 0) {
79
87
  console.warn(
@@ -82,7 +90,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
82
90
  );
83
91
  }
84
92
  }
85
- await checkConfiguredProviderKeys(config, (provider) =>
93
+ await checkConfiguredProviderKeys(config, routers.map(([, router]) => router), (provider) =>
86
94
  configuredProviderApiKey({ config, providerApiKey, env }, provider));
87
95
  const selectorBackend: SelectorBackend = autoRoutingKey
88
96
  ? createAutoRoutingSelectorBackend({
@@ -92,11 +100,15 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
92
100
  : createPrioritySelectorBackend();
93
101
  const gateway = createRequestHandler({ platform, selectorBackend });
94
102
 
103
+ // Subscriptions and model lists are managed with any gateway key; every
104
+ // other path is the gateway's own.
95
105
  const handler = async (request: Request): Promise<Response> => {
96
106
  const { pathname } = new URL(request.url);
97
- if (pathname !== SUBSCRIPTION_ROUTES && !pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)) {
98
- return await gateway(request);
99
- }
107
+ const manages = pathname === SUBSCRIPTION_ROUTES
108
+ || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
109
+ || pathname === CANONICAL_MODELS_ROUTE
110
+ || ROUTER_MODELS_ROUTE.test(pathname);
111
+ if (!manages) return await gateway(request);
100
112
  try {
101
113
  if (gatewayKeyIndex(gatewayKeys, bearerToken(request.headers)) === null) {
102
114
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
@@ -104,7 +116,11 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
104
116
  } catch (error) {
105
117
  return errorResponse(error);
106
118
  }
119
+ if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
120
+ return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
121
+ }
107
122
  return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
123
+ ?? (await handleRouterModelsRequest(request, { config, routerModels }))
108
124
  ?? errorResponse(new HttpError(404, "Not found", "not_found"));
109
125
  };
110
126
 
@@ -119,6 +135,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
119
135
  // The bound port, so PORT=0 reports the port the OS assigned.
120
136
  port: server.port,
121
137
  routers: Object.keys(config.routers),
138
+ // These serve lists saved with `dari gateway models`, not the config file's.
139
+ saved_model_lists: routerModels.routersWithSavedLists(),
122
140
  auto_routing: autoRoutingKey ? "dari" : "priority",
123
141
  }),
124
142
  );
@@ -131,10 +149,11 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
131
149
  */
132
150
  async function checkConfiguredProviderKeys(
133
151
  config: GatewayConfig,
152
+ routers: readonly RouterConfig[],
134
153
  providerApiKey: (provider: string) => Promise<string | undefined>,
135
154
  ): Promise<void> {
136
155
  const providers = new Set(
137
- Object.values(config.routers).flatMap((router) => router.models.map((model) => providerForModel(model.id))),
156
+ routers.flatMap((router) => allRouterModels(router).map((model) => providerForModel(model.id))),
138
157
  );
139
158
  const checks = await Promise.all([...providers].map(async (provider) => {
140
159
  const endpoint = config.providers[provider];
@@ -158,27 +177,6 @@ async function checkConfiguredProviderKeys(
158
177
 
159
178
  /** Run the gateway as a process: the `dari-gateway` bin and compiled binary. */
160
179
  export async function runSelfHostedGateway(): Promise<void> {
161
- // `--print-config` prints the router config the gateway would serve, as
162
- // JSON, and exits; `--print-default-config` prints the built-in default.
163
- // The Dari CLI edits a local gateway's models from them.
164
- if (process.argv.includes("--print-canonical-models")) {
165
- console.log(JSON.stringify(CANONICAL_MODELS));
166
- return;
167
- }
168
- if (process.argv.includes("--print-default-config")) {
169
- console.log(JSON.stringify(DEFAULT_GATEWAY_CONFIG));
170
- return;
171
- }
172
- if (process.argv.includes("--print-config")) {
173
- try {
174
- const config = await loadGatewayConfig(process.env.DARI_GATEWAY_CONFIG?.trim() || undefined);
175
- console.log(JSON.stringify(config));
176
- return;
177
- } catch (error) {
178
- console.error(`dari-gateway: ${error instanceof Error ? error.message : String(error)}`);
179
- process.exit(1);
180
- }
181
- }
182
180
  // Startup errors are configuration mistakes: print the message, not a stack.
183
181
  const started = await startSelfHostedGateway().catch((error: unknown) => {
184
182
  console.error(`dari-gateway: ${error instanceof Error ? error.message : String(error)}`);
@@ -11,7 +11,14 @@ import type { ResolveRouterRequest } from "../platform/platform.js";
11
11
  import { codexModelConfig } from "../models/subscriptions.js";
12
12
  import { registeredModelPrice } from "../providers/pi.js";
13
13
  import type { ProviderKeySource, ResolvedRouter } from "../types.js";
14
- import type { GatewayConfig, RouterConfig } from "./config.js";
14
+ import {
15
+ allRouterModels,
16
+ routerModelsFor,
17
+ type GatewayConfig,
18
+ type RouterConfig,
19
+ type RouterModelConfig,
20
+ } from "./config.js";
21
+ import type { RouterModelStore } from "./router_models.js";
15
22
  import {
16
23
  freshAccessToken,
17
24
  type OAuthFetch,
@@ -27,6 +34,8 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
27
34
 
28
35
  export type SelfHostedResolverDeps = {
29
36
  config: GatewayConfig;
37
+ // Model lists saved through the API, served in place of the config's.
38
+ routerModels: RouterModelStore;
30
39
  gatewayKeys: readonly string[];
31
40
  subscriptions: SubscriptionStore;
32
41
  prefixHits: (args: {
@@ -53,7 +62,8 @@ type ProviderCredential = {
53
62
  * Resolve a configured router for one request. Each provider is served by a
54
63
  * connected personal subscription when the router allows it and one is
55
64
  * available, otherwise by the provider's API key; models whose provider has
56
- * neither are left out.
65
+ * neither are left out. A coding agent with its own model list on the router
66
+ * is served that list.
57
67
  */
58
68
  export async function resolveSelfHostedRouter(
59
69
  deps: SelfHostedResolverDeps,
@@ -63,15 +73,17 @@ export async function resolveSelfHostedRouter(
63
73
  if (keyIndex === null) {
64
74
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
65
75
  }
66
- const router = deps.config.routers[request.routerId];
67
- if (router === undefined) {
76
+ const configured = deps.config.routers[request.routerId];
77
+ if (configured === undefined) {
68
78
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
69
79
  }
80
+ const router = deps.routerModels.served(request.routerId, configured);
70
81
 
82
+ const listed = routerModelsFor(router, request.clientHarness);
71
83
  const now = new Date();
72
84
  const credentials = new Map<string, ProviderCredential | null>();
73
85
  const exhausted = new Set<SubscriptionProvider>();
74
- for (const provider of new Set(router.models.map((model) => providerForModel(model.id)))) {
86
+ for (const provider of new Set(listed.map((model) => providerForModel(model.id)))) {
75
87
  const subscription = router.subscriptions
76
88
  ? subscriptionProviderFor(provider, request.clientHarness)
77
89
  : null;
@@ -97,7 +109,7 @@ export async function resolveSelfHostedRouter(
97
109
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
98
110
  }
99
111
 
100
- const models = router.models.filter((model) => credentials.get(providerForModel(model.id)) != null);
112
+ const models = listed.filter((model) => credentials.get(providerForModel(model.id)) != null);
101
113
  if (models.length === 0) {
102
114
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
103
115
  throw unavailableRouterError(request.routerId, exhausted, missing);
@@ -120,7 +132,7 @@ export async function resolveSelfHostedRouter(
120
132
  routing_strategy: "dari",
121
133
  custom_config: null,
122
134
  evals: [],
123
- model_thinking_levels: thinkingLevels(router),
135
+ model_thinking_levels: thinkingLevels(listed),
124
136
  model_prices: {},
125
137
  model_configs: {},
126
138
  prefix_hits: deps.prefixHits({
@@ -204,9 +216,9 @@ function servingProviders(provider: string, credential: ProviderCredential): str
204
216
  : [provider];
205
217
  }
206
218
 
207
- function thinkingLevels(router: RouterConfig): Record<string, ReasoningEffort[]> {
219
+ function thinkingLevels(models: readonly RouterModelConfig[]): Record<string, ReasoningEffort[]> {
208
220
  return Object.fromEntries(
209
- router.models.flatMap((model) => model.thinking ? [[model.id, model.thinking]] : []),
221
+ models.flatMap((model) => model.thinking ? [[model.id, model.thinking]] : []),
210
222
  );
211
223
  }
212
224
 
@@ -227,7 +239,7 @@ export async function providersWithoutCredentials(
227
239
  router: RouterConfig,
228
240
  ): Promise<string[]> {
229
241
  const missing: string[] = [];
230
- for (const provider of new Set(router.models.map((model) => providerForModel(model.id)))) {
242
+ for (const provider of new Set(allRouterModels(router).map((model) => providerForModel(model.id)))) {
231
243
  const plans = router.subscriptions
232
244
  ? [subscriptionProviderFor(provider, "claude_code"), subscriptionProviderFor(provider, "muse_code")]
233
245
  : [];