@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
@@ -17,6 +17,7 @@ import {
17
17
  type RouterConfig,
18
18
  type RouterModelConfig,
19
19
  } from "./config.js";
20
+ import type { RouterSpecStore } from "./router_specs.js";
20
21
 
21
22
  // A router's own list is saved under no agent.
22
23
  const ROUTER_LIST = "";
@@ -93,19 +94,21 @@ export const ROUTER_MODELS_ROUTE = /^(?:\/([^/]+))?\/v1\/router\/models(?:\/([^/
93
94
  * - `PUT` and `DELETE /v1/router/models/<agent>` do the same for one coding
94
95
  * agent's list.
95
96
  *
96
- * Each answers with the lists as served after the change. Returns null for
97
- * any other path.
97
+ * Each answers with the lists as served after the change. A router served
98
+ * from a spec has its spec's lists, which change with the spec. Returns null
99
+ * for any other path.
98
100
  */
99
101
  export async function handleRouterModelsRequest(
100
102
  request: Request,
101
- deps: { config: GatewayConfig; routerModels: RouterModelStore },
103
+ deps: { config: GatewayConfig; routerModels: RouterModelStore; routerSpecs: RouterSpecStore },
102
104
  ): Promise<Response | null> {
103
105
  const route = ROUTER_MODELS_ROUTE.exec(new URL(request.url).pathname);
104
106
  if (route === null) return null;
105
107
  try {
106
108
  const routerId = route[1] ?? DEFAULT_ROUTER_ALIAS;
109
+ const spec = deps.routerSpecs.get(routerId);
107
110
  const configured = deps.config.routers[routerId];
108
- if (configured === undefined) {
111
+ if (spec === undefined && configured === undefined) {
109
112
  throw new HttpError(404, `Router ${routerId} is not configured on this gateway.`, "router_not_found");
110
113
  }
111
114
  const agent = route[2] as ClientHarness | undefined;
@@ -116,6 +119,13 @@ export async function handleRouterModelsRequest(
116
119
  "coding_agent_not_found",
117
120
  );
118
121
  }
122
+ if (spec !== undefined && (request.method === "PUT" || request.method === "DELETE")) {
123
+ throw new HttpError(
124
+ 400,
125
+ `Router ${routerId} is served from a router spec; change its models in the spec (PUT /v1/routers/${routerId}).`,
126
+ "router_spec_models",
127
+ );
128
+ }
119
129
  if (request.method === "PUT") {
120
130
  deps.routerModels.save(routerId, agent, await requestedModels(request, routerId));
121
131
  } else if (request.method === "DELETE") {
@@ -123,14 +133,14 @@ export async function handleRouterModelsRequest(
123
133
  } else if (request.method !== "GET" || agent !== undefined) {
124
134
  throw new HttpError(405, "Method not allowed.", "method_not_allowed");
125
135
  }
126
- const served = deps.routerModels.served(routerId, configured);
136
+ const served = spec?.router ?? deps.routerModels.served(routerId, configured!);
127
137
  return Response.json(
128
138
  {
129
139
  models: served.models,
130
140
  agent_models: served.agentModels,
131
141
  // False while the router serves the gateway's built-in default
132
142
  // models, which nobody chose.
133
- chosen: deps.config !== DEFAULT_GATEWAY_CONFIG || deps.routerModels.hasRouterList(routerId),
143
+ chosen: spec !== undefined || deps.config !== DEFAULT_GATEWAY_CONFIG || deps.routerModels.hasRouterList(routerId),
134
144
  },
135
145
  { headers: { "Cache-Control": "no-store" } },
136
146
  );
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Router specs (see parseRouterSpec): whole routers saved through the
3
+ * gateway's API, which the Dari CLI pushes, and those read at startup from
4
+ * `DARI_GATEWAY_ROUTERS_DIR`. A spec is served in place of the config file's
5
+ * router of its id: a saved one first, then a file's. Saved specs live in
6
+ * SQLite, so a change needs no restart.
7
+ */
8
+ import type { Database } from "bun:sqlite";
9
+ import { readdirSync } from "node:fs";
10
+ import { basename, extname, join } from "node:path";
11
+
12
+ import { errorResponse, HttpError } from "../http/errors.js";
13
+ import {
14
+ parseRouterSpec,
15
+ parseRouterSpecText,
16
+ ROUTER_ID_PATTERN,
17
+ routerSpecFor,
18
+ routerSpecYaml,
19
+ type GatewayConfig,
20
+ type RouterConfig,
21
+ type RouterSpec,
22
+ } from "./config.js";
23
+ import type { RouterModelStore } from "./router_models.js";
24
+
25
+ // A spec as written: its YAML text, kept so it reads back as it was sent.
26
+ export type StoredRouterSpec = RouterSpec & { text: string };
27
+
28
+ export class RouterSpecStore {
29
+ private readonly saved = new Map<string, StoredRouterSpec>();
30
+
31
+ constructor(
32
+ private readonly db: Database,
33
+ // Specs from files, which the API cannot change.
34
+ readonly files: ReadonlyMap<string, StoredRouterSpec> = new Map(),
35
+ ) {
36
+ db.run(`CREATE TABLE IF NOT EXISTS router_specs (
37
+ router_id TEXT PRIMARY KEY,
38
+ spec TEXT NOT NULL
39
+ )`);
40
+ const rows = db.query<{ router_id: string; spec: string }, []>("SELECT router_id, spec FROM router_specs").all();
41
+ for (const row of rows) {
42
+ try {
43
+ this.saved.set(row.router_id, storedSpec(row.router_id, row.spec));
44
+ } catch (error) {
45
+ // A spec this version no longer accepts is not served; saving it again
46
+ // with a fix serves it.
47
+ console.warn(
48
+ "dari-gateway saved router spec is not served",
49
+ JSON.stringify({ router: row.router_id, error: error instanceof Error ? error.message : String(error) }),
50
+ );
51
+ }
52
+ }
53
+ }
54
+
55
+ /** The spec served for a router id: a saved one, else a file's. */
56
+ get(routerId: string): (StoredRouterSpec & { source: "saved" | "file" }) | undefined {
57
+ const saved = this.saved.get(routerId);
58
+ if (saved !== undefined) return { ...saved, source: "saved" };
59
+ const file = this.files.get(routerId);
60
+ return file === undefined ? undefined : { ...file, source: "file" };
61
+ }
62
+
63
+ /** The ids of every spec, saved or from a file. */
64
+ ids(): string[] {
65
+ return [...new Set([...this.files.keys(), ...this.saved.keys()])];
66
+ }
67
+
68
+ /** The ids with a saved spec. */
69
+ savedIds(): string[] {
70
+ return [...this.saved.keys()].sort();
71
+ }
72
+
73
+ save(routerId: string, spec: StoredRouterSpec): void {
74
+ this.db
75
+ .query(
76
+ `INSERT INTO router_specs (router_id, spec) VALUES (?, ?)
77
+ ON CONFLICT (router_id) DO UPDATE SET spec = excluded.spec`,
78
+ )
79
+ .run(routerId, spec.text);
80
+ this.saved.set(routerId, spec);
81
+ }
82
+
83
+ /** Forget a saved spec; returns it, or undefined when there was none. */
84
+ remove(routerId: string): StoredRouterSpec | undefined {
85
+ const saved = this.saved.get(routerId);
86
+ this.db.query("DELETE FROM router_specs WHERE router_id = ?").run(routerId);
87
+ this.saved.delete(routerId);
88
+ return saved;
89
+ }
90
+ }
91
+
92
+ function storedSpec(routerId: string, text: string): StoredRouterSpec {
93
+ return { ...parseRouterSpec(routerId, parseRouterSpecText(text)), text };
94
+ }
95
+
96
+ /**
97
+ * Read each `*.yaml` or `*.yml` spec in `dir` as the router its file name
98
+ * names: `opus-deepseek.yaml` is router `opus-deepseek`.
99
+ */
100
+ export async function loadRouterSpecDirectory(dir: string): Promise<Map<string, StoredRouterSpec>> {
101
+ const specs = new Map<string, StoredRouterSpec>();
102
+ for (const file of readdirSync(dir).sort()) {
103
+ const extension = extname(file);
104
+ if (extension !== ".yaml" && extension !== ".yml") continue;
105
+ const routerId = basename(file, extension);
106
+ if (!ROUTER_ID_PATTERN.test(routerId)) {
107
+ throw new Error(`Router spec ${file}: a router id may use only letters, digits, "-" and "_".`);
108
+ }
109
+ if (specs.has(routerId)) throw new Error(`Router spec ${file}: router ${routerId} has two spec files.`);
110
+ try {
111
+ specs.set(routerId, storedSpec(routerId, await Bun.file(join(dir, file)).text()));
112
+ } catch (error) {
113
+ throw new Error(`Router spec ${file}: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ }
116
+ return specs;
117
+ }
118
+
119
+ export type ServedRouters = {
120
+ config: GatewayConfig;
121
+ routerModels: RouterModelStore;
122
+ routerSpecs: RouterSpecStore;
123
+ };
124
+
125
+ /** The router served under an id: its spec, else the config file's with its saved model lists. */
126
+ export function servedRouter(routers: ServedRouters, routerId: string): RouterConfig | undefined {
127
+ const spec = routers.routerSpecs.get(routerId);
128
+ if (spec !== undefined) return spec.router;
129
+ const configured = routers.config.routers[routerId];
130
+ return configured === undefined ? undefined : routers.routerModels.served(routerId, configured);
131
+ }
132
+
133
+ /** Every router id the gateway serves: the config file's first. */
134
+ export function servedRouterIds(routers: ServedRouters): string[] {
135
+ const configured = Object.keys(routers.config.routers);
136
+ return [...configured, ...routers.routerSpecs.ids().filter((id) => !configured.includes(id)).sort()];
137
+ }
138
+
139
+ export const ROUTERS_ROUTE = /^\/v1\/routers(?:\/([^/]+))?$/;
140
+
141
+ // Hosted Dari's limit on a spec's text.
142
+ const SPEC_TEXT_MAX_LENGTH = 200_000;
143
+
144
+ /**
145
+ * Serve router specs. The caller authenticates the gateway key.
146
+ *
147
+ * - `GET /v1/routers` lists `{ routers: [{ id, name, source }] }`, where
148
+ * `source` is `saved` for a spec saved through this API and `config` for a
149
+ * router from the config file or a spec file.
150
+ * - `GET /v1/routers/<id>` answers the router's spec as YAML: a saved or
151
+ * file spec as written, a config file router as the spec it amounts to.
152
+ * - `PUT /v1/routers/<id>` with `{ "spec_yaml": "<YAML>" }` (or a JSON
153
+ * `{ "spec": {...} }`) saves the spec and serves it at once, in place of any
154
+ * router of that id, answering `{ id, name }`.
155
+ * - `DELETE /v1/routers/<id>` forgets a saved spec, answering `{ id, name }`;
156
+ * a router of that id from the config file serves again.
157
+ *
158
+ * `changed` runs after each save or removal. Returns null for any other path.
159
+ */
160
+ export async function handleRouterSpecsRequest(
161
+ request: Request,
162
+ deps: ServedRouters & { changed: (routerId: string) => void },
163
+ ): Promise<Response | null> {
164
+ const route = ROUTERS_ROUTE.exec(new URL(request.url).pathname);
165
+ if (route === null) return null;
166
+ try {
167
+ const routerId = route[1];
168
+ if (routerId === undefined) {
169
+ if (request.method !== "GET") throw new HttpError(405, "Method not allowed.", "method_not_allowed");
170
+ const routers = servedRouterIds(deps).map((id) => {
171
+ const spec = deps.routerSpecs.get(id);
172
+ return { id, name: spec?.name ?? id, source: spec?.source === "saved" ? "saved" : "config" };
173
+ });
174
+ return Response.json({ routers }, { headers: { "Cache-Control": "no-store" } });
175
+ }
176
+ if (request.method === "GET") {
177
+ const spec = deps.routerSpecs.get(routerId);
178
+ const router = servedRouter(deps, routerId);
179
+ if (router === undefined) throw routerNotFound(routerId);
180
+ return new Response(spec?.text ?? routerSpecYaml(routerSpecFor(routerId, router)), {
181
+ headers: { "Content-Type": "application/yaml; charset=utf-8", "Cache-Control": "no-store" },
182
+ });
183
+ }
184
+ if (request.method === "PUT") {
185
+ if (!ROUTER_ID_PATTERN.test(routerId)) {
186
+ throw new HttpError(400, `Router id "${routerId}" may use only letters, digits, "-" and "_".`, "invalid_request_error");
187
+ }
188
+ const spec = await requestedSpec(request, routerId);
189
+ deps.routerSpecs.save(routerId, spec);
190
+ deps.changed(routerId);
191
+ return Response.json({ id: routerId, name: spec.name });
192
+ }
193
+ if (request.method === "DELETE") {
194
+ if (deps.routerSpecs.get(routerId)?.source !== "saved") {
195
+ if (servedRouter(deps, routerId) === undefined) throw routerNotFound(routerId);
196
+ throw new HttpError(
197
+ 400,
198
+ `Router ${routerId} comes from the gateway's config files; edit them to change or remove it.`,
199
+ "router_not_saved",
200
+ );
201
+ }
202
+ const removed = deps.routerSpecs.remove(routerId)!;
203
+ deps.changed(routerId);
204
+ return Response.json({ id: routerId, name: removed.name });
205
+ }
206
+ throw new HttpError(405, "Method not allowed.", "method_not_allowed");
207
+ } catch (error) {
208
+ return errorResponse(error);
209
+ }
210
+ }
211
+
212
+ function routerNotFound(routerId: string): HttpError {
213
+ return new HttpError(404, `Router ${routerId} is not configured on this gateway.`, "router_not_found");
214
+ }
215
+
216
+ async function requestedSpec(request: Request, routerId: string): Promise<StoredRouterSpec> {
217
+ const body: unknown = await request.json().catch(() => null);
218
+ const payload = body !== null && typeof body === "object" && !Array.isArray(body)
219
+ ? body as Record<string, unknown>
220
+ : {};
221
+ const extra = Object.keys(payload).filter((key) => key !== "spec" && key !== "spec_yaml");
222
+ if (extra.length > 0 || (payload.spec === undefined) === (payload.spec_yaml === undefined)) {
223
+ throw new HttpError(400, 'Send a JSON body with "spec_yaml", the spec\'s YAML text, or "spec".', "invalid_request_error");
224
+ }
225
+ if (payload.spec_yaml !== undefined && (typeof payload.spec_yaml !== "string" || payload.spec_yaml.length > SPEC_TEXT_MAX_LENGTH)) {
226
+ throw new HttpError(400, `spec_yaml must be text of at most ${SPEC_TEXT_MAX_LENGTH} characters.`, "invalid_request_error", "spec_yaml");
227
+ }
228
+ const text = typeof payload.spec_yaml === "string"
229
+ ? payload.spec_yaml
230
+ : routerSpecYaml(payload.spec);
231
+ try {
232
+ return storedSpec(routerId, text);
233
+ } catch (error) {
234
+ throw new HttpError(400, error instanceof Error ? error.message : String(error), "invalid_router_spec");
235
+ }
236
+ }
@@ -104,6 +104,7 @@ function interactionObservabilityMetadata(
104
104
  openai_reasoning: 0,
105
105
  anthropic_thinking: 0,
106
106
  anthropic_redacted_thinking: 0,
107
+ google_thought_signatures: 0,
107
108
  };
108
109
 
109
110
  for (const item of request.items) {