@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
|
@@ -2,7 +2,6 @@ import { type ActivityFilters } from "./filters.js";
|
|
|
2
2
|
import type { ActivityRoute } from "./http.js";
|
|
3
3
|
import { type ActivityDb } from "./sql.js";
|
|
4
4
|
export declare const EXCHANGE_STATES: readonly ["matched", "unmatched_call", "orphan_result"];
|
|
5
|
-
export type ExchangeState = (typeof EXCHANGE_STATES)[number];
|
|
6
5
|
export declare const EXCHANGE_MAX_LIMIT = 200;
|
|
7
6
|
export type ExchangeQuery = {
|
|
8
7
|
states: readonly string[];
|
|
@@ -29,7 +29,6 @@ export type Decimal = {
|
|
|
29
29
|
export declare function parseDecimal(value: string | number): Decimal;
|
|
30
30
|
export declare function addDecimals(left: Decimal, right: Decimal): Decimal;
|
|
31
31
|
export declare function subtractDecimals(left: Decimal, right: Decimal): Decimal;
|
|
32
|
-
export declare function compareDecimals(left: Decimal, right: Decimal): number;
|
|
33
32
|
/** Python's `str(Decimal)`. */
|
|
34
33
|
export declare function formatDecimal(value: Decimal): string;
|
|
35
34
|
/** Python's `decimal_text`: a numeric column's value as API text, or null. */
|
package/dist/activity/values.js
CHANGED
|
@@ -103,10 +103,6 @@ export function addDecimals(left, right) {
|
|
|
103
103
|
export function subtractDecimals(left, right) {
|
|
104
104
|
return addDecimals(left, { coefficient: -right.coefficient, exponent: right.exponent });
|
|
105
105
|
}
|
|
106
|
-
export function compareDecimals(left, right) {
|
|
107
|
-
const difference = subtractDecimals(left, right).coefficient;
|
|
108
|
-
return difference === 0n ? 0 : difference < 0n ? -1 : 1;
|
|
109
|
-
}
|
|
110
106
|
/** Python's `str(Decimal)`. */
|
|
111
107
|
export function formatDecimal(value) {
|
|
112
108
|
const negative = value.coefficient < 0n;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { ResolvedRouter } from "../types.js";
|
|
2
|
-
export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean, direct?: boolean): Record<string, unknown>;
|
|
3
|
-
export declare function codexModelsEtag(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">): string;
|
|
2
|
+
export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction" | "model_thinking_levels">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean, direct?: boolean): Record<string, unknown>;
|
|
3
|
+
export declare function codexModelsEtag(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">): string;
|
|
@@ -98,14 +98,18 @@ export function codexModelsResponse(router, imageInputFor, nativeCompactionFor =
|
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
100
|
/* A version of the list Codex's /model menu shows: it changes when a model
|
|
101
|
-
is added or removed,
|
|
101
|
+
is added or removed, dari/routing comes or goes, or a model's thinking
|
|
102
|
+
levels or default change. Sent as
|
|
102
103
|
`X-Models-Etag` on the catalog and on Codex's responses, it makes a running
|
|
103
104
|
Codex re-read the catalog after the first turn that sees a new value,
|
|
104
105
|
instead of on its next timed refresh. Codex reads it only from a successful
|
|
105
106
|
response; a refused stale pick carries the menu hint instead. */
|
|
106
107
|
export function codexModelsEtag(router) {
|
|
107
|
-
const
|
|
108
|
-
|
|
108
|
+
const menu = codexCatalogEntries(router, () => false).map((entry) => {
|
|
109
|
+
const levels = entry.supported_reasoning_levels.map((level) => level.effort);
|
|
110
|
+
return `${entry.slug} ${entry.default_reasoning_level ?? ""} ${levels.join(",")}`;
|
|
111
|
+
});
|
|
112
|
+
return createHash("sha256").update(menu.join("\n")).digest("hex").slice(0, 16);
|
|
109
113
|
}
|
|
110
114
|
function codexCatalogEntries(router, imageInputFor) {
|
|
111
115
|
return [
|
|
@@ -126,10 +130,33 @@ function codexCatalogEntries(router, imageInputFor) {
|
|
|
126
130
|
contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
|
|
127
131
|
hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
|
|
128
132
|
imageInput: imageInputFor(model),
|
|
129
|
-
|
|
130
|
-
?.map((effort) => effort === "off" ? "none" : effort),
|
|
131
|
-
defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
|
|
132
|
-
? "none" : router.model_configs?.[model]?.default_thinking_level,
|
|
133
|
+
...codexThinkingChoices(router, model),
|
|
133
134
|
})),
|
|
134
135
|
];
|
|
135
136
|
}
|
|
137
|
+
const codexEffort = (effort) => effort === "off" ? "none" : effort;
|
|
138
|
+
/* The thinking levels a pinned `dari/model/<id>` actually serves, so Codex's
|
|
139
|
+
/model and /effort menus offer only levels that run as picked. The gateway
|
|
140
|
+
keeps a requested level only when the router enables it for the model and
|
|
141
|
+
the model supports it (`clampRequestedEffort`, and candidate compatibility
|
|
142
|
+
in the router package); otherwise it drops the level and serves the
|
|
143
|
+
model's default if the router enables that, else the router's first
|
|
144
|
+
enabled level (`pickCandidate`). The menu shows that same set and default.
|
|
145
|
+
A model the router sets no levels for serves every level it supports. */
|
|
146
|
+
function codexThinkingChoices(router, model) {
|
|
147
|
+
const config = router.model_configs?.[model];
|
|
148
|
+
const supported = config?.supported_thinking_levels;
|
|
149
|
+
if (!supported) {
|
|
150
|
+
const fallback = config?.default_thinking_level;
|
|
151
|
+
return { defaultReasoningLevel: fallback ? codexEffort(fallback) : fallback };
|
|
152
|
+
}
|
|
153
|
+
const configured = router.model_thinking_levels?.[model] ?? supported;
|
|
154
|
+
const served = configured.filter((level) => supported.includes(level));
|
|
155
|
+
const modelDefault = config.default_thinking_level;
|
|
156
|
+
const fallback = modelDefault && served.includes(modelDefault) ? modelDefault : served[0];
|
|
157
|
+
return {
|
|
158
|
+
// Codex lists levels in the order given: keep the model's low-to-high order.
|
|
159
|
+
reasoningLevels: supported.filter((level) => served.includes(level)).map(codexEffort),
|
|
160
|
+
defaultReasoningLevel: fallback ? codexEffort(fallback) : null,
|
|
161
|
+
};
|
|
162
|
+
}
|
package/dist/link/budget.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkBudget, LinkLimit, LinkSpend, LinkUsageTotals } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkLimit, LinkSpend, LinkSubscription, LinkUsageTotals } from "../platform/platform.js";
|
|
2
2
|
/** The windows a budget can cap: five hours and one week. */
|
|
3
3
|
export declare const LINK_BUDGET_WINDOW_MINUTES: readonly [300, 10080];
|
|
4
4
|
/** The tokens a request used, as each kind is recorded. */
|
|
@@ -33,19 +33,32 @@ export declare function monthStart(now: Date): Date;
|
|
|
33
33
|
export declare function nextMonthStart(now: Date): Date;
|
|
34
34
|
/** The earliest use a grant's budget and spend need: its windows, and this month. */
|
|
35
35
|
export declare function usesSince(budget: readonly LinkBudget[], now: Date): number;
|
|
36
|
-
/** Each granted plan or key's spend this month
|
|
37
|
-
export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], now: Date): LinkSpend[];
|
|
38
|
-
/**
|
|
36
|
+
/** Each granted plan or key's spend this month and standing against its limit. */
|
|
37
|
+
export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], plans: readonly LinkSubscription[], now: Date): LinkSpend[];
|
|
38
|
+
/**
|
|
39
|
+
* Limits from a request: `[{credential_id, max_percent}]` for a plan or
|
|
40
|
+
* `[{credential_id, monthly_usd}]` for an API key (the other field absent or
|
|
41
|
+
* null), each a distinct plan or key;
|
|
42
|
+
* `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
|
|
43
|
+
*/
|
|
39
44
|
export declare function validLimits(value: unknown): LinkLimit[] | null;
|
|
40
|
-
export declare function limitsBody(limits: readonly LinkLimit[]): {
|
|
45
|
+
export declare function limitsBody(limits: readonly LinkLimit[]): ({
|
|
46
|
+
monthly_usd: number | undefined;
|
|
41
47
|
credential_id: string;
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
} | {
|
|
49
|
+
max_percent: number;
|
|
50
|
+
credential_id: string;
|
|
51
|
+
})[];
|
|
44
52
|
export declare function spendBody(spend: readonly LinkSpend[]): {
|
|
45
53
|
credential_id: string;
|
|
46
54
|
spent_usd: number;
|
|
55
|
+
requests: number;
|
|
56
|
+
tokens: number;
|
|
47
57
|
monthly_usd: number | null;
|
|
58
|
+
max_percent: number | null;
|
|
59
|
+
used_percent: number | null;
|
|
48
60
|
reached: boolean;
|
|
61
|
+
resets_at: string | null;
|
|
49
62
|
}[];
|
|
50
63
|
/** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
|
|
51
64
|
export declare function validBudget(value: unknown): LinkBudget[] | null;
|
package/dist/link/budget.js
CHANGED
|
@@ -10,11 +10,13 @@
|
|
|
10
10
|
A window at its cap is back once enough of its oldest requests roll off to
|
|
11
11
|
bring it under the cap again: `resetsAt` is when that happens.
|
|
12
12
|
|
|
13
|
-
A grant may also limit
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
A grant may also limit each of its plans and API keys. A plan's limit is a
|
|
14
|
+
share of its own quota: while any plan-wide window the provider last
|
|
15
|
+
reported is at `maxPercent` used (by anyone, so the rest stays the user's),
|
|
16
|
+
the plan leaves the grant until that window resets. A plan with no reported
|
|
17
|
+
usage is never at its limit. An API key's limit is what the grant may spend
|
|
18
|
+
on it in a calendar month (UTC), as its provider charged; at the limit it
|
|
19
|
+
leaves the grant until the month ends. The grant serves on the rest. */
|
|
18
20
|
/** The windows a budget can cap: five hours and one week. */
|
|
19
21
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080];
|
|
20
22
|
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
@@ -61,22 +63,53 @@ export function nextMonthStart(now) {
|
|
|
61
63
|
export function usesSince(budget, now) {
|
|
62
64
|
return Math.min(now.getTime() - budgetLookbackMs(budget), monthStart(now).getTime());
|
|
63
65
|
}
|
|
64
|
-
/** Each granted plan or key's spend this month
|
|
65
|
-
export function grantSpend(credentialIds, limits, uses, now) {
|
|
66
|
+
/** Each granted plan or key's spend this month and standing against its limit. */
|
|
67
|
+
export function grantSpend(credentialIds, limits, uses, plans, now) {
|
|
66
68
|
const since = monthStart(now).getTime();
|
|
67
69
|
const spent = new Map();
|
|
68
70
|
for (const use of uses) {
|
|
69
71
|
if (use.credentialId === null || use.at.getTime() < since)
|
|
70
72
|
continue;
|
|
71
|
-
|
|
73
|
+
const total = spent.get(use.credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
|
|
74
|
+
total.usd += use.costUsd;
|
|
75
|
+
total.requests += 1;
|
|
76
|
+
total.tokens += use.inputTokens + use.outputTokens + use.cacheReadTokens + use.cacheWriteTokens;
|
|
77
|
+
spent.set(use.credentialId, total);
|
|
72
78
|
}
|
|
73
79
|
return [...credentialIds].map((credentialId) => {
|
|
74
|
-
const spentUsd = spent.get(credentialId) ?? 0;
|
|
75
|
-
const
|
|
76
|
-
|
|
80
|
+
const { usd: spentUsd, requests, tokens } = spent.get(credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
|
|
81
|
+
const limit = limits.find((entry) => entry.credentialId === credentialId);
|
|
82
|
+
const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
|
|
83
|
+
.filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
|
|
84
|
+
const usedPercent = windows.length === 0 ? null : Math.max(...windows.map((window) => window.utilization * 100));
|
|
85
|
+
let resetsAt = null;
|
|
86
|
+
if (limit?.maxPercent !== undefined) {
|
|
87
|
+
const full = windows.filter((window) => window.utilization * 100 >= limit.maxPercent);
|
|
88
|
+
if (full.length > 0)
|
|
89
|
+
resetsAt = new Date(Math.max(...full.map((window) => Date.parse(window.resetsAt))));
|
|
90
|
+
}
|
|
91
|
+
else if (limit?.monthlyUsd !== undefined && spentUsd >= limit.monthlyUsd) {
|
|
92
|
+
resetsAt = nextMonthStart(now);
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
credentialId,
|
|
96
|
+
spentUsd,
|
|
97
|
+
requests,
|
|
98
|
+
tokens,
|
|
99
|
+
monthlyUsd: limit?.monthlyUsd ?? null,
|
|
100
|
+
maxPercent: limit?.maxPercent ?? null,
|
|
101
|
+
usedPercent,
|
|
102
|
+
reached: resetsAt !== null,
|
|
103
|
+
resetsAt: resetsAt?.toISOString() ?? null,
|
|
104
|
+
};
|
|
77
105
|
});
|
|
78
106
|
}
|
|
79
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* Limits from a request: `[{credential_id, max_percent}]` for a plan or
|
|
109
|
+
* `[{credential_id, monthly_usd}]` for an API key (the other field absent or
|
|
110
|
+
* null), each a distinct plan or key;
|
|
111
|
+
* `max_percent` is above 0 and at most 100, `monthly_usd` 0 or more.
|
|
112
|
+
*/
|
|
80
113
|
export function validLimits(value) {
|
|
81
114
|
if (!Array.isArray(value))
|
|
82
115
|
return null;
|
|
@@ -84,25 +117,42 @@ export function validLimits(value) {
|
|
|
84
117
|
for (const entry of value) {
|
|
85
118
|
if (typeof entry !== "object" || entry === null)
|
|
86
119
|
return null;
|
|
87
|
-
const { credential_id: credentialId, monthly_usd: monthlyUsd } = entry;
|
|
88
|
-
if (typeof credentialId !== "string" || credentialId.length === 0
|
|
89
|
-
|
|
90
|
-
|
|
120
|
+
const { credential_id: credentialId, monthly_usd: monthlyUsd, max_percent: maxPercent } = entry;
|
|
121
|
+
if (typeof credentialId !== "string" || credentialId.length === 0)
|
|
122
|
+
return null;
|
|
123
|
+
if (limits.some((other) => other.credentialId === credentialId))
|
|
124
|
+
return null;
|
|
125
|
+
if (monthlyUsd == null
|
|
126
|
+
&& typeof maxPercent === "number" && Number.isFinite(maxPercent) && maxPercent > 0 && maxPercent <= 100) {
|
|
127
|
+
limits.push({ credentialId, maxPercent });
|
|
128
|
+
}
|
|
129
|
+
else if (maxPercent == null
|
|
130
|
+
&& typeof monthlyUsd === "number" && Number.isFinite(monthlyUsd) && monthlyUsd >= 0) {
|
|
131
|
+
limits.push({ credentialId, monthlyUsd });
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
91
134
|
return null;
|
|
92
135
|
}
|
|
93
|
-
limits.push({ credentialId, monthlyUsd });
|
|
94
136
|
}
|
|
95
137
|
return limits;
|
|
96
138
|
}
|
|
97
139
|
export function limitsBody(limits) {
|
|
98
|
-
return limits.map((limit) => ({
|
|
140
|
+
return limits.map((limit) => ({
|
|
141
|
+
credential_id: limit.credentialId,
|
|
142
|
+
...(limit.maxPercent === undefined ? { monthly_usd: limit.monthlyUsd } : { max_percent: limit.maxPercent }),
|
|
143
|
+
}));
|
|
99
144
|
}
|
|
100
145
|
export function spendBody(spend) {
|
|
101
146
|
return spend.map((entry) => ({
|
|
102
147
|
credential_id: entry.credentialId,
|
|
103
148
|
spent_usd: entry.spentUsd,
|
|
149
|
+
requests: entry.requests,
|
|
150
|
+
tokens: entry.tokens,
|
|
104
151
|
monthly_usd: entry.monthlyUsd,
|
|
152
|
+
max_percent: entry.maxPercent,
|
|
153
|
+
used_percent: entry.usedPercent,
|
|
105
154
|
reached: entry.reached,
|
|
155
|
+
resets_at: entry.resetsAt,
|
|
106
156
|
}));
|
|
107
157
|
}
|
|
108
158
|
/** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
|
package/dist/link/endpoints.js
CHANGED
|
@@ -64,7 +64,7 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
64
64
|
import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
|
|
65
65
|
import { CANONICAL_MODELS, canonicalModelName } from "../models/canonical.js";
|
|
66
66
|
import { gatewayFor } from "../models/gateways.js";
|
|
67
|
-
import { budgetBody, limitsBody,
|
|
67
|
+
import { budgetBody, limitsBody, spendBody, validBudget, validLimits } from "./budget.js";
|
|
68
68
|
import { catalogModelFor } from "./grant_access.js";
|
|
69
69
|
import { requestTags } from "../runtime/request_tags.js";
|
|
70
70
|
import { parseJsonRequest } from "../ingress/json.js";
|
|
@@ -270,7 +270,7 @@ function credentialIdsFrom(value) {
|
|
|
270
270
|
function limitsFrom(value) {
|
|
271
271
|
const limits = validLimits(value ?? []);
|
|
272
272
|
if (limits === null) {
|
|
273
|
-
throw new HttpError(400, "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.", "invalid_request_error", "limits");
|
|
273
|
+
throw new HttpError(400, "limits must be a list of {credential_id, max_percent} for plans and {credential_id, monthly_usd} for API keys, with distinct credential_ids, max_percent above 0 and at most 100, and monthly_usd a dollar amount of 0 or more; [] removes them.", "invalid_request_error", "limits");
|
|
274
274
|
}
|
|
275
275
|
return limits;
|
|
276
276
|
}
|
|
@@ -1225,30 +1225,33 @@ ${session.account ? `<form method="post" action="${CONNECTIONS_PATH}">${csrf}${S
|
|
|
1225
1225
|
</div>`);
|
|
1226
1226
|
}
|
|
1227
1227
|
function connectionCard(connection, csrf) {
|
|
1228
|
-
const
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
};
|
|
1235
|
-
// The most the grant may spend on each plan or key a month.
|
|
1236
|
-
const spendLimit = (plan) => {
|
|
1228
|
+
const names = connection.subscriptions.map(planName);
|
|
1229
|
+
// A plan's account tells it apart only when the app shares two of the same name.
|
|
1230
|
+
const shown = (plan) => names.filter((name) => name === planName(plan)).length > 1 ? `${planName(plan)} (${planLabel(plan)})` : planName(plan);
|
|
1231
|
+
// One row per shared plan or key: a plan's use of its quota and the most of
|
|
1232
|
+
// it the app may use; a key's spend this month and the most it may spend.
|
|
1233
|
+
const row = (plan) => {
|
|
1237
1234
|
const spend = connection.spend.find((entry) => entry.credentialId === plan.id);
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1235
|
+
// A plan still limited in dollars, as before shares, keeps its dollars.
|
|
1236
|
+
const key = plan.apiKeyProvider !== undefined || (spend?.monthlyUsd ?? null) !== null;
|
|
1237
|
+
const field = `${key ? "usd" : "pct"}_${escapeHtml(plan.id)}`;
|
|
1238
|
+
const id = `${field}_${escapeHtml(connection.id)}`;
|
|
1239
|
+
const used = key
|
|
1240
|
+
? `${dollars(spend?.spentUsd ?? 0)} this month`
|
|
1241
|
+
: spend?.usedPercent == null ? "Usage not reported yet" : `Plan ${Math.round(spend.usedPercent)}% used`;
|
|
1242
|
+
const value = key ? spend?.monthlyUsd : spend?.maxPercent;
|
|
1243
|
+
return `<div class="limit">${logo(plan.apiKeyProvider ?? plan.provider, planName(plan))}<label class="grow" for="${id}"><strong>${escapeHtml(shown(plan))}</strong><small>${used}${spend?.reached ? ", at the limit" : ""}</small></label>
|
|
1244
|
+
<input id="${id}" type="text" inputmode="decimal" name="${field}" value="${value ?? ""}" placeholder="${key ? "$ / Month" : "% Of Plan"}" aria-label="${escapeHtml(shown(plan))} ${key ? "Monthly Limit ($)" : "Most Of Plan (%)"}" autocomplete="off"></div>`;
|
|
1242
1245
|
};
|
|
1246
|
+
const limited = connection.spend.some((entry) => entry.monthlyUsd !== null || entry.maxPercent !== null);
|
|
1243
1247
|
return `<form class="card" id="${escapeHtml(connection.id)}" method="post" action="${CONNECTIONS_PATH}">${csrf}
|
|
1244
1248
|
<input type="hidden" name="grant_id" value="${escapeHtml(connection.id)}">
|
|
1245
1249
|
<strong>${escapeHtml(connection.appName)}${connection.endpoint ? " (Endpoint)" : ""}</strong>
|
|
1246
|
-
<small>
|
|
1247
|
-
|
|
1248
|
-
${
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
<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>
|
|
1250
|
+
${connection.subscriptions.length === 0 ? "<small>Shares nothing</small>" : `<span class="logos" role="img" aria-label="Shares ${escapeHtml(connection.subscriptions.map(shown).join(", "))}">${[...new Map(connection.subscriptions.map((plan) => [plan.apiKeyProvider ?? plan.provider, plan])).values()].map((plan) => logo(plan.apiKeyProvider ?? plan.provider, planName(plan))).join("")}</span>`}
|
|
1251
|
+
${connection.subscriptions.length === 0 ? "" : `<details${limited ? " open" : ""}><summary>Set Limit</summary>
|
|
1252
|
+
${connection.subscriptions.map(row).join("\n")}
|
|
1253
|
+
<button class="btn outline" type="submit" name="decision" value="limits">Save</button></details>`}
|
|
1254
|
+
<div class="row"><button class="btn outline" type="submit" name="decision" value="disconnect">Disconnect</button></div>
|
|
1252
1255
|
</form>`;
|
|
1253
1256
|
}
|
|
1254
1257
|
async function connectionsSubmit(approval, request, form) {
|
|
@@ -1271,23 +1274,18 @@ async function connectionsSubmit(approval, request, form) {
|
|
|
1271
1274
|
await approval.disconnect(session.subject, grantId);
|
|
1272
1275
|
return back;
|
|
1273
1276
|
}
|
|
1274
|
-
if (decision === "
|
|
1275
|
-
const entries = [300, 10080].flatMap((minutes) => {
|
|
1276
|
-
const value = (form.get(`max_${minutes}`) ?? "").replace(/[\s,_]/g, "");
|
|
1277
|
-
return value === "" ? [] : [{ window_minutes: minutes, max_tokens: /^\d+$/.test(value) ? Number(value) : Number.NaN }];
|
|
1278
|
-
});
|
|
1279
|
-
const budget = validBudget(entries);
|
|
1280
|
-
if (budget === null)
|
|
1281
|
-
return await connectionsPage(approval, request, "Each limit is a whole number of tokens; leave it empty for none.");
|
|
1277
|
+
if (decision === "limits") {
|
|
1282
1278
|
const limits = validLimits([...form.entries()].flatMap(([field, raw]) => {
|
|
1283
|
-
const value = raw.replace(/[\s
|
|
1284
|
-
|
|
1279
|
+
const value = raw.replace(/[\s,$%]/g, "");
|
|
1280
|
+
const kind = field.slice(0, 4);
|
|
1281
|
+
if ((kind !== "usd_" && kind !== "pct_") || value === "")
|
|
1285
1282
|
return [];
|
|
1286
|
-
|
|
1283
|
+
const amount = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
|
|
1284
|
+
return [{ credential_id: field.slice(4), [kind === "usd_" ? "monthly_usd" : "max_percent"]: amount }];
|
|
1287
1285
|
}));
|
|
1288
|
-
if (limits === null)
|
|
1289
|
-
return await connectionsPage(approval, request, "Each
|
|
1290
|
-
|
|
1286
|
+
if (limits === null) {
|
|
1287
|
+
return await connectionsPage(approval, request, "Each plan limit is a percent above 0 and at most 100, and each key limit a dollar amount; leave it empty for none.");
|
|
1288
|
+
}
|
|
1291
1289
|
await approval.setLimits(session.subject, grantId, limits);
|
|
1292
1290
|
return back;
|
|
1293
1291
|
}
|
|
@@ -1317,9 +1315,6 @@ function planName(subscription) {
|
|
|
1317
1315
|
? `${subscription.name} API Key`
|
|
1318
1316
|
: KINDS[subscription.provider]?.name ?? subscription.name;
|
|
1319
1317
|
}
|
|
1320
|
-
function count(value) {
|
|
1321
|
-
return value.toLocaleString("en-US");
|
|
1322
|
-
}
|
|
1323
1318
|
// Back to the approval page by GET, so no form is left to resubmit.
|
|
1324
1319
|
function seeAuthorize(authorize, cookies) {
|
|
1325
1320
|
const headers = new Headers({ Location: `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`, "Cache-Control": "no-store" });
|
|
@@ -1811,13 +1806,17 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
|
|
|
1811
1806
|
.bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
|
|
1812
1807
|
.actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
|
|
1813
1808
|
.fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
|
|
1809
|
+
.card:has(details[open]) .logos{display:none}
|
|
1810
|
+
.logos{display:flex;gap:8px;margin:8px 0 0}.logos .logo,.limit .logo{width:16px;height:16px}
|
|
1811
|
+
.limit{display:flex;align-items:center;gap:10px;margin:10px 0 0}.limit small{display:block}.limit input{width:110px;margin:0}
|
|
1812
|
+
details{margin:12px 0 0}summary{cursor:pointer;list-style:none;display:inline-block;font-size:13px;color:var(--faint);text-decoration:underline;text-underline-offset:3px}summary::-webkit-details-marker{display:none}summary:hover{color:inherit}details[open] summary{display:none}details .btn{margin:12px 0 0}
|
|
1814
1813
|
.card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
|
|
1815
1814
|
.row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
|
|
1816
1815
|
.nav{position:absolute;top:10px;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--muted);cursor:pointer}
|
|
1817
1816
|
.nav:hover{background:rgba(237,237,237,.06);color:var(--ink)}.back{left:12px}.close{right:12px}
|
|
1818
1817
|
.done{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;margin:0 0 20px;border:1px solid rgba(142,230,189,.4);border-radius:6px;background:rgba(142,230,189,.1);color:var(--mint)}.done .icon{width:22px;height:22px}
|
|
1819
1818
|
a:focus-visible,button:focus-visible,input[type=checkbox]:focus-visible{outline:1px solid var(--mint);outline-offset:1px}
|
|
1820
|
-
[role=alert]{margin:16px 0
|
|
1819
|
+
[role=alert]{margin:16px 0 24px;padding:10px 12px;border:1px solid rgba(214,69,72,.5);border-radius:6px;background:rgba(214,69,72,.1);color:var(--ink);font-size:13px}
|
|
1821
1820
|
::selection{background:var(--mint);color:var(--page)}`;
|
|
1822
1821
|
function escapeHtml(value) {
|
|
1823
1822
|
return value
|
package/dist/link/errors.js
CHANGED
|
@@ -83,7 +83,7 @@ export function budgetExhausted(resetsAt) {
|
|
|
83
83
|
export function limitsReached(resetsAt) {
|
|
84
84
|
return {
|
|
85
85
|
code: "grant_budget_exhausted",
|
|
86
|
-
message: `Every plan and API key of this Dari Link grant is at the
|
|
86
|
+
message: `Every plan and API key of this Dari Link grant is at the limit the user set. The first is back at ${resetsAt.toISOString()}.`,
|
|
87
87
|
resets_at: resetsAt.toISOString(),
|
|
88
88
|
};
|
|
89
89
|
}
|
|
@@ -86,12 +86,17 @@ function clientReasoning(credentials, model, reasoning) {
|
|
|
86
86
|
const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
87
87
|
/* The model id in `models` a name means: the id itself, the one id it is the
|
|
88
88
|
bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
|
|
89
|
-
of those for a dated snapshot of it. A name two models share means neither.
|
|
89
|
+
of those for a dated snapshot of it. A name two models share means neither.
|
|
90
|
+
Names match in any case and answer the catalog's own id: some ids carry
|
|
91
|
+
capitals (`deepseek-ai/DeepSeek-V4.1-Flash-1017`), which a lowercased name
|
|
92
|
+
would never equal. */
|
|
90
93
|
export function catalogModelFor(name, models) {
|
|
94
|
+
const lower = models.map((id) => id.toLowerCase());
|
|
91
95
|
for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
const exact = lower.indexOf(candidate);
|
|
97
|
+
if (exact >= 0)
|
|
98
|
+
return models[exact];
|
|
99
|
+
const matches = models.filter((_, i) => lower[i].endsWith(`/${candidate}`));
|
|
95
100
|
if (matches.length === 1)
|
|
96
101
|
return matches[0];
|
|
97
102
|
}
|
package/dist/link/grants.d.ts
CHANGED
|
@@ -141,7 +141,6 @@ export declare function linkGrants(repo: LinkRepo): {
|
|
|
141
141
|
/** What a grant's requests used, filtered by tags and receive time. */
|
|
142
142
|
usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Promise<Omit<LinkUsage, "completeThrough">>;
|
|
143
143
|
};
|
|
144
|
-
export type LinkGrants = ReturnType<typeof linkGrants>;
|
|
145
144
|
export declare const TOKEN_PREFIX: Record<LinkTokenKind, string>;
|
|
146
145
|
/** What a stored access, child, or key token is now; null when it serves nothing. */
|
|
147
146
|
export declare function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import type { LinkPlatform } from "../platform/platform.js";
|
|
1
|
+
import type { LinkPlatform, LinkSubscription } from "../platform/platform.js";
|
|
2
2
|
import { type SelfHostedResolverDeps } from "../self_host/resolve.js";
|
|
3
|
+
import { type SubscriptionCredential } from "../self_host/subscriptions/index.js";
|
|
3
4
|
export declare function selfHostedLink(deps: Pick<SelfHostedResolverDeps, "gatewayKeys" | "subscriptions" | "links" | "env" | "config" | "fetch">): LinkPlatform;
|
|
5
|
+
export declare function linkSubscription(credential: SubscriptionCredential): LinkSubscription;
|
package/dist/link/self_hosted.js
CHANGED
|
@@ -154,7 +154,7 @@ function linkKey(key) {
|
|
|
154
154
|
usage: [],
|
|
155
155
|
};
|
|
156
156
|
}
|
|
157
|
-
function linkSubscription(credential) {
|
|
157
|
+
export function linkSubscription(credential) {
|
|
158
158
|
const now = new Date();
|
|
159
159
|
return {
|
|
160
160
|
id: credential.id,
|
|
@@ -165,11 +165,21 @@ function linkSubscription(credential) {
|
|
|
165
165
|
unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
|
|
166
166
|
? credential.unavailableUntil.toISOString()
|
|
167
167
|
: null,
|
|
168
|
-
usage: (currentUsage(credential, now)
|
|
169
|
-
...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
|
|
170
|
-
minutes: window.minutes,
|
|
171
|
-
utilization: window.utilization,
|
|
172
|
-
resetsAt: window.resetsAt.toISOString(),
|
|
173
|
-
})),
|
|
168
|
+
usage: linkUsageWindows(currentUsage(credential, now), now),
|
|
174
169
|
};
|
|
175
170
|
}
|
|
171
|
+
// Usage reported without per-window detail has only its binding window; it
|
|
172
|
+
// still counts against a plan's share limit, so it is one window here.
|
|
173
|
+
function linkUsageWindows(usage, now) {
|
|
174
|
+
if (usage === null || usage === undefined)
|
|
175
|
+
return [];
|
|
176
|
+
const windows = usage.windows.length > 0
|
|
177
|
+
? usage.windows
|
|
178
|
+
: [{ minutes: Math.max(1, Math.ceil((usage.resetsAt.getTime() - now.getTime()) / 60_000)), utilization: usage.utilization, resetsAt: usage.resetsAt }];
|
|
179
|
+
return windows.map((window) => ({
|
|
180
|
+
...("modelFamily" in window && window.modelFamily !== undefined ? { modelFamily: window.modelFamily } : {}),
|
|
181
|
+
minutes: window.minutes,
|
|
182
|
+
utilization: window.utilization,
|
|
183
|
+
resetsAt: window.resetsAt.toISOString(),
|
|
184
|
+
}));
|
|
185
|
+
}
|
package/dist/link/service.d.ts
CHANGED
|
@@ -124,9 +124,9 @@ export declare function newLinkClientSecret(): {
|
|
|
124
124
|
};
|
|
125
125
|
/**
|
|
126
126
|
* The grant a link token serves a request for: null when the key is no link
|
|
127
|
-
* token. Its plans and keys at their
|
|
128
|
-
*
|
|
129
|
-
*
|
|
127
|
+
* token. Its plans and keys at their limit are left out. Throws the 401 a dead
|
|
128
|
+
* token gets, and the 424 a grant at its budget, or with every plan and key at
|
|
129
|
+
* its limit, gets until it serves again.
|
|
130
130
|
*/
|
|
131
|
-
export declare function linkTokenGrant(store: LinkStore, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
|
|
131
|
+
export declare function linkTokenGrant(store: LinkStore, users: Pick<LinkUsers, "plansWithIds">, token: string, now?: Date): Promise<ActiveLinkGrant | null>;
|
|
132
132
|
export {};
|