@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/src/link/endpoints.ts
CHANGED
|
@@ -19,11 +19,23 @@
|
|
|
19
19
|
- GET /v1/link/grant the grant a link access token belongs to
|
|
20
20
|
- GET /v1/link/usage what the grant's requests used, by tag and time
|
|
21
21
|
- POST /v1/link/apps register an app (bearer: the user's key)
|
|
22
|
-
- GET /v1/link/grants the user's grants
|
|
22
|
+
- GET /v1/link/grants the user's grants, each granted plan and
|
|
23
|
+
key's spend this month with it
|
|
23
24
|
- DELETE /v1/link/grants/{id} the user revokes a grant and its tokens
|
|
24
25
|
- PUT /v1/link/grants/{id}/budget the user sets or removes the grant's
|
|
25
26
|
budget: the most tokens the app may use per
|
|
26
27
|
five hours and per week
|
|
28
|
+
- PUT /v1/link/grants/{id}/limits the user sets the most the grant may
|
|
29
|
+
spend on each of its plans and keys a month
|
|
30
|
+
- GET /v1/link/plans the plans and keys the user can grant
|
|
31
|
+
- POST /v1/link/endpoints the user makes a personal endpoint: a grant
|
|
32
|
+
for themselves, and its key, which an app
|
|
33
|
+
that takes their own key calls with
|
|
34
|
+
- PUT /v1/link/grants/{id} rename an endpoint or change its plans
|
|
35
|
+
- POST /v1/link/grants/{id}/keys another key for an endpoint
|
|
36
|
+
|
|
37
|
+
The user's own routes take their personal key, or on hosted Dari their
|
|
38
|
+
signed-in session, as the bearer.
|
|
27
39
|
- GET /v1/link/session where a platform's sign-in returns the user
|
|
28
40
|
- GET /v1/link/connections the page where the approval page's user sees
|
|
29
41
|
the apps they connected, sets each one's
|
|
@@ -61,6 +73,7 @@ import type {
|
|
|
61
73
|
LinkPlanAdded,
|
|
62
74
|
LinkGrantDetail,
|
|
63
75
|
LinkKeyProvider,
|
|
76
|
+
LinkManagedGrant,
|
|
64
77
|
LinkUsageTotals,
|
|
65
78
|
LinkUsageWindow,
|
|
66
79
|
LinkPlatform,
|
|
@@ -74,7 +87,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
74
87
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
75
88
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
76
89
|
import { gatewayFor } from "../models/gateways.js";
|
|
77
|
-
import { budgetBody, linkTokens, validBudget } from "./budget.js";
|
|
90
|
+
import { budgetBody, limitsBody, linkTokens, spendBody, validBudget, validLimits } from "./budget.js";
|
|
78
91
|
import { catalogModelFor } from "./grant_access.js";
|
|
79
92
|
import { requestTags } from "../runtime/request_tags.js";
|
|
80
93
|
import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
|
|
@@ -93,6 +106,9 @@ const MAX_REGISTRATION_BYTES = 8_192;
|
|
|
93
106
|
const MAX_REGISTRATIONS_PER_MINUTE = 20;
|
|
94
107
|
const GRANT_ROUTE = /^\/v1\/link\/grants\/([^/]+)$/;
|
|
95
108
|
const GRANT_BUDGET_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/budget$/;
|
|
109
|
+
const GRANT_LIMITS_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/limits$/;
|
|
110
|
+
const GRANT_KEYS_ROUTE = /^\/v1\/link\/grants\/([^/]+)\/keys$/;
|
|
111
|
+
const MAX_ENDPOINT_CREDENTIALS = 50;
|
|
96
112
|
const MAX_TAG_KEY_CHARS = 64;
|
|
97
113
|
// Who the approval page's user is. Without accounts the cookie is who they
|
|
98
114
|
// are, so it lasts a year from their last plan; with accounts, a month from
|
|
@@ -216,18 +232,123 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
|
|
|
216
232
|
if (pathname === "/v1/link/apps" && request.method === "POST") {
|
|
217
233
|
return await registerApp(link, request);
|
|
218
234
|
}
|
|
235
|
+
if (isManagementPath(pathname)) {
|
|
236
|
+
if (request.method === "OPTIONS") return withManagementCors(new Response(null, { status: 204 }));
|
|
237
|
+
const response = await manage(link, request, pathname);
|
|
238
|
+
if (response !== null) return withManagementCors(response);
|
|
239
|
+
}
|
|
240
|
+
return errorResponse(new HttpError(404, "Not found", "not_found"));
|
|
241
|
+
} catch (error) {
|
|
242
|
+
const response = linkErrorResponse(error);
|
|
243
|
+
if (isManagementPath(pathname)) return withManagementCors(response);
|
|
244
|
+
return CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname) ? withCors(response) : response;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function isManagementPath(pathname: string): boolean {
|
|
249
|
+
return pathname === "/v1/link/grants" || pathname === "/v1/link/plans" || pathname === "/v1/link/endpoints"
|
|
250
|
+
|| pathname.startsWith("/v1/link/grants/");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The user's own routes are called from Dari's web app too, with a bearer
|
|
254
|
+
// token and no cookie, so any origin may call.
|
|
255
|
+
function withManagementCors(response: Response): Response {
|
|
256
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
257
|
+
response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
258
|
+
response.headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
|
|
259
|
+
response.headers.set("Access-Control-Max-Age", "600");
|
|
260
|
+
return response;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function managedGrantBody(grant: LinkManagedGrant) {
|
|
264
|
+
return {
|
|
265
|
+
id: grant.id,
|
|
266
|
+
client_id: grant.clientId,
|
|
267
|
+
app_name: grant.appName,
|
|
268
|
+
endpoint: grant.endpoint,
|
|
269
|
+
credential_ids: grant.credentialIds,
|
|
270
|
+
created_at: grant.createdAt,
|
|
271
|
+
budget: budgetBody(grant.budget),
|
|
272
|
+
limits: limitsBody(grant.limits),
|
|
273
|
+
spend: spendBody(grant.spend),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// A plan or key the user can grant, as the grant body names its plans.
|
|
278
|
+
function planBody(plan: LinkSubscription) {
|
|
279
|
+
const keyFor = plan.apiKeyProvider;
|
|
280
|
+
const kind = plan.provider as SubscriptionKind;
|
|
281
|
+
const client = keyFor === undefined ? subscriptionClient(kind) : undefined;
|
|
282
|
+
return {
|
|
283
|
+
id: plan.id,
|
|
284
|
+
kind: keyFor === undefined ? kind : API_KEY,
|
|
285
|
+
title: keyFor === undefined ? KINDS[kind]?.name ?? kind : plan.name,
|
|
286
|
+
...(keyFor === undefined ? {} : { provider: keyFor }),
|
|
287
|
+
plan: keyFor === undefined ? SUBSCRIPTION_PLAN_LABELS[kind] ?? kind : `${plan.name} API Key`,
|
|
288
|
+
label: planLabel(plan),
|
|
289
|
+
account_email: plan.accountEmail,
|
|
290
|
+
serves: client === undefined ? "any_app" : `${client}_only`,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// The credential ids a request names: distinct, and not too many.
|
|
295
|
+
function credentialIdsFrom(value: unknown): string[] {
|
|
296
|
+
if (
|
|
297
|
+
!Array.isArray(value) || value.length === 0 || value.length > MAX_ENDPOINT_CREDENTIALS
|
|
298
|
+
|| !value.every((id) => typeof id === "string" && id.length > 0)
|
|
299
|
+
) {
|
|
300
|
+
throw new HttpError(400, "credential_ids must list one or more of your plans and keys.", "invalid_request_error", "credential_ids");
|
|
301
|
+
}
|
|
302
|
+
return [...new Set(value as string[])];
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function limitsFrom(value: unknown) {
|
|
306
|
+
const limits = validLimits(value ?? []);
|
|
307
|
+
if (limits === null) {
|
|
308
|
+
throw new HttpError(
|
|
309
|
+
400,
|
|
310
|
+
"limits must be a list of {credential_id, monthly_usd} with distinct credential_ids and monthly_usd a dollar amount of 0 or more; [] removes them.",
|
|
311
|
+
"invalid_request_error",
|
|
312
|
+
"limits",
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
return limits;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The user's own routes; null for a path and method none of them serve. */
|
|
319
|
+
async function manage(link: LinkPlatform, request: Request, pathname: string): Promise<Response | null> {
|
|
320
|
+
const apiKey = bearerToken(request.headers);
|
|
219
321
|
if (pathname === "/v1/link/grants" && request.method === "GET") {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
322
|
+
return Response.json({ grants: (await link.grants(apiKey)).map(managedGrantBody) });
|
|
323
|
+
}
|
|
324
|
+
if (pathname === "/v1/link/plans" && request.method === "GET") {
|
|
325
|
+
return Response.json({ plans: (await link.plans(apiKey)).map(planBody) });
|
|
326
|
+
}
|
|
327
|
+
if (pathname === "/v1/link/endpoints" && request.method === "POST") {
|
|
328
|
+
const body = (await parseJsonRequest(request)) as Record<string, unknown> | null;
|
|
329
|
+
const { grant, key } = await link.createEndpoint({
|
|
330
|
+
apiKey,
|
|
331
|
+
name: typeof body?.name === "string" ? body.name : "",
|
|
332
|
+
credentialIds: credentialIdsFrom(body?.credential_ids),
|
|
333
|
+
limits: limitsFrom(body?.limits),
|
|
230
334
|
});
|
|
335
|
+
return Response.json({ grant: managedGrantBody(grant), key }, { status: 201 });
|
|
336
|
+
}
|
|
337
|
+
const keysRoute = GRANT_KEYS_ROUTE.exec(pathname);
|
|
338
|
+
if (keysRoute !== null && request.method === "POST") {
|
|
339
|
+
const grantId = decodeURIComponent(keysRoute[1]!);
|
|
340
|
+
const key = await link.issueEndpointKey({ apiKey, grantId });
|
|
341
|
+
if (key === null) throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
342
|
+
return Response.json({ id: grantId, key }, { status: 201 });
|
|
343
|
+
}
|
|
344
|
+
const limitsRoute = GRANT_LIMITS_ROUTE.exec(pathname);
|
|
345
|
+
if (limitsRoute !== null && request.method === "PUT") {
|
|
346
|
+
const grantId = decodeURIComponent(limitsRoute[1]!);
|
|
347
|
+
const limits = limitsFrom(((await parseJsonRequest(request)) as { limits?: unknown } | null)?.limits);
|
|
348
|
+
if (!(await link.setLimits({ apiKey, grantId, limits }))) {
|
|
349
|
+
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
350
|
+
}
|
|
351
|
+
return Response.json({ id: grantId, limits: limitsBody(limits) });
|
|
231
352
|
}
|
|
232
353
|
const budgetRoute = GRANT_BUDGET_ROUTE.exec(pathname);
|
|
233
354
|
if (budgetRoute !== null && request.method === "PUT") {
|
|
@@ -242,24 +363,34 @@ export async function handleLinkRequest(request: Request, platform: GatewayPlatf
|
|
|
242
363
|
"budget",
|
|
243
364
|
);
|
|
244
365
|
}
|
|
245
|
-
if (!(await link.setBudget({ apiKey
|
|
366
|
+
if (!(await link.setBudget({ apiKey, grantId, budget }))) {
|
|
246
367
|
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
247
368
|
}
|
|
248
369
|
return Response.json({ id: grantId, budget: budgetBody(budget) });
|
|
249
370
|
}
|
|
250
371
|
const grantRoute = GRANT_ROUTE.exec(pathname);
|
|
372
|
+
if (grantRoute !== null && request.method === "PUT") {
|
|
373
|
+
const grantId = decodeURIComponent(grantRoute[1]!);
|
|
374
|
+
const body = (await parseJsonRequest(request)) as Record<string, unknown> | null;
|
|
375
|
+
const updated = await link.updateEndpoint({
|
|
376
|
+
apiKey,
|
|
377
|
+
grantId,
|
|
378
|
+
...(typeof body?.name === "string" ? { name: body.name } : {}),
|
|
379
|
+
...(body?.credential_ids === undefined ? {} : { credentialIds: credentialIdsFrom(body.credential_ids) }),
|
|
380
|
+
});
|
|
381
|
+
if (!updated) throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
382
|
+
const grant = (await link.grants(apiKey)).find((candidate) => candidate.id === grantId);
|
|
383
|
+
if (grant === undefined) throw new HttpError(404, `No endpoint ${grantId}.`, "not_found");
|
|
384
|
+
return Response.json(managedGrantBody(grant));
|
|
385
|
+
}
|
|
251
386
|
if (grantRoute !== null && request.method === "DELETE") {
|
|
252
387
|
const grantId = decodeURIComponent(grantRoute[1]!);
|
|
253
|
-
if (!(await link.revokeGrant({ apiKey
|
|
388
|
+
if (!(await link.revokeGrant({ apiKey, grantId }))) {
|
|
254
389
|
throw new HttpError(404, `No grant ${grantId}.`, "not_found");
|
|
255
390
|
}
|
|
256
391
|
return Response.json({ id: grantId, revoked: true });
|
|
257
392
|
}
|
|
258
|
-
return
|
|
259
|
-
} catch (error) {
|
|
260
|
-
const response = linkErrorResponse(error);
|
|
261
|
-
return CORS_PATHS.has(pathname) || USAGE_REQUEST_ROUTE.test(pathname) ? withCors(response) : response;
|
|
262
|
-
}
|
|
393
|
+
return null;
|
|
263
394
|
}
|
|
264
395
|
|
|
265
396
|
// A refusal keeps its own message; a failure says nothing of its cause but a
|
|
@@ -1245,14 +1376,23 @@ function connectionCard(connection: LinkConnection, csrf: string): string {
|
|
|
1245
1376
|
return `<label class="field" for="max_${minutes}_${escapeHtml(connection.id)}">Most Tokens ${label}</label>
|
|
1246
1377
|
<input id="max_${minutes}_${escapeHtml(connection.id)}" type="text" inputmode="numeric" name="max_${minutes}" value="${standing === undefined ? "" : standing.maxTokens}" placeholder="No Limit" autocomplete="off">
|
|
1247
1378
|
${standing === undefined ? "" : `<p class="hint">${count(standing.usedTokens)} used${standing.resetsAt === null ? "" : `, at the limit until ${escapeHtml(new Date(standing.resetsAt).toUTCString())}`}</p>`}`;
|
|
1379
|
+
};
|
|
1380
|
+
// The most the grant may spend on each plan or key a month.
|
|
1381
|
+
const spendLimit = (plan: LinkSubscription) => {
|
|
1382
|
+
const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
|
|
1383
|
+
const id = `usd_${escapeHtml(plan.id)}_${escapeHtml(connection.id)}`;
|
|
1384
|
+
return `<label class="field" for="${id}">${escapeHtml(planName(plan))} Per Month ($)</label>
|
|
1385
|
+
<input id="${id}" type="text" inputmode="decimal" name="usd_${escapeHtml(plan.id)}" value="${spend?.monthlyUsd ?? ""}" placeholder="No Limit" autocomplete="off">
|
|
1386
|
+
<p class="hint">${dollars(spend?.spentUsd ?? 0)} this month${spend?.reached ? ", at the limit until the month ends" : ""}</p>`;
|
|
1248
1387
|
};
|
|
1249
1388
|
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1250
1389
|
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1251
|
-
<strong>${escapeHtml(connection.appName)}</strong>
|
|
1390
|
+
<strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
|
|
1252
1391
|
<small>Connected ${escapeHtml(new Date(connection.createdAt).toDateString())} · ${count(connection.usage.requests)} requests · ${count(tokens)} tokens</small>
|
|
1253
1392
|
<small>Shares ${connection.subscriptions.length === 0 ? "nothing" : connection.subscriptions.map((plan) => escapeHtml(planName(plan))).join(", ")}</small>
|
|
1254
1393
|
${limit(300, "Per 5 Hours")}
|
|
1255
1394
|
${limit(10080, "Per Week")}
|
|
1395
|
+
${connection.subscriptions.map(spendLimit).join("\n")}
|
|
1256
1396
|
<div class="row"><button class="btn outline" type="submit" name="decision" value="budget">Save Limits</button><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
|
|
1257
1397
|
</form>`;
|
|
1258
1398
|
}
|
|
@@ -1282,7 +1422,14 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
|
|
|
1282
1422
|
});
|
|
1283
1423
|
const budget = validBudget(entries);
|
|
1284
1424
|
if (budget === null) return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1425
|
+
const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
|
|
1426
|
+
const value = raw.replace(/[\s,$]/g, "");
|
|
1427
|
+
if (!field.startsWith("usd_") || value === "") return [];
|
|
1428
|
+
return [{ credential_id: field.slice(4), monthly_usd: /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN }];
|
|
1429
|
+
}));
|
|
1430
|
+
if (limits === null) return await connectionsPage(approval, request, "Each monthly limit is a dollar amount; leave it empty for none.");
|
|
1285
1431
|
await approval.setBudget(session.subject, grantId, budget);
|
|
1432
|
+
await approval.setLimits(session.subject, grantId, limits);
|
|
1286
1433
|
return back;
|
|
1287
1434
|
}
|
|
1288
1435
|
const removing = form.get("remove_id");
|
|
@@ -1302,6 +1449,10 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
|
|
|
1302
1449
|
return back;
|
|
1303
1450
|
}
|
|
1304
1451
|
|
|
1452
|
+
function dollars(value: number): string {
|
|
1453
|
+
return `$${value.toFixed(2)}`;
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1305
1456
|
// What a plan or key is called: "Claude", or "OpenRouter API Key".
|
|
1306
1457
|
function planName(subscription: LinkSubscription): string {
|
|
1307
1458
|
return subscription.apiKeyProvider !== undefined
|
package/src/link/errors.ts
CHANGED
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
their usage limits; `resets_at` (and Retry-After) says when the first one
|
|
14
14
|
is back, when that is known.
|
|
15
15
|
- `grant_budget_exhausted`: the grant used the most tokens the user
|
|
16
|
-
allowed it in a window (per five hours or per week)
|
|
17
|
-
|
|
16
|
+
allowed it in a window (per five hours or per week), or every plan and
|
|
17
|
+
key it shares is at its monthly spend limit; `resets_at` (and
|
|
18
|
+
Retry-After) says when it serves again.
|
|
18
19
|
- `subscription_client_mismatch`: the granted plans serve only another
|
|
19
20
|
client (a Claude Code plan serves only Claude Code itself); the user must
|
|
20
21
|
grant a plan that serves any app, such as a ChatGPT plan.
|
|
@@ -92,6 +93,15 @@ export function budgetExhausted(resetsAt: Date): LinkUnavailable {
|
|
|
92
93
|
};
|
|
93
94
|
}
|
|
94
95
|
|
|
96
|
+
/** Every plan and key of the grant is at the monthly spend limit its user set. */
|
|
97
|
+
export function limitsReached(resetsAt: Date): LinkUnavailable {
|
|
98
|
+
return {
|
|
99
|
+
code: "grant_budget_exhausted",
|
|
100
|
+
message: `Every plan and API key of this Dari Link grant is at the monthly spend limit the user set. It is back at ${resetsAt.toISOString()}.`,
|
|
101
|
+
resets_at: resetsAt.toISOString(),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
95
105
|
/** The granted plans for a provider serve only another client. */
|
|
96
106
|
export function plansForAnotherClient(plans: readonly SubscriptionKind[]): LinkUnavailable {
|
|
97
107
|
const only = [...new Set(plans.map((plan) => `${SUBSCRIPTION_PLAN_LABELS[plan]} plans serve only ${ONLY_CLIENT[plan] ?? "their own client"}`))];
|
package/src/link/grants.ts
CHANGED
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
race, and later reuse revokes the grant. A confidential client, which
|
|
12
12
|
also proves its secret, keeps its own;
|
|
13
13
|
- a child token serves only its models, for up to twelve hours, and cannot
|
|
14
|
-
refresh, mint, or read the grant
|
|
14
|
+
refresh, mint, or read the grant;
|
|
15
|
+
- a personal endpoint's key does not expire: it is what a user pastes into
|
|
16
|
+
an app that takes their own key, and acts as the grant's access token.
|
|
15
17
|
|
|
16
18
|
Revoking the grant stops them all at once. */
|
|
17
19
|
|
|
@@ -25,13 +27,19 @@ import type {
|
|
|
25
27
|
LinkChildToken,
|
|
26
28
|
LinkClient,
|
|
27
29
|
LinkCodeExchange,
|
|
30
|
+
LinkLimit,
|
|
28
31
|
LinkTokenExchange,
|
|
29
32
|
LinkTokens,
|
|
30
33
|
LinkUsage,
|
|
31
34
|
LinkUsageQuery,
|
|
32
35
|
LinkUsageTotals,
|
|
33
36
|
} from "../platform/platform.js";
|
|
34
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
LINK_ACCESS_TOKEN_PREFIX,
|
|
39
|
+
LINK_CHILD_TOKEN_PREFIX,
|
|
40
|
+
LINK_KEY_TOKEN_PREFIX,
|
|
41
|
+
isLinkToken,
|
|
42
|
+
} from "../protocol/input/router_model.js";
|
|
35
43
|
|
|
36
44
|
export const LINK_ACCESS_TOKEN_TTL_MS = 60 * 60_000;
|
|
37
45
|
export const LINK_CODE_TTL_MS = 10 * 60_000;
|
|
@@ -47,7 +55,7 @@ export const LINK_CODE_PREFIX = "dlk_code_";
|
|
|
47
55
|
export const LINK_CLIENT_SECRET_PREFIX = "dlk_cs_";
|
|
48
56
|
|
|
49
57
|
export type LinkRevoker = "user" | "app" | "reuse_detected";
|
|
50
|
-
export type LinkTokenKind = "access" | "refresh" | "child";
|
|
58
|
+
export type LinkTokenKind = "access" | "refresh" | "child" | "key";
|
|
51
59
|
export type LinkPin = { model: string; thinking: string | null };
|
|
52
60
|
|
|
53
61
|
export type ActiveLinkGrant = {
|
|
@@ -55,6 +63,7 @@ export type ActiveLinkGrant = {
|
|
|
55
63
|
clientId: string;
|
|
56
64
|
credentialIds: ReadonlySet<string>;
|
|
57
65
|
budget: LinkBudget[];
|
|
66
|
+
limits: LinkLimit[];
|
|
58
67
|
// Set for a child token: the models it serves, each with its pinned thinking.
|
|
59
68
|
pins?: LinkPin[];
|
|
60
69
|
tags?: Record<string, string>;
|
|
@@ -79,8 +88,9 @@ export type LinkTokenRecord = {
|
|
|
79
88
|
grantId: string;
|
|
80
89
|
clientId: string;
|
|
81
90
|
credentialIds: string[];
|
|
82
|
-
// The grant's budget.
|
|
91
|
+
// The grant's budget and monthly spend limits.
|
|
83
92
|
budget: LinkBudget[];
|
|
93
|
+
limits: LinkLimit[];
|
|
84
94
|
revokedAt: number | null;
|
|
85
95
|
revokedBy: string | null;
|
|
86
96
|
// False when the platform no longer serves the grant for a reason of its
|
|
@@ -326,24 +336,23 @@ export function linkGrants(repo: LinkRepo) {
|
|
|
326
336
|
|
|
327
337
|
export type LinkGrants = ReturnType<typeof linkGrants>;
|
|
328
338
|
|
|
329
|
-
const TOKEN_PREFIX: Record<LinkTokenKind, string> = {
|
|
339
|
+
export const TOKEN_PREFIX: Record<LinkTokenKind, string> = {
|
|
330
340
|
access: LINK_ACCESS_TOKEN_PREFIX,
|
|
331
341
|
child: LINK_CHILD_TOKEN_PREFIX,
|
|
342
|
+
key: LINK_KEY_TOKEN_PREFIX,
|
|
332
343
|
refresh: LINK_REFRESH_TOKEN_PREFIX,
|
|
333
344
|
};
|
|
334
345
|
|
|
335
|
-
/**
|
|
336
|
-
export function isLinkToken(token: string): boolean {
|
|
337
|
-
return token.startsWith(LINK_ACCESS_TOKEN_PREFIX) || token.startsWith(LINK_CHILD_TOKEN_PREFIX);
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/** What a stored access or child token is now; null when it serves nothing. */
|
|
346
|
+
/** What a stored access, child, or key token is now; null when it serves nothing. */
|
|
341
347
|
export function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null {
|
|
342
348
|
if (record === null || record.kind === "refresh") return null;
|
|
343
349
|
if (record.revokedAt !== null) {
|
|
344
350
|
return { status: "revoked", revokedBy: record.revokedBy, revokedAt: new Date(record.revokedAt).toISOString() };
|
|
345
351
|
}
|
|
346
|
-
|
|
352
|
+
// An endpoint's key never expires; every other token does.
|
|
353
|
+
if (record.kind !== "key" && (record.expiresAt === null || record.expiresAt <= now.getTime())) {
|
|
354
|
+
return { status: "expired" };
|
|
355
|
+
}
|
|
347
356
|
if (!record.usable) return null;
|
|
348
357
|
const pins = record.kind === "child" ? record.pins ?? [] : undefined;
|
|
349
358
|
// A child token that names no model serves nothing.
|
|
@@ -355,6 +364,7 @@ export function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTo
|
|
|
355
364
|
clientId: record.clientId,
|
|
356
365
|
credentialIds: new Set(record.credentialIds),
|
|
357
366
|
budget: record.budget,
|
|
367
|
+
limits: record.limits,
|
|
358
368
|
...(pins === undefined ? {} : { pins }),
|
|
359
369
|
...(record.tags === null ? {} : { tags: record.tags }),
|
|
360
370
|
},
|