@mupt-ai/dari-gateway 1.0.313 → 1.0.314

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 (71) hide show
  1. package/README.md +17 -20
  2. package/dist/http/handler.js +1 -1
  3. package/dist/ingress/anthropic_messages.js +1 -1
  4. package/dist/ingress/models.js +1 -1
  5. package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
  6. package/dist/{link_client.js → link/client.js} +5 -6
  7. package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
  8. package/dist/{ingress/link.js → link/endpoints.js} +158 -62
  9. package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
  10. package/dist/link/grants.d.ts +151 -0
  11. package/dist/link/grants.js +275 -0
  12. package/dist/link/key_providers.d.ts +6 -0
  13. package/dist/link/key_providers.js +21 -0
  14. package/dist/link/self_hosted.d.ts +3 -0
  15. package/dist/link/self_hosted.js +166 -0
  16. package/dist/link/service.d.ts +85 -0
  17. package/dist/link/service.js +187 -0
  18. package/dist/link/sqlite_store.d.ts +74 -0
  19. package/dist/link/sqlite_store.js +381 -0
  20. package/dist/models/canonical_models.json +19 -0
  21. package/dist/platform/platform.d.ts +42 -47
  22. package/dist/runtime/explicit_model.js +1 -1
  23. package/dist/runtime/prepare_routed_completion.js +1 -1
  24. package/dist/self_host/main.js +2 -2
  25. package/dist/self_host/platform.js +4 -249
  26. package/dist/self_host/resolve.d.ts +2 -2
  27. package/dist/self_host/resolve.js +3 -19
  28. package/dist/self_host/stub_gateway.js +3 -3
  29. package/dist/self_host/subscriptions/http.js +2 -2
  30. package/dist/telemetry/report.js +1 -1
  31. package/package.json +2 -2
  32. package/src/http/handler.ts +1 -1
  33. package/src/ingress/anthropic_messages.ts +1 -1
  34. package/src/ingress/models.ts +1 -1
  35. package/src/{link_client.ts → link/client.ts} +11 -14
  36. package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
  37. package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
  38. package/src/link/grants.ts +436 -0
  39. package/src/link/key_providers.ts +25 -0
  40. package/src/link/self_hosted.ts +186 -0
  41. package/src/link/service.ts +281 -0
  42. package/src/link/sqlite_store.ts +512 -0
  43. package/src/models/canonical_models.json +19 -0
  44. package/src/platform/platform.ts +39 -45
  45. package/src/runtime/explicit_model.ts +1 -1
  46. package/src/runtime/prepare_routed_completion.ts +1 -1
  47. package/src/self_host/main.ts +2 -2
  48. package/src/self_host/platform.ts +5 -267
  49. package/src/self_host/resolve.ts +6 -21
  50. package/src/self_host/stub_gateway.ts +3 -3
  51. package/src/self_host/subscriptions/http.ts +2 -2
  52. package/src/telemetry/report.ts +1 -1
  53. package/dist/self_host/link_store.d.ts +0 -167
  54. package/dist/self_host/link_store.js +0 -564
  55. package/src/self_host/link_store.ts +0 -782
  56. /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
  57. /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
  58. /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
  59. /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
  60. /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
  61. /package/dist/{models/link_errors.js → link/errors.js} +0 -0
  62. /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
  63. /package/dist/{ingress/link_font.js → link/font.js} +0 -0
  64. /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
  65. /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
  66. /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
  67. /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
  68. /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
  69. /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
  70. /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
  71. /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
