@mupt-ai/dari-gateway 1.0.301 → 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.
package/README.md CHANGED
@@ -63,7 +63,7 @@ docker run -p 8080:8080 \
63
63
  | --- | --- |
64
64
  | `DARI_GATEWAY_KEYS` | Required. Comma-separated bearer keys clients authenticate with. |
65
65
  | `DARI_GATEWAY_CONFIG` | Router config file. Default `dari-gateway.yaml`. |
66
- | `DARI_GATEWAY_DB` | SQLite database for subscriptions and conversation state. Default `dari-gateway.db`. It stores subscription tokens in plaintext; protect it like a secret. |
66
+ | `DARI_GATEWAY_DB` | SQLite database for subscriptions, model lists saved with `dari gateway models`, and conversation state. Default `dari-gateway.db`. It stores subscription tokens in plaintext; protect it like a secret. |
67
67
  | `DARI_AUTO_ROUTING_API_KEY` | Optional. Select among a router's models with Dari Auto Routing. |
68
68
  | `PORT` | Listen port. Default `8080`. |
69
69
  | `DARI_GATEWAY_HOST` | Listen address. Default `127.0.0.1`, so only this machine can connect. The container image sets `0.0.0.0`; set it yourself to expose a process on your network. |
@@ -78,6 +78,8 @@ routers:
78
78
  - anthropic/claude-sonnet-5-5
79
79
  - id: openai/gpt-6.1-sol
80
80
  thinking: [medium, high]
81
+ agentModels: # optional: a coding agent's own list, in place of `models`
82
+ codex: [openai/gpt-6.1-sol, openai/gpt-6.1-terra]
81
83
  subscriptions: true # prefer connected subscriptions over API keys
82
84
  sessionPinning: false # route each session and subagent once, then keep its model
83
85
  local: # serves /local/v1/...
@@ -89,7 +91,9 @@ providers: # endpoints outside the built-in catalog
89
91
  apiKeyEnv: LOCAL_API_KEY
