@mupt-ai/dari-gateway 1.0.371 → 1.0.373

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.
@@ -1,5 +1,5 @@
1
1
  /* The Activity overview, series, routers, models, and filter options. */
2
- import { baseCriteria, bucketIndex, bucketStart, criteria, identityCriteria, MODEL, readActivityQuery, readSourceScope, SELECTOR_UNRESOLVED_MODEL, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
2
+ import { baseCriteria, bucket, bucketIndex, bucketStart, criteria, identityCriteria, MODEL, readActivityQuery, readSourceScope, SELECTOR_UNRESOLVED_MODEL, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
3
3
  import { loadRouterSavings, loadSavings, routeKey } from "./savings.js";
4
4
  import { and, sql } from "./sql.js";
5
5
  import { CONVERSATION_ID, REASONING_EFFORTS, THINKING_LEVEL, thinkingLevelValue } from "./shared.js";
@@ -67,7 +67,7 @@ async function loadSeries(db, filters, where) {
67
67
  ) as predicted_warm_without_read
68
68
  from routing_requests r
69
69
  where ${where}
70
- group by 1, 2, 3, 4
70
+ group by ${bucket(db, filters)}, 2, 3, 4
71
71
  order by 1, 2, 3 nulls last, 4 nulls last`);
72
72
  return rows.map((row) => ({
73
73
  bucket_start: bucketStart(filters, row.bucket_index),
@@ -230,7 +230,7 @@ export const routers = async (request) => {
230
230
  from routing_requests r
231
231
  where ${where}
232
232
  and r.router_id is not null
233
- group by 1, 2
233
+ group by 1, ${bucket(db, filters)}
234
234
  order by 1, 2`),
235
235
  ]);
236
236
  const seriesByRouter = new Map();