@@ -0,0 +1,512 @@
1
+ /**
2
+ * The self-hosted gateway's Dari Link storage, in SQLite: registered apps, the
3
+ * grants users approve for them, each grant's tokens and usage, and the API
4
+ * keys users add. A grant names the subscriptions it may use. The rules over
5
+ * these tables are link/service.ts and link/grants.ts.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import { randomUUID } from "node:crypto";
9
+
10
+ import { type SecretBox, openWithoutKey } from "../self_host/secret_box.js";
11
+ import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
12
+ import type { BudgetUse } from "./budget.js";
13
+ import {
14
+ LINK_TOKEN_RETENTION_MS,
15
+ type LinkAppRecord,
16
+ type LinkPin,
17
+ type LinkRevoker,
18
+ type LinkTokenIssue,
19
+ type LinkTokenKind,
20
+ type LinkTokenRecord,
21
+ type LinkUsageRecord,
22
+ } from "./grants.js";
23
+ import type { LinkGrantRecord, LinkStore } from "./service.js";
24
+
25
+ type AppRow = {
26
+ client_id: string;
27
+ name: string;
28
+ redirect_uris: string;
29
+ client_secret_hash: string | null;
30
+ };
31
+
32
+ type GrantRow = {
33
+ id: string;
34
+ client_id: string;
35
+ credential_ids: string;
36
+ created_at: number;
37
+ budget: string | null;
38
+ subject: string | null;
39
+ };
40
+
41
+ /** An API key a user added on the approval page, for one model provider or gateway. */
42
+ export type LinkApiKey = { id: string; subject: string; provider: string; apiKey: string };
43
+
44
+ type KeyRow = { id: string; subject: string; provider: string; api_key: string };
45
+
46
+ // Where a stored API key belongs, which its encryption is bound to.
47
+ function keyPlace(id: string): string {
48
+ return `link_api_keys:${id}:api_key`;
49
+ }
50
+
51
+ type TokenRow = {
52
+ kind: LinkTokenKind;
53
+ expires_at: number | null;
54
+ rotated_at: number | null;
55
+ model: string | null;
56
+ thinking: string | null;
57
+ pins: string | null;
58
+ tags: string | null;
59
+ grant_id: string;
60
+ client_id: string;
61
+ credential_ids: string;
62
+ budget: string | null;
63
+ revoked_at: number | null;
64
+ revoked_by: string | null;
65
+ };
66
+
67
+ const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
68
+ link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
69
+ link_grants.credential_ids, link_grants.budget, link_grants.revoked_at, link_grants.revoked_by
70
+ FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
71
+ WHERE link_tokens.token_hash = ?`;
72
+
73
+ const LIVE_GRANTS = `SELECT link_grants.id, link_grants.client_id, link_grants.credential_ids, link_grants.created_at,
74
+ link_grants.budget, link_grants.subject, link_apps.name AS app_name
75
+ FROM link_grants JOIN link_apps ON link_apps.client_id = link_grants.client_id
76
+ WHERE link_grants.revoked_at IS NULL`;
77
+
78
+ export class SqliteLinkStore implements LinkStore {
79
+ constructor(private readonly db: Database, private readonly box: SecretBox | null = null) {
80
+ db.run(`CREATE TABLE IF NOT EXISTS link_apps (
81
+ client_id TEXT PRIMARY KEY,
82
+ name TEXT NOT NULL,
83
+ redirect_uris TEXT NOT NULL,
84
+ client_secret_hash TEXT,
85
+ created_at INTEGER NOT NULL
86
+ )`);
87
+ db.run(`CREATE TABLE IF NOT EXISTS link_grants (
88
+ id TEXT PRIMARY KEY,
89
+ client_id TEXT NOT NULL REFERENCES link_apps (client_id),
90
+ credential_ids TEXT NOT NULL,
91
+ code_hash TEXT UNIQUE,
92
+ code_challenge TEXT,
93
+ redirect_uri TEXT,
94
+ code_expires_at INTEGER,
95
+ created_at INTEGER NOT NULL,
96
+ revoked_at INTEGER,
97
+ revoked_by TEXT
98
+ )`);
99
+ db.run(`CREATE TABLE IF NOT EXISTS link_tokens (
100
+ token_hash TEXT PRIMARY KEY,
101
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
102
+ kind TEXT NOT NULL,
103
+ expires_at INTEGER,
104
+ rotated_at INTEGER,
105
+ model TEXT,
106
+ thinking TEXT,
107
+ tags TEXT,
108
+ created_at INTEGER NOT NULL
109
+ )`);
110
+ db.run("CREATE INDEX IF NOT EXISTS link_tokens_grant_id ON link_tokens (grant_id)");
111
+ db.run(`CREATE TABLE IF NOT EXISTS link_usage (
112
+ request_id TEXT PRIMARY KEY,
113
+ grant_id TEXT NOT NULL REFERENCES link_grants (id),
114
+ received_at INTEGER NOT NULL,
115
+ model TEXT,
116
+ thinking TEXT,
117
+ tags TEXT NOT NULL,
118
+ input_tokens INTEGER NOT NULL,
119
+ output_tokens INTEGER NOT NULL,
120
+ cache_read_tokens INTEGER NOT NULL,
121
+ cache_write_tokens INTEGER NOT NULL
122
+ )`);
123
+ db.run("CREATE INDEX IF NOT EXISTS link_usage_grant_received ON link_usage (grant_id, received_at)");
124
+ // Added after link_grants shipped: a gateway database from before gains it.
125
+ const grantColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_grants)").all();
126
+ if (!grantColumns.some((column) => column.name === "budget")) db.run("ALTER TABLE link_grants ADD COLUMN budget TEXT");
127
+ // The user who approved the grant on the approval page.
128
+ if (!grantColumns.some((column) => column.name === "subject")) db.run("ALTER TABLE link_grants ADD COLUMN subject TEXT");
129
+ const tokenColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_tokens)").all();
130
+ if (!tokenColumns.some((column) => column.name === "pins")) db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
131
+ const usageColumns = db.query<{ name: string }, []>("PRAGMA table_info(link_usage)").all();
132
+ if (!usageColumns.some((column) => column.name === "status")) db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
133
+ // API keys users added on the approval page: one per user and provider.
134
+ db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
135
+ id TEXT PRIMARY KEY,
136
+ subject TEXT NOT NULL,
137
+ provider TEXT NOT NULL,
138
+ api_key TEXT NOT NULL,
139
+ created_at INTEGER NOT NULL,
140
+ UNIQUE (subject, provider)
141
+ )`);
142
+ this.encryptStored();
143
+ }
144
+
145
+ // Seal API keys stored before encryption was turned on, or under a key
146
+ // that no longer encrypts.
147
+ private encryptStored(): void {
148
+ const box = this.box;
149
+ if (box === null) return;
150
+ this.db.transaction(() => {
151
+ for (const row of this.db.query<KeyRow, []>("SELECT * FROM link_api_keys").all()) {
152
+ if (box.current(row.api_key)) continue;
153
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [
154
+ box.seal(box.adopt(row.api_key, keyPlace(row.id)), keyPlace(row.id)),
155
+ row.id,
156
+ ]);
157
+ }
158
+ })();
159
+ }
160
+
161
+ private seal(value: string, place: string): string {
162
+ return this.box === null ? value : this.box.seal(value, place);
163
+ }
164
+
165
+ private key(row: KeyRow): LinkApiKey {
166
+ const stored = row.api_key;
167
+ return {
168
+ id: row.id,
169
+ subject: row.subject,
170
+ provider: row.provider,
171
+ apiKey: this.box === null ? openWithoutKey(stored) : this.box.open(stored, keyPlace(row.id)),
172
+ };
173
+ }
174
+
175
+ /** Store a user's API key for a provider, replacing their earlier one for it. */
176
+ addKey(subject: string, provider: string, apiKey: string, now = new Date()): LinkApiKey {
177
+ const existing = this.keys(subject).find((key) => key.provider === provider);
178
+ if (existing !== undefined) {
179
+ this.db.run("UPDATE link_api_keys SET api_key = ? WHERE id = ?", [this.seal(apiKey, keyPlace(existing.id)), existing.id]);
180
+ return { ...existing, apiKey };
181
+ }
182
+ const id = `key_${randomUUID().replaceAll("-", "")}`;
183
+ this.db.run(
184
+ "INSERT INTO link_api_keys (id, subject, provider, api_key, created_at) VALUES (?, ?, ?, ?, ?)",
185
+ [id, subject, provider, this.seal(apiKey, keyPlace(id)), now.getTime()],
186
+ );
187
+ return { id, subject, provider, apiKey };
188
+ }
189
+
190
+ /** Delete a user's API key; false when they have none by that id. */
191
+ removeKey(subject: string, id: string): boolean {
192
+ return this.db.run("DELETE FROM link_api_keys WHERE id = ? AND subject = ?", [id, subject]).changes > 0;
193
+ }
194
+
195
+ /** The API keys a user added, oldest first. */
196
+ keys(subject: string): LinkApiKey[] {
197
+ return this.db
198
+ .query<KeyRow, [string]>("SELECT * FROM link_api_keys WHERE subject = ? ORDER BY created_at, rowid")
199
+ .all(subject)
200
+ .map((row) => this.key(row));
201
+ }
202
+
203
+ /** The API keys with these ids, whoever added them. */
204
+ keysWithIds(ids: ReadonlySet<string>): LinkApiKey[] {
205
+ return this.db
206
+ .query<KeyRow, []>("SELECT * FROM link_api_keys ORDER BY created_at, rowid")
207
+ .all()
208
+ .filter((row) => ids.has(row.id))
209
+ .map((row) => this.key(row));
210
+ }
211
+
212
+ budgetUses(grantId: string, since: number): BudgetUse[] {
213
+ return this.db
214
+ .query<{ received_at: number; tokens: number }, [string, number]>(
215
+ `SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
216
+ FROM link_usage WHERE grant_id = ? AND received_at > ?`,
217
+ )
218
+ .all(grantId, since)
219
+ .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
220
+ }
221
+
222
+ /** Record what one of a grant's requests used; a repeated request id is ignored. */
223
+ recordUsage(entry: LinkUsageEntry): void {
224
+ this.db.run(
225
+ `INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
226
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
227
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
228
+ [
229
+ entry.requestId,
230
+ entry.grantId,
231
+ entry.receivedAt.getTime(),
232
+ entry.model,
233
+ entry.thinking,
234
+ JSON.stringify(entry.tags),
235
+ entry.inputTokens,
236
+ entry.outputTokens,
237
+ entry.cacheReadTokens,
238
+ entry.cacheWriteTokens,
239
+ entry.status,
240
+ ],
241
+ );
242
+ }
243
+
244
+ usageRecords(grantId: string, query: Pick<LinkUsageQuery, "since" | "until" | "requestId">): LinkUsageRecord[] {
245
+ const rows = query.requestId !== undefined
246
+ ? this.db
247
+ .query<UsageRow, [string, string]>("SELECT * FROM link_usage WHERE grant_id = ? AND request_id = ?")
248
+ .all(grantId, query.requestId)
249
+ : this.db
250
+ .query<UsageRow, [string, number, number]>(
251
+ `SELECT * FROM link_usage WHERE grant_id = ? AND received_at >= ? AND received_at < ?`,
252
+ )
253
+ .all(grantId, query.since?.getTime() ?? 0, query.until?.getTime() ?? Number.MAX_SAFE_INTEGER);
254
+ return rows.map((row) => ({
255
+ status: row.status,
256
+ model: row.model,
257
+ thinking: row.thinking,
258
+ tags: JSON.parse(row.tags) as Record<string, string>,
259
+ inputTokens: row.input_tokens,
260
+ outputTokens: row.output_tokens,
261
+ cacheReadTokens: row.cache_read_tokens,
262
+ cacheWriteTokens: row.cache_write_tokens,
263
+ }));
264
+ }
265
+
266
+ addApp(app: LinkAppRecord, now = new Date()): void {
267
+ this.db.run(
268
+ "INSERT INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, ?, ?, ?)",
269
+ [app.clientId, app.name, JSON.stringify(app.redirectUris), app.clientSecretHash, now.getTime()],
270
+ );
271
+ }
272
+
273
+ appRecord(clientId: string): LinkAppRecord | null {
274
+ const row = this.db.query<AppRow, [string]>("SELECT * FROM link_apps WHERE client_id = ?").get(clientId);
275
+ return row === null
276
+ ? null
277
+ : {
278
+ clientId: row.client_id,
279
+ name: row.name,
280
+ redirectUris: JSON.parse(row.redirect_uris) as string[],
281
+ confidential: row.client_secret_hash !== null,
282
+ clientSecretHash: row.client_secret_hash,
283
+ };
284
+ }
285
+
286
+ saveGrant(request: Parameters<LinkStore["saveGrant"]>[0]): string | null {
287
+ const budget = request.budget.length === 0 ? null : JSON.stringify(request.budget);
288
+ if (request.grantId !== undefined) {
289
+ const updated = this.db.run(
290
+ `UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
291
+ code_expires_at = ?
292
+ WHERE id = ? AND client_id = ? AND subject = ? AND revoked_at IS NULL`,
293
+ [
294
+ JSON.stringify(request.credentialIds),
295
+ budget,
296
+ request.codeHash,
297
+ request.codeChallenge,
298
+ request.redirectUri,
299
+ request.codeExpiresAt,
300
+ request.grantId,
301
+ request.clientId,
302
+ request.subject,
303
+ ],
304
+ ).changes;
305
+ return updated === 0 ? null : request.grantId;
306
+ }
307
+ const id = `lgr_${randomUUID().replaceAll("-", "")}`;
308
+ this.db.run(
309
+ `INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
310
+ code_expires_at, created_at, budget, subject)
311
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
312
+ [
313
+ id,
314
+ request.clientId,
315
+ JSON.stringify(request.credentialIds),
316
+ request.codeHash,
317
+ request.codeChallenge,
318
+ request.redirectUri,
319
+ request.codeExpiresAt,
320
+ request.now,
321
+ budget,
322
+ request.subject,
323
+ ],
324
+ );
325
+ return id;
326
+ }
327
+
328
+ updateGrant(grantId: string, change: { credentialIds?: string[]; budget?: LinkBudget[] }): boolean {
329
+ return this.db.transaction(() => {
330
+ const changed = this.grant(grantId) !== null;
331
+ if (changed && change.credentialIds !== undefined) {
332
+ this.db.run("UPDATE link_grants SET credential_ids = ? WHERE id = ?", [JSON.stringify(change.credentialIds), grantId]);
333
+ }
334
+ if (changed && change.budget !== undefined) {
335
+ this.db.run("UPDATE link_grants SET budget = ? WHERE id = ?", [
336
+ change.budget.length === 0 ? null : JSON.stringify(change.budget),
337
+ grantId,
338
+ ]);
339
+ }
340
+ return changed;
341
+ })();
342
+ }
343
+
344
+ grants(subject: string | null): LinkGrantRecord[] {
345
+ const order = " ORDER BY link_grants.created_at, link_grants.id";
346
+ const rows = subject === null
347
+ ? this.db.query<GrantRow & { app_name: string }, []>(LIVE_GRANTS + order).all()
348
+ : this.db.query<GrantRow & { app_name: string }, [string]>(`${LIVE_GRANTS} AND link_grants.subject = ?${order}`).all(subject);
349
+ return rows.map(grantRecord);
350
+ }
351
+
352
+ grant(grantId: string): LinkGrantRecord | null {
353
+ const row = this.db.query<GrantRow & { app_name: string }, [string]>(`${LIVE_GRANTS} AND link_grants.id = ?`).get(grantId);
354
+ return row === null ? null : grantRecord(row);
355
+ }
356
+
357
+ redeemCode(request: Parameters<LinkStore["redeemCode"]>[0]): string | null {
358
+ return this.db.transaction(() => {
359
+ const row = this.db
360
+ .query<{ id: string }, [string, string, string, string, number]>(
361
+ `SELECT id FROM link_grants WHERE code_hash = ? AND client_id = ? AND redirect_uri = ? AND code_challenge = ?
362
+ AND code_expires_at > ? AND revoked_at IS NULL`,
363
+ )
364
+ .get(request.codeHash, request.clientId, request.redirectUri, request.codeChallenge, request.now);
365
+ if (row === null) return null;
366
+ this.db.run(
367
+ "UPDATE link_grants SET code_hash = NULL, code_challenge = NULL, code_expires_at = NULL WHERE id = ?",
368
+ [row.id],
369
+ );
370
+ this.insertTokens(row.id, request.tokens, request.now);
371
+ return row.id;
372
+ })();
373
+ }
374
+
375
+ tokenRecord(tokenHash: string): LinkTokenRecord | null {
376
+ const row = this.db.query<TokenRow, [string]>(TOKEN_WITH_GRANT).get(tokenHash);
377
+ return row === null
378
+ ? null
379
+ : {
380
+ kind: row.kind,
381
+ expiresAt: row.expires_at,
382
+ rotatedAt: row.rotated_at,
383
+ pins: childPins(row),
384
+ tags: row.tags === null ? null : JSON.parse(row.tags) as Record<string, string>,
385
+ grantId: row.grant_id,
386
+ clientId: row.client_id,
387
+ credentialIds: parseIds(row.credential_ids),
388
+ budget: parseBudget(row.budget),
389
+ revokedAt: row.revoked_at,
390
+ revokedBy: row.revoked_by,
391
+ usable: true,
392
+ };
393
+ }
394
+
395
+ issueTokens(request: { grantId: string; tokens: LinkTokenIssue[]; rotate?: string; now: number }): "ok" | "race" | "revoked" {
396
+ return this.db.transaction((): "ok" | "race" | "revoked" => {
397
+ const live = this.db
398
+ .query<{ id: string }, [string]>("SELECT id FROM link_grants WHERE id = ? AND revoked_at IS NULL")
399
+ .get(request.grantId);
400
+ if (live === null) return "revoked";
401
+ if (request.rotate !== undefined) {
402
+ const rotated = this.db.run(
403
+ "UPDATE link_tokens SET rotated_at = ? WHERE token_hash = ? AND rotated_at IS NULL",
404
+ [request.now, request.rotate],
405
+ ).changes;
406
+ if (rotated === 0) return "race";
407
+ }
408
+ const stale = request.now - LINK_TOKEN_RETENTION_MS;
409
+ // Rotated refresh tokens stay while the grant lives (revoking it deletes
410
+ // them): presenting one again is how a stolen refresh token is caught.
411
+ this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
412
+ this.insertTokens(request.grantId, request.tokens, request.now);
413
+ return "ok";
414
+ })();
415
+ }
416
+
417
+ private insertTokens(grantId: string, tokens: LinkTokenIssue[], now: number): void {
418
+ for (const token of tokens) {
419
+ this.db.run(
420
+ `INSERT INTO link_tokens (token_hash, grant_id, kind, expires_at, pins, tags, created_at)
421
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
422
+ [
423
+ token.tokenHash,
424
+ grantId,
425
+ token.kind,
426
+ token.expiresAt,
427
+ token.pins === undefined ? null : JSON.stringify(token.pins),
428
+ token.tags === undefined ? null : JSON.stringify(token.tags),
429
+ now,
430
+ ],
431
+ );
432
+ }
433
+ }
434
+
435
+ deleteToken(tokenHash: string): void {
436
+ this.db.run("DELETE FROM link_tokens WHERE token_hash = ?", [tokenHash]);
437
+ }
438
+
439
+ /** The subscriptions a grant may use; empty once it is revoked. */
440
+ credentialIds(grantId: string): ReadonlySet<string> {
441
+ const row = this.db
442
+ .query<GrantRow, [string]>("SELECT * FROM link_grants WHERE id = ? AND revoked_at IS NULL")
443
+ .get(grantId);
444
+ return new Set(row === null ? [] : parseIds(row.credential_ids));
445
+ }
446
+
447
+ revokeGrant(grantId: string, by: LinkRevoker, now = Date.now()): boolean {
448
+ const result = this.db.run(
449
+ "UPDATE link_grants SET revoked_at = ?, revoked_by = ?, code_hash = NULL WHERE id = ? AND revoked_at IS NULL",
450
+ [now, by, grantId],
451
+ );
452
+ if (result.changes === 0) return false;
453
+ this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND kind = 'refresh'", [grantId]);
454
+ return true;
455
+ }
456
+ }
457
+
458
+ export type LinkUsageEntry = {
459
+ requestId: string;
460
+ grantId: string;
461
+ receivedAt: Date;
462
+ model: string | null;
463
+ thinking: string | null;
464
+ tags: Record<string, string>;
465
+ inputTokens: number;
466
+ outputTokens: number;
467
+ cacheReadTokens: number;
468
+ cacheWriteTokens: number;
469
+ // The request's outcome, as the request record's `status`.
470
+ status: string;
471
+ };
472
+
473
+ type UsageRow = {
474
+ status: string | null;
475
+ model: string | null;
476
+ thinking: string | null;
477
+ tags: string;
478
+ input_tokens: number;
479
+ output_tokens: number;
480
+ cache_read_tokens: number;
481
+ cache_write_tokens: number;
482
+ };
483
+
484
+ // A child token's models. One minted before `pins` existed kept its one model
485
+ // in `model` and `thinking`.
486
+ function childPins(row: TokenRow): LinkPin[] | null {
487
+ if (row.kind !== "child") return null;
488
+ if (row.pins !== null) return JSON.parse(row.pins) as LinkPin[];
489
+ return row.model === null ? [] : [{ model: row.model, thinking: row.thinking }];
490
+ }
491
+
492
+ function grantRecord(row: GrantRow & { app_name: string }): LinkGrantRecord {
493
+ return {
494
+ id: row.id,
495
+ clientId: row.client_id,
496
+ appName: row.app_name,
497
+ subject: row.subject,
498
+ credentialIds: parseIds(row.credential_ids),
499
+ createdAt: new Date(row.created_at).toISOString(),
500
+ budget: parseBudget(row.budget),
501
+ };
502
+ }
503
+
504
+ function parseIds(value: string): string[] {
505
+ return JSON.parse(value) as string[];
506
+ }
507
+
508
+ // An entry without maxTokens (a share-of-plan limit from before token caps) is no limit.
509
+ function parseBudget(value: string | null): LinkBudget[] {
510
+ const entries = value === null ? [] : JSON.parse(value) as Array<Partial<LinkBudget>>;
511
+ return entries.filter((entry): entry is LinkBudget => typeof entry.maxTokens === "number");
512
+ }
@@ -231,6 +231,16 @@
231
231
  "max"
232
232
  ]
233
233
  },
234
+ {
235
+ "id": "meta/muse-spark-open",
236
+ "name": "Muse Spark Open",
237
+ "thinking_levels": [
238
+ "low",
239
+ "medium",
240
+ "high",
241
+ "xhigh"
242
+ ]
243
+ },
234
244
  {
235
245
  "id": "meta/muse-spark-1.2",
236
246
  "name": "Muse Spark 1.2",
@@ -251,6 +261,15 @@
251
261
  "max"
252
262
  ]
253
263
  },
264
+ {
265
+ "id": "moonshotai/Kimi-K3.1-Pro",
266
+ "name": "Kimi K3.1 Pro",
267
+ "thinking_levels": [
268
+ "low",
269
+ "high",
270
+ "max"
271
+ ]
272
+ },
254
273
  {
255
274
  "id": "zai-org/GLM-5.3",
256
275
  "name": "GLM 5.3",