90
92
  ```
91
93
 
92
- Model ids are `provider/model`. Clients send `model: "dari/routing"` to let the router choose, or `model: "dari/model/<id>"` to pin one of its models. A Claude Code subscription serves Anthropic models only for Claude Code itself; a ChatGPT subscription serves OpenAI models for every client.
94
+ Model ids are `provider/model`. Clients send `model: "dari/routing"` to let the router choose, or `model: "dari/model/<id>"` to pin one of its models. A Claude Code subscription serves Anthropic models only for Claude Code itself; a ChatGPT subscription serves OpenAI models for every client. Each coding agent is offered the router's models that a credential can serve it, or its own `agentModels` list (`claude_code`, `codex`, `muse_code`, `opencode`, `pi`, `openclaw`, `hermes`) when the router has one.
95
+
96
+ `dari gateway models` changes either list on a running gateway, with any gateway key: `dari gateway models --agent codex openai/gpt-6.1-sol`, or no models for the picker. It calls `PUT` and `DELETE /v1/router/models[/<agent>]` (`GET /v1/router/models` reads them). The gateway saves the list in its database and serves it at once in place of the config file's, until `--reset` removes it.
93
97
 
94
98
  ### Model catalog
95
99
 
@@ -9,6 +9,12 @@ routers:
9
9
  - anthropic/claude-sonnet-5-5
10
10
  - id: openai/gpt-6.1-sol
11
11
  thinking: [medium, high]
12
+ # A coding agent's own list, served to it in place of `models`. Agents
13
+ # are claude_code, codex, muse_code, opencode, pi, openclaw, and hermes.
14
+ # agentModels:
15
+ # codex:
16
+ # - openai/gpt-6.1-sol
17
+ # - openai/gpt-6.1-terra
12
18
  # Serve with connected Claude Code / ChatGPT subscriptions before API
13
19
  # keys (default true).
14
20
  subscriptions: true
@@ -8,6 +8,7 @@ import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_mess
8
8
  import { explicitModelId } from "../protocol/input/router_model.js";
9
9
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
10
10
  import { claudeCodeRequestContext } from "./claude_code/request_context.js";
11
+ import { claimedClientHarness } from "./client_harness.js";
11
12
  import { claudeCodeConversationIdentity, } from "../runtime/harness_identity/index.js";
12
13
  import { parseJsonRequest } from "./json.js";
13
14
  const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
@@ -43,7 +44,7 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
43
44
  streamBody: anthropicMessagesSseStream,
44
45
  errorResponse: anthropicErrorResponse,
45
46
  selectorBackend,
46
- clientHarness: isClaudeCode ? "claude_code" : undefined,
47
+ clientHarness: isClaudeCode ? "claude_code" : claimedClientHarness(request.headers),
47
48
  harnessConversationIdentity: isClaudeCode
48
49
  ? claudeCodeConversationIdentity(request.headers, payload.promptCacheKey)
49
50
  : undefined,
@@ -5,6 +5,7 @@ import { chatCompletionResponse, chatCompletionsSseStream } from "../protocol/ou
5
5
  import { chatCompletionsToInteraction } from "../protocol/input/chat_completions.js";
6
6
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
7
7
  import { chatCompletionsConversationIdentity, openCodeRequestContext, piRequestContext, } from "../runtime/harness_identity/index.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
  export async function handleChatCompletions(request, routerId, selectorBackend) {
@@ -12,8 +13,16 @@ export async function handleChatCompletions(request, routerId, selectorBackend)
12
13
  const apiKey = bearerToken(request.headers);
13
14
  const payload = await parseJsonRequest(request);
14
15
  const interaction = chatCompletionsToInteraction({ ...payload, source_protocol: "openai_chat" });
15
- const agentContext = piRequestContext(request.headers) ?? openCodeRequestContext(request.headers);
16
+ const piContext = piRequestContext(request.headers);
17
+ const openCodeContext = openCodeRequestContext(request.headers);
18
+ const agentContext = piContext ?? openCodeContext;
16
19
  const museClientId = museCodeClientId(request.headers);
20
+ // OpenClaw and Hermes send nothing of their own that tells them apart,
21
+ // so the Dari CLI sets them up to name themselves.
22
+ const clientHarness = museClientId !== undefined ? "muse_code"
23
+ : piContext !== undefined ? "pi"
24
+ : openCodeContext !== undefined ? "opencode"
25
+ : claimedClientHarness(request.headers);
17
26
  return await handleRoutedCompletion({
18
27
  request,
19
28
  routerId,
@@ -27,7 +36,7 @@ export async function handleChatCompletions(request, routerId, selectorBackend)
27
36
  streamBody: chatCompletionsSseStream,
28
37
  errorResponse,
29
38
  selectorBackend,
30
- clientHarness: museClientId === undefined ? undefined : "muse_code",
39
+ clientHarness,
31
40
  harnessConversationIdentity: chatCompletionsConversationIdentity(request.headers, payload.prompt_cache_key),
32
41
  });
33
42
  }
@@ -0,0 +1,13 @@
1
+ import type { ClientHarness } from "../types.js";
2
+ export declare const CLIENT_HARNESSES: readonly string[];
3
+ /**
4
+ * The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
5
+ * model list. The header is a claim, not proof.
6
+ */
7
+ export declare function namedClientHarness(headers: Headers): ClientHarness | undefined;
8
+ /**
9
+ * The coding agent a request with none of an agent's own headers claims to
10
+ * come from. A Claude Code or Muse Code plan serves only that agent, so a
11
+ * claim never names those two.
12
+ */
13
+ export declare function claimedClientHarness(headers: Headers): ClientHarness | undefined;
@@ -0,0 +1,27 @@
1
+ const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
2
+ export const CLIENT_HARNESSES = [
3
+ "claude_code",
4
+ "codex",
5
+ "muse_code",
6
+ "opencode",
7
+ "pi",
8
+ "openclaw",
9
+ "hermes",
10
+ ];
11
+ /**
12
+ * The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
13
+ * model list. The header is a claim, not proof.
14
+ */
15
+ export function namedClientHarness(headers) {
16
+ const value = headers.get(CLIENT_HARNESS_HEADER)?.trim();
17
+ return value !== undefined && CLIENT_HARNESSES.includes(value) ? value : undefined;
18
+ }
19
+ /**
20
+ * The coding agent a request with none of an agent's own headers claims to
21
+ * come from. A Claude Code or Muse Code plan serves only that agent, so a
22
+ * claim never names those two.
23
+ */
24
+ export function claimedClientHarness(headers) {
25
+ const named = namedClientHarness(headers);
26
+ return named === "claude_code" || named === "muse_code" ? undefined : named;
27
+ }
@@ -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";
@@ -45,7 +46,10 @@ export async function handleResponses(request, routerId, selectorBackend) {
45
46
  streamBody: openAIResponsesSseStream,
46
47
  errorResponse,
47
48
  selectorBackend,
48
- clientHarness: museClientId === undefined ? undefined : "muse_code",
49
+ clientHarness: museClientId !== undefined ? "muse_code"
50
+ // Codex describes every request in its turn metadata.
51
+ : agentContext !== undefined ? "codex"
52
+ : claimedClientHarness(request.headers),
49
53
  harnessConversationIdentity,
50
54
  });
51
55
  }
@@ -14,6 +14,7 @@ import { modelSupportsImageInput } from "../providers/model_capabilities.js";
14
14
  import { modelMetadataLookup } from "../providers/pi.js";
15
15
  import { resolveRouter } from "../strategies/routing.js";
16
16
  import { anthropicModelsResponse } from "./anthropic_models.js";
17
+ import { namedClientHarness } from "./client_harness.js";
17
18
  import { codexModelsResponse } from "./codex_models.js";
18
19
  export async function handleModels(request, routerId) {
19
20
  // Anthropic SDK clients always send anthropic-version, and API-key probes
@@ -25,7 +26,9 @@ export async function handleModels(request, routerId) {
25
26
  const apiKey = anthropicClient ? anthropicToken(request.headers) : bearerToken(request.headers);
26
27
  // Resolution authenticates the key and confirms the router exists even
27
28
  // when the response body (Anthropic shape) does not depend on it.
28
- const clientHarness = listedClientHarness(request.headers);
29
+ // A model list is for the agent the Dari CLI names: it changes only what
30
+ // is listed, and each request is still recognized by its own headers.
31
+ const clientHarness = namedClientHarness(request.headers);
29
32
  const router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
30
33
  const query = new URL(request.url).searchParams;
31
34
  if (query.get("detail") === "1") {
@@ -64,12 +67,3 @@ export async function handleModels(request, routerId) {
64
67
  return response;
65
68
  }
66
69
  }
67
- // The Dari CLI names the agent a model list is for, so subscriptions that
68
- // serve only that agent (a Claude Code or Muse Code plan) count toward the
69
- // list as they will for its requests. It changes only what is listed: each
70
- // request is still recognized by its own headers.
71
- const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
72
- function listedClientHarness(headers) {
73
- const value = headers.get(CLIENT_HARNESS_HEADER)?.trim();
74
- return value === "claude_code" || value === "muse_code" ? value : undefined;
75
- }
@@ -197,7 +197,7 @@ export function buildModel(pi, modelId, pricing, config) {
197
197
  throw new HttpError(502, `No base URL is configured for provider ${provider}.`, "provider_configuration_error");
198
198
  }
199
199
  const contextWindow = contextWindowForModel(modelId, registered, config) ?? 128000;
200
- const compat = responsesToolContract(api, runtimeCompat(provider, registered, modelId));
200
+ const compat = gatewayRuntimeCompat(api, runtimeCompat(provider, registered, modelId));
201
201
  return {
202
202
  ...(registered ?? {}),
203
203
  ...(compat !== undefined ? { compat } : {}),
@@ -273,7 +273,13 @@ function contextWindowForModel(modelId, registered, config) {
273
273
  // `tools` field, when a model supports mid-conversation system messages. The gateway
274
274
  // keeps tools at the request level until that native tool-change path is validated.
275
275
  const RESPONSES_APIS = new Set(["openai-responses", "azure-openai-responses", "openai-codex-responses"]);
276
- function responsesToolContract(api, compat) {
276
+ function gatewayRuntimeCompat(api, compat) {
277
+ // Pi 1.5 enables server-side message threads whenever sessionId is set.
278
+ // Gateway sessions serve affinity, not permission to retain a conversation
279
+ // remotely; keep full-history requests, including on ZDR routes.
280
+ if (api === "anthropic-messages") {
281
+ return { ...(isRecord(compat) ? compat : {}), supportsMessageThreads: false };
282
+ }
277
283
  if (typeof api !== "string" || !RESPONSES_APIS.has(api))
278
284
  return compat;
279
285
  if (!isRecord(compat) || compat.supportsMidConvoSystemMessages !== true)
@@ -1,4 +1,5 @@
1
1
  import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
+ import type { ClientHarness } from "../types.js";
2
3
  /**
3
4
  * The self-hosted gateway's configuration file (YAML or JSON):
4
5
  *
@@ -9,6 +10,9 @@ import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
9
10
  * - anthropic/claude-sonnet-5-5
10
11
  * - id: openai/gpt-6.1-sol
11
12
  * thinking: [medium, high]
13
+ * agentModels: # optional: a coding agent's own list
14
+ * codex:
15
+ * - openai/gpt-6.1-sol
12
16
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
13
17
  * sessionPinning: false # route each session and subagent once, then keep its model
14
18
  * providers: # optional: OpenAI-compatible or self-run endpoints
@@ -19,7 +23,9 @@ import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
19
23
  *
20
24
  * Secrets never live here: gateway keys come from `DARI_GATEWAY_KEYS`,
21
25
  * provider API keys from each provider's standard environment variable, and
22
- * personal subscriptions from the gateway database.
26
+ * personal subscriptions from the gateway database. Model lists saved through
27
+ * the gateway's API (`dari gateway models`) live in the database too, and are
28
+ * served in place of this file's.
23
29
  */
24
30
  export type GatewayConfig = {
25
31
  routers: Record<string, RouterConfig>;
@@ -32,6 +38,7 @@ export type ProviderEndpointConfig = {
32
38
  };
33
39
  export type RouterConfig = {
34
40
  models: RouterModelConfig[];
41
+ agentModels: Partial<Record<ClientHarness, RouterModelConfig[]>>;
35
42
  retries: number;
36
43
  subscriptions: boolean;
37
44
  sessionPinning: boolean;
@@ -49,3 +56,9 @@ export declare const DEFAULT_GATEWAY_CONFIG: GatewayConfig;
49
56
  */
50
57
  export declare function loadGatewayConfig(path: string | undefined): Promise<GatewayConfig>;
51
58
  export declare function parseGatewayConfig(raw: unknown): GatewayConfig;
59
+ /** The models a router serves a client: its coding agent's own list, else the router's. */
60
+ export declare function routerModelsFor(router: RouterConfig, clientHarness?: ClientHarness): RouterModelConfig[];
61
+ /** Every model a router can serve, to any client. */
62
+ export declare function allRouterModels(router: RouterConfig): RouterModelConfig[];
63
+ /** Read one model list of a router, naming `field` in what it rejects. */
64
+ export declare function parseRouterModels(routerId: string, field: string, raw: unknown): RouterModelConfig[];
@@ -1,4 +1,5 @@
1
1
  import { isReasoningEffort, isRecord, } from "@mupt-ai/dari-router/policy-engine";
2
+ import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
2
3
  const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
3
4
  const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*$/;
4
5
  const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
@@ -84,25 +85,52 @@ function parseProvider(id, raw) {
84
85
  ...(typeof raw.apiKeyEnv === "string" ? { apiKeyEnv: raw.apiKeyEnv.trim() } : {}),
85
86
  };
86
87
  }
88
+ /** The models a router serves a client: its coding agent's own list, else the router's. */
89
+ export function routerModelsFor(router, clientHarness) {
90
+ return (clientHarness === undefined ? undefined : router.agentModels[clientHarness]) ?? router.models;
91
+ }
92
+ /** Every model a router can serve, to any client. */
93
+ export function allRouterModels(router) {
94
+ return [router.models, ...Object.values(router.agentModels)].flat();
95
+ }
87
96
  function parseRouter(id, raw) {
88
- if (!isRecord(raw) || !Array.isArray(raw.models) || raw.models.length === 0) {
97
+ if (!isRecord(raw))
89
98
  throw new Error(`Router "${id}" needs a non-empty \`models\` list.`);
