@mupt-ai/dari-gateway 1.0.334 → 1.0.336
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/dist/activity/conversation_detail.js +4 -1
- package/dist/activity/conversations.js +2 -1
- package/dist/activity/http.d.ts +28 -3
- package/dist/activity/http.js +15 -10
- package/dist/activity/imports.d.ts +29 -0
- package/dist/activity/imports.js +230 -0
- package/dist/activity/pull_requests.d.ts +29 -0
- package/dist/activity/pull_requests.js +295 -0
- package/dist/activity/routes.d.ts +1 -1
- package/dist/activity/routes.js +7 -1
- package/dist/http/handler.d.ts +3 -2
- package/dist/http/handler.js +8 -2
- package/dist/ingress/git_events.d.ts +2 -0
- package/dist/ingress/git_events.js +143 -0
- package/dist/link/budget.d.ts +27 -2
- package/dist/link/budget.js +63 -1
- package/dist/link/endpoints.js +179 -36
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.js +11 -2
- package/dist/link/grants.d.ts +6 -5
- package/dist/link/grants.js +11 -9
- package/dist/link/service.d.ts +27 -6
- package/dist/link/service.js +145 -21
- package/dist/link/sqlite_store.d.ts +7 -2
- package/dist/link/sqlite_store.js +57 -6
- package/dist/platform/platform.d.ts +72 -3
- package/dist/protocol/input/router_model.d.ts +1 -0
- package/dist/protocol/input/router_model.js +6 -2
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +3 -0
- package/dist/self_host/activity_store.d.ts +15 -2
- package/dist/self_host/activity_store.js +60 -7
- package/dist/self_host/platform.js +6 -0
- package/dist/self_host/resolve.d.ts +4 -5
- package/dist/self_host/resolve.js +20 -22
- package/dist/telemetry/report.js +21 -2
- package/dist/telemetry/tools/git_events.d.ts +36 -0
- package/dist/telemetry/tools/git_events.js +109 -0
- package/dist/telemetry/tools/observations.d.ts +8 -1
- package/dist/telemetry/tools/observations.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +4 -1
- package/src/activity/conversations.ts +3 -2
- package/src/activity/http.ts +43 -12
- package/src/activity/imports.ts +278 -0
- package/src/activity/pull_requests.ts +342 -0
- package/src/activity/routes.ts +8 -2
- package/src/http/handler.ts +8 -2
- package/src/ingress/git_events.ts +145 -0
- package/src/link/budget.ts +80 -4
- package/src/link/endpoints.ts +171 -20
- package/src/link/errors.ts +12 -2
- package/src/link/grants.ts +22 -12
- package/src/link/service.ts +187 -24
- package/src/link/sqlite_store.ts +73 -10
- package/src/platform/platform.ts +57 -4
- package/src/protocol/input/router_model.ts +6 -2
- package/src/runtime/runtime_reporter.ts +5 -0
- package/src/self_host/activity_store.ts +79 -8
- package/src/self_host/platform.ts +6 -0
- package/src/self_host/resolve.ts +20 -25
- package/src/telemetry/report.ts +21 -2
- package/src/telemetry/tools/git_events.ts +125 -0
- package/src/telemetry/tools/observations.ts +1 -1
- package/src/types.ts +3 -0
package/dist/link/service.js
CHANGED
|
@@ -2,24 +2,74 @@
|
|
|
2
2
|
storage (`LinkStore`: the self-hosted gateway's SQLite database, hosted
|
|
3
3
|
Dari's control plane) and its users (`LinkUsers`: who a key or a page
|
|
4
4
|
visitor is, and where their plans and API keys live); `linkPlatform` makes
|
|
5
|
-
the rest: approving grants, managing them, budgets
|
|
6
|
-
(grants.ts).
|
|
5
|
+
the rest: approving grants, managing them, budgets and spend limits,
|
|
6
|
+
personal endpoints, and the token protocol (grants.ts).
|
|
7
|
+
|
|
8
|
+
A personal endpoint is a grant the user makes for themselves, on the plans
|
|
9
|
+
and keys they choose, called with a key that does not expire from any app
|
|
10
|
+
that takes the user's own key. Its grants belong to one built-in app,
|
|
11
|
+
`LINK_PERSONAL_CLIENT_ID`, which nothing can sign in to. */
|
|
7
12
|
import { randomUUID } from "node:crypto";
|
|
8
13
|
import { HttpError } from "../http/errors.js";
|
|
9
|
-
import {
|
|
10
|
-
import { budgetExhausted, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
11
|
-
import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, } from "./grants.js";
|
|
14
|
+
import { budgetStandings, grantSpend, nextMonthStart, overBudgetUntil, usesSince, } from "./budget.js";
|
|
15
|
+
import { budgetExhausted, limitsReached, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
16
|
+
import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, LINK_TOKEN_RETENTION_MS, TOKEN_PREFIX, } from "./grants.js";
|
|
17
|
+
/** The built-in app every personal endpoint's grant belongs to. */
|
|
18
|
+
export const LINK_PERSONAL_CLIENT_ID = "lnk_personal";
|
|
12
19
|
export function linkPlatform(store, users) {
|
|
13
20
|
const protocol = linkGrants(store);
|
|
14
|
-
const standings = async (grant, now = new Date()) => (await linkBudgetStandings(store, grant, now)).map((standing) => ({
|
|
15
|
-
...standing,
|
|
16
|
-
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
17
|
-
}));
|
|
18
21
|
// A live grant of this user's; null for anyone else's.
|
|
19
22
|
const ownGrant = async (subject, grantId) => {
|
|
20
23
|
const grant = await store.grant(grantId);
|
|
21
24
|
return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
|
|
22
25
|
};
|
|
26
|
+
// A grant's budget windows and each granted plan or key's spend this month.
|
|
27
|
+
const standings = async (grant, now = new Date()) => {
|
|
28
|
+
const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
|
|
29
|
+
return {
|
|
30
|
+
budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
|
|
31
|
+
...standing,
|
|
32
|
+
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
33
|
+
})),
|
|
34
|
+
spend: grantSpend(grant.credentialIds, grant.limits, uses, now),
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
const publicGrant = ({ subject: _, ...grant }) => ({
|
|
38
|
+
...grant,
|
|
39
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
40
|
+
});
|
|
41
|
+
const managedGrant = async (grant) => ({
|
|
42
|
+
...publicGrant(grant),
|
|
43
|
+
spend: (await standings(grant)).spend,
|
|
44
|
+
});
|
|
45
|
+
// Plans and keys the user can grant, and limits only on them.
|
|
46
|
+
const ownedCredentials = async (subject, credentialIds, limits = []) => {
|
|
47
|
+
const owned = new Set((await users.plans(subject)).map((plan) => plan.id));
|
|
48
|
+
if (credentialIds.length === 0 || !credentialIds.every((id) => owned.has(id))) {
|
|
49
|
+
throw new HttpError(400, "Choose one or more of your connected plans or API keys.", "invalid_request");
|
|
50
|
+
}
|
|
51
|
+
if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
|
|
52
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
53
|
+
}
|
|
54
|
+
return [...new Set(credentialIds)].sort();
|
|
55
|
+
};
|
|
56
|
+
// The one user a key acts for: endpoints are personal, so an operator key
|
|
57
|
+
// that manages everyone cannot make one.
|
|
58
|
+
const endpointOwner = async (apiKey) => {
|
|
59
|
+
const subject = await users.manager(apiKey);
|
|
60
|
+
if (subject === null) {
|
|
61
|
+
throw new HttpError(403, "Use your personal key: an endpoint serves one user's plans.", "permission_denied");
|
|
62
|
+
}
|
|
63
|
+
return subject;
|
|
64
|
+
};
|
|
65
|
+
const ownEndpoint = async (subject, grantId) => {
|
|
66
|
+
const grant = await ownGrant(subject, grantId);
|
|
67
|
+
return grant !== null && grant.clientId === LINK_PERSONAL_CLIENT_ID ? grant : null;
|
|
68
|
+
};
|
|
69
|
+
const newKey = () => {
|
|
70
|
+
const key = linkSecret(TOKEN_PREFIX.key);
|
|
71
|
+
return { key, issue: { tokenHash: linkHash(key), kind: "key", expiresAt: null } };
|
|
72
|
+
};
|
|
23
73
|
const revoke = (grantId) => store.revokeGrant(grantId, "user", Date.now());
|
|
24
74
|
return {
|
|
25
75
|
httpRedirectHosts: users.httpRedirectHosts ?? [],
|
|
@@ -91,8 +141,9 @@ export function linkPlatform(store, users) {
|
|
|
91
141
|
id: grant.id,
|
|
92
142
|
clientId: grant.clientId,
|
|
93
143
|
appName: grant.appName,
|
|
144
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
94
145
|
createdAt: grant.createdAt,
|
|
95
|
-
|
|
146
|
+
...(await standings(grant)),
|
|
96
147
|
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
97
148
|
usage,
|
|
98
149
|
};
|
|
@@ -104,6 +155,13 @@ export function linkPlatform(store, users) {
|
|
|
104
155
|
async setBudget(subject, grantId, budget) {
|
|
105
156
|
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
106
157
|
},
|
|
158
|
+
async setLimits(subject, grantId, limits) {
|
|
159
|
+
const grant = await ownGrant(subject, grantId);
|
|
160
|
+
if (grant === null)
|
|
161
|
+
return false;
|
|
162
|
+
await ownedCredentials(subject, grant.credentialIds, limits);
|
|
163
|
+
return await store.updateGrant(grantId, { limits });
|
|
164
|
+
},
|
|
107
165
|
},
|
|
108
166
|
async registerApp({ apiKey, name, redirectUris, confidential }) {
|
|
109
167
|
if (apiKey === undefined && !users.openRegistration) {
|
|
@@ -135,8 +193,9 @@ export function linkPlatform(store, users) {
|
|
|
135
193
|
id: grant.id,
|
|
136
194
|
clientId: grant.clientId,
|
|
137
195
|
appName: grant.appName,
|
|
196
|
+
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
138
197
|
createdAt: grant.createdAt,
|
|
139
|
-
|
|
198
|
+
...(await standings(grant)),
|
|
140
199
|
subscriptions: await users.plansWithIds(grant.credentialIds),
|
|
141
200
|
};
|
|
142
201
|
},
|
|
@@ -148,7 +207,60 @@ export function linkPlatform(store, users) {
|
|
|
148
207
|
},
|
|
149
208
|
async grants(apiKey) {
|
|
150
209
|
const subject = await users.manager(apiKey);
|
|
151
|
-
return (await store.grants(subject)).map(
|
|
210
|
+
return await Promise.all((await store.grants(subject)).map(managedGrant));
|
|
211
|
+
},
|
|
212
|
+
async plans(apiKey) {
|
|
213
|
+
return await users.plans(await endpointOwner(apiKey));
|
|
214
|
+
},
|
|
215
|
+
async createEndpoint({ apiKey, name, credentialIds, limits }) {
|
|
216
|
+
const subject = await endpointOwner(apiKey);
|
|
217
|
+
const granted = await ownedCredentials(subject, credentialIds, limits);
|
|
218
|
+
const { key, issue } = newKey();
|
|
219
|
+
const grantId = await store.createEndpoint({
|
|
220
|
+
subject,
|
|
221
|
+
name: endpointName(name),
|
|
222
|
+
credentialIds: granted,
|
|
223
|
+
limits,
|
|
224
|
+
key: issue,
|
|
225
|
+
now: Date.now(),
|
|
226
|
+
});
|
|
227
|
+
const grant = await store.grant(grantId);
|
|
228
|
+
if (grant === null)
|
|
229
|
+
throw new Error("A new endpoint's grant was not stored.");
|
|
230
|
+
return { grant: await managedGrant(grant), key };
|
|
231
|
+
},
|
|
232
|
+
async updateEndpoint({ apiKey, grantId, name, credentialIds }) {
|
|
233
|
+
const subject = await endpointOwner(apiKey);
|
|
234
|
+
const grant = await ownEndpoint(subject, grantId);
|
|
235
|
+
if (grant === null)
|
|
236
|
+
return false;
|
|
237
|
+
const granted = credentialIds === undefined ? undefined : await ownedCredentials(subject, credentialIds);
|
|
238
|
+
return await store.updateGrant(grantId, {
|
|
239
|
+
...(name === undefined ? {} : { name: endpointName(name) }),
|
|
240
|
+
...(granted === undefined
|
|
241
|
+
? {}
|
|
242
|
+
// A plan or key the endpoint no longer shares keeps no limit.
|
|
243
|
+
: { credentialIds: granted, limits: grant.limits.filter((limit) => granted.includes(limit.credentialId)) }),
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
async issueEndpointKey({ apiKey, grantId }) {
|
|
247
|
+
const subject = await endpointOwner(apiKey);
|
|
248
|
+
if ((await ownEndpoint(subject, grantId)) === null)
|
|
249
|
+
return null;
|
|
250
|
+
const { key, issue } = newKey();
|
|
251
|
+
const now = Date.now();
|
|
252
|
+
const result = await store.issueTokens({ grantId, tokens: [issue], now, forgetBefore: now - LINK_TOKEN_RETENTION_MS });
|
|
253
|
+
return result === "ok" ? key : null;
|
|
254
|
+
},
|
|
255
|
+
async setLimits({ apiKey, grantId, limits }) {
|
|
256
|
+
const subject = await users.manager(apiKey);
|
|
257
|
+
const grant = await ownGrant(subject, grantId);
|
|
258
|
+
if (grant === null)
|
|
259
|
+
return false;
|
|
260
|
+
if (!limits.every((limit) => grant.credentialIds.includes(limit.credentialId))) {
|
|
261
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
262
|
+
}
|
|
263
|
+
return await store.updateGrant(grantId, { limits });
|
|
152
264
|
},
|
|
153
265
|
async setBudget({ apiKey, grantId, budget }) {
|
|
154
266
|
const subject = await users.manager(apiKey);
|
|
@@ -183,8 +295,9 @@ export function newLinkClientSecret() {
|
|
|
183
295
|
}
|
|
184
296
|
/**
|
|
185
297
|
* The grant a link token serves a request for: null when the key is no link
|
|
186
|
-
* token.
|
|
187
|
-
* gets
|
|
298
|
+
* token. Its plans and keys at their monthly spend limit are left out. Throws
|
|
299
|
+
* the 401 a dead token gets, and the 424 a grant at its budget, or with every
|
|
300
|
+
* plan and key at its limit, gets until it serves again.
|
|
188
301
|
*/
|
|
189
302
|
export async function linkTokenGrant(store, token, now = new Date()) {
|
|
190
303
|
const auth = await linkGrants(store).authenticate(token, now);
|
|
@@ -194,14 +307,25 @@ export async function linkTokenGrant(store, token, now = new Date()) {
|
|
|
194
307
|
throw linkTokenExpired();
|
|
195
308
|
if (auth.status === "revoked")
|
|
196
309
|
throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
|
|
197
|
-
const
|
|
310
|
+
const { grant } = auth;
|
|
311
|
+
if (grant.budget.length === 0 && grant.limits.length === 0)
|
|
312
|
+
return grant;
|
|
313
|
+
const uses = await store.budgetUses(grant.id, usesSince(grant.budget, now));
|
|
314
|
+
const back = overBudgetUntil(budgetStandings(grant.budget, uses, now));
|
|
198
315
|
if (back !== undefined)
|
|
199
316
|
throw linkUnavailableError(budgetExhausted(back));
|
|
200
|
-
|
|
317
|
+
const reached = new Set(grantSpend(grant.credentialIds, grant.limits, uses, now).filter((entry) => entry.reached).map((entry) => entry.credentialId));
|
|
318
|
+
if (reached.size === 0)
|
|
319
|
+
return grant;
|
|
320
|
+
const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.has(id)));
|
|
321
|
+
if (credentialIds.size === 0)
|
|
322
|
+
throw linkUnavailableError(limitsReached(nextMonthStart(now)));
|
|
323
|
+
return { ...grant, credentialIds };
|
|
201
324
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
325
|
+
function endpointName(name) {
|
|
326
|
+
const trimmed = name.trim();
|
|
327
|
+
if (trimmed.length === 0 || trimmed.length > 120) {
|
|
328
|
+
throw new HttpError(400, "Name the endpoint, in 120 characters or fewer.", "invalid_request");
|
|
329
|
+
}
|
|
330
|
+
return trimmed;
|
|
207
331
|
}
|
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { Database } from "bun:sqlite";
|
|
8
8
|
import { type SecretBox } from "../self_host/secret_box.js";
|
|
9
|
-
import type { LinkBudget, LinkUsageQuery } from "../platform/platform.js";
|
|
9
|
+
import type { LinkBudget, LinkLimit, LinkUsageQuery } from "../platform/platform.js";
|
|
10
10
|
import type { BudgetUse } from "./budget.js";
|
|
11
11
|
import { type LinkAppRecord, type LinkRevoker, type LinkTokenIssue, type LinkTokenRecord, type LinkUsageRecord } from "./grants.js";
|
|
12
|
-
import type
|
|
12
|
+
import { type LinkGrantRecord, type LinkStore } from "./service.js";
|
|
13
13
|
/** An API key a user added on the approval page, for one model provider or gateway. */
|
|
14
14
|
export type LinkApiKey = {
|
|
15
15
|
id: string;
|
|
@@ -39,9 +39,12 @@ export declare class SqliteLinkStore implements LinkStore {
|
|
|
39
39
|
addApp(app: LinkAppRecord, now?: Date): void;
|
|
40
40
|
appRecord(clientId: string): LinkAppRecord | null;
|
|
41
41
|
saveGrant(request: Parameters<LinkStore["saveGrant"]>[0]): string | null;
|
|
42
|
+
createEndpoint(request: Parameters<LinkStore["createEndpoint"]>[0]): string;
|
|
42
43
|
updateGrant(grantId: string, change: {
|
|
43
44
|
credentialIds?: string[];
|
|
44
45
|
budget?: LinkBudget[];
|
|
46
|
+
limits?: LinkLimit[];
|
|
47
|
+
name?: string;
|
|
45
48
|
}): boolean;
|
|
46
49
|
grants(subject: string | null): LinkGrantRecord[];
|
|
47
50
|
grant(grantId: string): LinkGrantRecord | null;
|
|
@@ -72,4 +75,6 @@ export type LinkUsageEntry = {
|
|
|
72
75
|
cacheReadTokens: number;
|
|
73
76
|
cacheWriteTokens: number;
|
|
74
77
|
status: string;
|
|
78
|
+
costUsd: number | null;
|
|
79
|
+
credentialId: string | null;
|
|
75
80
|
};
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { openWithoutKey } from "../self_host/secret_box.js";
|
|
3
|
+
import { LINK_PERSONAL_CLIENT_ID } from "./service.js";
|
|
3
4
|
// Where a stored API key belongs, which its encryption is bound to.
|
|
4
5
|
function keyPlace(id) {
|
|
5
6
|
return `link_api_keys:${id}:api_key`;
|
|
6
7
|
}
|
|
7
8
|
const TOKEN_WITH_GRANT = `SELECT link_tokens.kind, link_tokens.expires_at, link_tokens.rotated_at, link_tokens.model,
|
|
8
9
|
link_tokens.thinking, link_tokens.pins, link_tokens.tags, link_grants.id AS grant_id, link_grants.client_id,
|
|
9
|
-
link_grants.credential_ids, link_grants.budget, link_grants.revoked_at, link_grants.revoked_by
|
|
10
|
+
link_grants.credential_ids, link_grants.budget, link_grants.limits, link_grants.revoked_at, link_grants.revoked_by
|
|
10
11
|
FROM link_tokens JOIN link_grants ON link_grants.id = link_tokens.grant_id
|
|
11
12
|
WHERE link_tokens.token_hash = ?`;
|
|
12
13
|
const LIVE_GRANTS = `SELECT link_grants.id, link_grants.client_id, link_grants.credential_ids, link_grants.created_at,
|
|
13
|
-
link_grants.budget, link_grants.subject, link_apps.name AS app_name
|
|
14
|
+
link_grants.budget, link_grants.limits, link_grants.subject, COALESCE(link_grants.name, link_apps.name) AS app_name
|
|
14
15
|
FROM link_grants JOIN link_apps ON link_apps.client_id = link_grants.client_id
|
|
15
16
|
WHERE link_grants.revoked_at IS NULL`;
|
|
16
17
|
export class SqliteLinkStore {
|
|
@@ -73,9 +74,21 @@ export class SqliteLinkStore {
|
|
|
73
74
|
const tokenColumns = db.query("PRAGMA table_info(link_tokens)").all();
|
|
74
75
|
if (!tokenColumns.some((column) => column.name === "pins"))
|
|
75
76
|
db.run("ALTER TABLE link_tokens ADD COLUMN pins TEXT");
|
|
77
|
+
// A personal endpoint's name, and each grant's monthly spend limits.
|
|
78
|
+
if (!grantColumns.some((column) => column.name === "name"))
|
|
79
|
+
db.run("ALTER TABLE link_grants ADD COLUMN name TEXT");
|
|
80
|
+
if (!grantColumns.some((column) => column.name === "limits"))
|
|
81
|
+
db.run("ALTER TABLE link_grants ADD COLUMN limits TEXT");
|
|
76
82
|
const usageColumns = db.query("PRAGMA table_info(link_usage)").all();
|
|
77
83
|
if (!usageColumns.some((column) => column.name === "status"))
|
|
78
84
|
db.run("ALTER TABLE link_usage ADD COLUMN status TEXT");
|
|
85
|
+
// What a request cost, and the plan or key that served it.
|
|
86
|
+
if (!usageColumns.some((column) => column.name === "cost_usd"))
|
|
87
|
+
db.run("ALTER TABLE link_usage ADD COLUMN cost_usd REAL");
|
|
88
|
+
if (!usageColumns.some((column) => column.name === "credential_id"))
|
|
89
|
+
db.run("ALTER TABLE link_usage ADD COLUMN credential_id TEXT");
|
|
90
|
+
// The app every personal endpoint's grant belongs to.
|
|
91
|
+
db.run("INSERT OR IGNORE INTO link_apps (client_id, name, redirect_uris, client_secret_hash, created_at) VALUES (?, ?, '[]', NULL, 0)", [LINK_PERSONAL_CLIENT_ID, "Personal Endpoint"]);
|
|
79
92
|
// API keys users added on the approval page: one per user and provider.
|
|
80
93
|
db.run(`CREATE TABLE IF NOT EXISTS link_api_keys (
|
|
81
94
|
id TEXT PRIMARY KEY,
|
|
@@ -148,16 +161,21 @@ export class SqliteLinkStore {
|
|
|
148
161
|
}
|
|
149
162
|
budgetUses(grantId, since) {
|
|
150
163
|
return this.db
|
|
151
|
-
.query(`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
|
|
164
|
+
.query(`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd, credential_id
|
|
152
165
|
FROM link_usage WHERE grant_id = ? AND received_at > ?`)
|
|
153
166
|
.all(grantId, since)
|
|
154
|
-
.map((row) => ({
|
|
167
|
+
.map((row) => ({
|
|
168
|
+
at: new Date(row.received_at),
|
|
169
|
+
...tokenCounts(row),
|
|
170
|
+
costUsd: row.cost_usd ?? 0,
|
|
171
|
+
credentialId: row.credential_id,
|
|
172
|
+
}));
|
|
155
173
|
}
|
|
156
174
|
/** Record what one of a grant's requests used; a repeated request id is ignored. */
|
|
157
175
|
recordUsage(entry) {
|
|
158
176
|
this.db.run(`INSERT OR IGNORE INTO link_usage (request_id, grant_id, received_at, model, thinking, tags,
|
|
159
|
-
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status)
|
|
160
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
177
|
+
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, status, cost_usd, credential_id)
|
|
178
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
161
179
|
entry.requestId,
|
|
162
180
|
entry.grantId,
|
|
163
181
|
entry.receivedAt.getTime(),
|
|
@@ -169,6 +187,8 @@ export class SqliteLinkStore {
|
|
|
169
187
|
entry.cacheReadTokens,
|
|
170
188
|
entry.cacheWriteTokens,
|
|
171
189
|
entry.status,
|
|
190
|
+
entry.costUsd,
|
|
191
|
+
entry.credentialId,
|
|
172
192
|
]);
|
|
173
193
|
}
|
|
174
194
|
usageRecords(grantId, query) {
|
|
@@ -237,6 +257,23 @@ export class SqliteLinkStore {
|
|
|
237
257
|
]);
|
|
238
258
|
return id;
|
|
239
259
|
}
|
|
260
|
+
createEndpoint(request) {
|
|
261
|
+
const id = `lgr_${randomUUID().replaceAll("-", "")}`;
|
|
262
|
+
this.db.transaction(() => {
|
|
263
|
+
this.db.run(`INSERT INTO link_grants (id, client_id, credential_ids, created_at, limits, subject, name)
|
|
264
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`, [
|
|
265
|
+
id,
|
|
266
|
+
LINK_PERSONAL_CLIENT_ID,
|
|
267
|
+
JSON.stringify(request.credentialIds),
|
|
268
|
+
request.now,
|
|
269
|
+
request.limits.length === 0 ? null : JSON.stringify(request.limits),
|
|
270
|
+
request.subject,
|
|
271
|
+
request.name,
|
|
272
|
+
]);
|
|
273
|
+
this.insertTokens(id, [request.key], request.now);
|
|
274
|
+
})();
|
|
275
|
+
return id;
|
|
276
|
+
}
|
|
240
277
|
updateGrant(grantId, change) {
|
|
241
278
|
return this.db.transaction(() => {
|
|
242
279
|
const changed = this.grant(grantId) !== null;
|
|
@@ -249,6 +286,15 @@ export class SqliteLinkStore {
|
|
|
249
286
|
grantId,
|
|
250
287
|
]);
|
|
251
288
|
}
|
|
289
|
+
if (changed && change.limits !== undefined) {
|
|
290
|
+
this.db.run("UPDATE link_grants SET limits = ? WHERE id = ?", [
|
|
291
|
+
change.limits.length === 0 ? null : JSON.stringify(change.limits),
|
|
292
|
+
grantId,
|
|
293
|
+
]);
|
|
294
|
+
}
|
|
295
|
+
if (changed && change.name !== undefined) {
|
|
296
|
+
this.db.run("UPDATE link_grants SET name = ? WHERE id = ?", [change.name, grantId]);
|
|
297
|
+
}
|
|
252
298
|
return changed;
|
|
253
299
|
})();
|
|
254
300
|
}
|
|
@@ -290,6 +336,7 @@ export class SqliteLinkStore {
|
|
|
290
336
|
clientId: row.client_id,
|
|
291
337
|
credentialIds: parseIds(row.credential_ids),
|
|
292
338
|
budget: parseBudget(row.budget),
|
|
339
|
+
limits: parseLimits(row.limits),
|
|
293
340
|
revokedAt: row.revoked_at,
|
|
294
341
|
revokedBy: row.revoked_by,
|
|
295
342
|
usable: true,
|
|
@@ -370,8 +417,12 @@ function grantRecord(row) {
|
|
|
370
417
|
credentialIds: parseIds(row.credential_ids),
|
|
371
418
|
createdAt: new Date(row.created_at).toISOString(),
|
|
372
419
|
budget: parseBudget(row.budget),
|
|
420
|
+
limits: parseLimits(row.limits),
|
|
373
421
|
};
|
|
374
422
|
}
|
|
423
|
+
function parseLimits(value) {
|
|
424
|
+
return value === null ? [] : JSON.parse(value);
|
|
425
|
+
}
|
|
375
426
|
function parseIds(value) {
|
|
376
427
|
return JSON.parse(value);
|
|
377
428
|
}
|
|
@@ -163,8 +163,50 @@ export type LinkPlatform = {
|
|
|
163
163
|
revokeToken(request: LinkClient & {
|
|
164
164
|
token: string;
|
|
165
165
|
}): Promise<void>;
|
|
166
|
-
/**
|
|
167
|
-
|
|
166
|
+
/**
|
|
167
|
+
* The user's grants that are not revoked, app connections and personal
|
|
168
|
+
* endpoints alike, each with every granted credential's spend this month.
|
|
169
|
+
* `apiKey` is a personal management key, or on hosted Dari the user's session.
|
|
170
|
+
*/
|
|
171
|
+
grants(apiKey: string): Promise<LinkManagedGrant[]>;
|
|
172
|
+
/** The plans and API keys the user can grant. */
|
|
173
|
+
plans(apiKey: string): Promise<LinkSubscription[]>;
|
|
174
|
+
/**
|
|
175
|
+
* A personal endpoint: a grant the user makes for themselves on their chosen
|
|
176
|
+
* plans and keys, and its key, returned this once, which an app that takes
|
|
177
|
+
* the user's own key calls with. Throws HttpError(400) for a plan or key the
|
|
178
|
+
* user does not have, or for bad limits.
|
|
179
|
+
*/
|
|
180
|
+
createEndpoint(request: {
|
|
181
|
+
apiKey: string;
|
|
182
|
+
name: string;
|
|
183
|
+
credentialIds: string[];
|
|
184
|
+
limits: LinkLimit[];
|
|
185
|
+
}): Promise<{
|
|
186
|
+
grant: LinkManagedGrant;
|
|
187
|
+
key: string;
|
|
188
|
+
}>;
|
|
189
|
+
/** Rename one of the user's endpoints or change its plans; false when they have none by that id. */
|
|
190
|
+
updateEndpoint(request: {
|
|
191
|
+
apiKey: string;
|
|
192
|
+
grantId: string;
|
|
193
|
+
name?: string;
|
|
194
|
+
credentialIds?: string[];
|
|
195
|
+
}): Promise<boolean>;
|
|
196
|
+
/** Another key for one of the user's endpoints, returned this once; null when they have none by that id. */
|
|
197
|
+
issueEndpointKey(request: {
|
|
198
|
+
apiKey: string;
|
|
199
|
+
grantId: string;
|
|
200
|
+
}): Promise<string | null>;
|
|
201
|
+
/**
|
|
202
|
+
* Replace one of the user's grants' monthly spend limits (empty removes
|
|
203
|
+
* them); false when the user has no grant by that id.
|
|
204
|
+
*/
|
|
205
|
+
setLimits(request: {
|
|
206
|
+
apiKey: string;
|
|
207
|
+
grantId: string;
|
|
208
|
+
limits: LinkLimit[];
|
|
209
|
+
}): Promise<boolean>;
|
|
168
210
|
/** Revoke one of the user's grants; false when it has none by that id. */
|
|
169
211
|
revokeGrant(request: {
|
|
170
212
|
apiKey: string;
|
|
@@ -241,6 +283,8 @@ export type LinkApprovalPage = {
|
|
|
241
283
|
disconnect(subject: string, grantId: string): Promise<boolean>;
|
|
242
284
|
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
243
285
|
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
286
|
+
/** Replace one of the user's grants' monthly spend limits; false when they have none by that id. */
|
|
287
|
+
setLimits(subject: string, grantId: string, limits: LinkLimit[]): Promise<boolean>;
|
|
244
288
|
};
|
|
245
289
|
/**
|
|
246
290
|
* The platform's own sign-in. The page sends the user to `url()` with `state`
|
|
@@ -291,6 +335,22 @@ export type LinkBudget = {
|
|
|
291
335
|
windowMinutes: number;
|
|
292
336
|
maxTokens: number;
|
|
293
337
|
};
|
|
338
|
+
/**
|
|
339
|
+
* The most a grant may spend on one of its plans or API keys in a calendar
|
|
340
|
+
* month (UTC), in US dollars. A plan's spend is what its requests would have
|
|
341
|
+
* cost at API prices. See link/budget.ts.
|
|
342
|
+
*/
|
|
343
|
+
export type LinkLimit = {
|
|
344
|
+
credentialId: string;
|
|
345
|
+
monthlyUsd: number;
|
|
346
|
+
};
|
|
347
|
+
/** A granted plan or key's spend this month, and its limit when it has one. */
|
|
348
|
+
export type LinkSpend = {
|
|
349
|
+
credentialId: string;
|
|
350
|
+
spentUsd: number;
|
|
351
|
+
monthlyUsd: number | null;
|
|
352
|
+
reached: boolean;
|
|
353
|
+
};
|
|
294
354
|
/** A budget window as it stands for a grant. */
|
|
295
355
|
export type LinkBudgetStanding = {
|
|
296
356
|
windowMinutes: number;
|
|
@@ -363,9 +423,15 @@ export type LinkGrant = {
|
|
|
363
423
|
id: string;
|
|
364
424
|
clientId: string;
|
|
365
425
|
appName: string;
|
|
426
|
+
endpoint: boolean;
|
|
366
427
|
credentialIds: string[];
|
|
367
428
|
createdAt: string;
|
|
368
429
|
budget: LinkBudget[];
|
|
430
|
+
limits: LinkLimit[];
|
|
431
|
+
};
|
|
432
|
+
/** A grant as its user manages it. */
|
|
433
|
+
export type LinkManagedGrant = LinkGrant & {
|
|
434
|
+
spend: LinkSpend[];
|
|
369
435
|
};
|
|
370
436
|
/** A grant as its app sees it: the granted subscriptions themselves. */
|
|
371
437
|
export type LinkUsageQuery = {
|
|
@@ -395,8 +461,9 @@ export type LinkUsage = LinkUsageTotals & {
|
|
|
395
461
|
}>;
|
|
396
462
|
completeThrough: string | null;
|
|
397
463
|
};
|
|
398
|
-
export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget"> & {
|
|
464
|
+
export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget" | "limits"> & {
|
|
399
465
|
budget: LinkBudgetStanding[];
|
|
466
|
+
spend: LinkSpend[];
|
|
400
467
|
subscriptions: LinkSubscription[];
|
|
401
468
|
};
|
|
402
469
|
export type ResolveRouterRequest = {
|
|
@@ -478,6 +545,8 @@ export type RequestRecord = {
|
|
|
478
545
|
link?: {
|
|
479
546
|
grantId: string;
|
|
480
547
|
thinking: string | null;
|
|
548
|
+
costUsd: number | null;
|
|
549
|
+
credentialId: string | null;
|
|
481
550
|
};
|
|
482
551
|
router: RequestRecordRouter;
|
|
483
552
|
candidates: Array<{
|
|
@@ -6,6 +6,7 @@ export declare function explicitModelId(model: string | undefined): string | nul
|
|
|
6
6
|
export declare function explicitModelSlug(modelId: string): string;
|
|
7
7
|
export declare const LINK_ACCESS_TOKEN_PREFIX = "dlk_at_";
|
|
8
8
|
export declare const LINK_CHILD_TOKEN_PREFIX = "dlk_ct_";
|
|
9
|
+
export declare const LINK_KEY_TOKEN_PREFIX = "dlk_key_";
|
|
9
10
|
export declare function isLinkToken(token: string): boolean;
|
|
10
11
|
export declare function linkTokenModel<T>(token: string, model: T): T | string;
|
|
11
12
|
export declare function unsupportedModelMessage(): string;
|
|
@@ -40,11 +40,15 @@ export function explicitModelId(model) {
|
|
|
40
40
|
export function explicitModelSlug(modelId) {
|
|
41
41
|
return EXPLICIT_MODEL_PREFIX + modelId;
|
|
42
42
|
}
|
|
43
|
-
// A Dari Link token's access and
|
|
43
|
+
// A Dari Link token's access, child, and endpoint key tokens, which every
|
|
44
|
+
// platform issues.
|
|
44
45
|
export const LINK_ACCESS_TOKEN_PREFIX = "dlk_at_";
|
|
45
46
|
export const LINK_CHILD_TOKEN_PREFIX = "dlk_ct_";
|
|
47
|
+
export const LINK_KEY_TOKEN_PREFIX = "dlk_key_";
|
|
46
48
|
export function isLinkToken(token) {
|
|
47
|
-
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX)
|
|
49
|
+
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX)
|
|
50
|
+
|| token.startsWith(LINK_CHILD_TOKEN_PREFIX)
|
|
51
|
+
|| token.startsWith(LINK_KEY_TOKEN_PREFIX);
|
|
48
52
|
}
|
|
49
53
|
/* A Dari Link token is served exactly the model it names, so every name but
|
|
50
54
|
the router's own (`dari/routing`, the Anthropic tier names, the Claude app's
|
|
@@ -7,6 +7,7 @@ export type ReportedProviderExecution = {
|
|
|
7
7
|
model: string;
|
|
8
8
|
providerKeySource: ProviderKeySource;
|
|
9
9
|
thinkingLevel?: string;
|
|
10
|
+
subscriptionCredentialId?: string;
|
|
10
11
|
};
|
|
11
12
|
export declare function reportedExecution(execution: ReportedProviderExecution): ReportedProviderExecution;
|
|
12
13
|
export type ReportableProviderOutcome = {
|
|
@@ -4,6 +4,9 @@ export function reportedExecution(execution) {
|
|
|
4
4
|
model: execution.model,
|
|
5
5
|
providerKeySource: execution.providerKeySource,
|
|
6
6
|
...(execution.thinkingLevel === undefined ? {} : { thinkingLevel: execution.thinkingLevel }),
|
|
7
|
+
...(execution.subscriptionCredentialId === undefined
|
|
8
|
+
? {}
|
|
9
|
+
: { subscriptionCredentialId: execution.subscriptionCredentialId }),
|
|
7
10
|
};
|
|
8
11
|
}
|
|
9
12
|
export function createExperimentRoutedRuntimeReporter() {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* nothing is retained for a ZDR router.
|
|
10
10
|
*/
|
|
11
11
|
import type { Database } from "bun:sqlite";
|
|
12
|
+
import type { SessionGitEvents } from "../activity/http.js";
|
|
12
13
|
import { type ActivityDb } from "../activity/sql.js";
|
|
13
14
|
export declare const SELF_HOSTED_BLOB_BUCKET = "gateway";
|
|
14
15
|
type Row = Record<string, unknown>;
|
|
@@ -26,8 +27,20 @@ export declare class ActivityStore {
|
|
|
26
27
|
id: string;
|
|
27
28
|
zdr: boolean;
|
|
28
29
|
}>, gatewayKeyCount: number): void;
|
|
29
|
-
/**
|
|
30
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Store one imported request's report under the "Imported" router, adding
|
|
32
|
+
* the router when Activity has none. False when the request is stored
|
|
33
|
+
* already.
|
|
34
|
+
*/
|
|
35
|
+
importRequest(organizationId: string, report: Row): boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Store one served request's report: its row, tool events, and bodies.
|
|
38
|
+
* False when a request with its ID is stored already.
|
|
39
|
+
*/
|
|
40
|
+
record(report: Row): boolean;
|
|
41
|
+
saveSessionGitEvents(write: SessionGitEvents): Promise<void>;
|
|
42
|
+
/** Store a session's git events: what a step's tool output showed, or commits its git hook reported. */
|
|
43
|
+
private insertGitEvents;
|
|
31
44
|
/** A retained body, or null. */
|
|
32
45
|
readBlob(key: string): string | null;
|
|
33
46
|
private modelSwitched;
|