@mupt-ai/dari-gateway 1.0.340 → 1.0.342
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/tool_exchanges.d.ts +0 -1
- package/dist/activity/values.d.ts +0 -1
- package/dist/activity/values.js +0 -4
- package/dist/ingress/codex_models.d.ts +2 -2
- package/dist/ingress/codex_models.js +34 -7
- package/dist/link/budget.d.ts +20 -7
- package/dist/link/budget.js +68 -18
- package/dist/link/endpoints.js +38 -39
- package/dist/link/errors.js +1 -1
- package/dist/link/grant_access.js +9 -4
- package/dist/link/grants.d.ts +0 -1
- package/dist/link/self_hosted.d.ts +3 -1
- package/dist/link/self_hosted.js +17 -7
- package/dist/link/service.d.ts +4 -4
- package/dist/link/service.js +41 -22
- package/dist/platform/platform.d.ts +13 -7
- package/dist/providers/subscription_limits.d.ts +6 -0
- package/dist/providers/subscription_limits.js +14 -0
- package/dist/self_host/resolve.js +2 -1
- package/dist/self_host/subscriptions/index.d.ts +3 -3
- package/dist/self_host/subscriptions/index.js +3 -3
- package/dist/self_host/subscriptions/usage.d.ts +1 -1
- package/dist/self_host/subscriptions/usage.js +28 -11
- package/dist/strategies/auto_routing_selector.js +7 -18
- package/dist/telemetry/tools/git_events.d.ts +0 -2
- package/dist/telemetry/tools/git_events.js +0 -4
- package/package.json +2 -2
- package/src/activity/tool_exchanges.ts +0 -1
- package/src/activity/values.ts +0 -5
- package/src/ingress/codex_models.ts +43 -10
- package/src/link/budget.ts +64 -21
- package/src/link/endpoints.ts +39 -38
- package/src/link/errors.ts +1 -1
- package/src/link/grant_access.ts +8 -3
- package/src/link/grants.ts +0 -2
- package/src/link/self_hosted.ts +17 -7
- package/src/link/service.ts +45 -23
- package/src/platform/platform.ts +16 -8
- package/src/providers/subscription_limits.ts +18 -0
- package/src/self_host/resolve.ts +2 -1
- package/src/self_host/subscriptions/index.ts +3 -3
- package/src/self_host/subscriptions/usage.ts +32 -10
- package/src/strategies/auto_routing_selector.ts +7 -22
- package/src/telemetry/tools/git_events.ts +0 -5
package/dist/link/service.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
`LINK_PERSONAL_CLIENT_ID`, which nothing can sign in to. */
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import { HttpError } from "../http/errors.js";
|
|
14
|
-
import { budgetStandings, grantSpend,
|
|
14
|
+
import { budgetStandings, grantSpend, overBudgetUntil, usesSince, } from "./budget.js";
|
|
15
15
|
import { budgetExhausted, limitsReached, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
16
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
17
|
/** The built-in app every personal endpoint's grant belongs to. */
|
|
@@ -25,13 +25,16 @@ export function linkPlatform(store, users) {
|
|
|
25
25
|
};
|
|
26
26
|
// A grant's budget windows and each granted plan or key's spend this month.
|
|
27
27
|
const standings = async (grant, now = new Date()) => {
|
|
28
|
-
const uses = await
|
|
28
|
+
const [uses, plans] = await Promise.all([
|
|
29
|
+
store.budgetUses(grant.id, usesSince(grant.budget, now)),
|
|
30
|
+
users.plansWithIds(grant.credentialIds),
|
|
31
|
+
]);
|
|
29
32
|
return {
|
|
30
33
|
budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
|
|
31
34
|
...standing,
|
|
32
35
|
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
33
36
|
})),
|
|
34
|
-
spend: grantSpend(grant.credentialIds, grant.limits, uses, now),
|
|
37
|
+
spend: grantSpend(grant.credentialIds, grant.limits, uses, plans, now),
|
|
35
38
|
};
|
|
36
39
|
};
|
|
37
40
|
const publicGrant = ({ subject: _, ...grant }) => ({
|
|
@@ -44,13 +47,12 @@ export function linkPlatform(store, users) {
|
|
|
44
47
|
});
|
|
45
48
|
// Plans and keys the user can grant, and limits only on them.
|
|
46
49
|
const ownedCredentials = async (subject, credentialIds, limits = []) => {
|
|
47
|
-
const
|
|
50
|
+
const plans = await users.plans(subject);
|
|
51
|
+
const owned = new Set(plans.map((plan) => plan.id));
|
|
48
52
|
if (credentialIds.length === 0 || !credentialIds.every((id) => owned.has(id))) {
|
|
49
53
|
throw new HttpError(400, "Choose one or more of your connected plans or API keys.", "invalid_request");
|
|
50
54
|
}
|
|
51
|
-
|
|
52
|
-
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
53
|
-
}
|
|
55
|
+
requireLimitsFit(limits, credentialIds, plans);
|
|
54
56
|
return [...new Set(credentialIds)].sort();
|
|
55
57
|
};
|
|
56
58
|
// The one user a key acts for: endpoints are personal, so an operator key
|
|
@@ -152,9 +154,6 @@ export function linkPlatform(store, users) {
|
|
|
152
154
|
async disconnect(subject, grantId) {
|
|
153
155
|
return (await ownGrant(subject, grantId)) !== null && (await revoke(grantId));
|
|
154
156
|
},
|
|
155
|
-
async setBudget(subject, grantId, budget) {
|
|
156
|
-
return (await ownGrant(subject, grantId)) !== null && (await store.updateGrant(grantId, { budget }));
|
|
157
|
-
},
|
|
158
157
|
async setLimits(subject, grantId, limits) {
|
|
159
158
|
const grant = await ownGrant(subject, grantId);
|
|
160
159
|
if (grant === null)
|
|
@@ -257,9 +256,7 @@ export function linkPlatform(store, users) {
|
|
|
257
256
|
const grant = await ownGrant(subject, grantId);
|
|
258
257
|
if (grant === null)
|
|
259
258
|
return false;
|
|
260
|
-
|
|
261
|
-
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
262
|
-
}
|
|
259
|
+
requireLimitsFit(limits, grant.credentialIds, await users.plansWithIds(grant.credentialIds));
|
|
263
260
|
return await store.updateGrant(grantId, { limits });
|
|
264
261
|
},
|
|
265
262
|
async setBudget({ apiKey, grantId, budget }) {
|
|
@@ -288,6 +285,22 @@ export function newLinkApp(request) {
|
|
|
288
285
|
};
|
|
289
286
|
return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
|
|
290
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Limits only on the grant's plans and keys, and a share of quota only on a
|
|
290
|
+
* plan. A plan may still carry dollars a month, as limits did before shares;
|
|
291
|
+
* the apps offer a share for a plan that has none.
|
|
292
|
+
*/
|
|
293
|
+
function requireLimitsFit(limits, credentialIds, plans) {
|
|
294
|
+
if (!limits.every((limit) => credentialIds.includes(limit.credentialId))) {
|
|
295
|
+
throw new HttpError(400, "Set limits only on the plans and keys the grant shares.", "invalid_request");
|
|
296
|
+
}
|
|
297
|
+
for (const limit of limits) {
|
|
298
|
+
const key = plans.find((plan) => plan.id === limit.credentialId)?.apiKeyProvider !== undefined;
|
|
299
|
+
if (key && limit.monthlyUsd === undefined) {
|
|
300
|
+
throw new HttpError(400, "Limit an API key with monthly_usd; max_percent is for plans.", "invalid_request");
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
291
304
|
/** A confidential app's client secret, and the hash that is kept of it. */
|
|
292
305
|
export function newLinkClientSecret() {
|
|
293
306
|
const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
|
|
@@ -295,11 +308,11 @@ export function newLinkClientSecret() {
|
|
|
295
308
|
}
|
|
296
309
|
/**
|
|
297
310
|
* The grant a link token serves a request for: null when the key is no link
|
|
298
|
-
* token. Its plans and keys at their
|
|
299
|
-
*
|
|
300
|
-
*
|
|
311
|
+
* token. Its plans and keys at their limit are left out. Throws the 401 a dead
|
|
312
|
+
* token gets, and the 424 a grant at its budget, or with every plan and key at
|
|
313
|
+
* its limit, gets until it serves again.
|
|
301
314
|
*/
|
|
302
|
-
export async function linkTokenGrant(store, token, now = new Date()) {
|
|
315
|
+
export async function linkTokenGrant(store, users, token, now = new Date()) {
|
|
303
316
|
const auth = await linkGrants(store).authenticate(token, now);
|
|
304
317
|
if (auth === null)
|
|
305
318
|
return null;
|
|
@@ -314,12 +327,18 @@ export async function linkTokenGrant(store, token, now = new Date()) {
|
|
|
314
327
|
const back = overBudgetUntil(budgetStandings(grant.budget, uses, now));
|
|
315
328
|
if (back !== undefined)
|
|
316
329
|
throw linkUnavailableError(budgetExhausted(back));
|
|
317
|
-
|
|
318
|
-
if (reached.size === 0)
|
|
330
|
+
if (grant.limits.length === 0)
|
|
319
331
|
return grant;
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
332
|
+
const plans = grant.limits.some((limit) => limit.maxPercent !== undefined)
|
|
333
|
+
? await users.plansWithIds(grant.limits.map((limit) => limit.credentialId))
|
|
334
|
+
: [];
|
|
335
|
+
const reached = grantSpend(grant.credentialIds, grant.limits, uses, plans, now).filter((entry) => entry.reached);
|
|
336
|
+
if (reached.length === 0)
|
|
337
|
+
return grant;
|
|
338
|
+
const credentialIds = new Set([...grant.credentialIds].filter((id) => !reached.some((entry) => entry.credentialId === id)));
|
|
339
|
+
if (credentialIds.size === 0) {
|
|
340
|
+
throw linkUnavailableError(limitsReached(new Date(Math.min(...reached.map((entry) => Date.parse(entry.resetsAt))))));
|
|
341
|
+
}
|
|
323
342
|
return { ...grant, credentialIds };
|
|
324
343
|
}
|
|
325
344
|
function endpointName(name) {
|
|
@@ -281,8 +281,6 @@ export type LinkApprovalPage = {
|
|
|
281
281
|
connections(subject: string): Promise<LinkConnection[]>;
|
|
282
282
|
/** The user ends one of their grants; false when they have none by that id. */
|
|
283
283
|
disconnect(subject: string, grantId: string): Promise<boolean>;
|
|
284
|
-
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
285
|
-
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
286
284
|
/** Replace one of the user's grants' monthly spend limits; false when they have none by that id. */
|
|
287
285
|
setLimits(subject: string, grantId: string, limits: LinkLimit[]): Promise<boolean>;
|
|
288
286
|
};
|
|
@@ -336,20 +334,28 @@ export type LinkBudget = {
|
|
|
336
334
|
maxTokens: number;
|
|
337
335
|
};
|
|
338
336
|
/**
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
337
|
+
* A grant's limit on one of its plans or API keys; exactly one field is set.
|
|
338
|
+
* A plan leaves the grant while any of its plan-wide quota windows is at
|
|
339
|
+
* `maxPercent` used, whoever used it, until that window resets: the rest is
|
|
340
|
+
* the user's. An API key leaves it once the grant's spend on it this calendar
|
|
341
|
+
* month (UTC) reaches `monthlyUsd`. See link/budget.ts.
|
|
342
342
|
*/
|
|
343
343
|
export type LinkLimit = {
|
|
344
344
|
credentialId: string;
|
|
345
|
-
|
|
345
|
+
maxPercent?: number;
|
|
346
|
+
monthlyUsd?: number;
|
|
346
347
|
};
|
|
347
|
-
/** A granted plan or key's spend
|
|
348
|
+
/** A granted plan or key's spend and standing, and its limit when it has one. */
|
|
348
349
|
export type LinkSpend = {
|
|
349
350
|
credentialId: string;
|
|
350
351
|
spentUsd: number;
|
|
352
|
+
requests: number;
|
|
353
|
+
tokens: number;
|
|
351
354
|
monthlyUsd: number | null;
|
|
355
|
+
maxPercent: number | null;
|
|
356
|
+
usedPercent: number | null;
|
|
352
357
|
reached: boolean;
|
|
358
|
+
resetsAt: string | null;
|
|
353
359
|
};
|
|
354
360
|
/** A budget window as it stands for a grant. */
|
|
355
361
|
export type LinkBudgetStanding = {
|
|
@@ -48,6 +48,12 @@ export declare function subscriptionUsageFromHeaders(provider: string, keySource
|
|
|
48
48
|
* percent that may exceed 100.
|
|
49
49
|
*/
|
|
50
50
|
export declare function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null;
|
|
51
|
+
/**
|
|
52
|
+
* The Token Pass usage AI Gateway reports at `GET /v1/credits`:
|
|
53
|
+
* `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
|
|
54
|
+
* or null while Vercel cannot read the balance.
|
|
55
|
+
*/
|
|
56
|
+
export declare function tokenPassUsageFromCredits(credits: unknown, now: Date): SubscriptionUsage | null;
|
|
51
57
|
/**
|
|
52
58
|
* The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
|
|
53
59
|
* own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
|
|
@@ -75,6 +75,20 @@ export function museSubscriptionUsage(snapshot, now) {
|
|
|
75
75
|
// OpenCode Go's windows by their usage report names; the monthly one follows
|
|
76
76
|
// the billing cycle.
|
|
77
77
|
const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]];
|
|
78
|
+
// Each Token Pass billing period grants $150 of credit; Vercel reports only
|
|
79
|
+
// what remains, so usage is measured against the full grant.
|
|
80
|
+
const TOKEN_PASS_CREDIT_USD = 150;
|
|
81
|
+
/**
|
|
82
|
+
* The Token Pass usage AI Gateway reports at `GET /v1/credits`:
|
|
83
|
+
* `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
|
|
84
|
+
* or null while Vercel cannot read the balance.
|
|
85
|
+
*/
|
|
86
|
+
export function tokenPassUsageFromCredits(credits, now) {
|
|
87
|
+
const pass = isRecord(credits) && isRecord(credits.token_pass) ? credits.token_pass : null;
|
|
88
|
+
if (pass === null || typeof pass.remaining !== "string" || typeof pass.resets_at !== "string")
|
|
89
|
+
return null;
|
|
90
|
+
return subscriptionUsageFromWindows([{ minutes: 30 * 24 * 60, used: 1 - Number(pass.remaining) / TOKEN_PASS_CREDIT_USD, resetsAt: new Date(pass.resets_at) }], now);
|
|
91
|
+
}
|
|
78
92
|
/**
|
|
79
93
|
* The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
|
|
80
94
|
* own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
|
|
@@ -8,6 +8,7 @@ import { gatewayFor } from "../models/gateways.js";
|
|
|
8
8
|
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
9
9
|
import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
|
|
10
10
|
import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
|
|
11
|
+
import { linkSubscription } from "../link/self_hosted.js";
|
|
11
12
|
import { linkTokenGrant } from "../link/service.js";
|
|
12
13
|
import { servedRouter } from "./router_specs.js";
|
|
13
14
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
@@ -31,7 +32,7 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
|
|
|
31
32
|
*/
|
|
32
33
|
export async function resolveSelfHostedRouter(deps, request) {
|
|
33
34
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
34
|
-
const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
|
|
35
|
+
const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
|
|
35
36
|
if (keyIndex === null && grant === null) {
|
|
36
37
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
37
38
|
}
|
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
* database file; protect that file like a secret.
|
|
11
11
|
* - `access.ts`: `freshAccessToken` refreshes a token expiring within five
|
|
12
12
|
* minutes before handing it out, one refresh per credential at a time.
|
|
13
|
-
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go
|
|
14
|
-
* usage
|
|
15
|
-
* asks.
|
|
13
|
+
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
|
|
14
|
+
* plan usage from their usage endpoints, which their responses never report,
|
|
15
|
+
* when the accounts view asks.
|
|
16
16
|
* - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
|
|
17
17
|
* Dari CLI uses to connect, list, rename, release, and disconnect
|
|
18
18
|
* subscriptions. The caller authenticates the request first.
|
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
* database file; protect that file like a secret.
|
|
11
11
|
* - `access.ts`: `freshAccessToken` refreshes a token expiring within five
|
|
12
12
|
* minutes before handing it out, one refresh per credential at a time.
|
|
13
|
-
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go
|
|
14
|
-
* usage
|
|
15
|
-
* asks.
|
|
13
|
+
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
|
|
14
|
+
* plan usage from their usage endpoints, which their responses never report,
|
|
15
|
+
* when the accounts view asks.
|
|
16
16
|
* - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
|
|
17
17
|
* Dari CLI uses to connect, list, rename, release, and disconnect
|
|
18
18
|
* subscriptions. The caller authenticates the request first.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { OAuthFetch } from "./oauth.js";
|
|
2
2
|
import type { SubscriptionStore } from "./store.js";
|
|
3
|
-
/** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
|
|
3
|
+
/** Read every stale OpenCode Go and Token Pass plan again; a failed read keeps the last one. */
|
|
4
4
|
export declare function refreshStaleUsage(store: SubscriptionStore, options: {
|
|
5
5
|
fetch: OAuthFetch;
|
|
6
6
|
now?: Date;
|
|
@@ -1,24 +1,26 @@
|
|
|
1
|
-
import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
|
|
1
|
+
import { openCodeGoUsageFromReport, tokenPassUsageFromCredits } from "../../providers/subscription_limits.js";
|
|
2
2
|
import { refreshedAccessToken } from "./access.js";
|
|
3
3
|
/**
|
|
4
4
|
* Claude Code, ChatGPT, and Muse Code report usage on the responses the
|
|
5
|
-
* gateway serves. OpenCode Go
|
|
6
|
-
* that takes the plan's workspace,
|
|
7
|
-
*
|
|
5
|
+
* gateway serves. OpenCode Go and Vercel Token Pass do not: Go reports it from
|
|
6
|
+
* a usage endpoint that takes the plan's workspace, and Token Pass its
|
|
7
|
+
* remaining credit from AI Gateway's credits endpoint. The accounts view reads
|
|
8
|
+
* these again when the last reading is stale.
|
|
8
9
|
*/
|
|
9
10
|
// A read, failed or not, is not repeated within this interval.
|
|
10
11
|
const READ_INTERVAL_MS = 60_000;
|
|
11
12
|
const READ_TIMEOUT_MS = 8_000;
|
|
12
13
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
14
|
+
const TOKEN_PASS_CREDITS_URL = "https://ai-gateway.vercel.sh/v1/credits";
|
|
13
15
|
// Reads that recorded nothing (failed, or no running window), so such a plan is
|
|
14
16
|
// not re-read on every listing. A recorded reading stamps the credential
|
|
15
17
|
// itself, which a reconnect clears.
|
|
16
18
|
const unrecordedAt = new Map();
|
|
17
|
-
/** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
|
|
19
|
+
/** Read every stale OpenCode Go and Token Pass plan again; a failed read keeps the last one. */
|
|
18
20
|
export async function refreshStaleUsage(store, options) {
|
|
19
21
|
const now = options.now ?? new Date();
|
|
20
22
|
const due = (at) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
|
|
21
|
-
const stale = store.list("opencode_go").filter((credential) => due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id)));
|
|
23
|
+
const stale = [...store.list("opencode_go"), ...store.list("vercel_token_pass")].filter((credential) => due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id)));
|
|
22
24
|
await Promise.all(stale.map(async (credential) => {
|
|
23
25
|
unrecordedAt.set(credential.id, now.getTime());
|
|
24
26
|
try {
|
|
@@ -31,6 +33,15 @@ export async function refreshStaleUsage(store, options) {
|
|
|
31
33
|
}
|
|
32
34
|
async function readUsage(store, credential, options) {
|
|
33
35
|
const token = await refreshedAccessToken(store, credential, options);
|
|
36
|
+
const usage = credential.provider === "vercel_token_pass"
|
|
37
|
+
? await readTokenPassUsage(token, options)
|
|
38
|
+
: await readOpenCodeGoUsage(credential, token, options);
|
|
39
|
+
if (usage === null)
|
|
40
|
+
return;
|
|
41
|
+
unrecordedAt.delete(credential.id);
|
|
42
|
+
store.recordUsage(credential.id, usage, options.now);
|
|
43
|
+
}
|
|
44
|
+
async function readOpenCodeGoUsage(credential, token, options) {
|
|
34
45
|
const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
|
|
35
46
|
method: "GET",
|
|
36
47
|
headers: {
|
|
@@ -44,9 +55,15 @@ async function readUsage(store, credential, options) {
|
|
|
44
55
|
// Go answers 403 for a workspace without a Go plan.
|
|
45
56
|
if (!response.ok)
|
|
46
57
|
throw new Error(`OpenCode Go usage read failed with status ${response.status}.`);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
58
|
+
return openCodeGoUsageFromReport(await response.json(), options.now);
|
|
59
|
+
}
|
|
60
|
+
async function readTokenPassUsage(token, options) {
|
|
61
|
+
const response = await options.fetch(TOKEN_PASS_CREDITS_URL, {
|
|
62
|
+
method: "GET",
|
|
63
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${token}`, "User-Agent": "dari-gateway" },
|
|
64
|
+
signal: AbortSignal.timeout(READ_TIMEOUT_MS),
|
|
65
|
+
});
|
|
66
|
+
if (!response.ok)
|
|
67
|
+
throw new Error(`Token Pass usage read failed with status ${response.status}.`);
|
|
68
|
+
return tokenPassUsageFromCredits(await response.json(), options.now);
|
|
52
69
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestAutoRouterSelection } from "@mupt-ai/dari-router";
|
|
1
2
|
import { parseSelectorDecision, SELECTOR_LEASE_TURNS } from "@mupt-ai/dari-router/policy-engine";
|
|
2
3
|
import { HttpError } from "../http/errors.js";
|
|
3
4
|
export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-router";
|
|
@@ -5,7 +6,6 @@ export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-rout
|
|
|
5
6
|
// @mupt-ai/dari-router, which calls the same API.
|
|
6
7
|
const AUTO_ROUTER_MODEL = "dari/auto-router";
|
|
7
8
|
const AUTO_ROUTER_CONTEXT_WINDOW_CHARS = 32_000;
|
|
8
|
-
const AUTO_ROUTER_TIMEOUT_MS = 30_000;
|
|
9
9
|
/**
|
|
10
10
|
* Choose among a router's models with Dari Auto Routing, the hosted routing
|
|
11
11
|
* policy. Each selection is one call to the Auto Router API with a Dari API
|
|
@@ -16,10 +16,6 @@ export function createAutoRoutingSelectorBackend(config) {
|
|
|
16
16
|
if (!apiKey) {
|
|
17
17
|
throw new Error("Dari Auto Routing needs an API key.");
|
|
18
18
|
}
|
|
19
|
-
const endpoint = (config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT)
|
|
20
|
-
.replace(/\/+$/, "")
|
|
21
|
-
.replace(/\/select$/, "");
|
|
22
|
-
const fetchImpl = config.fetch ?? fetch;
|
|
23
19
|
return {
|
|
24
20
|
selectorModel: AUTO_ROUTER_MODEL,
|
|
25
21
|
contextWindowChars: async () => AUTO_ROUTER_CONTEXT_WINDOW_CHARS,
|
|
@@ -27,25 +23,18 @@ export function createAutoRoutingSelectorBackend(config) {
|
|
|
27
23
|
// the policy rather than the runtime's stateless hold.
|
|
28
24
|
negotiatedLeaseTurns: async () => SELECTOR_LEASE_TURNS,
|
|
29
25
|
select: async (args) => {
|
|
30
|
-
let
|
|
26
|
+
let outputText;
|
|
31
27
|
try {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
},
|
|
38
|
-
body: JSON.stringify(args.selectorRequest),
|
|
39
|
-
signal: AbortSignal.timeout(AUTO_ROUTER_TIMEOUT_MS),
|
|
28
|
+
outputText = await requestAutoRouterSelection({
|
|
29
|
+
apiKey,
|
|
30
|
+
endpoint: config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT,
|
|
31
|
+
request: args.selectorRequest,
|
|
32
|
+
fetch: config.fetch,
|
|
40
33
|
});
|
|
41
34
|
}
|
|
42
35
|
catch {
|
|
43
36
|
throw new HttpError(502, "Dari Auto Routing request failed.", "selector_execution_failed");
|
|
44
37
|
}
|
|
45
|
-
if (!response.ok) {
|
|
46
|
-
throw new HttpError(502, `Dari Auto Routing returned HTTP ${response.status}.`, "selector_execution_failed");
|
|
47
|
-
}
|
|
48
|
-
const outputText = await response.text();
|
|
49
38
|
return {
|
|
50
39
|
decision: parseSelectorDecision(outputText).decision,
|
|
51
40
|
selectorModel: args.selectorModel,
|
|
@@ -31,6 +31,4 @@ export type CommitEvent = {
|
|
|
31
31
|
};
|
|
32
32
|
/** The GitHub pull requests and pushes in the request's newly submitted tool results. */
|
|
33
33
|
export declare function gitEvents(request: InteractionRequest, zdr: boolean): GitEventReport[];
|
|
34
|
-
/** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
|
|
35
|
-
export declare function allGitEvents(request: InteractionRequest): GitEventReport[];
|
|
36
34
|
export {};
|
|
@@ -25,10 +25,6 @@ export function gitEvents(request, zdr) {
|
|
|
25
25
|
return [];
|
|
26
26
|
return gitEventsIn(request.items, newlySubmittedToolResults(request).results.map(({ ordinal }) => ordinal));
|
|
27
27
|
}
|
|
28
|
-
/** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
|
|
29
|
-
export function allGitEvents(request) {
|
|
30
|
-
return gitEventsIn(request.items, request.items.flatMap((item, ordinal) => (item.type === "tool_result" ? [ordinal] : [])));
|
|
31
|
-
}
|
|
32
28
|
function gitEventsIn(items, resultOrdinals) {
|
|
33
29
|
const calls = new Map();
|
|
34
30
|
for (const item of items) {
|
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.342",
|
|
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.342",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -18,7 +18,6 @@ import { join, raw, sql, type ActivityDb, type Sql } from "./sql.js";
|
|
|
18
18
|
import { formatInstant, readInt, readOptionalInstant, readOptionalString } from "./values.js";
|
|
19
19
|
|
|
20
20
|
export const EXCHANGE_STATES = ["matched", "unmatched_call", "orphan_result"] as const;
|
|
21
|
-
export type ExchangeState = (typeof EXCHANGE_STATES)[number];
|
|
22
21
|
export const EXCHANGE_MAX_LIMIT = 200;
|
|
23
22
|
const EXCHANGE_MAX_REQUEST_IDS = 100;
|
|
24
23
|
|
package/src/activity/values.ts
CHANGED
|
@@ -119,11 +119,6 @@ export function subtractDecimals(left: Decimal, right: Decimal): Decimal {
|
|
|
119
119
|
return addDecimals(left, { coefficient: -right.coefficient, exponent: right.exponent });
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
export function compareDecimals(left: Decimal, right: Decimal): number {
|
|
123
|
-
const difference = subtractDecimals(left, right).coefficient;
|
|
124
|
-
return difference === 0n ? 0 : difference < 0n ? -1 : 1;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
122
|
/** Python's `str(Decimal)`. */
|
|
128
123
|
export function formatDecimal(value: Decimal): string {
|
|
129
124
|
const negative = value.coefficient < 0n;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
|
|
3
|
+
import type { ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
3
4
|
import type { ResolvedRouter } from "../types.js";
|
|
4
5
|
import { CANONICAL_ROUTER_MODEL, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
5
6
|
import { effectiveContextWindow } from "../models/context_limits.js";
|
|
@@ -112,7 +113,7 @@ function codexReadable(entry: Record<string, unknown>): Record<string, unknown>
|
|
|
112
113
|
that this gateway serves one, so it can point Codex at the URL instead of
|
|
113
114
|
a snapshot that goes stale when the router's models change. */
|
|
114
115
|
export function codexModelsResponse(
|
|
115
|
-
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">,
|
|
116
|
+
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction" | "model_thinking_levels">,
|
|
116
117
|
imageInputFor: (model: string) => boolean,
|
|
117
118
|
nativeCompactionFor: (model: string) => boolean = () => false,
|
|
118
119
|
direct = false,
|
|
@@ -127,20 +128,24 @@ export function codexModelsResponse(
|
|
|
127
128
|
}
|
|
128
129
|
|
|
129
130
|
/* A version of the list Codex's /model menu shows: it changes when a model
|
|
130
|
-
is added or removed,
|
|
131
|
+
is added or removed, dari/routing comes or goes, or a model's thinking
|
|
132
|
+
levels or default change. Sent as
|
|
131
133
|
`X-Models-Etag` on the catalog and on Codex's responses, it makes a running
|
|
132
134
|
Codex re-read the catalog after the first turn that sees a new value,
|
|
133
135
|
instead of on its next timed refresh. Codex reads it only from a successful
|
|
134
136
|
response; a refused stale pick carries the menu hint instead. */
|
|
135
137
|
export function codexModelsEtag(
|
|
136
|
-
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
|
|
138
|
+
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">,
|
|
137
139
|
): string {
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
+
const menu = codexCatalogEntries(router, () => false).map((entry) => {
|
|
141
|
+
const levels = (entry.supported_reasoning_levels as Array<{ effort: string }>).map((level) => level.effort);
|
|
142
|
+
return `${entry.slug} ${entry.default_reasoning_level ?? ""} ${levels.join(",")}`;
|
|
143
|
+
});
|
|
144
|
+
return createHash("sha256").update(menu.join("\n")).digest("hex").slice(0, 16);
|
|
140
145
|
}
|
|
141
146
|
|
|
142
147
|
function codexCatalogEntries(
|
|
143
|
-
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
|
|
148
|
+
router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">,
|
|
144
149
|
imageInputFor: (model: string) => boolean,
|
|
145
150
|
): Record<string, unknown>[] {
|
|
146
151
|
return [
|
|
@@ -162,11 +167,39 @@ function codexCatalogEntries(
|
|
|
162
167
|
contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
|
|
163
168
|
hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
|
|
164
169
|
imageInput: imageInputFor(model),
|
|
165
|
-
|
|
166
|
-
?.map((effort) => effort === "off" ? "none" : effort),
|
|
167
|
-
defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
|
|
168
|
-
? "none" : router.model_configs?.[model]?.default_thinking_level,
|
|
170
|
+
...codexThinkingChoices(router, model),
|
|
169
171
|
})
|
|
170
172
|
),
|
|
171
173
|
];
|
|
172
174
|
}
|
|
175
|
+
|
|
176
|
+
const codexEffort = (effort: ReasoningEffort): string => effort === "off" ? "none" : effort;
|
|
177
|
+
|
|
178
|
+
/* The thinking levels a pinned `dari/model/<id>` actually serves, so Codex's
|
|
179
|
+
/model and /effort menus offer only levels that run as picked. The gateway
|
|
180
|
+
keeps a requested level only when the router enables it for the model and
|
|
181
|
+
the model supports it (`clampRequestedEffort`, and candidate compatibility
|
|
182
|
+
in the router package); otherwise it drops the level and serves the
|
|
183
|
+
model's default if the router enables that, else the router's first
|
|
184
|
+
enabled level (`pickCandidate`). The menu shows that same set and default.
|
|
185
|
+
A model the router sets no levels for serves every level it supports. */
|
|
186
|
+
function codexThinkingChoices(
|
|
187
|
+
router: Pick<ResolvedRouter, "model_configs" | "model_thinking_levels">,
|
|
188
|
+
model: string,
|
|
189
|
+
): Pick<CodexCatalogEntry, "reasoningLevels" | "defaultReasoningLevel"> {
|
|
190
|
+
const config = router.model_configs?.[model];
|
|
191
|
+
const supported = config?.supported_thinking_levels;
|
|
192
|
+
if (!supported) {
|
|
193
|
+
const fallback = config?.default_thinking_level;
|
|
194
|
+
return { defaultReasoningLevel: fallback ? codexEffort(fallback) : fallback };
|
|
195
|
+
}
|
|
196
|
+
const configured = router.model_thinking_levels?.[model] ?? supported;
|
|
197
|
+
const served = configured.filter((level) => supported.includes(level));
|
|
198
|
+
const modelDefault = config.default_thinking_level;
|
|
199
|
+
const fallback = modelDefault && served.includes(modelDefault) ? modelDefault : served[0];
|
|
200
|
+
return {
|
|
201
|
+
// Codex lists levels in the order given: keep the model's low-to-high order.
|
|
202
|
+
reasoningLevels: supported.filter((level) => served.includes(level)).map(codexEffort),
|
|
203
|
+
defaultReasoningLevel: fallback ? codexEffort(fallback) : null,
|
|
204
|
+
};
|
|
205
|
+
}
|