@mupt-ai/dari-gateway 1.0.370 → 1.0.371
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 +1 -0
- package/dist/self_host/activity_store.d.ts +7 -0
- package/dist/self_host/activity_store.js +24 -0
- package/dist/self_host/hosted_sync.d.ts +2 -0
- package/dist/self_host/hosted_sync.js +4 -0
- package/dist/self_host/main.d.ts +2 -0
- package/dist/self_host/main.js +38 -0
- package/package.json +2 -2
- package/src/self_host/activity_store.ts +28 -0
- package/src/self_host/hosted_sync.ts +5 -0
- package/src/self_host/main.ts +37 -0
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. |
|
|
@@ -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;
|
|
@@ -359,6 +359,30 @@ export class ActivityStore {
|
|
|
359
359
|
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
360
|
}
|
|
361
361
|
}
|
|
362
|
+
/**
|
|
363
|
+
* Delete up to `limit` requests received before `cutoff`, with their bodies
|
|
364
|
+
* and (by cascade) their tool and git events, and up to `limit` git events
|
|
365
|
+
* reported apart from any request. Returns how many went, so a caller
|
|
366
|
+
* clears a large backlog a batch at a time without holding the database.
|
|
367
|
+
*/
|
|
368
|
+
prune(cutoff, limit = 500) {
|
|
369
|
+
const before = canonicalInstant(instantFromDate(cutoff));
|
|
370
|
+
return this.db.transaction(() => {
|
|
371
|
+
const old = this.db.query(`select id, request_blob_key, response_blob_key, selector_prompt_blob_key, selector_output_blob_key
|
|
372
|
+
from routing_requests where received_at < ? limit ?`).all(before, limit);
|
|
373
|
+
for (const row of old) {
|
|
374
|
+
for (const key of [row.request_blob_key, row.response_blob_key, row.selector_prompt_blob_key, row.selector_output_blob_key]) {
|
|
375
|
+
if (key)
|
|
376
|
+
this.db.query("delete from routing_request_blobs where object_key = ?").run(key);
|
|
377
|
+
}
|
|
378
|
+
this.db.query("delete from routing_requests where id = ?").run(row.id);
|
|
379
|
+
}
|
|
380
|
+
const events = this.db.query(`delete from routing_git_events where id in (
|
|
381
|
+
select id from routing_git_events where routing_request_id is null and occurred_at < ? limit ?
|
|
382
|
+
)`).run(before, limit);
|
|
383
|
+
return old.length + events.changes;
|
|
384
|
+
})();
|
|
385
|
+
}
|
|
362
386
|
/** A retained body, or null. */
|
|
363
387
|
readBlob(key) {
|
|
364
388
|
const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key);
|
|
@@ -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?.();
|
package/dist/self_host/main.d.ts
CHANGED
|
@@ -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
|
package/dist/self_host/main.js
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "1.0.371",
|
|
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.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.371",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -415,6 +415,34 @@ export class ActivityStore {
|
|
|
415
415
|
}
|
|
416
416
|
}
|
|
417
417
|
|
|
418
|
+
/**
|
|
419
|
+
* Delete up to `limit` requests received before `cutoff`, with their bodies
|
|
420
|
+
* and (by cascade) their tool and git events, and up to `limit` git events
|
|
421
|
+
* reported apart from any request. Returns how many went, so a caller
|
|
422
|
+
* clears a large backlog a batch at a time without holding the database.
|
|
423
|
+
*/
|
|
424
|
+
prune(cutoff: Date, limit = 500): number {
|
|
425
|
+
const before = canonicalInstant(instantFromDate(cutoff));
|
|
426
|
+
return this.db.transaction(() => {
|
|
427
|
+
const old = this.db.query(
|
|
428
|
+
`select id, request_blob_key, response_blob_key, selector_prompt_blob_key, selector_output_blob_key
|
|
429
|
+
from routing_requests where received_at < ? limit ?`,
|
|
430
|
+
).all(before, limit) as Array<Record<string, string | null>>;
|
|
431
|
+
for (const row of old) {
|
|
432
|
+
for (const key of [row.request_blob_key, row.response_blob_key, row.selector_prompt_blob_key, row.selector_output_blob_key]) {
|
|
433
|
+
if (key) this.db.query("delete from routing_request_blobs where object_key = ?").run(key);
|
|
434
|
+
}
|
|
435
|
+
this.db.query("delete from routing_requests where id = ?").run(row.id!);
|
|
436
|
+
}
|
|
437
|
+
const events = this.db.query(
|
|
438
|
+
`delete from routing_git_events where id in (
|
|
439
|
+
select id from routing_git_events where routing_request_id is null and occurred_at < ? limit ?
|
|
440
|
+
)`,
|
|
441
|
+
).run(before, limit);
|
|
442
|
+
return old.length + events.changes;
|
|
443
|
+
})();
|
|
444
|
+
}
|
|
445
|
+
|
|
418
446
|
/** A retained body, or null. */
|
|
419
447
|
readBlob(key: string): string | null {
|
|
420
448
|
const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key) as { body: string } | null;
|
|
@@ -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?.();
|
package/src/self_host/main.ts
CHANGED
|
@@ -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.
|