90
- }
91
- const models = raw.models.map((model) => parseModel(id, model));
92
- const seen = new Set();
93
- for (const model of models) {
94
- if (seen.has(model.id))
95
- throw new Error(`Router "${id}" lists ${model.id} twice.`);
96
- seen.add(model.id);
99
+ const agentModels = {};
100
+ if (raw.agentModels !== undefined) {
101
+ if (!isRecord(raw.agentModels)) {
102
+ throw new Error(`routers.${id}.agentModels must map coding agents to model lists.`);
103
+ }
104
+ for (const [agent, models] of Object.entries(raw.agentModels)) {
105
+ if (!CLIENT_HARNESSES.includes(agent)) {
106
+ throw new Error(`Router "${id}" has models for an unknown coding agent "${agent}"; use ${CLIENT_HARNESSES.join(", ")}.`);
107
+ }
108
+ agentModels[agent] = parseRouterModels(id, `agentModels.${agent}`, models);
109
+ }
97
110
  }
98
111
  return {
99
- models,
112
+ models: parseRouterModels(id, "models", raw.models),
113
+ agentModels,
100
114
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
101
115
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
102
116
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
103
117
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
104
118
  };
105
119
  }
120
+ /** Read one model list of a router, naming `field` in what it rejects. */
121
+ export function parseRouterModels(routerId, field, raw) {
122
+ if (!Array.isArray(raw) || raw.length === 0) {
123
+ throw new Error(`Router "${routerId}" needs a non-empty \`${field}\` list.`);
124
+ }
125
+ const models = raw.map((model) => parseModel(routerId, model));
126
+ const seen = new Set();
127
+ for (const model of models) {
128
+ if (seen.has(model.id))
129
+ throw new Error(`Router "${routerId}" lists ${model.id} twice in \`${field}\`.`);
130
+ seen.add(model.id);
131
+ }
132
+ return models;
133
+ }
106
134
  function parseModel(routerId, raw) {
107
135
  const entry = typeof raw === "string" ? { id: raw } : raw;
108
136
  if (!isRecord(entry) || typeof entry.id !== "string" || !MODEL_ID_PATTERN.test(entry.id)) {
@@ -5,8 +5,9 @@
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_DB`: SQLite database for subscriptions and prefix-cache
9
- * state (default `dari-gateway.db`). It holds subscription tokens.
8
+ * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, saved model lists,
9
+ * and prefix-cache state (default `dari-gateway.db`). It holds subscription
10
+ * tokens.
10
11
  * - `DARI_AUTO_ROUTING_API_KEY`: choose among a router's models with Dari
11
12
  * Auto Routing; without it, `dari/routing` serves the first listed model.
12
13
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
@@ -12,20 +12,24 @@ import { createSelfHostedPlatform } from "./platform.js";
12
12
  import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
13
13
  import { checkProviderKey } from "../providers/key_check.js";
14
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
15
- import { DEFAULT_GATEWAY_CONFIG, loadGatewayConfig } from "./config.js";
15
+ import { allRouterModels, loadGatewayConfig } from "./config.js";
16
16
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
17
17
  import { PrefixStore } from "./prefix_store.js";
18
+ import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
18
19
  import { SessionPinStore } from "./session_pin_store.js";
19
20
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
20
21
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
22
+ // The models Dari serves, which the Dari CLI's model picker offers.
23
+ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
21
24
  /**
22
25
  * Start a self-hosted Dari Gateway from environment variables:
23
26
  *
24
27
  * - `DARI_GATEWAY_KEYS` (required): comma-separated bearer keys clients use.
25
28
  * - `DARI_GATEWAY_CONFIG`: router config file. Unset, `dari-gateway.yaml`
26
29
  * serves when present, and otherwise the default router.
27
- * - `DARI_GATEWAY_DB`: SQLite database for subscriptions and prefix-cache
28
- * state (default `dari-gateway.db`). It holds subscription tokens.
30
+ * - `DARI_GATEWAY_DB`: SQLite database for subscriptions, saved model lists,
31
+ * and prefix-cache state (default `dari-gateway.db`). It holds subscription
32
+ * tokens.
29
33
  * - `DARI_AUTO_ROUTING_API_KEY`: choose among a router's models with Dari
30
34
  * Auto Routing; without it, `dari/routing` serves the first listed model.
31
35
  * - `PORT` (default 8080), `DARI_GATEWAY_HOST` (default 127.0.0.1; the container
@@ -49,6 +53,7 @@ export async function startSelfHostedGateway(env = process.env) {
49
53
  const subscriptions = new SubscriptionStore(db);
50
54
  const prefixes = new PrefixStore(db);
51
55
  const sessionPins = new SessionPinStore(db);
56
+ const routerModels = new RouterModelStore(db);
52
57
  // Pi's provider auth reads each provider's standard key variable, such as
53
58
  // OPENAI_API_KEY, from this environment only.
54
59
  const piModels = builtinModels({
@@ -58,6 +63,7 @@ export async function startSelfHostedGateway(env = process.env) {
58
63
  const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
59
64
  const platform = createSelfHostedPlatform({
60
65
  config,
66
+ routerModels,
61
67
  gatewayKeys,
62
68
  subscriptions,
63
69
  prefixes,
@@ -69,13 +75,15 @@ export async function startSelfHostedGateway(env = process.env) {
69
75
  });
70
76
  // A model without a credential is dropped at request time, so a missing key
71
77
  // would otherwise surface only as a 424 on the first request.
72
- for (const [routerId, router] of Object.entries(config.routers)) {
78
+ const routers = Object.entries(config.routers)
79
+ .map(([routerId, router]) => [routerId, routerModels.served(routerId, router)]);
80
+ for (const [routerId, router] of routers) {
73
81
  const missing = await providersWithoutCredentials({ config, subscriptions, providerApiKey, env }, router);
74
82
  if (missing.length > 0) {
75
83
  console.warn("dari-gateway router has providers without credentials; their models are not served", JSON.stringify({ router: routerId, providers: missing }));
76
84
  }
77
85
  }
78
- await checkConfiguredProviderKeys(config, (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
86
+ await checkConfiguredProviderKeys(config, routers.map(([, router]) => router), (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
79
87
  const selectorBackend = autoRoutingKey
80
88
  ? createAutoRoutingSelectorBackend({
81
89
  apiKey: autoRoutingKey,
@@ -83,11 +91,16 @@ export async function startSelfHostedGateway(env = process.env) {
83
91
  })
84
92
  : createPrioritySelectorBackend();
85
93
  const gateway = createRequestHandler({ platform, selectorBackend });
94
+ // Subscriptions and model lists are managed with any gateway key; every
95
+ // other path is the gateway's own.
86
96
  const handler = async (request) => {
87
97
  const { pathname } = new URL(request.url);
88
- if (pathname !== SUBSCRIPTION_ROUTES && !pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)) {
98
+ const manages = pathname === SUBSCRIPTION_ROUTES
99
+ || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
100
+ || pathname === CANONICAL_MODELS_ROUTE
101
+ || ROUTER_MODELS_ROUTE.test(pathname);
102
+ if (!manages)
89
103
  return await gateway(request);
90
- }
91
104
  try {
92
105
  if (gatewayKeyIndex(gatewayKeys, bearerToken(request.headers)) === null) {
93
106
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
@@ -96,7 +109,11 @@ export async function startSelfHostedGateway(env = process.env) {
96
109
  catch (error) {
97
110
  return errorResponse(error);
98
111
  }
112
+ if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
113
+ return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
114
+ }
99
115
  return (await handleSubscriptionRequest(request, { store: subscriptions, fetch }))
116
+ ?? (await handleRouterModelsRequest(request, { config, routerModels }))
100
117
  ?? errorResponse(new HttpError(404, "Not found", "not_found"));
101
118
  };
102
119
  const port = Number(env.PORT ?? "8080");
@@ -108,6 +125,8 @@ export async function startSelfHostedGateway(env = process.env) {
108
125
  // The bound port, so PORT=0 reports the port the OS assigned.
109
126
  port: server.port,
110
127
  routers: Object.keys(config.routers),
128
+ // These serve lists saved with `dari gateway models`, not the config file's.
129
+ saved_model_lists: routerModels.routersWithSavedLists(),
111
130
  auto_routing: autoRoutingKey ? "dari" : "priority",
112
131
  }));
113
132
  return { server, close: () => db.close() };
@@ -116,8 +135,8 @@ export async function startSelfHostedGateway(env = process.env) {
116
135
  * Check each provider API key the routers use before serving: a key its
117
136
  * provider rejects fails startup, and one no check could answer is reported.
118
137
  */
119
- async function checkConfiguredProviderKeys(config, providerApiKey) {
120
- const providers = new Set(Object.values(config.routers).flatMap((router) => router.models.map((model) => providerForModel(model.id))));
138
+ async function checkConfiguredProviderKeys(config, routers, providerApiKey) {
139
+ const providers = new Set(routers.flatMap((router) => allRouterModels(router).map((model) => providerForModel(model.id))));
121
140
  const checks = await Promise.all([...providers].map(async (provider) => {
122
141
  const endpoint = config.providers[provider];
123
142
  // Endpoints configured without a key variable take no key.
@@ -139,28 +158,6 @@ async function checkConfiguredProviderKeys(config, providerApiKey) {
139
158
  }
140
159
  /** Run the gateway as a process: the `dari-gateway` bin and compiled binary. */
141
160
  export async function runSelfHostedGateway() {
142
- // `--print-config` prints the router config the gateway would serve, as
143
- // JSON, and exits; `--print-default-config` prints the built-in default.
144
- // The Dari CLI edits a local gateway's models from them.
145
- if (process.argv.includes("--print-canonical-models")) {
146
- console.log(JSON.stringify(CANONICAL_MODELS));
147
- return;
148
- }
149
- if (process.argv.includes("--print-default-config")) {
150
- console.log(JSON.stringify(DEFAULT_GATEWAY_CONFIG));
151
- return;
152
- }
153
- if (process.argv.includes("--print-config")) {
154
- try {
155
- const config = await loadGatewayConfig(process.env.DARI_GATEWAY_CONFIG?.trim() || undefined);
156
- console.log(JSON.stringify(config));
157
- return;
158
- }
159
- catch (error) {
160
- console.error(`dari-gateway: ${error instanceof Error ? error.message : String(error)}`);
161
- process.exit(1);
162
- }
163
- }
164
161
  // Startup errors are configuration mistakes: print the message, not a stack.
165
162
  const started = await startSelfHostedGateway().catch((error) => {
166
163
  console.error(`dari-gateway: ${error instanceof Error ? error.message : String(error)}`);
@@ -1,12 +1,14 @@
1
1
  import { type RouterPrefixHit } from "@mupt-ai/dari-router/policy-engine";
2
2
  import type { ResolveRouterRequest } from "../platform/platform.js";
3
3
  import type { ResolvedRouter } from "../types.js";
4
- import type { GatewayConfig, RouterConfig } from "./config.js";
4
+ import { type GatewayConfig, type RouterConfig } from "./config.js";
5
+ import type { RouterModelStore } from "./router_models.js";
5
6
  import { type OAuthFetch, type SubscriptionStore } from "./subscriptions/index.js";
6
7
  export declare const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
7
8
  export declare const SELF_HOSTED_USER_ID = "self-hosted";
8
9
  export type SelfHostedResolverDeps = {
9
10
  config: GatewayConfig;
11
+ routerModels: RouterModelStore;
10
12
  gatewayKeys: readonly string[];
11
13
  subscriptions: SubscriptionStore;
12
14
  prefixHits: (args: {
@@ -23,7 +25,8 @@ export type SelfHostedResolverDeps = {
23
25
  * Resolve a configured router for one request. Each provider is served by a
24
26
  * connected personal subscription when the router allows it and one is
25
27
  * available, otherwise by the provider's API key; models whose provider has
26
- * neither are left out.
28
+ * neither are left out. A coding agent with its own model list on the router
29
+ * is served that list.
27
30
  */
28
31
  export declare function resolveSelfHostedRouter(deps: SelfHostedResolverDeps, request: ResolveRouterRequest): Promise<ResolvedRouter>;
29
32
  export declare function configuredProviderApiKey(deps: Pick<SelfHostedResolverDeps, "config" | "providerApiKey" | "env">, provider: string): Promise<string | undefined>;
@@ -3,6 +3,7 @@ import { nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-en
3
3
  import { HttpError } from "../http/errors.js";
4
4
  import { codexModelConfig } from "../models/subscriptions.js";
5
5
  import { registeredModelPrice } from "../providers/pi.js";
6
+ import { allRouterModels, routerModelsFor, } from "./config.js";
6
7
  import { freshAccessToken, } from "./subscriptions/index.js";
7
8
  // A self-hosted gateway is one tenant; these stand in for the hosted
8
9
  // organization and the user a personal subscription belongs to.
@@ -12,21 +13,24 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
12
13
  * Resolve a configured router for one request. Each provider is served by a
13
14
  * connected personal subscription when the router allows it and one is
14
15
  * available, otherwise by the provider's API key; models whose provider has
15
- * neither are left out.
16
+ * neither are left out. A coding agent with its own model list on the router
17
+ * is served that list.
16
18
  */
17
19
  export async function resolveSelfHostedRouter(deps, request) {
18
20
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
19
21
  if (keyIndex === null) {
20
22
  throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
21
23
  }
22
- const router = deps.config.routers[request.routerId];
23
- if (router === undefined) {
24
+ const configured = deps.config.routers[request.routerId];
25
+ if (configured === undefined) {
24
26
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
25
27
  }
28
+ const router = deps.routerModels.served(request.routerId, configured);
29
+ const listed = routerModelsFor(router, request.clientHarness);
26
30
  const now = new Date();
27
31
  const credentials = new Map();
28
32
  const exhausted = new Set();
29
- for (const provider of new Set(router.models.map((model) => providerForModel(model.id)))) {
33
+ for (const provider of new Set(listed.map((model) => providerForModel(model.id)))) {
30
34
  const subscription = router.subscriptions
31
35
  ? subscriptionProviderFor(provider, request.clientHarness)
32
36
  : null;
@@ -51,7 +55,7 @@ export async function resolveSelfHostedRouter(deps, request) {
51
55
  const apiKey = await configuredProviderApiKey(deps, provider);
52
56
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
53
57
  }
54
- const models = router.models.filter((model) => credentials.get(providerForModel(model.id)) != null);
58
+ const models = listed.filter((model) => credentials.get(providerForModel(model.id)) != null);
55
59
  if (models.length === 0) {
56
60
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
57
61
  throw unavailableRouterError(request.routerId, exhausted, missing);
@@ -73,7 +77,7 @@ export async function resolveSelfHostedRouter(deps, request) {
73
77
  routing_strategy: "dari",
74
78
  custom_config: null,
75
79
  evals: [],
76
- model_thinking_levels: thinkingLevels(router),
80
+ model_thinking_levels: thinkingLevels(listed),
77
81
  model_prices: {},
78
82
  model_configs: {},
79
83
  prefix_hits: deps.prefixHits({
@@ -153,8 +157,8 @@ function servingProviders(provider, credential) {
153
157
  ? [provider, "openai-codex"]
154
158
  : [provider];
155
159
  }
156
- function thinkingLevels(router) {
157
- return Object.fromEntries(router.models.flatMap((model) => model.thinking ? [[model.id, model.thinking]] : []));
160
+ function thinkingLevels(models) {
161
+ return Object.fromEntries(models.flatMap((model) => model.thinking ? [[model.id, model.thinking]] : []));
158
162
  }
159
163
  const SUBSCRIPTION_PLAN_NAMES = {
160
164
  anthropic_claude_code: "Claude Code",
@@ -169,7 +173,7 @@ const SUBSCRIPTION_PLAN_NAMES = {
169
173
  */
170
174
  export async function providersWithoutCredentials(deps, router) {
171
175
  const missing = [];
172
- for (const provider of new Set(router.models.map((model) => providerForModel(model.id)))) {
176
+ for (const provider of new Set(allRouterModels(router).map((model) => providerForModel(model.id)))) {
173
177
  const plans = router.subscriptions
174
178
  ? [subscriptionProviderFor(provider, "claude_code"), subscriptionProviderFor(provider, "muse_code")]
175
179
  : [];
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The model lists saved through the gateway's API, which `dari gateway models`
3
+ * calls: a router's own list and each coding agent's. They live in SQLite and
4
+ * are served in place of the config file's, so the file is never rewritten
5
+ * and a change needs no restart.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import type { ClientHarness } from "../types.js";
9
+ import { type GatewayConfig, type RouterConfig, type RouterModelConfig } from "./config.js";
10
+ export declare class RouterModelStore {
11
+ private readonly db;
12
+ constructor(db: Database);
13
+ /** The router as served: each saved list in place of its config's. */
14
+ served(routerId: string, router: RouterConfig): RouterConfig;
15
+ /** The routers with a saved list. */
16
+ routersWithSavedLists(): string[];
17
+ /** Whether the router's own list is a saved one. */
18
+ hasRouterList(routerId: string): boolean;
19
+ /** Save the router's own list, or one coding agent's. */
20
+ save(routerId: string, agent: ClientHarness | undefined, models: RouterModelConfig[]): void;
21
+ /** Forget a saved list, so the config's is served again. */
22
+ remove(routerId: string, agent: ClientHarness | undefined): void;
23
+ }
24
+ /** `/v1/router/models` for the default router, `/<router>/v1/router/models` for another; a coding agent's list is one segment below. */
25
+ export declare const ROUTER_MODELS_ROUTE: RegExp;
26
+ /**
27
+ * Serve a router's model lists. The caller authenticates the gateway key.
28
+ *
29
+ * - `GET /v1/router/models` returns the lists as served.
30
+ * - `PUT /v1/router/models` with `{ "models": [...] }` saves the router's own
31
+ * list, and `DELETE` goes back to the config file's.
32
+ * - `PUT` and `DELETE /v1/router/models/<agent>` do the same for one coding
33
+ * agent's list.
34
+ *
35
+ * Each answers with the lists as served after the change. Returns null for
36
+ * any other path.
37
+ */
38
+ export declare function handleRouterModelsRequest(request: Request, deps: {
39
+ config: GatewayConfig;
40
+ routerModels: RouterModelStore;
41
+ }): Promise<Response | null>;