@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
@@ -70,8 +70,9 @@ export const ROUTER_MODELS_ROUTE = /^(?:\/([^/]+))?\/v1\/router\/models(?:\/([^/
70
70
  * - `PUT` and `DELETE /v1/router/models/<agent>` do the same for one coding
71
71
  * agent's list.
72
72
  *
73
- * Each answers with the lists as served after the change. Returns null for
74
- * any other path.
73
+ * Each answers with the lists as served after the change. A router served
74
+ * from a spec has its spec's lists, which change with the spec. Returns null
75
+ * for any other path.
75
76
  */
76
77
  export async function handleRouterModelsRequest(request, deps) {
77
78
  const route = ROUTER_MODELS_ROUTE.exec(new URL(request.url).pathname);
@@ -79,14 +80,18 @@ export async function handleRouterModelsRequest(request, deps) {
79
80
  return null;
80
81
  try {
81
82
  const routerId = route[1] ?? DEFAULT_ROUTER_ALIAS;
83
+ const spec = deps.routerSpecs.get(routerId);
82
84
  const configured = deps.config.routers[routerId];
83
- if (configured === undefined) {
85
+ if (spec === undefined && configured === undefined) {
84
86
  throw new HttpError(404, `Router ${routerId} is not configured on this gateway.`, "router_not_found");
85
87
  }
86
88
  const agent = route[2];
87
89
  if (agent !== undefined && !CLIENT_HARNESSES.includes(agent)) {
88
90
  throw new HttpError(404, `Unknown coding agent '${agent}'; use ${CLIENT_HARNESSES.join(", ")}.`, "coding_agent_not_found");
89
91
  }
92
+ if (spec !== undefined && (request.method === "PUT" || request.method === "DELETE")) {
93
+ throw new HttpError(400, `Router ${routerId} is served from a router spec; change its models in the spec (PUT /v1/routers/${routerId}).`, "router_spec_models");
94
+ }
90
95
  if (request.method === "PUT") {
91
96
  deps.routerModels.save(routerId, agent, await requestedModels(request, routerId));
92
97
  }
@@ -96,13 +101,13 @@ export async function handleRouterModelsRequest(request, deps) {
96
101
  else if (request.method !== "GET" || agent !== undefined) {
97
102
  throw new HttpError(405, "Method not allowed.", "method_not_allowed");
98
103
  }
99
- const served = deps.routerModels.served(routerId, configured);
104
+ const served = spec?.router ?? deps.routerModels.served(routerId, configured);
100
105
  return Response.json({
101
106
  models: served.models,
102
107
  agent_models: served.agentModels,
103
108
  // False while the router serves the gateway's built-in default
104
109
  // models, which nobody chose.
105
- chosen: deps.config !== DEFAULT_GATEWAY_CONFIG || deps.routerModels.hasRouterList(routerId),
110
+ chosen: spec !== undefined || deps.config !== DEFAULT_GATEWAY_CONFIG || deps.routerModels.hasRouterList(routerId),
106
111
  }, { headers: { "Cache-Control": "no-store" } });
107
112
  }
108
113
  catch (error) {
@@ -0,0 +1,64 @@
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 { type GatewayConfig, type RouterConfig, type RouterSpec } from "./config.js";
10
+ import type { RouterModelStore } from "./router_models.js";
11
+ export type StoredRouterSpec = RouterSpec & {
12
+ text: string;
13
+ };
14
+ export declare class RouterSpecStore {
15
+ private readonly db;
16
+ readonly files: ReadonlyMap<string, StoredRouterSpec>;
17
+ private readonly saved;
18
+ constructor(db: Database, files?: ReadonlyMap<string, StoredRouterSpec>);
19
+ /** The spec served for a router id: a saved one, else a file's. */
20
+ get(routerId: string): (StoredRouterSpec & {
21
+ source: "saved" | "file";
22
+ }) | undefined;
23
+ /** The ids of every spec, saved or from a file. */
24
+ ids(): string[];
25
+ /** The ids with a saved spec. */
26
+ savedIds(): string[];
27
+ save(routerId: string, spec: StoredRouterSpec): void;
28
+ /** Forget a saved spec; returns it, or undefined when there was none. */
29
+ remove(routerId: string): StoredRouterSpec | undefined;
30
+ }
31
+ /**
32
+ * Read each `*.yaml` or `*.yml` spec in `dir` as the router its file name
33
+ * names: `opus-deepseek.yaml` is router `opus-deepseek`.
34
+ */
35
+ export declare function loadRouterSpecDirectory(dir: string): Promise<Map<string, StoredRouterSpec>>;
36
+ export type ServedRouters = {
37
+ config: GatewayConfig;
38
+ routerModels: RouterModelStore;
39
+ routerSpecs: RouterSpecStore;
40
+ };
41
+ /** The router served under an id: its spec, else the config file's with its saved model lists. */
42
+ export declare function servedRouter(routers: ServedRouters, routerId: string): RouterConfig | undefined;
43
+ /** Every router id the gateway serves: the config file's first. */
44
+ export declare function servedRouterIds(routers: ServedRouters): string[];
45
+ export declare const ROUTERS_ROUTE: RegExp;
46
+ /**
47
+ * Serve router specs. The caller authenticates the gateway key.
48
+ *
49
+ * - `GET /v1/routers` lists `{ routers: [{ id, name, source }] }`, where
50
+ * `source` is `saved` for a spec saved through this API and `config` for a
51
+ * router from the config file or a spec file.
52
+ * - `GET /v1/routers/<id>` answers the router's spec as YAML: a saved or
53
+ * file spec as written, a config file router as the spec it amounts to.
54
+ * - `PUT /v1/routers/<id>` with `{ "spec_yaml": "<YAML>" }` (or a JSON
55
+ * `{ "spec": {...} }`) saves the spec and serves it at once, in place of any
56
+ * router of that id, answering `{ id, name }`.
57
+ * - `DELETE /v1/routers/<id>` forgets a saved spec, answering `{ id, name }`;
58
+ * a router of that id from the config file serves again.
59
+ *
60
+ * `changed` runs after each save or removal. Returns null for any other path.
61
+ */
62
+ export declare function handleRouterSpecsRequest(request: Request, deps: ServedRouters & {
63
+ changed: (routerId: string) => void;
64
+ }): Promise<Response | null>;
@@ -0,0 +1,194 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { basename, extname, join } from "node:path";
3
+ import { errorResponse, HttpError } from "../http/errors.js";
4
+ import { parseRouterSpec, parseRouterSpecText, ROUTER_ID_PATTERN, routerSpecFor, routerSpecYaml, } from "./config.js";
5
+ export class RouterSpecStore {
6
+ db;
7
+ files;
8
+ saved = new Map();
9
+ constructor(db,
10
+ // Specs from files, which the API cannot change.
11
+ files = new Map()) {
12
+ this.db = db;
13
+ this.files = files;
14
+ db.run(`CREATE TABLE IF NOT EXISTS router_specs (
15
+ router_id TEXT PRIMARY KEY,
16
+ spec TEXT NOT NULL
17
+ )`);
18
+ const rows = db.query("SELECT router_id, spec FROM router_specs").all();
19
+ for (const row of rows) {
20
+ try {
21
+ this.saved.set(row.router_id, storedSpec(row.router_id, row.spec));
22
+ }
23
+ catch (error) {
24
+ // A spec this version no longer accepts is not served; saving it again
25
+ // with a fix serves it.
26
+ console.warn("dari-gateway saved router spec is not served", JSON.stringify({ router: row.router_id, error: error instanceof Error ? error.message : String(error) }));
27
+ }
28
+ }
29
+ }
30
+ /** The spec served for a router id: a saved one, else a file's. */
31
+ get(routerId) {
32
+ const saved = this.saved.get(routerId);
33
+ if (saved !== undefined)
34
+ return { ...saved, source: "saved" };
35
+ const file = this.files.get(routerId);
36
+ return file === undefined ? undefined : { ...file, source: "file" };
37
+ }
38
+ /** The ids of every spec, saved or from a file. */
39
+ ids() {
40
+ return [...new Set([...this.files.keys(), ...this.saved.keys()])];
41
+ }
42
+ /** The ids with a saved spec. */
43
+ savedIds() {
44
+ return [...this.saved.keys()].sort();
45
+ }
46
+ save(routerId, spec) {
47
+ this.db
48
+ .query(`INSERT INTO router_specs (router_id, spec) VALUES (?, ?)
49
+ ON CONFLICT (router_id) DO UPDATE SET spec = excluded.spec`)
50
+ .run(routerId, spec.text);
51
+ this.saved.set(routerId, spec);
52
+ }
53
+ /** Forget a saved spec; returns it, or undefined when there was none. */
54
+ remove(routerId) {
55
+ const saved = this.saved.get(routerId);
56
+ this.db.query("DELETE FROM router_specs WHERE router_id = ?").run(routerId);
57
+ this.saved.delete(routerId);
58
+ return saved;
59
+ }
60
+ }
61
+ function storedSpec(routerId, text) {
62
+ return { ...parseRouterSpec(routerId, parseRouterSpecText(text)), text };
63
+ }
64
+ /**
65
+ * Read each `*.yaml` or `*.yml` spec in `dir` as the router its file name
66
+ * names: `opus-deepseek.yaml` is router `opus-deepseek`.
67
+ */
68
+ export async function loadRouterSpecDirectory(dir) {
69
+ const specs = new Map();
70
+ for (const file of readdirSync(dir).sort()) {
71
+ const extension = extname(file);
72
+ if (extension !== ".yaml" && extension !== ".yml")
73
+ continue;
74
+ const routerId = basename(file, extension);
75
+ if (!ROUTER_ID_PATTERN.test(routerId)) {
76
+ throw new Error(`Router spec ${file}: a router id may use only letters, digits, "-" and "_".`);
77
+ }
78
+ if (specs.has(routerId))
79
+ throw new Error(`Router spec ${file}: router ${routerId} has two spec files.`);
80
+ try {
81
+ specs.set(routerId, storedSpec(routerId, await Bun.file(join(dir, file)).text()));
82
+ }
83
+ catch (error) {
84
+ throw new Error(`Router spec ${file}: ${error instanceof Error ? error.message : String(error)}`);
85
+ }
86
+ }
87
+ return specs;
88
+ }
89
+ /** The router served under an id: its spec, else the config file's with its saved model lists. */
90
+ export function servedRouter(routers, routerId) {
91
+ const spec = routers.routerSpecs.get(routerId);
92
+ if (spec !== undefined)
93
+ return spec.router;
94
+ const configured = routers.config.routers[routerId];
95
+ return configured === undefined ? undefined : routers.routerModels.served(routerId, configured);
96
+ }
97
+ /** Every router id the gateway serves: the config file's first. */
98
+ export function servedRouterIds(routers) {
99
+ const configured = Object.keys(routers.config.routers);
100
+ return [...configured, ...routers.routerSpecs.ids().filter((id) => !configured.includes(id)).sort()];
101
+ }
102
+ export const ROUTERS_ROUTE = /^\/v1\/routers(?:\/([^/]+))?$/;
103
+ // Hosted Dari's limit on a spec's text.
104
+ const SPEC_TEXT_MAX_LENGTH = 200_000;
105
+ /**
106
+ * Serve router specs. The caller authenticates the gateway key.
107
+ *
108
+ * - `GET /v1/routers` lists `{ routers: [{ id, name, source }] }`, where
109
+ * `source` is `saved` for a spec saved through this API and `config` for a
110
+ * router from the config file or a spec file.
111
+ * - `GET /v1/routers/<id>` answers the router's spec as YAML: a saved or
112
+ * file spec as written, a config file router as the spec it amounts to.
113
+ * - `PUT /v1/routers/<id>` with `{ "spec_yaml": "<YAML>" }` (or a JSON
114
+ * `{ "spec": {...} }`) saves the spec and serves it at once, in place of any
115
+ * router of that id, answering `{ id, name }`.
116
+ * - `DELETE /v1/routers/<id>` forgets a saved spec, answering `{ id, name }`;
117
+ * a router of that id from the config file serves again.
118
+ *
119
+ * `changed` runs after each save or removal. Returns null for any other path.
120
+ */
121
+ export async function handleRouterSpecsRequest(request, deps) {
122
+ const route = ROUTERS_ROUTE.exec(new URL(request.url).pathname);
123
+ if (route === null)
124
+ return null;
125
+ try {
126
+ const routerId = route[1];
127
+ if (routerId === undefined) {
128
+ if (request.method !== "GET")
129
+ throw new HttpError(405, "Method not allowed.", "method_not_allowed");
130
+ const routers = servedRouterIds(deps).map((id) => {
131
+ const spec = deps.routerSpecs.get(id);
132
+ return { id, name: spec?.name ?? id, source: spec?.source === "saved" ? "saved" : "config" };
133
+ });
134
+ return Response.json({ routers }, { headers: { "Cache-Control": "no-store" } });
135
+ }
136
+ if (request.method === "GET") {
137
+ const spec = deps.routerSpecs.get(routerId);
138
+ const router = servedRouter(deps, routerId);
139
+ if (router === undefined)
140
+ throw routerNotFound(routerId);
141
+ return new Response(spec?.text ?? routerSpecYaml(routerSpecFor(routerId, router)), {
142
+ headers: { "Content-Type": "application/yaml; charset=utf-8", "Cache-Control": "no-store" },
143
+ });
144
+ }
145
+ if (request.method === "PUT") {
146
+ if (!ROUTER_ID_PATTERN.test(routerId)) {
147
+ throw new HttpError(400, `Router id "${routerId}" may use only letters, digits, "-" and "_".`, "invalid_request_error");
148
+ }
149
+ const spec = await requestedSpec(request, routerId);
150
+ deps.routerSpecs.save(routerId, spec);
151
+ deps.changed(routerId);
152
+ return Response.json({ id: routerId, name: spec.name });
153
+ }
154
+ if (request.method === "DELETE") {
155
+ if (deps.routerSpecs.get(routerId)?.source !== "saved") {
156
+ if (servedRouter(deps, routerId) === undefined)
157
+ throw routerNotFound(routerId);
158
+ throw new HttpError(400, `Router ${routerId} comes from the gateway's config files; edit them to change or remove it.`, "router_not_saved");
159
+ }
160
+ const removed = deps.routerSpecs.remove(routerId);
161
+ deps.changed(routerId);
162
+ return Response.json({ id: routerId, name: removed.name });
163
+ }
164
+ throw new HttpError(405, "Method not allowed.", "method_not_allowed");
165
+ }
166
+ catch (error) {
167
+ return errorResponse(error);
168
+ }
169
+ }
170
+ function routerNotFound(routerId) {
171
+ return new HttpError(404, `Router ${routerId} is not configured on this gateway.`, "router_not_found");
172
+ }
173
+ async function requestedSpec(request, routerId) {
174
+ const body = await request.json().catch(() => null);
175
+ const payload = body !== null && typeof body === "object" && !Array.isArray(body)
176
+ ? body
177
+ : {};
178
+ const extra = Object.keys(payload).filter((key) => key !== "spec" && key !== "spec_yaml");
179
+ if (extra.length > 0 || (payload.spec === undefined) === (payload.spec_yaml === undefined)) {
180
+ throw new HttpError(400, 'Send a JSON body with "spec_yaml", the spec\'s YAML text, or "spec".', "invalid_request_error");
181
+ }
182
+ if (payload.spec_yaml !== undefined && (typeof payload.spec_yaml !== "string" || payload.spec_yaml.length > SPEC_TEXT_MAX_LENGTH)) {
183
+ throw new HttpError(400, `spec_yaml must be text of at most ${SPEC_TEXT_MAX_LENGTH} characters.`, "invalid_request_error", "spec_yaml");
184
+ }
185
+ const text = typeof payload.spec_yaml === "string"
186
+ ? payload.spec_yaml
187
+ : routerSpecYaml(payload.spec);
188
+ try {
189
+ return storedSpec(routerId, text);
190
+ }
191
+ catch (error) {
192
+ throw new HttpError(400, error instanceof Error ? error.message : String(error), "invalid_router_spec");
193
+ }
194
+ }
@@ -39,6 +39,7 @@ function interactionObservabilityMetadata(request) {
39
39
  openai_reasoning: 0,
40
40
  anthropic_thinking: 0,
41
41
  anthropic_redacted_thinking: 0,
42
+ google_thought_signatures: 0,
42
43
  };
43
44
  for (const item of request.items) {
44
45
  if (item.type === "message") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.330",
3
+ "version": "1.0.331",
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": {
@@ -52,8 +52,8 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.330",
56
- "@mupt-ai/pi-ai": "1.5.2-mupt.1"
55
+ "@mupt-ai/dari-router": "1.0.331",
56
+ "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/bun": "^1.3.4",
@@ -166,8 +166,10 @@ export const conversations: ActivityRoute = async (request) => {
166
166
  }
167
167
  const items: object[] = [];
168
168
  if (keys.length > 0) {
169
- const records = await loadRecords(db, sql`${where} and ${groupsCondition(keys)}`);
170
- const titles = await conversationTitles(db, organizationId, keys);
169
+ const [records, titles] = await Promise.all([
170
+ loadRecords(db, sql`${where} and ${groupsCondition(keys)}`),
171
+ conversationTitles(db, organizationId, keys),
172
+ ]);
171
173
  const entities = await loadEntities(db, records);
172
174
  const byGroup = new Map<string, ConversationRecord[]>();
173
175
  for (const record of records) {
@@ -18,7 +18,7 @@ import {
18
18
  } from "./filters.js";
19
19
  import { loadRouterSavings, loadSavings, routeKey } from "./savings.js";
20
20
  import { and, sql, type ActivityDb, type Sql } from "./sql.js";
21
- import { CONVERSATION_ID, THINKING_LEVEL, thinkingLevelValue, type ReasoningEffort } from "./shared.js";
21
+ import { CONVERSATION_ID, REASONING_EFFORTS, THINKING_LEVEL, thinkingLevelValue, type ReasoningEffort } from "./shared.js";
22
22
  import {
23
23
  decimalText,
24
24
  formatInstant,
@@ -244,8 +244,12 @@ export const overview: ActivityRoute = async (request) => {
244
244
  const { organizationId, filters } = readFilters(request, true);
245
245
  const db = request.db;
246
246
  const where = criteria(db, organizationId, filters);
247
- const points = await loadSeries(db, filters, where);
248
- const savings = await loadSavings(db, where);
247
+ const [points, savings, apiKeys, keySources] = await Promise.all([
248
+ loadSeries(db, filters, where),
249
+ loadSavings(db, where),
250
+ loadApiKeys(db, where),
251
+ loadKeySources(db, where),
252
+ ]);
249
253
  return {
250
254
  from_at: formatInstant(filters.start),
251
255
  to_at: formatInstant(filters.end),
@@ -253,8 +257,8 @@ export const overview: ActivityRoute = async (request) => {
253
257
  summary: summary(points, savings.total),
254
258
  series: points.map(seriesPointBody),
255
259
  model_mix: modelMix(points),
256
- api_keys: await loadApiKeys(db, where),
257
- key_sources: await loadKeySources(db, where),
260
+ api_keys: apiKeys,
261
+ key_sources: keySources,
258
262
  };
259
263
  };
260
264
 
@@ -264,7 +268,8 @@ export const routers: ActivityRoute = async (request) => {
264
268
  const { organizationId, filters } = readFilters(request, true);
265
269
  const db = request.db;
266
270
  const where = criteria(db, organizationId, filters);
267
- const summaries = await db.all(sql`
271
+ const [summaries, savings, seriesRows] = await Promise.all([
272
+ db.all(sql`
268
273
  select
269
274
  r.router_id,
270
275
  count(*) filter (where r.status = 'completed') as completed,
@@ -276,9 +281,9 @@ export const routers: ActivityRoute = async (request) => {
276
281
  where ${where}
277
282
  and r.router_id is not null
278
283
  group by r.router_id
279
- order by r.router_id`);
280
- const savings = await loadRouterSavings(db, where);
281
- const seriesRows = await db.all(sql`
284
+ order by r.router_id`),
285
+ loadRouterSavings(db, where),
286
+ db.all(sql`
282
287
  select
283
288
  r.router_id,
284
289
  ${bucketIndex(db, filters)} as bucket_index,
@@ -287,7 +292,8 @@ export const routers: ActivityRoute = async (request) => {
287
292
  where ${where}
288
293
  and r.router_id is not null
289
294
  group by 1, 2
290
- order by 1, 2`);
295
+ order by 1, 2`),
296
+ ]);
291
297
  const seriesByRouter = new Map<string, Array<{ bucket_start: string; messages_sent: number }>>();
292
298
  for (const row of seriesRows) {
293
299
  const routerId = String(row.router_id);
@@ -321,6 +327,22 @@ export const routers: ActivityRoute = async (request) => {
321
327
 
322
328
  /** The p95 provider latency per model, thinking level, and provider (`percentile_disc(0.95)`). */
323
329
  async function loadLatencyP95(db: ActivityDb, where: Sql): Promise<Map<string, number>> {
330
+ const key = (row: Row) => JSON.stringify([String(row.model), thinkingLevelValue(row.thinking_level), readOptionalString(row.provider)]);
331
+ if (db.dialect === "postgres") {
332
+ // Group by the thinking level as the key reads it: an unknown one is none.
333
+ const rows = await db.all(sql`
334
+ select
335
+ ${MODEL} as model,
336
+ case when ${THINKING_LEVEL} in (${REASONING_EFFORTS}) then ${THINKING_LEVEL} end as thinking_level,
337
+ r.selected_provider as provider,
338
+ percentile_disc(0.95) within group (order by r.provider_latency_ms) as latency
339
+ from routing_requests r
340
+ where ${where}
341
+ and r.provider_latency_ms > 0
342
+ group by 1, 2, 3`);
343
+ return new Map(rows.map((row) => [key(row), readInt(row.latency)]));
344
+ }
345
+ // SQLite has no percentile_disc: read every latency and pick the same value.
324
346
  const rows = await db.all(sql`
325
347
  select
326
348
  ${MODEL} as model,
@@ -332,10 +354,9 @@ async function loadLatencyP95(db: ActivityDb, where: Sql): Promise<Map<string, n
332
354
  and r.provider_latency_ms > 0`);
333
355
  const grouped = new Map<string, number[]>();
334
356
  for (const row of rows) {
335
- const key = JSON.stringify([String(row.model), thinkingLevelValue(row.thinking_level), readOptionalString(row.provider)]);
336
- const values = grouped.get(key) ?? [];
357
+ const values = grouped.get(key(row)) ?? [];
337
358
  values.push(readInt(row.latency));
338
- grouped.set(key, values);
359
+ grouped.set(key(row), values);
339
360
  }
340
361
  const p95 = new Map<string, number>();
341
362
  for (const [key, values] of grouped) {
@@ -346,7 +367,7 @@ async function loadLatencyP95(db: ActivityDb, where: Sql): Promise<Map<string, n
346
367
  }
347
368
 
348
369
  async function loadModelRows(db: ActivityDb, where: Sql) {
349
- const rows = await db.all<Row>(sql`
370
+ const [rows, latency] = await Promise.all([db.all<Row>(sql`
350
371
  select
351
372
  ${MODEL} as model,
352
373
  ${THINKING_LEVEL} as thinking_level,
@@ -356,8 +377,7 @@ async function loadModelRows(db: ActivityDb, where: Sql) {
356
377
  from routing_requests r
357
378
  where ${where}
358
379
  group by 1, 2, 3
359
- order by model_steps desc, 1, 2 nulls last, 3 nulls last`);
360
- const latency = await loadLatencyP95(db, where);
380
+ order by model_steps desc, 1, 2 nulls last, 3 nulls last`), loadLatencyP95(db, where)]);
361
381
  return rows.map((row) => {
362
382
  const model = String(row.model);
363
383
  const thinkingLevel = thinkingLevelValue(row.thinking_level);
@@ -515,15 +535,17 @@ export const models: ActivityRoute = async (request) => {
515
535
  const { organizationId, filters } = readFilters(request, false);
516
536
  const db = request.db;
517
537
  const where = criteria(db, organizationId, filters);
518
- const modelRows = await loadModelRows(db, where);
519
- const switches = await loadTransitions(db, organizationId, filters);
520
- const savings = await loadSavings(db, where);
538
+ const [modelRows, switches, savings, observed] = await Promise.all([
539
+ loadModelRows(db, where),
540
+ loadTransitions(db, organizationId, filters),
541
+ loadSavings(db, where),
542
+ loadObservedConversations(db, where),
543
+ ]);
521
544
  for (const model of modelRows) {
522
545
  if (model.provider !== null) {
523
546
  model.savings_vs_most_expensive_usd = savings.byModel.get(routeKey(model.model, model.thinking_level, model.provider)) ?? null;
524
547
  }
525
548
  }
526
- const observed = await loadObservedConversations(db, where);
527
549
  const totalSwitches = switches.modelSwitches + switches.thinkingLevelSwitches;
528
550
  const transitions = switches.transitions.map((item) => ({ ...item, switch_share: ratio(item.occurrences, totalSwitches) }));
529
551
  return {
@@ -606,7 +628,8 @@ export const filterOptions: ActivityRoute = async (request) => {
606
628
  const { organizationId, filters } = readFilters(request, false);
607
629
  const db = request.db;
608
630
  const where = baseCriteria(db, organizationId, filters);
609
- const routerRows = await db.all(sql`
631
+ const [routerRows, keyRows, userRows, modelRows] = await Promise.all([
632
+ db.all(sql`
610
633
  select distinct
611
634
  r.router_id,
612
635
  m.name
@@ -614,8 +637,8 @@ export const filterOptions: ActivityRoute = async (request) => {
614
637
  left join model_routers m on m.id = r.router_id
615
638
  where ${where}
616
639
  and r.router_id is not null
617
- order by m.name nulls last, r.router_id`);
618
- const keyRows = await db.all(sql`
640
+ order by m.name nulls last, r.router_id`),
641
+ db.all(sql`
619
642
  select distinct
620
643
  k.id,
621
644
  k.label,
@@ -628,8 +651,8 @@ export const filterOptions: ActivityRoute = async (request) => {
628
651
  left join users u on u.id = coalesce(k.created_for_user_id, k.attributed_to_user_id)
629
652
  where ${where}
630
653
  and k.organization_id = ${organizationId}
631
- order by k.label, k.id`);
632
- const userRows = await db.all(sql`
654
+ order by k.label, k.id`),
655
+ db.all(sql`
633
656
  select distinct
634
657
  r.attributed_user_id,
635
658
  u.display_name,
@@ -638,13 +661,14 @@ export const filterOptions: ActivityRoute = async (request) => {
638
661
  join users u on u.id = r.attributed_user_id
639
662
  where ${where}
640
663
  and r.attributed_user_id is not null
641
- order by u.display_name nulls last, u.email, r.attributed_user_id`);
642
- const modelRows = await db.all(sql`
664
+ order by u.display_name nulls last, u.email, r.attributed_user_id`),
665
+ db.all(sql`
643
666
  select distinct
644
667
  ${MODEL} as model,
645
668
  r.selected_provider
646
669
  from routing_requests r
647
- where ${where}`);
670
+ where ${where}`),
671
+ ]);
648
672
 
649
673
  const providersByModel = new Map<string, Set<string>>();
650
674
  const providers = new Set<string>();
@@ -92,7 +92,8 @@ export const peopleSeries: ActivityRoute = async (request) => {
92
92
  const where = criteria(db, organizationId, filters);
93
93
  const bucket = bucketIndex(db, filters);
94
94
 
95
- const activeRows = await db.all<Row>(sql`
95
+ const [activeRows, busiest] = await Promise.all([
96
+ db.all<Row>(sql`
96
97
  select
97
98
  ${bucket} as bucket_index,
98
99
  count(distinct r.attributed_user_id) as active_people
@@ -100,25 +101,24 @@ export const peopleSeries: ActivityRoute = async (request) => {
100
101
  where ${where}
101
102
  and r.attributed_user_id is not null
102
103
  group by 1
103
- order by 1`);
104
-
105
- if (userIds.length === 0) {
106
- const busiest = await db.all<Row>(sql`
104
+ order by 1`),
105
+ userIds.length > 0 ? [] : db.all<Row>(sql`
107
106
  select r.attributed_user_id
108
107
  from routing_requests r
109
108
  where ${where}
110
109
  and r.attributed_user_id is not null
111
110
  group by r.attributed_user_id
112
111
  order by count(*) desc, r.attributed_user_id
113
- limit ${DEFAULT_COMPARISON_USERS}`);
114
- userIds.push(...busiest.map((row) => String(row.attributed_user_id)));
115
- }
112
+ limit ${DEFAULT_COMPARISON_USERS}`),
113
+ ]);
114
+ userIds.push(...busiest.map((row) => String(row.attributed_user_id)));
116
115
 
117
116
  const users = await loadComparisonUsers(db, userIds);
118
117
  const compared = users.map((user) => user.id);
119
118
  const peopleSeries: object[] = [];
120
119
  if (compared.length > 0) {
121
- const points = await db.all<Row>(sql`
120
+ const [points, counts] = await Promise.all([
121
+ db.all<Row>(sql`
122
122
  select
123
123
  ${bucket} as bucket_index,
124
124
  r.attributed_user_id,
@@ -130,8 +130,8 @@ export const peopleSeries: ActivityRoute = async (request) => {
130
130
  where ${where}
131
131
  and r.attributed_user_id in (${compared})
132
132
  group by 1, 2
133
- order by 1, 2`);
134
- const counts = await db.all<Row>(sql`
133
+ order by 1, 2`),
134
+ db.all<Row>(sql`
135
135
  select
136
136
  d.bucket_index,
137
137
  d.attributed_user_id,
@@ -148,7 +148,8 @@ export const peopleSeries: ActivityRoute = async (request) => {
148
148
  where ${where}
149
149
  and r.attributed_user_id in (${compared})
150
150
  ) d
151
- group by d.bucket_index, d.attributed_user_id`);
151
+ group by d.bucket_index, d.attributed_user_id`),
152
+ ]);
152
153
  const conversations = new Map(
153
154
  counts.map((row) => [`${readInt(row.bucket_index)}\0${row.attributed_user_id}`, readInt(row.conversations)]),
154
155
  );
@@ -299,15 +300,17 @@ async function loadIdentityPage(db: ActivityDb, organizationId: string, filters:
299
300
  or (s.identity_api_key_id is null and c.identity_api_key_id is null))
300
301
  where ${and(conditions)}`;
301
302
 
302
- const [countRow] = await db.all<Row>(sql`select count(*) as count from (${statement}) page`);
303
- const identityCount = readInt(countRow?.count);
304
- const rows = await db.all<Row>(sql`
303
+ const [[countRow], rows] = await Promise.all([
304
+ db.all<Row>(sql`select count(*) as count from (${statement}) page`),
305
+ db.all<Row>(sql`
305
306
  ${statement}
306
307
  order by
307
308
  ${SORTS[query.sortBy]} ${raw(query.direction)},
308
309
  lower(${IDENTITY_NAME}),
309
310
  coalesce(s.attributed_user_id, s.identity_api_key_id, '')
310
- limit ${query.limit} offset ${query.offset}`);
311
+ limit ${query.limit} offset ${query.offset}`),
312
+ ]);
313
+ const identityCount = readInt(countRow?.count);
311
314
  if (rows.length === 0) return { identities: [], identityCount };
312
315
 
313
316
  const page = rows.map((row) => ({
@@ -316,8 +319,7 @@ async function loadIdentityPage(db: ActivityDb, organizationId: string, filters:
316
319
  apiKeyId: readOptionalString(row.identity_api_key_id),
317
320
  }));
318
321
  const pageWhere = sql`${where} and ${pageIdentityCriterion(page)}`;
319
- const mix = await identityModelMix(db, pageWhere);
320
- const usage = await identityKeyUsage(db, pageWhere);
322
+ const [mix, usage] = await Promise.all([identityModelMix(db, pageWhere), identityKeyUsage(db, pageWhere)]);
321
323
  const keys = await loadApiKeys(db, organizationId, new Set([...usage.values()].flatMap((used) => [...used.keys()])));
322
324
 
323
325
  const identities = page.map(({ row, userId, apiKeyId }) => {