@mupt-ai/dari-gateway 1.0.370 → 1.0.372

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
@@ -67,6 +67,7 @@ docker run -p 8080:8080 \
67
67
  | `DARI_GATEWAY_CONFIG` | Router config file. Default `dari-gateway.yaml`. |
68
68
  | `DARI_GATEWAY_ROUTERS_DIR` | Optional. A directory of [router specs](#router-specs), read at startup: each `<id>.yaml` or `<id>.yml` is router `<id>`. |
69
69
  | `DARI_GATEWAY_DB` | SQLite database for subscriptions, Dari Link grants, model lists saved with `dari setup <agent>`, router specs saved through the API, conversation state, and Activity (each request's log row and, outside ZDR routers, its request and response bodies). Default `dari-gateway.db`. Without `DARI_GATEWAY_ENCRYPTION_KEY` it stores subscription tokens in plaintext; protect it like a secret either way. |
70
+ | `DARI_GATEWAY_RETENTION_DAYS` | How many days of Activity the database keeps, and of requests still waiting to sync to hosted Dari. Older ones are deleted at startup and every hour. Default `7`. |
70
71
  | `DARI_GATEWAY_ENCRYPTION_KEY` | Encrypts the subscription tokens, pending sign-ins, and API keys in the database: a 32-byte key in base64 (`openssl rand -base64 32`). Each value is sealed with AES-256-GCM and bound to its own row, so a copied database, or a token moved into another row, is useless without the key. Keep the key outside the database's storage and backups (a secret manager, not the same disk). To rotate, list the new key first and the old one after a comma, start the gateway once (it re-encrypts everything under the first), then drop the old one. Required for Dari Link: without it the approval page takes nobody's subscriptions or keys. Losing the key loses the stored subscriptions; users connect again. |
71
72
  | `DARI_LINK_SESSION_SECRET` | Signs the cookie that remembers the user of Dari Link's approval and connections pages. Unset, each gateway process makes its own, so a restart forgets who connected which plans. Set it on any gateway that serves Dari Link. |
72
73
  | `DARI_AUTO_ROUTING_API_KEY` | Optional. Select among a router's models with Dari Auto Routing. |
@@ -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);
@@ -41,6 +41,13 @@ export declare class ActivityStore {
41
41
  saveSessionGitEvents(write: SessionGitEvents): Promise<void>;
42
42
  /** Store a session's git events: what a step's tool output showed, or commits its git hook reported. */
43
43
  private insertGitEvents;
44
+ /**
45
+ * Delete up to `limit` requests received before `cutoff`, with their bodies
46
+ * and (by cascade) their tool and git events, and up to `limit` git events
47
+ * reported apart from any request. Returns how many went, so a caller
48
+ * clears a large backlog a batch at a time without holding the database.
49
+ */
50
+ prune(cutoff: Date, limit?: number): number;
44
51
  /** A retained body, or null. */
45
52
  readBlob(key: string): string | null;
46
53
  private modelSwitched;
@@ -44,6 +44,7 @@ create table if not exists routing_requests (
44
44
  selected_model text,
45
45
  model_switched integer not null default 0,
46
46
  selected_provider text,
47
+ selected_reasoning_effort text,
47
48
  provider_key_source text,
48
49
  blob_bucket text,
49
50
  request_blob_key text,
@@ -190,6 +191,7 @@ export class ActivityStore {
190
191
  this.db = db;
191
192
  db.exec("PRAGMA foreign_keys = ON");
192
193
  db.exec(SCHEMA);
194
+ addReasoningEffortColumn(db);
193
195
  this.reads = sqliteActivityDb(db);
194
196
  }
195
197
  /**
@@ -277,6 +279,7 @@ export class ActivityStore {
277
279
  selected_model: model,
278
280
  model_switched: this.modelSwitched(report, model, conversationId, receivedAt) ? 1 : 0,
279
281
  selected_provider: text(report.selected_provider),
282
+ selected_reasoning_effort: text(record(report.decision_details)?.selected_reasoning_effort),
280
283
  provider_key_source: text(report.provider_key_source),
281
284
  blob_bucket: wroteBodies ? SELF_HOSTED_BLOB_BUCKET : null,
282
285
  request_blob_key: keys.client_request,
@@ -359,6 +362,30 @@ export class ActivityStore {
359
362
  values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(`rge_${randomUUID().replaceAll("-", "")}`, organizationId, routingRequestId, sourceProtocol ?? "", agentSessionId, occurredAt, int(event.ordinal), text(event.kind), text(event.repository), int(event.number), text(event.title), text(event.branch), text(event.commit_sha));
360
363
  }
361
364
  }
365
+ /**
366
+ * Delete up to `limit` requests received before `cutoff`, with their bodies
367
+ * and (by cascade) their tool and git events, and up to `limit` git events
368
+ * reported apart from any request. Returns how many went, so a caller
369
+ * clears a large backlog a batch at a time without holding the database.
370
+ */
371
+ prune(cutoff, limit = 500) {
372
+ const before = canonicalInstant(instantFromDate(cutoff));
373
+ return this.db.transaction(() => {
374
+ const old = this.db.query(`select id, request_blob_key, response_blob_key, selector_prompt_blob_key, selector_output_blob_key
375
+ from routing_requests where received_at < ? limit ?`).all(before, limit);
376
+ for (const row of old) {
377
+ for (const key of [row.request_blob_key, row.response_blob_key, row.selector_prompt_blob_key, row.selector_output_blob_key]) {
378
+ if (key)
379
+ this.db.query("delete from routing_request_blobs where object_key = ?").run(key);
380
+ }
381
+ this.db.query("delete from routing_requests where id = ?").run(row.id);
382
+ }
383
+ const events = this.db.query(`delete from routing_git_events where id in (
384
+ select id from routing_git_events where routing_request_id is null and occurred_at < ? limit ?
385
+ )`).run(before, limit);
386
+ return old.length + events.changes;
387
+ })();
388
+ }
362
389
  /** A retained body, or null. */
363
390
  readBlob(key) {
364
391
  const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key);
@@ -378,6 +405,19 @@ export class ActivityStore {
378
405
  return previous !== null && previous.selected_model !== model;
379
406
  }
380
407
  }
408
+ // Databases from before the column read it from their steps' decision_details once.
409
+ function addReasoningEffortColumn(db) {
410
+ const columns = db.query("PRAGMA table_info(routing_requests)").all();
411
+ if (columns.some((column) => column.name === "selected_reasoning_effort"))
412
+ return;
413
+ db.transaction(() => {
414
+ db.run("ALTER TABLE routing_requests ADD COLUMN selected_reasoning_effort TEXT");
415
+ db.run(`update routing_requests
416
+ set selected_reasoning_effort = json_extract(decision_details, '$.selected_reasoning_effort')
417
+ where json_valid(decision_details)
418
+ and json_type(decision_details, '$.selected_reasoning_effort') = 'text'`);
419
+ })();
420
+ }
381
421
  function usageColumns(prefix, usage) {
382
422
  return {
383
423
  [`${prefix}_input_tokens`]: int(usage?.input_tokens),
@@ -27,6 +27,8 @@ export declare class HostedSync {
27
27
  stop(): void;
28
28
  /** Queue a served request's log row for hosted Activity. */
29
29
  enqueue(row: Record<string, unknown>): void;
30
+ /** Drop rows queued before `cutoff` that hosted never took. */
31
+ prune(cutoff: Date): void;
30
32
  private scheduleAccountsCheck;
31
33
  private checkAccounts;
32
34
  /** Send the queued request rows a batch at a time, unless hosted failed lately. */
@@ -69,6 +69,10 @@ export class HostedSync {
69
69
  }
70
70
  this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
71
71
  }
72
+ /** Drop rows queued before `cutoff` that hosted never took. */
73
+ prune(cutoff) {
74
+ this.db.run("DELETE FROM hosted_request_outbox WHERE queued_at < ?", [cutoff.getTime()]);
75
+ }
72
76
  scheduleAccountsCheck(delayMs) {
73
77
  this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
74
78
  this.accountsTimer.unref?.();
@@ -13,6 +13,8 @@
13
13
  * saved model lists and router specs, prefix-cache state, and Activity:
14
14
  * each request's log row and, outside ZDR routers, its request and response
15
15
  * bodies (default `dari-gateway.db`). It holds subscription tokens.
16
+ * - `DARI_GATEWAY_RETENTION_DAYS`: how many days of Activity, and of requests
17
+ * waiting to sync to hosted Dari, the database keeps (default 7).
16
18
  * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
17
19
  * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
18
20
  * rotation). Unset, they are stored as they are, and the Dari Link approval
@@ -32,6 +32,10 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
32
32
  // How often a connected gateway reads idle plans' usage, so their meters move
33
33
  // without a request here.
34
34
  const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
35
+ // How long Activity and unsent outbox rows are kept, unless
36
+ // DARI_GATEWAY_RETENTION_DAYS says otherwise, and how often old ones go.
37
+ const DEFAULT_RETENTION_DAYS = 7;
38
+ const PRUNE_INTERVAL_MS = 60 * 60_000;
35
39
  /**
36
40
  * Start a self-hosted Dari Gateway from environment variables:
37
41
  *
@@ -46,6 +50,8 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
46
50
  * saved model lists and router specs, prefix-cache state, and Activity:
47
51
  * each request's log row and, outside ZDR routers, its request and response
48
52
  * bodies (default `dari-gateway.db`). It holds subscription tokens.
53
+ * - `DARI_GATEWAY_RETENTION_DAYS`: how many days of Activity, and of requests
54
+ * waiting to sync to hosted Dari, the database keeps (default 7).
49
55
  * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
50
56
  * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
51
57
  * rotation). Unset, they are stored as they are, and the Dari Link approval
@@ -73,6 +79,7 @@ export async function startSelfHostedGateway(env = process.env) {
73
79
  if (gatewayKeys.length === 0) {
74
80
  throw new Error("Set DARI_GATEWAY_KEYS to the comma-separated keys clients authenticate with.");
75
81
  }
82
+ const retentionDays = retentionDaysFromEnv(env.DARI_GATEWAY_RETENTION_DAYS);
76
83
  const config = await loadGatewayConfig(env.DARI_GATEWAY_CONFIG?.trim() || undefined);
77
84
  const routersDir = env.DARI_GATEWAY_ROUTERS_DIR?.trim();
78
85
  const specFiles = routersDir ? await loadRouterSpecDirectory(routersDir) : undefined;
@@ -218,6 +225,24 @@ export async function startSelfHostedGateway(env = process.env) {
218
225
  if (env.DARI_SESSION_PORT_FILE)
219
226
  await Bun.write(env.DARI_SESSION_PORT_FILE, String(server.port));
220
227
  sync?.start();
228
+ // A batch at a time, so a large backlog never holds up requests.
229
+ let closed = false;
230
+ let pruned = null;
231
+ const prune = () => {
232
+ pruned ??= (async () => {
233
+ const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60_000);
234
+ sync?.prune(cutoff);
235
+ while (!closed && activity.prune(cutoff) > 0)
236
+ await Bun.sleep(0);
237
+ })().catch((error) => {
238
+ console.error("Activity retention failed", error instanceof Error ? error.message : String(error));
239
+ }).finally(() => {
240
+ pruned = null;
241
+ });
242
+ };
243
+ prune();
244
+ const pruning = setInterval(prune, PRUNE_INTERVAL_MS);
245
+ pruning.unref?.();
221
246
  const idleUsage = sync === null ? null : setInterval(() => {
222
247
  void refreshStaleUsage(subscriptions, { fetch, baseUrls });
223
248
  }, IDLE_USAGE_INTERVAL_MS);
@@ -225,6 +250,8 @@ export async function startSelfHostedGateway(env = process.env) {
225
250
  return {
226
251
  server,
227
252
  close: () => {
253
+ closed = true;
254
+ clearInterval(pruning);
228
255
  if (idleUsage !== null)
229
256
  clearInterval(idleUsage);
230
257
  sync?.stop();
@@ -232,6 +259,17 @@ export async function startSelfHostedGateway(env = process.env) {
232
259
  },
233
260
  };
234
261
  }
262
+ /** DARI_GATEWAY_RETENTION_DAYS as a whole number of days; unset, the default. */
263
+ function retentionDaysFromEnv(raw) {
264
+ const value = raw?.trim();
265
+ if (!value)
266
+ return DEFAULT_RETENTION_DAYS;
267
+ const days = Number(value);
268
+ if (!Number.isInteger(days) || days < 1) {
269
+ throw new Error(`DARI_GATEWAY_RETENTION_DAYS must be a whole number of days, at least 1; got ${JSON.stringify(raw)}.`);
270
+ }
271
+ return days;
272
+ }
235
273
  /**
236
274
  * Check each provider API key the routers use before serving: a key its
237
275
  * provider rejects fails startup, and one no check could answer is reported.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.370",
3
+ "version": "1.0.372",
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,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.370",
55
+ "@mupt-ai/dari-router": "1.0.372",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -3,6 +3,7 @@
3
3
  import type { ActivityRequest, ActivityRoute } from "./http.js";
4
4
  import {
5
5
  baseCriteria,
6
+ bucket,
6
7
  bucketIndex,
7
8
  bucketStart,
8
9
  criteria,
@@ -121,7 +122,7 @@ async function loadSeries(db: ActivityDb, filters: ActivityFilters, where: Sql):
121
122
  ) as predicted_warm_without_read
122
123
  from routing_requests r
123
124
  where ${where}
124
- group by 1, 2, 3, 4
125
+ group by ${bucket(db, filters)}, 2, 3, 4
125
126
  order by 1, 2, 3 nulls last, 4 nulls last`);
126
127
  return rows.map((row) => ({
127
128
  bucket_start: bucketStart(filters, row.bucket_index),
@@ -291,7 +292,7 @@ export const routers: ActivityRoute = async (request) => {
291
292
  from routing_requests r
292
293
  where ${where}
293
294
  and r.router_id is not null
294
- group by 1, 2
295
+ group by 1, ${bucket(db, filters)}
295
296
  order by 1, 2`),
296
297
  ]);
297
298
  const seriesByRouter = new Map<string, Array<{ bucket_start: string; messages_sent: number }>>();
@@ -638,8 +639,10 @@ export const filterOptions: ActivityRoute = async (request) => {
638
639
  where ${where}
639
640
  and r.router_id is not null
640
641
  order by m.name nulls last, r.router_id`),
642
+ // The distinct IDs first, then their names: joining every step to its
643
+ // key or person costs more than the read itself.
641
644
  db.all(sql`
642
- select distinct
645
+ select
643
646
  k.id,
644
647
  k.label,
645
648
  k.key_prefix,
@@ -647,21 +650,23 @@ export const filterOptions: ActivityRoute = async (request) => {
647
650
  u.display_name,
648
651
  u.email
649
652
  from organization_api_keys k
650
- join routing_requests r on r.api_key_id = k.id
651
653
  left join users u on u.id = coalesce(k.created_for_user_id, k.attributed_to_user_id)
652
- where ${where}
653
- and k.organization_id = ${organizationId}
654
+ where k.organization_id = ${organizationId}
655
+ and k.id in (select distinct r.api_key_id from routing_requests r where ${where})
654
656
  order by k.label, k.id`),
655
657
  db.all(sql`
656
- select distinct
657
- r.attributed_user_id,
658
+ select
659
+ u.id as attributed_user_id,
658
660
  u.display_name,
659
661
  u.email
660
- from routing_requests r
661
- join users u on u.id = r.attributed_user_id
662
- where ${where}
663
- and r.attributed_user_id is not null
664
- order by u.display_name nulls last, u.email, r.attributed_user_id`),
662
+ from users u
663
+ where u.id in (
664
+ select distinct r.attributed_user_id
665
+ from routing_requests r
666
+ where ${where}
667
+ and r.attributed_user_id is not null
668
+ )
669
+ order by u.display_name nulls last, u.email, u.id`),
665
670
  db.all(sql`
666
671
  select distinct
667
672
  ${MODEL} as model,
@@ -191,13 +191,30 @@ export function criteria(db: ActivityDb, organizationId: string, filters: Activi
191
191
  return sql`(${baseCriteria(db, organizationId, filters)} and ${dimensionCriteria(filters)})`;
192
192
  }
193
193
 
194
- /** The zero-based time bucket of a request row. */
195
- export function bucketIndex(db: ActivityDb, filters: ActivityFilters): Sql {
194
+ /**
195
+ * The time bucket of a request row, to group by. Postgres bins the timestamp
196
+ * itself, which costs far less per row than epoch arithmetic and lets it hash
197
+ * the groups instead of sorting a week of rows. The start is written into the
198
+ * SQL rather than bound, so `bucketIndex` repeats this exact expression and
199
+ * Postgres reads it from the group.
200
+ */
201
+ export function bucket(db: ActivityDb, filters: ActivityFilters): Sql {
202
+ if (db.dialect === "postgres") {
203
+ return sql`date_bin(interval '${filters.bucketSeconds} seconds', r.received_at, ${inlineStart(filters)})`;
204
+ }
196
205
  const start = timestamp(db, filters.start);
197
- const seconds = db.dialect === "postgres"
198
- ? sql`extract(epoch from (r.received_at - ${start}))`
199
- : sql`(unixepoch(r.received_at, 'subsec') - unixepoch(${start}, 'subsec'))`;
200
- return sql`floor(${seconds} / ${filters.bucketSeconds})`;
206
+ return sql`floor((unixepoch(r.received_at, 'subsec') - unixepoch(${start}, 'subsec')) / ${filters.bucketSeconds})`;
207
+ }
208
+
209
+ /** The zero-based time bucket of a request row, as a query grouped by `bucket` selects it. */
210
+ export function bucketIndex(db: ActivityDb, filters: ActivityFilters): Sql {
211
+ if (db.dialect === "sqlite") return bucket(db, filters);
212
+ return sql`floor(extract(epoch from (${bucket(db, filters)} - ${inlineStart(filters)})) / ${filters.bucketSeconds})`;
213
+ }
214
+
215
+ // A canonical instant is digits and separators, never a caller's text.
216
+ function inlineStart(filters: ActivityFilters): Sql {
217
+ return raw(`'${canonicalInstant(filters.start)}'::timestamptz`);
201
218
  }
202
219
 
203
220
  /** The start of a time bucket, as the API writes it. */
@@ -2,6 +2,7 @@
2
2
  is attributed to (`people-keys`), and people over time (`people-series`). */
3
3
 
4
4
  import {
5
+ bucket,
5
6
  bucketIndex,
6
7
  bucketStart,
7
8
  criteria,
@@ -90,17 +91,18 @@ export const peopleSeries: ActivityRoute = async (request) => {
90
91
  const filters = validatedBucketFilters(query, protocols, bucketSeconds);
91
92
  const userIds = validatedComparisonUserIds(requested);
92
93
  const where = criteria(db, organizationId, filters);
93
- const bucket = bucketIndex(db, filters);
94
+ const index = bucketIndex(db, filters);
95
+ const group = bucket(db, filters);
94
96
 
95
97
  const [activeRows, busiest] = await Promise.all([
96
98
  db.all<Row>(sql`
97
99
  select
98
- ${bucket} as bucket_index,
100
+ ${index} as bucket_index,
99
101
  count(distinct r.attributed_user_id) as active_people
100
102
  from routing_requests r
101
103
  where ${where}
102
104
  and r.attributed_user_id is not null
103
- group by 1
105
+ group by ${group}
104
106
  order by 1`),
105
107
  userIds.length > 0 ? [] : db.all<Row>(sql`
106
108
  select r.attributed_user_id
@@ -120,7 +122,7 @@ export const peopleSeries: ActivityRoute = async (request) => {
120
122
  const [points, counts] = await Promise.all([
121
123
  db.all<Row>(sql`
122
124
  select
123
- ${bucket} as bucket_index,
125
+ ${index} as bucket_index,
124
126
  r.attributed_user_id,
125
127
  count(*) filter (where r.request_kind = 'user_message') as messages_sent,
126
128
  count(*) as model_steps,
@@ -129,7 +131,7 @@ export const peopleSeries: ActivityRoute = async (request) => {
129
131
  from routing_requests r
130
132
  where ${where}
131
133
  and r.attributed_user_id in (${compared})
132
- group by 1, 2
134
+ group by ${group}, 2
133
135
  order by 1, 2`),
134
136
  db.all<Row>(sql`
135
137
  select
@@ -138,7 +140,7 @@ export const peopleSeries: ActivityRoute = async (request) => {
138
140
  count(*) as conversations
139
141
  from (
140
142
  select distinct
141
- ${bucket} as bucket_index,
143
+ ${index} as bucket_index,
142
144
  r.attributed_user_id,
143
145
  r.router_id,
144
146
  r.api_key_id,
@@ -8,7 +8,7 @@ export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
8
8
  /* Expressions over a `routing_requests` row under the alias `r`. */
9
9
 
10
10
  /** The thinking level of the model and thinking pair that served the step. */
11
- export const THINKING_LEVEL = sql`(r.decision_details ->> 'selected_reasoning_effort')`;
11
+ export const THINKING_LEVEL = sql`r.selected_reasoning_effort`;
12
12
 
13
13
  /** The persisted conversation ID, with blank IDs as missing. */
14
14
  export const CONVERSATION_ID = sql`nullif(r.conversation_id, '')`;
@@ -2,7 +2,7 @@
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
4
 
5
- import { bucketIndex, bucketStart, criteria, type ActivityFilters } from "./filters.js";
5
+ import { bucket, bucketIndex, bucketStart, criteria, type ActivityFilters } from "./filters.js";
6
6
  import { likePattern, raw, sql, type ActivityDb, type Sql } from "./sql.js";
7
7
  import { formatInstant, readInstant, readInt, type Instant } from "./values.js";
8
8
  import {
@@ -141,8 +141,6 @@ export async function toolSkillActivity(scope: Scope, metric: SeriesMetric, seri
141
141
  }
142
142
  }
143
143
  const names = new Map(rows.map((row) => [row.capability_id, row.observed_name]));
144
- // Positional grouping: the bucket expression binds a value, and Postgres
145
- // does not match two bound copies of it.
146
144
  const aggregate = await db.all(sql`
147
145
  select
148
146
  ${bucketIndex(db, filters)} as bucket_index,
@@ -151,7 +149,7 @@ export async function toolSkillActivity(scope: Scope, metric: SeriesMetric, seri
151
149
  from routing_tool_skill_events e
152
150
  join routing_requests r on r.id = e.routing_request_id
153
151
  where ${where}
154
- group by 1
152
+ group by ${bucket(db, filters)}
155
153
  order by 1`);
156
154
  return {
157
155
  from_at: formatInstant(filters.start),
@@ -186,7 +184,7 @@ async function loadSeries(scope: Scope, ids: string[], names: Map<string, string
186
184
  join routing_requests r on r.id = e.routing_request_id
187
185
  where ${scopeCriteria(scope)}
188
186
  and ${item} in (${ids})
189
- group by 1, 2
187
+ group by ${bucket(scope.db, scope.filters)}, 2
190
188
  order by 1, 2`);
191
189
  return rows.map((row) => {
192
190
  const id = String(row.capability_id);
@@ -59,6 +59,7 @@ create table if not exists routing_requests (
59
59
  selected_model text,
60
60
  model_switched integer not null default 0,
61
61
  selected_provider text,
62
+ selected_reasoning_effort text,
62
63
  provider_key_source text,
63
64
  blob_bucket text,
64
65
  request_blob_key text,
@@ -207,6 +208,7 @@ export class ActivityStore {
207
208
  constructor(private readonly db: Database) {
208
209
  db.exec("PRAGMA foreign_keys = ON");
209
210
  db.exec(SCHEMA);
211
+ addReasoningEffortColumn(db);
210
212
  this.reads = sqliteActivityDb(db);
211
213
  }
212
214
 
@@ -308,6 +310,7 @@ export class ActivityStore {
308
310
  selected_model: model,
309
311
  model_switched: this.modelSwitched(report, model, conversationId, receivedAt) ? 1 : 0,
310
312
  selected_provider: text(report.selected_provider),
313
+ selected_reasoning_effort: text(record(report.decision_details)?.selected_reasoning_effort),
311
314
  provider_key_source: text(report.provider_key_source),
312
315
  blob_bucket: wroteBodies ? SELF_HOSTED_BLOB_BUCKET : null,
313
316
  request_blob_key: keys.client_request,
@@ -415,6 +418,34 @@ export class ActivityStore {
415
418
  }
416
419
  }
417
420
 
421
+ /**
422
+ * Delete up to `limit` requests received before `cutoff`, with their bodies
423
+ * and (by cascade) their tool and git events, and up to `limit` git events
424
+ * reported apart from any request. Returns how many went, so a caller
425
+ * clears a large backlog a batch at a time without holding the database.
426
+ */
427
+ prune(cutoff: Date, limit = 500): number {
428
+ const before = canonicalInstant(instantFromDate(cutoff));
429
+ return this.db.transaction(() => {
430
+ const old = this.db.query(
431
+ `select id, request_blob_key, response_blob_key, selector_prompt_blob_key, selector_output_blob_key
432
+ from routing_requests where received_at < ? limit ?`,
433
+ ).all(before, limit) as Array<Record<string, string | null>>;
434
+ for (const row of old) {
435
+ for (const key of [row.request_blob_key, row.response_blob_key, row.selector_prompt_blob_key, row.selector_output_blob_key]) {
436
+ if (key) this.db.query("delete from routing_request_blobs where object_key = ?").run(key);
437
+ }
438
+ this.db.query("delete from routing_requests where id = ?").run(row.id!);
439
+ }
440
+ const events = this.db.query(
441
+ `delete from routing_git_events where id in (
442
+ select id from routing_git_events where routing_request_id is null and occurred_at < ? limit ?
443
+ )`,
444
+ ).run(before, limit);
445
+ return old.length + events.changes;
446
+ })();
447
+ }
448
+
418
449
  /** A retained body, or null. */
419
450
  readBlob(key: string): string | null {
420
451
  const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key) as { body: string } | null;
@@ -440,6 +471,19 @@ export class ActivityStore {
440
471
  }
441
472
  }
442
473
 
474
+ // Databases from before the column read it from their steps' decision_details once.
475
+ function addReasoningEffortColumn(db: Database): void {
476
+ const columns = db.query<{ name: string }, []>("PRAGMA table_info(routing_requests)").all();
477
+ if (columns.some((column) => column.name === "selected_reasoning_effort")) return;
478
+ db.transaction(() => {
479
+ db.run("ALTER TABLE routing_requests ADD COLUMN selected_reasoning_effort TEXT");
480
+ db.run(`update routing_requests
481
+ set selected_reasoning_effort = json_extract(decision_details, '$.selected_reasoning_effort')
482
+ where json_valid(decision_details)
483
+ and json_type(decision_details, '$.selected_reasoning_effort') = 'text'`);
484
+ })();
485
+ }
486
+
443
487
  function usageColumns(prefix: "selector" | "provider", usage: Row | null): Row {
444
488
  return {
445
489
  [`${prefix}_input_tokens`]: int(usage?.input_tokens),
@@ -80,6 +80,11 @@ export class HostedSync {
80
80
  this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
81
81
  }
82
82
 
83
+ /** Drop rows queued before `cutoff` that hosted never took. */
84
+ prune(cutoff: Date): void {
85
+ this.db.run("DELETE FROM hosted_request_outbox WHERE queued_at < ?", [cutoff.getTime()]);
86
+ }
87
+
83
88
  private scheduleAccountsCheck(delayMs: number): void {
84
89
  this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
85
90
  this.accountsTimer.unref?.();
@@ -48,6 +48,10 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
48
48
  // How often a connected gateway reads idle plans' usage, so their meters move
49
49
  // without a request here.
50
50
  const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
51
+ // How long Activity and unsent outbox rows are kept, unless
52
+ // DARI_GATEWAY_RETENTION_DAYS says otherwise, and how often old ones go.
53
+ const DEFAULT_RETENTION_DAYS = 7;
54
+ const PRUNE_INTERVAL_MS = 60 * 60_000;
51
55
 
52
56
  /**
53
57
  * Start a self-hosted Dari Gateway from environment variables:
@@ -63,6 +67,8 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
63
67
  * saved model lists and router specs, prefix-cache state, and Activity:
64
68
  * each request's log row and, outside ZDR routers, its request and response
65
69
  * bodies (default `dari-gateway.db`). It holds subscription tokens.
70
+ * - `DARI_GATEWAY_RETENTION_DAYS`: how many days of Activity, and of requests
71
+ * waiting to sync to hosted Dari, the database keeps (default 7).
66
72
  * - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
67
73
  * keys in the database (`openssl rand -base64 32`; see secret_box.ts for
68
74
  * rotation). Unset, they are stored as they are, and the Dari Link approval
@@ -90,6 +96,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
90
96
  if (gatewayKeys.length === 0) {
91
97
  throw new Error("Set DARI_GATEWAY_KEYS to the comma-separated keys clients authenticate with.");
92
98
  }
99
+ const retentionDays = retentionDaysFromEnv(env.DARI_GATEWAY_RETENTION_DAYS);
93
100
  const config = await loadGatewayConfig(env.DARI_GATEWAY_CONFIG?.trim() || undefined);
94
101
  const routersDir = env.DARI_GATEWAY_ROUTERS_DIR?.trim();
95
102
  const specFiles = routersDir ? await loadRouterSpecDirectory(routersDir) : undefined;
@@ -242,6 +249,23 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
242
249
  );
243
250
  if (env.DARI_SESSION_PORT_FILE) await Bun.write(env.DARI_SESSION_PORT_FILE, String(server.port));
244
251
  sync?.start();
252
+ // A batch at a time, so a large backlog never holds up requests.
253
+ let closed = false;
254
+ let pruned: Promise<void> | null = null;
255
+ const prune = () => {
256
+ pruned ??= (async () => {
257
+ const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60_000);
258
+ sync?.prune(cutoff);
259
+ while (!closed && activity.prune(cutoff) > 0) await Bun.sleep(0);
260
+ })().catch((error: unknown) => {
261
+ console.error("Activity retention failed", error instanceof Error ? error.message : String(error));
262
+ }).finally(() => {
263
+ pruned = null;
264
+ });
265
+ };
266
+ prune();
267
+ const pruning = setInterval(prune, PRUNE_INTERVAL_MS);
268
+ pruning.unref?.();
245
269
  const idleUsage = sync === null ? null : setInterval(() => {
246
270
  void refreshStaleUsage(subscriptions, { fetch, baseUrls });
247
271
  }, IDLE_USAGE_INTERVAL_MS);
@@ -249,6 +273,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
249
273
  return {
250
274
  server,
251
275
  close: () => {
276
+ closed = true;
277
+ clearInterval(pruning);
252
278
  if (idleUsage !== null) clearInterval(idleUsage);
253
279
  sync?.stop();
254
280
  db.close();
@@ -256,6 +282,17 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
256
282
  };
257
283
  }
258
284
 
285
+ /** DARI_GATEWAY_RETENTION_DAYS as a whole number of days; unset, the default. */
286
+ function retentionDaysFromEnv(raw: string | undefined): number {
287
+ const value = raw?.trim();
288
+ if (!value) return DEFAULT_RETENTION_DAYS;
289
+ const days = Number(value);
290
+ if (!Number.isInteger(days) || days < 1) {
291
+ throw new Error(`DARI_GATEWAY_RETENTION_DAYS must be a whole number of days, at least 1; got ${JSON.stringify(raw)}.`);
292
+ }
293
+ return days;
294
+ }
295
+
259
296
  /**
260
297
  * Check each provider API key the routers use before serving: a key its
261
298
  * provider rejects fails startup, and one no check could answer is reported.