@@ -574,8 +574,10 @@ export const filterOptions = async (request) => {
574
574
  where ${where}
575
575
  and r.router_id is not null
576
576
  order by m.name nulls last, r.router_id`),
577
+ // The distinct IDs first, then their names: joining every step to its
578
+ // key or person costs more than the read itself.
577
579
  db.all(sql `
578
- select distinct
580
+ select
579
581
  k.id,
580
582
  k.label,
581
583
  k.key_prefix,
@@ -583,21 +585,23 @@ export const filterOptions = async (request) => {
583
585
  u.display_name,
584
586
  u.email
585
587
  from organization_api_keys k
586
- join routing_requests r on r.api_key_id = k.id
587
588
  left join users u on u.id = coalesce(k.created_for_user_id, k.attributed_to_user_id)
588
- where ${where}
589
- and k.organization_id = ${organizationId}
589
+ where k.organization_id = ${organizationId}
590
+ and k.id in (select distinct r.api_key_id from routing_requests r where ${where})
590
591
  order by k.label, k.id`),
591
592
  db.all(sql `
592
- select distinct
593
- r.attributed_user_id,
593
+ select
594
+ u.id as attributed_user_id,
594
595
  u.display_name,
595
596
  u.email
596
- from routing_requests r
597
- join users u on u.id = r.attributed_user_id
598
- where ${where}
599
- and r.attributed_user_id is not null
600
- order by u.display_name nulls last, u.email, r.attributed_user_id`),
597
+ from users u
598
+ where u.id in (
599
+ select distinct r.attributed_user_id
600
+ from routing_requests r
601
+ where ${where}
602
+ and r.attributed_user_id is not null
603
+ )
604
+ order by u.display_name nulls last, u.email, u.id`),
601
605
  db.all(sql `
602
606
  select distinct
603
607
  ${MODEL} as model,
@@ -65,7 +65,15 @@ export declare function routeCriteria(filters: ActivityFilters, alias?: string):
65
65
  export declare function dimensionCriteria(filters: ActivityFilters, alias?: string): Sql;
66
66
  /** Base and dimension criteria: what most reads filter by. */
67
67
  export declare function criteria(db: ActivityDb, organizationId: string, filters: ActivityFilters): Sql;
68
- /** The zero-based time bucket of a request row. */
68
+ /**
69
+ * The time bucket of a request row, to group by. Postgres bins the timestamp
70
+ * itself, which costs far less per row than epoch arithmetic and lets it hash
71
+ * the groups instead of sorting a week of rows. The start is written into the
72
+ * SQL rather than bound, so `bucketIndex` repeats this exact expression and
73
+ * Postgres reads it from the group.
74
+ */
75
+ export declare function bucket(db: ActivityDb, filters: ActivityFilters): Sql;
76
+ /** The zero-based time bucket of a request row, as a query grouped by `bucket` selects it. */
69
77
  export declare function bucketIndex(db: ActivityDb, filters: ActivityFilters): Sql;
70
78
  /** The start of a time bucket, as the API writes it. */
71
79
  export declare function bucketStart(filters: ActivityFilters, index: unknown): string;
@@ -155,13 +155,29 @@ export function dimensionCriteria(filters, alias = "r") {
155
155
  export function criteria(db, organizationId, filters) {
156
156
  return sql `(${baseCriteria(db, organizationId, filters)} and ${dimensionCriteria(filters)})`;
157
157
  }
158
- /** The zero-based time bucket of a request row. */
159
- export function bucketIndex(db, filters) {
158
+ /**
159
+ * The time bucket of a request row, to group by. Postgres bins the timestamp
160
+ * itself, which costs far less per row than epoch arithmetic and lets it hash
161
+ * the groups instead of sorting a week of rows. The start is written into the
162
+ * SQL rather than bound, so `bucketIndex` repeats this exact expression and
163
+ * Postgres reads it from the group.
164
+ */
165
+ export function bucket(db, filters) {
166
+ if (db.dialect === "postgres") {
167
+ return sql `date_bin(interval '${filters.bucketSeconds} seconds', r.received_at, ${inlineStart(filters)})`;
168
+ }
160
169
  const start = timestamp(db, filters.start);
161
- const seconds = db.dialect === "postgres"
162
- ? sql `extract(epoch from (r.received_at - ${start}))`
163
- : sql `(unixepoch(r.received_at, 'subsec') - unixepoch(${start}, 'subsec'))`;
164
- return sql `floor(${seconds} / ${filters.bucketSeconds})`;
170
+ return sql `floor((unixepoch(r.received_at, 'subsec') - unixepoch(${start}, 'subsec')) / ${filters.bucketSeconds})`;
171
+ }
172
+ /** The zero-based time bucket of a request row, as a query grouped by `bucket` selects it. */
173
+ export function bucketIndex(db, filters) {
174
+ if (db.dialect === "sqlite")
175
+ return bucket(db, filters);
176
+ return sql `floor(extract(epoch from (${bucket(db, filters)} - ${inlineStart(filters)})) / ${filters.bucketSeconds})`;
177
+ }
178
+ // A canonical instant is digits and separators, never a caller's text.
179
+ function inlineStart(filters) {
180
+ return raw(`'${canonicalInstant(filters.start)}'::timestamptz`);
165
181
  }
166
182
  /** The start of a time bucket, as the API writes it. */
167
183
  export function bucketStart(filters, index) {
@@ -1,6 +1,6 @@
1
1
  /* People & Keys: Activity per person, and per API key for traffic no person
2
2
  is attributed to (`people-keys`), and people over time (`people-series`). */
3
- import { bucketIndex, bucketStart, criteria, MODEL, readActivityQuery, readSourceScope, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
3
+ import { bucket, bucketIndex, bucketStart, criteria, MODEL, readActivityQuery, readSourceScope, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
4
4
  import { badRequest } from "./params.js";
5
5
  import { and, likePattern, or, raw, sql } from "./sql.js";
6
6
  import { AGENT_SESSION_KEY, IDENTITY_API_KEY, THINKING_LEVEL, thinkingLevelValue, } from "./shared.js";
@@ -57,16 +57,17 @@ export const peopleSeries = async (request) => {
57
57
  const filters = validatedBucketFilters(query, protocols, bucketSeconds);
58
58
  const userIds = validatedComparisonUserIds(requested);
59
59
  const where = criteria(db, organizationId, filters);
60
- const bucket = bucketIndex(db, filters);
60
+ const index = bucketIndex(db, filters);
61
+ const group = bucket(db, filters);
61
62
  const [activeRows, busiest] = await Promise.all([
62
63
  db.all(sql `
63
64
  select
64
- ${bucket} as bucket_index,
65
+ ${index} as bucket_index,
65
66
  count(distinct r.attributed_user_id) as active_people
66
67
  from routing_requests r
67
68
  where ${where}
68
69
  and r.attributed_user_id is not null
69
- group by 1
70
+ group by ${group}
70
71
  order by 1`),
71
72
  userIds.length > 0 ? [] : db.all(sql `
72
73
  select r.attributed_user_id
@@ -85,7 +86,7 @@ export const peopleSeries = async (request) => {
85
86
  const [points, counts] = await Promise.all([
86
87
  db.all(sql `
87
88
  select
88
- ${bucket} as bucket_index,
89
+ ${index} as bucket_index,
89
90
  r.attributed_user_id,
90
91
  count(*) filter (where r.request_kind = 'user_message') as messages_sent,
91
92
  count(*) as model_steps,
@@ -94,7 +95,7 @@ export const peopleSeries = async (request) => {
94
95
  from routing_requests r
95
96
  where ${where}
96
97
  and r.attributed_user_id in (${compared})
97
- group by 1, 2
98
+ group by ${group}, 2
98
99
  order by 1, 2`),
99
100
  db.all(sql `
100
101
  select
@@ -103,7 +104,7 @@ export const peopleSeries = async (request) => {
103
104
  count(*) as conversations
104
105
  from (
105
106
  select distinct
106
- ${bucket} as bucket_index,
107
+ ${index} as bucket_index,
107
108
  r.attributed_user_id,
108
109
  r.router_id,
109
110
  r.api_key_id,
@@ -3,7 +3,7 @@ import { sql } from "./sql.js";
3
3
  export const REASONING_EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
4
4
  /* Expressions over a `routing_requests` row under the alias `r`. */
5
5
  /** The thinking level of the model and thinking pair that served the step. */
6
- export const THINKING_LEVEL = sql `(r.decision_details ->> 'selected_reasoning_effort')`;
6
+ export const THINKING_LEVEL = sql `r.selected_reasoning_effort`;
7
7
  /** The persisted conversation ID, with blank IDs as missing. */
8
8
  export const CONVERSATION_ID = sql `nullif(r.conversation_id, '')`;
9
9
  /** The step's conversation: harness context runs grouped under their stable agent session. */
@@ -1,7 +1,7 @@
1
1
  /* Tool and skill Activity: aggregates over `routing_tool_skill_events`, the
2
2
  named tool calls, skill uses, and skill file reads found in routed
3
3
  requests. Tools group by capability ID, skills by observed name. */
4
- import { bucketIndex, bucketStart, criteria } from "./filters.js";
4
+ import { bucket, bucketIndex, bucketStart, criteria } from "./filters.js";
5
5
  import { likePattern, raw, sql } from "./sql.js";
6
6
  import { formatInstant, readInstant, readInt } from "./values.js";
7
7
  import { loadDetailIdentities, loadItemIdentities, topIdentity, } from "./tool_skill_identities.js";
@@ -118,8 +118,6 @@ export async function toolSkillActivity(scope, metric, seriesIds) {
118
118
  }
119
119
  }
120
120
  const names = new Map(rows.map((row) => [row.capability_id, row.observed_name]));
121
- // Positional grouping: the bucket expression binds a value, and Postgres
122
- // does not match two bound copies of it.
123
121
  const aggregate = await db.all(sql `
124
122
  select
125
123
  ${bucketIndex(db, filters)} as bucket_index,
@@ -128,7 +126,7 @@ export async function toolSkillActivity(scope, metric, seriesIds) {
128
126
  from routing_tool_skill_events e
129
127
  join routing_requests r on r.id = e.routing_request_id
130
128
  where ${where}
131
- group by 1
129
+ group by ${bucket(db, filters)}
132
130
  order by 1`);
133
131
  return {
134
132
  from_at: formatInstant(filters.start),
@@ -163,7 +161,7 @@ async function loadSeries(scope, ids, names) {
163
161
  join routing_requests r on r.id = e.routing_request_id
164
162
  where ${scopeCriteria(scope)}
165
163
  and ${item} in (${ids})
166
- group by 1, 2
164
+ group by ${bucket(scope.db, scope.filters)}, 2
167
165
  order by 1, 2`);
168
166
  return rows.map((row) => {
169
167
  const id = String(row.capability_id);
@@ -1,17 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug } from "../protocol/input/router_model.js";
3
- import { effectiveContextWindow } from "../models/context_limits.js";
3
+ import { listedContextWindow } from "../models/context_limits.js";
4
4
  import { modelSupportsHostedWebSearch } from "../providers/model_capabilities.js";
5
- const DEFAULT_CODEX_CONTEXT_WINDOW = 128_000;
6
- function codexRouterContextWindow(router) {
7
- const windows = router.enabled_models.map((model) => {
8
- const configured = effectiveContextWindow(router.model_configs?.[model], router.allow_long_context === true);
9
- return typeof configured === "number" && Number.isFinite(configured) && configured > 0
10
- ? Math.floor(configured)
11
- : DEFAULT_CODEX_CONTEXT_WINDOW;
12
- });
13
- return windows.length > 0 ? Math.max(...windows) : DEFAULT_CODEX_CONTEXT_WINDOW;
14
- }
15
5
  function codexRouterSupportsHostedWebSearch(router) {
16
6
  return router.enabled_models.some((model) => {
17
7
  const config = router.model_configs?.[model];
@@ -118,7 +108,7 @@ function codexCatalogEntries(router, imageInputFor) {
118
108
  displayName: "Dari Routing",
119
109
  description: "Routes Codex HTTP Responses requests through the configured Dari model router.",
120
110
  priority: 0,
121
- contextWindow: codexRouterContextWindow(router),
111
+ contextWindow: listedContextWindow(router, router.enabled_models),
122
112
  hostedWebSearch: codexRouterSupportsHostedWebSearch(router),
123
113
  imageInput: router.enabled_models.some(imageInputFor),
124
114
  })]),
@@ -127,7 +117,7 @@ function codexCatalogEntries(router, imageInputFor) {
127
117
  displayName: model,
128
118
  description: `Serves ${model} directly, without routing.`,
129
119
  priority: index + 1,
130
- contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
120
+ contextWindow: listedContextWindow(router, [model]),
131
121
  hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
132
122
  imageInput: imageInputFor(model),
133
123
  ...codexThinkingChoices(router, model),
@@ -3,7 +3,8 @@ import type { ResolvedRouter } from "../types.js";
3
3
  * Muse Code fetches its model list from its base URL's origin
4
4
  * (`/muse-code/models`) before its first request. A list of only the router's
5
5
  * models lets Muse Code pick from them and start on the first; `dari/routing`
6
- * leads it only on the Autorouting plan.
6
+ * leads it only on the Autorouting plan. Muse Code compacts against the
7
+ * context limit each entry states in its `muse-code` metadata.
7
8
  */
8
- export declare function museCodeModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "autorouting_enabled" | "routing_listed">): Record<string, unknown>;
9
+ export declare function museCodeModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">): Record<string, unknown>;
9
10
  export declare function handleMuseCodeModels(request: Request, routerId: string): Promise<Response>;
@@ -1,22 +1,27 @@
1
1
  import { bearerToken } from "../http/auth.js";
2
2
  import { errorResponse } from "../http/errors.js";
3
3
  import { resolveRouter } from "../strategies/routing.js";
4
+ import { listedContextWindow } from "../models/context_limits.js";
4
5
  /**
5
6
  * Muse Code fetches its model list from its base URL's origin
6
7
  * (`/muse-code/models`) before its first request. A list of only the router's
7
8
  * models lets Muse Code pick from them and start on the first; `dari/routing`
8
- * leads it only on the Autorouting plan.
9
+ * leads it only on the Autorouting plan. Muse Code compacts against the
10
+ * context limit each entry states in its `muse-code` metadata.
9
11
  */
10
12
  export function museCodeModelsResponse(router) {
11
- const ids = [
12
- ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : ["dari/routing"]),
13
- ...router.enabled_models.map((model) => `dari/model/${model}`),
13
+ const entries = [
14
+ ...(router.autorouting_enabled === false || router.routing_listed === false
15
+ ? []
16
+ : [{ id: "dari/routing", label: "Dari Routing", models: router.enabled_models }]),
17
+ ...router.enabled_models.map((model) => ({ id: `dari/model/${model}`, label: model, models: [model] })),
14
18
  ];
15
19
  return {
16
- data: ids.map((id, index) => ({
17
- id,
18
- display_label: id === "dari/routing" ? "Dari Routing" : id.slice("dari/model/".length),
20
+ data: entries.map((entry, index) => ({
21
+ id: entry.id,
22
+ display_label: entry.label,
19
23
  is_default: index === 0,
24
+ metadata: { "muse-code": { limit: { context: listedContextWindow(router, entry.models) } } },
20
25
  })),
21
26
  };
22
27
  }
@@ -1,8 +1,11 @@
1
+ import type { ResolvedRouterModelConfig } from "../types.js";
1
2
  export type CanonicalModel = {
2
3
  id: string;
3
4
  name: string;
4
5
  maker: string;
5
6
  thinking_levels: string[];
7
+ context_window: number | null;
8
+ standard_context_limit: number | null;
6
9
  providers: string[];
7
10
  };
8
11
  /** The canonical models Dari serves, from the monorepo's router catalog. */
@@ -21,8 +24,15 @@ export type ProviderModel = {
21
24
  native_model_id: string;
22
25
  api: string;
23
26
  base_url: string | null;
27
+ context_window: number | null;
28
+ standard_context_limit: number | null;
24
29
  };
25
30
  /** How `provider` serves a model whose id names another provider, if it does. */
26
31
  export declare function providerModel(modelId: string, provider: string): ProviderModel | undefined;
27
32
  /** The providers and gateways besides the one its id names that serve a model. */
28
33
  export declare function otherModelProviders(modelId: string): string[];
34
+ /**
35
+ * A model's context limits as `provider` serves it, else as its default
36
+ * provider does; undefined for a model the catalog does not list.
37
+ */
38
+ export declare function catalogContextLimits(modelId: string, provider: string | undefined): Pick<ResolvedRouterModelConfig, "context_window" | "standard_context_limit"> | undefined;
@@ -23,3 +23,11 @@ export function providerModel(modelId, provider) {
23
23
  export function otherModelProviders(modelId) {
24
24
  return PROVIDER_MODELS.filter((row) => row.model_id === modelId).map((row) => row.provider);
25
25
  }
26
+ /**
27
+ * A model's context limits as `provider` serves it, else as its default
28
+ * provider does; undefined for a model the catalog does not list.
29
+ */
30
+ export function catalogContextLimits(modelId, provider) {
31
+ return (provider === undefined ? undefined : providerModel(modelId, provider))
32
+ ?? CANONICAL_MODELS.find((model) => model.id === modelId);
33
+ }