tuxevil-rotator 4.3.0 → 4.4.1
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/CHANGELOG.md +33 -0
- package/README.md +5 -2
- package/package.json +5 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/auto-access-shadow.ts +11 -0
- package/src/auto-model-access.ts +185 -0
- package/src/auto-output-health.ts +12 -0
- package/src/auto-routing-evaluation.ts +80 -0
- package/src/auto-routing-quality.ts +308 -0
- package/src/auto-routing.ts +403 -26
- package/src/compat.ts +223 -36
- package/src/compression/index.ts +6 -6
- package/src/compression/lite.ts +3 -9
- package/src/compression/rtk/index.ts +0 -3
- package/src/config-defaults.ts +7 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/model-access-api.ts +74 -0
- package/src/model-access.ts +56 -0
- package/src/ollama-output-gate.ts +18 -0
- package/src/onboarding.ts +1 -1
- package/src/provider-catalog-evidence.ts +26 -0
- package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
- package/src/providers/google-antigravity/quota.ts +3 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/compat.ts +5 -1
- package/src/providers/openai-codex/credentials.ts +22 -6
- package/src/providers/openai-codex/index.ts +9 -1
- package/src/providers/openai-codex/quota.ts +19 -6
- package/src/providers/opencode-zen/forward.ts +1 -1
- package/src/providers/opencode-zen/quota.ts +2 -0
- package/src/proxy.ts +78 -3
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +151 -38
- package/src/settings-repository.ts +1 -0
- package/src/telemetry.ts +3 -1
- package/src/types.ts +28 -0
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/components/icons.tsx +15 -0
- package/src/web/components/overlays.tsx +4 -0
- package/src/web/components/ui.tsx +9 -9
- package/src/web/lib/playground.ts +35 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/pages/AccountDetail.tsx +2 -1
- package/src/web/pages/ModelAccess.tsx +88 -0
- package/src/web/pages/Models.tsx +2 -0
- package/src/web/pages/Overview.tsx +26 -9
- package/src/web/pages/Playground.tsx +1132 -551
- package/src/web/pages/Transcription.tsx +304 -170
- package/src/web/state/api.ts +3 -0
- package/src/web/styles/app.css +501 -45
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile, link, unlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
5
|
+
import type { DashboardOverview } from "./dashboard-types.js";
|
|
6
|
+
import { buildProviderGroups } from "./quota-pools.js";
|
|
7
|
+
import { isUsageReadToken, usageReadToken } from "./usage-limits-auth.js";
|
|
8
|
+
import { getConfiguredAdminToken } from "./admin-auth.js";
|
|
9
|
+
import { getConfigDir } from "./paths.js";
|
|
10
|
+
|
|
11
|
+
export const USAGE_LIMITS_PATH = "/api/usage-limits/v1";
|
|
12
|
+
|
|
13
|
+
/** Atomic publication avoids partial identities across simultaneous processes. */
|
|
14
|
+
export async function loadUsageInstanceId(directory: string): Promise<string> {
|
|
15
|
+
await mkdir(directory, { recursive: true });
|
|
16
|
+
const path = join(directory, "usage-limits-instance-id");
|
|
17
|
+
try { return validateIdentity(await readFile(path, "utf8")); }
|
|
18
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
19
|
+
const id = randomUUID();
|
|
20
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
21
|
+
await writeFile(temporary, id + "\n", { mode: 0o600, flag: "wx" });
|
|
22
|
+
try {
|
|
23
|
+
try { await link(temporary, path); }
|
|
24
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
|
25
|
+
} finally { await unlink(temporary); }
|
|
26
|
+
return validateIdentity(await readFile(path, "utf8"));
|
|
27
|
+
}
|
|
28
|
+
function validateIdentity(text: string): string {
|
|
29
|
+
const id = text.trim();
|
|
30
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid installation identity");
|
|
31
|
+
return id;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface UsageLimitsPoolV1 {
|
|
35
|
+
id: string;
|
|
36
|
+
scope: "pool" | "provider";
|
|
37
|
+
name: string;
|
|
38
|
+
providerId: string;
|
|
39
|
+
knowledge: "known" | "unknown" | "not-applicable";
|
|
40
|
+
remainingPercent: number | null;
|
|
41
|
+
quotaCoverage: { knownAccounts: number; totalAccounts: number };
|
|
42
|
+
partialObservation: {
|
|
43
|
+
remainingPercent: number;
|
|
44
|
+
accountsWithQuota: number;
|
|
45
|
+
percentageBasis: "tier-estimate" | "included-credits";
|
|
46
|
+
observedAt: number | null;
|
|
47
|
+
freshness: "fresh" | "stale" | "unknown";
|
|
48
|
+
} | null;
|
|
49
|
+
percentageBasis: "tier-estimate" | "included-credits" | "unknown";
|
|
50
|
+
accountsWithQuota: number | null;
|
|
51
|
+
accountsEligible: number | null;
|
|
52
|
+
accountsConsidered: number;
|
|
53
|
+
availability: "available" | "unavailable" | "unknown";
|
|
54
|
+
nextResetAt: number | null;
|
|
55
|
+
resetBasis: "reported" | "estimated" | "unknown";
|
|
56
|
+
observedAt: number | null;
|
|
57
|
+
freshness: "fresh" | "stale" | "unknown";
|
|
58
|
+
quotaUnit: "usd" | "percent" | "unknown";
|
|
59
|
+
credits: { balanceUsd: number; allowanceUsd: number; purchasedUsd: number } | null;
|
|
60
|
+
catalogAccessible: boolean | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Explicit aggregate allowlist. Never serialize a ModelPool or ModelQuota. */
|
|
64
|
+
export function buildUsageLimitsSnapshot(overview: DashboardOverview, instanceId: string, now: number) {
|
|
65
|
+
return {
|
|
66
|
+
schemaVersion: 1 as const,
|
|
67
|
+
instanceId,
|
|
68
|
+
generatedAt: now,
|
|
69
|
+
pools: buildProviderGroups(overview, now).flatMap<UsageLimitsPoolV1>(group => group.pools.length ? group.pools.map(pool => ({
|
|
70
|
+
id: pool.id,
|
|
71
|
+
scope: "pool" as const,
|
|
72
|
+
name: pool.name,
|
|
73
|
+
providerId: pool.provider,
|
|
74
|
+
knowledge: pool.observedCapacity === null ? "unknown" as const : "known" as const,
|
|
75
|
+
remainingPercent: pool.observedCapacity,
|
|
76
|
+
quotaCoverage: { knownAccounts: pool.quotaCoverage.knownAccounts, totalAccounts: pool.quotaCoverage.totalAccounts },
|
|
77
|
+
partialObservation: pool.partialObservation ? {
|
|
78
|
+
remainingPercent: pool.partialObservation.remainingPercent,
|
|
79
|
+
accountsWithQuota: pool.partialObservation.accountsWithQuota,
|
|
80
|
+
percentageBasis: pool.partialObservation.percentageBasis,
|
|
81
|
+
observedAt: pool.partialObservation.observedAt,
|
|
82
|
+
freshness: pool.partialObservation.freshness,
|
|
83
|
+
} : null,
|
|
84
|
+
percentageBasis: pool.capacityBasis,
|
|
85
|
+
accountsWithQuota: pool.observedWithQuota,
|
|
86
|
+
accountsEligible: pool.eligibleNow,
|
|
87
|
+
accountsConsidered: pool.members.length,
|
|
88
|
+
availability: pool.eligibleNow === null ? "unknown" as const : pool.eligibleNow > 0 ? "available" as const : "unavailable" as const,
|
|
89
|
+
nextResetAt: pool.observedNextResetAt,
|
|
90
|
+
resetBasis: pool.resetBasis,
|
|
91
|
+
observedAt: pool.observedAt,
|
|
92
|
+
freshness: pool.freshness,
|
|
93
|
+
quotaUnit: pool.credits ? "usd" as const : pool.observedCapacity === null ? "unknown" as const : "percent" as const,
|
|
94
|
+
credits: pool.observedCapacity !== null && pool.credits ? {
|
|
95
|
+
balanceUsd: pool.credits.balanceUsd,
|
|
96
|
+
allowanceUsd: pool.credits.allowanceUsd,
|
|
97
|
+
purchasedUsd: pool.credits.purchasedUsd,
|
|
98
|
+
} : null,
|
|
99
|
+
catalogAccessible: pool.catalogAccessible,
|
|
100
|
+
})) : [{
|
|
101
|
+
scope: "provider" as const,
|
|
102
|
+
id: JSON.stringify([group.provider, null]), name: group.provider, providerId: group.provider,
|
|
103
|
+
quotaCoverage: { knownAccounts: 0, totalAccounts: group.accounts.length }, partialObservation: null,
|
|
104
|
+
knowledge: "unknown" as const, remainingPercent: null, percentageBasis: "unknown" as const,
|
|
105
|
+
accountsWithQuota: null, accountsEligible: null, accountsConsidered: group.accounts.length,
|
|
106
|
+
availability: "unknown" as const, nextResetAt: null, resetBasis: "unknown" as const,
|
|
107
|
+
observedAt: null, freshness: "unknown" as const, quotaUnit: "unknown" as const,
|
|
108
|
+
credits: null, catalogAccessible: null,
|
|
109
|
+
}]),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export type UsageLimitsSnapshotV1 = ReturnType<typeof buildUsageLimitsSnapshot>;
|
|
113
|
+
|
|
114
|
+
/** Per-server short cache coalesces readers. Reads local state only; never polls. */
|
|
115
|
+
export function createUsageLimitsHandler(readOverview: () => DashboardOverview, directory = () => getConfigDir()) {
|
|
116
|
+
let pending: Promise<string> | null = null;
|
|
117
|
+
let cached: { expires: number; body: string } | null = null;
|
|
118
|
+
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
|
119
|
+
const send = (status: number, body: string) => {
|
|
120
|
+
if (res.destroyed) return;
|
|
121
|
+
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
|
|
122
|
+
res.end(body);
|
|
123
|
+
};
|
|
124
|
+
const auth = req.headers.authorization;
|
|
125
|
+
if (!usageReadToken() || usageReadToken() === getConfiguredAdminToken() || typeof auth !== "string" ||
|
|
126
|
+
!/^Bearer /i.test(auth) || !isUsageReadToken(auth.slice(7)) || (req.url || "").includes("?")) {
|
|
127
|
+
send(401, '{"error":"unauthorized"}'); return;
|
|
128
|
+
}
|
|
129
|
+
if (req.method !== "GET") { res.setHeader("Allow", "GET"); send(405, '{"error":"method_not_allowed"}'); return; }
|
|
130
|
+
try {
|
|
131
|
+
pending ??= loadUsageInstanceId(directory()).catch(error => { pending = null; throw error; });
|
|
132
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
133
|
+
let id: string;
|
|
134
|
+
try {
|
|
135
|
+
id = await Promise.race([pending, new Promise<never>((_, reject) => {
|
|
136
|
+
timer = setTimeout(() => reject(new Error("Identity timeout")), 5000);
|
|
137
|
+
})]);
|
|
138
|
+
} finally { clearTimeout(timer); }
|
|
139
|
+
const now = Date.now();
|
|
140
|
+
if (!cached || now >= cached.expires) {
|
|
141
|
+
const body = JSON.stringify(buildUsageLimitsSnapshot(readOverview(), id, now));
|
|
142
|
+
if (Buffer.byteLength(body) > 1024 * 1024) throw new Error("Snapshot too large");
|
|
143
|
+
cached = { expires: now + 1000, body };
|
|
144
|
+
}
|
|
145
|
+
send(200, cached.body);
|
|
146
|
+
} catch { send(503, '{"error":"snapshot_unavailable"}'); }
|
|
147
|
+
};
|
|
148
|
+
}
|
package/src/validators.ts
CHANGED
|
@@ -315,11 +315,37 @@ export function validateConfig(value: unknown): ValidationResult<Config> {
|
|
|
315
315
|
}
|
|
316
316
|
}
|
|
317
317
|
}
|
|
318
|
+
if (value.modelAccessShadow !== undefined && typeof value.modelAccessShadow !== "boolean") errors.push("config.modelAccessShadow must be a boolean");
|
|
318
319
|
if (value.typesafeRouting !== undefined) {
|
|
319
320
|
if (!isRecord(value.typesafeRouting)) {
|
|
320
321
|
errors.push("config.typesafeRouting must be an object when provided");
|
|
321
322
|
} else {
|
|
322
323
|
const routing = value.typesafeRouting;
|
|
324
|
+
if (routing.restrictToEffortPools !== undefined && typeof routing.restrictToEffortPools !== "boolean") errors.push("config.typesafeRouting.restrictToEffortPools must be a boolean");
|
|
325
|
+
if (routing.restrictToEffortPools === true && routing.selectionPolicy !== "effort-pools") errors.push("restrictToEffortPools requires effort-pools selectionPolicy");
|
|
326
|
+
if (routing.selectionPolicy !== undefined && !["model-choice", "effort-pools"].includes(String(routing.selectionPolicy))) {
|
|
327
|
+
errors.push("config.typesafeRouting.selectionPolicy must be model-choice or effort-pools");
|
|
328
|
+
}
|
|
329
|
+
if (routing.effortPools !== undefined || routing.selectionPolicy === "effort-pools") {
|
|
330
|
+
if (!isRecord(routing.effortPools)) {
|
|
331
|
+
errors.push("config.typesafeRouting.effortPools must be an object");
|
|
332
|
+
} else {
|
|
333
|
+
for (const [effort, pool] of Object.entries(routing.effortPools)) {
|
|
334
|
+
if (!["low", "medium", "high", "max"].includes(effort) || !Array.isArray(pool) || pool.length === 0 || pool.length > 128 || pool.some(id => typeof id !== "string" || !/^[^/\s]+\/.+/.test(id))) {
|
|
335
|
+
errors.push("config.typesafeRouting.effortPools must contain nonempty pools of provider/model IDs for low, medium, high or max");
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (routing.stallEscalation !== undefined && typeof routing.stallEscalation !== "boolean") {
|
|
341
|
+
errors.push("config.typesafeRouting.stallEscalation must be a boolean");
|
|
342
|
+
}
|
|
343
|
+
if (routing.sessionAffinity !== undefined && typeof routing.sessionAffinity !== "boolean") {
|
|
344
|
+
errors.push("config.typesafeRouting.sessionAffinity must be a boolean");
|
|
345
|
+
}
|
|
346
|
+
if (routing.sessionAffinityTtlSeconds !== undefined && (!isNonNegativeInteger(routing.sessionAffinityTtlSeconds) || routing.sessionAffinityTtlSeconds < 1 || routing.sessionAffinityTtlSeconds > 86400)) {
|
|
347
|
+
errors.push("config.typesafeRouting.sessionAffinityTtlSeconds must be an integer between 1 and 86400");
|
|
348
|
+
}
|
|
323
349
|
if (routing.enabled !== undefined && typeof routing.enabled !== "boolean") {
|
|
324
350
|
errors.push("config.typesafeRouting.enabled must be a boolean");
|
|
325
351
|
}
|
|
@@ -177,6 +177,21 @@ const PATHS = {
|
|
|
177
177
|
</>
|
|
178
178
|
),
|
|
179
179
|
play: <path d="M7 4.5v15l12-7.5z" />,
|
|
180
|
+
stop: <rect x="6" y="6" width="12" height="12" rx="2" />,
|
|
181
|
+
mic: (
|
|
182
|
+
<>
|
|
183
|
+
<rect x="9" y="2" width="6" height="13" rx="3" />
|
|
184
|
+
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
|
|
185
|
+
<path d="M12 19v3" />
|
|
186
|
+
</>
|
|
187
|
+
),
|
|
188
|
+
image: (
|
|
189
|
+
<>
|
|
190
|
+
<rect x="3" y="3" width="18" height="18" rx="2" />
|
|
191
|
+
<circle cx="9" cy="9" r="2" />
|
|
192
|
+
<path d="m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21" />
|
|
193
|
+
</>
|
|
194
|
+
),
|
|
180
195
|
pause: (
|
|
181
196
|
<>
|
|
182
197
|
<path d="M7 4h3v16H7z" />
|
|
@@ -215,6 +215,7 @@ export function Menu({
|
|
|
215
215
|
trigger,
|
|
216
216
|
triggerClass,
|
|
217
217
|
header,
|
|
218
|
+
disabled,
|
|
218
219
|
}: {
|
|
219
220
|
label: string;
|
|
220
221
|
icon?: IconName;
|
|
@@ -226,6 +227,8 @@ export function Menu({
|
|
|
226
227
|
trigger?: ComponentChildren;
|
|
227
228
|
triggerClass?: string;
|
|
228
229
|
header?: ComponentChildren;
|
|
230
|
+
/** Disables the trigger, e.g. when none of the items can be used. */
|
|
231
|
+
disabled?: boolean;
|
|
229
232
|
}): JSX.Element {
|
|
230
233
|
const layer = useAnchoredLayer(placement, "button:not([disabled])");
|
|
231
234
|
|
|
@@ -248,6 +251,7 @@ export function Menu({
|
|
|
248
251
|
aria-expanded={layer.open}
|
|
249
252
|
aria-label={text ? undefined : label}
|
|
250
253
|
title={trigger ? undefined : label}
|
|
254
|
+
disabled={disabled}
|
|
251
255
|
onClick={layer.toggle}
|
|
252
256
|
>
|
|
253
257
|
{trigger ?? (
|
|
@@ -318,23 +318,23 @@ export function Meter({
|
|
|
318
318
|
tone,
|
|
319
319
|
size = "md",
|
|
320
320
|
}: {
|
|
321
|
-
value: number;
|
|
321
|
+
value: number | null;
|
|
322
322
|
label: string;
|
|
323
323
|
tone?: Tone;
|
|
324
324
|
size?: "sm" | "md";
|
|
325
325
|
}): JSX.Element {
|
|
326
|
-
const clamped = Math.max(0, Math.min(100, Math.round(value)));
|
|
327
|
-
const resolved = tone ?? quotaTone(clamped);
|
|
326
|
+
const clamped = value === null ? null : Math.max(0, Math.min(100, Math.round(value)));
|
|
327
|
+
const resolved = clamped === null ? "neutral" : tone ?? quotaTone(clamped);
|
|
328
328
|
return (
|
|
329
329
|
<span
|
|
330
|
-
class={`meter meter-${size} tone-${resolved}`}
|
|
331
|
-
role="meter"
|
|
332
|
-
aria-valuemin={0}
|
|
333
|
-
aria-valuemax={100}
|
|
334
|
-
aria-valuenow={clamped}
|
|
330
|
+
class={`meter meter-${size} tone-${resolved}${clamped === null ? " meter-unknown" : ""}`}
|
|
331
|
+
role={clamped === null ? "img" : "meter"}
|
|
332
|
+
aria-valuemin={clamped === null ? undefined : 0}
|
|
333
|
+
aria-valuemax={clamped === null ? undefined : 100}
|
|
334
|
+
aria-valuenow={clamped ?? undefined}
|
|
335
335
|
aria-label={label}
|
|
336
336
|
>
|
|
337
|
-
<span class="meter-fill" style={{ width: `${clamped}%` }} />
|
|
337
|
+
{clamped !== null && <span class="meter-fill" style={{ width: `${clamped}%` }} />}
|
|
338
338
|
</span>
|
|
339
339
|
);
|
|
340
340
|
}
|
|
@@ -130,6 +130,41 @@ export const VERDICT_LABELS: Record<Verdict, string> = {
|
|
|
130
130
|
error: "Error",
|
|
131
131
|
cancelled: "Cancelled",
|
|
132
132
|
};
|
|
133
|
+
/**
|
|
134
|
+
* Transcription-only compatibility names (whisper-1). They are listed by
|
|
135
|
+
* /api/models but cannot serve Chat Completions; Gemini models, which the
|
|
136
|
+
* Transcription tab also offers, handle both.
|
|
137
|
+
*/
|
|
138
|
+
export function isAudioOnlyModel(id: string): boolean {
|
|
139
|
+
return /^whisper(?:-1)?$/i.test(id.trim());
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Saved or imported selections may still hold an audio-only model; those
|
|
143
|
+
* cannot answer chat requests, so they are shown in the picker but never run.
|
|
144
|
+
*/
|
|
145
|
+
export function runnableComplianceModels(
|
|
146
|
+
doc: Pick<PlaygroundDocument, "complianceModels">,
|
|
147
|
+
): string[] {
|
|
148
|
+
return doc.complianceModels.filter((model) => !isAudioOnlyModel(model));
|
|
149
|
+
}
|
|
150
|
+
export function complianceJobs(
|
|
151
|
+
doc: Pick<PlaygroundDocument, "complianceModels" | "cases" | "results">,
|
|
152
|
+
retry = false,
|
|
153
|
+
): Array<{ model: string; cases: CaseId[] }> {
|
|
154
|
+
const failed = doc.results.filter(
|
|
155
|
+
(r) => r.verdict === "failed" || r.verdict === "error",
|
|
156
|
+
);
|
|
157
|
+
return runnableComplianceModels(doc)
|
|
158
|
+
.map((model) => ({
|
|
159
|
+
model,
|
|
160
|
+
cases: doc.cases.filter(
|
|
161
|
+
(caseId) =>
|
|
162
|
+
!retry ||
|
|
163
|
+
failed.some((r) => r.model === model && r.caseId === caseId),
|
|
164
|
+
),
|
|
165
|
+
}))
|
|
166
|
+
.filter((job) => job.cases.length > 0);
|
|
167
|
+
}
|
|
133
168
|
// randomUUID requires a secure context; getRandomValues also works on LAN HTTP dashboards.
|
|
134
169
|
export const newId = (): string =>
|
|
135
170
|
typeof crypto.randomUUID === "function"
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Alerts address router model keys; rows have provider-qualified identities. */
|
|
2
|
+
export function findPoolTarget<T extends { dataset: { poolModel?: string } }>(rows: Iterable<T>, model: string): T | undefined {
|
|
3
|
+
return Array.from(rows).find(row => row.dataset.poolModel === model);
|
|
4
|
+
}
|
package/src/web/lib/pools.ts
CHANGED
|
@@ -1,243 +1,2 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import type { AccountTier, ModelQuota } from "../../types.js";
|
|
5
|
-
import type {
|
|
6
|
-
DashboardAccount,
|
|
7
|
-
DashboardOverview,
|
|
8
|
-
DashboardRoutingAccount,
|
|
9
|
-
DashboardRoutingDiagnostics,
|
|
10
|
-
} from "../../dashboard-types.js";
|
|
11
|
-
import { isOutOfService, providerRank, providerIds, quotaProvider } from "./status.js";
|
|
12
|
-
|
|
13
|
-
/** Rough requests per full quota window, used only to weight pooled capacity. */
|
|
14
|
-
const TIER_CAPACITY: Record<string, number> = {
|
|
15
|
-
ultra: 2000,
|
|
16
|
-
max: 2000,
|
|
17
|
-
team: 1500,
|
|
18
|
-
pro: 1500,
|
|
19
|
-
plus: 1000,
|
|
20
|
-
free: 250,
|
|
21
|
-
unknown: 250,
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export function tierWeight(tier: AccountTier | string | undefined): number {
|
|
25
|
-
return TIER_CAPACITY[String(tier || "unknown")] ?? 250;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export type PoolState = "ok" | "low" | "empty" | "blocked";
|
|
29
|
-
|
|
30
|
-
export interface PoolMember {
|
|
31
|
-
account: DashboardAccount;
|
|
32
|
-
quota: ModelQuota;
|
|
33
|
-
diagnostic: DashboardRoutingAccount | null;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface ModelPool {
|
|
37
|
-
key: string;
|
|
38
|
-
name: string;
|
|
39
|
-
provider: string;
|
|
40
|
-
/** In-service accounts that carry this pool. */
|
|
41
|
-
members: PoolMember[];
|
|
42
|
-
/** Members with quota left. */
|
|
43
|
-
withQuota: number;
|
|
44
|
-
/** Remaining included quota, weighted by credit allowance or account tier, 0–100. */
|
|
45
|
-
capacity: number;
|
|
46
|
-
/** Actual included credits, summed across in-service accounts. */
|
|
47
|
-
credits: ModelQuota["credits"] | null;
|
|
48
|
-
/** The account routing this pool now; null before its first request or after it stops being routable. */
|
|
49
|
-
serving: DashboardAccount | null;
|
|
50
|
-
/** Eligible accounts after `serving`, the policy's pick first. */
|
|
51
|
-
nextUp: DashboardAccount[];
|
|
52
|
-
nextResetAt: number | null;
|
|
53
|
-
/** Requests per hour over the last hour (estimate). */
|
|
54
|
-
burnPerHour: number;
|
|
55
|
-
/** Hours until the pool runs dry at the current burn; null when idle. */
|
|
56
|
-
hoursLeft: number | null;
|
|
57
|
-
breakerUntil: number | null;
|
|
58
|
-
diagnostics: DashboardRoutingDiagnostics | null;
|
|
59
|
-
state: PoolState;
|
|
60
|
-
/** Why nothing is serving, when that is the case. */
|
|
61
|
-
blockedReason: string | null;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Map a request model id to the quota pool it draws from (best effort). */
|
|
65
|
-
export function poolKeyForModel(model: string): string {
|
|
66
|
-
const lower = model.toLowerCase();
|
|
67
|
-
if (lower === "big-pickle" || lower.endsWith("-free")) return "opencode-zen";
|
|
68
|
-
if (lower.includes("claude") || lower.startsWith("gpt-oss-120b")) return "claude";
|
|
69
|
-
if (lower.includes("gemini")) return "gemini";
|
|
70
|
-
if (/^gpt-\d/.test(lower) || lower.includes("codex")) return "openai-codex";
|
|
71
|
-
return "session";
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function isRollingFullWindow(quota: ModelQuota, remaining: number): boolean {
|
|
75
|
-
// A pool at 100% whose reset is exactly one window away is a rolling
|
|
76
|
-
// window that has not started; its "reset" is not a real event.
|
|
77
|
-
if (quota.percentRemaining !== 100) return false;
|
|
78
|
-
const tolerance = 10 * 60_000;
|
|
79
|
-
return (
|
|
80
|
-
Math.abs(remaining - 5 * 3_600_000) < tolerance ||
|
|
81
|
-
Math.abs(remaining - 7 * 86_400_000) < tolerance
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function buildPools(overview: DashboardOverview, now: number): ModelPool[] {
|
|
86
|
-
const byKey = new Map<string, { name: string; provider: string; members: PoolMember[] }>();
|
|
87
|
-
|
|
88
|
-
for (const account of overview.accounts) {
|
|
89
|
-
for (const quota of account.quota || []) {
|
|
90
|
-
let pool = byKey.get(quota.modelKey);
|
|
91
|
-
if (!pool) {
|
|
92
|
-
pool = {
|
|
93
|
-
name: quota.displayName || quota.modelKey,
|
|
94
|
-
provider: quotaProvider(quota),
|
|
95
|
-
members: [],
|
|
96
|
-
};
|
|
97
|
-
byKey.set(quota.modelKey, pool);
|
|
98
|
-
}
|
|
99
|
-
if (isOutOfService(account) || account.disabledProviders?.includes(quotaProvider(quota))) continue;
|
|
100
|
-
const diag = overview.routingDiagnostics[quota.modelKey];
|
|
101
|
-
pool.members.push({
|
|
102
|
-
account,
|
|
103
|
-
quota,
|
|
104
|
-
diagnostic: diag?.accounts.find((d) => d.email === account.email) ?? null,
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const burnByPool: Record<string, number> = {};
|
|
110
|
-
for (const [model, requests] of Object.entries(overview.recentRequestsByModel || {})) {
|
|
111
|
-
const key = poolKeyForModel(model);
|
|
112
|
-
burnByPool[key] = (burnByPool[key] || 0) + requests;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
const accountByEmail = new Map(overview.accounts.map((a) => [a.email, a]));
|
|
116
|
-
const pools: ModelPool[] = [];
|
|
117
|
-
|
|
118
|
-
for (const [key, pool] of byKey) {
|
|
119
|
-
const diagnostics = overview.routingDiagnostics[key] ?? null;
|
|
120
|
-
let weighted = 0;
|
|
121
|
-
let weightTotal = 0;
|
|
122
|
-
let remainingRequests = 0;
|
|
123
|
-
let withQuota = 0;
|
|
124
|
-
let nextResetAt: number | null = null;
|
|
125
|
-
let credits: ModelQuota["credits"] | null = null;
|
|
126
|
-
|
|
127
|
-
for (const member of pool.members) {
|
|
128
|
-
const credit = member.quota.credits;
|
|
129
|
-
const weight = credit?.allowanceUsd ?? tierWeight(member.account.tier);
|
|
130
|
-
if (credit) {
|
|
131
|
-
credits ??= { balanceUsd: 0, allowanceUsd: 0, purchasedUsd: 0 };
|
|
132
|
-
credits.balanceUsd += credit.balanceUsd;
|
|
133
|
-
credits.allowanceUsd += credit.allowanceUsd;
|
|
134
|
-
credits.purchasedUsd += credit.purchasedUsd;
|
|
135
|
-
}
|
|
136
|
-
const pct = Math.max(0, Math.min(100, member.quota.percentRemaining || 0));
|
|
137
|
-
weighted += pct * weight;
|
|
138
|
-
weightTotal += weight;
|
|
139
|
-
remainingRequests += (pct / 100) * weight;
|
|
140
|
-
if (pct > 0 || (credit?.purchasedUsd ?? 0) > 0) withQuota += 1;
|
|
141
|
-
if (member.quota.resetTime && member.quota.timerType !== "fresh") {
|
|
142
|
-
const resetAt = Date.parse(member.quota.resetTime);
|
|
143
|
-
const remaining = resetAt - now;
|
|
144
|
-
if (remaining > 0 && !isRollingFullWindow(member.quota, remaining)) {
|
|
145
|
-
if (nextResetAt === null || resetAt < nextResetAt) nextResetAt = resetAt;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// The account routing this pool right now, the same one whose status reads
|
|
151
|
-
// Serving. The policy's pick for the next rotation leads nextUp.
|
|
152
|
-
const servingEmail = overview.activeAccounts[key] ?? null;
|
|
153
|
-
const serving = servingEmail ? accountByEmail.get(servingEmail) ?? null : null;
|
|
154
|
-
const selectedEmail = diagnostics?.selectedEmail ?? null;
|
|
155
|
-
|
|
156
|
-
const nextUp = (diagnostics?.accounts ?? [])
|
|
157
|
-
.filter((d) => !d.rejectedReason && d.email !== servingEmail)
|
|
158
|
-
.sort(
|
|
159
|
-
(a, b) =>
|
|
160
|
-
Number(b.email === selectedEmail) - Number(a.email === selectedEmail) ||
|
|
161
|
-
(b.score ?? -Infinity) - (a.score ?? -Infinity),
|
|
162
|
-
)
|
|
163
|
-
.map((d) => accountByEmail.get(d.email))
|
|
164
|
-
.filter((a): a is DashboardAccount => Boolean(a))
|
|
165
|
-
.slice(0, 2);
|
|
166
|
-
|
|
167
|
-
const capacity = credits && credits.allowanceUsd > 0
|
|
168
|
-
? Math.max(0, Math.min(100, Math.round(credits.balanceUsd / credits.allowanceUsd * 100)))
|
|
169
|
-
: weightTotal > 0 ? Math.round(weighted / weightTotal) : 0;
|
|
170
|
-
const availableCapacity = credits && credits.allowanceUsd > 0
|
|
171
|
-
? (credits.balanceUsd + credits.purchasedUsd) / credits.allowanceUsd * 100
|
|
172
|
-
: capacity;
|
|
173
|
-
const burnPerHour = burnByPool[key] || 0;
|
|
174
|
-
const hoursLeft = !credits && burnPerHour > 0 ? remainingRequests / burnPerHour : null;
|
|
175
|
-
const breaker = overview.circuitBreakers.model[key];
|
|
176
|
-
const breakerUntil = breaker && breaker > now ? breaker : null;
|
|
177
|
-
|
|
178
|
-
let state: PoolState = "ok";
|
|
179
|
-
if (breakerUntil || (pool.members.length > 0 && withQuota === 0)) state = "blocked";
|
|
180
|
-
else if (diagnostics && !diagnostics.selectedEmail && diagnostics.availableCandidates === 0)
|
|
181
|
-
state = "blocked";
|
|
182
|
-
else if (availableCapacity === 0) state = "empty";
|
|
183
|
-
else if (availableCapacity < 20) state = "low";
|
|
184
|
-
|
|
185
|
-
pools.push({
|
|
186
|
-
key,
|
|
187
|
-
name: pool.name,
|
|
188
|
-
provider: pool.provider,
|
|
189
|
-
members: pool.members,
|
|
190
|
-
withQuota,
|
|
191
|
-
capacity,
|
|
192
|
-
credits,
|
|
193
|
-
serving,
|
|
194
|
-
nextUp,
|
|
195
|
-
nextResetAt,
|
|
196
|
-
burnPerHour,
|
|
197
|
-
hoursLeft,
|
|
198
|
-
breakerUntil,
|
|
199
|
-
diagnostics,
|
|
200
|
-
state,
|
|
201
|
-
blockedReason:
|
|
202
|
-
state === "blocked"
|
|
203
|
-
? breakerUntil
|
|
204
|
-
? "Circuit breaker open after repeated provider rate limits."
|
|
205
|
-
: diagnostics?.reason || "No account has quota left in this pool."
|
|
206
|
-
: null,
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
return pools.sort(
|
|
211
|
-
(a, b) =>
|
|
212
|
-
providerRank(a.provider) - providerRank(b.provider) ||
|
|
213
|
-
a.name.localeCompare(b.name),
|
|
214
|
-
);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export interface ProviderGroup {
|
|
218
|
-
provider: string;
|
|
219
|
-
accounts: DashboardAccount[];
|
|
220
|
-
pools: ModelPool[];
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** Connected providers remain visible even before their first successful quota poll. */
|
|
224
|
-
export function buildProviderGroups(overview: DashboardOverview, now: number): ProviderGroup[] {
|
|
225
|
-
const groups = new Map<string, ProviderGroup>();
|
|
226
|
-
const ensure = (provider: string): ProviderGroup => {
|
|
227
|
-
let group = groups.get(provider);
|
|
228
|
-
if (!group) {
|
|
229
|
-
group = { provider, accounts: [], pools: [] };
|
|
230
|
-
groups.set(provider, group);
|
|
231
|
-
}
|
|
232
|
-
return group;
|
|
233
|
-
};
|
|
234
|
-
for (const account of overview.accounts) {
|
|
235
|
-
const providers = new Set([
|
|
236
|
-
...providerIds(account),
|
|
237
|
-
...account.quota.map(quotaProvider),
|
|
238
|
-
]);
|
|
239
|
-
for (const provider of providers) ensure(provider).accounts.push(account);
|
|
240
|
-
}
|
|
241
|
-
for (const pool of buildPools(overview, now)) ensure(pool.provider).pools.push(pool);
|
|
242
|
-
return [...groups.values()].sort((a, b) => providerRank(a.provider) - providerRank(b.provider));
|
|
243
|
-
}
|
|
1
|
+
// Shared pure observability aggregation, usable by the dashboard and future API.
|
|
2
|
+
export * from "../../quota-pools.js";
|
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
StatusPill,
|
|
36
36
|
} from "../components/ui.js";
|
|
37
37
|
import { accountMenuItems } from "./Accounts.js";
|
|
38
|
-
import { providerPath } from "../state/router.js";
|
|
38
|
+
import { BASE, providerPath } from "../state/router.js";
|
|
39
39
|
|
|
40
40
|
export function AccountDetail({ email, onClose }: { email: string; onClose: () => void }): JSX.Element {
|
|
41
41
|
const data = overview.value!;
|
|
@@ -73,6 +73,7 @@ export function AccountDetail({ email, onClose }: { email: string; onClose: () =
|
|
|
73
73
|
</Button>
|
|
74
74
|
</header>
|
|
75
75
|
|
|
76
|
+
<section class="detail-section"><Link href={`${BASE}/models?accessAccount=${encodeURIComponent(account.id ?? "")}#model-access`}>Inspect model access rules</Link></section>
|
|
76
77
|
<section class={`detail-status tone-${meta.tone}`}>
|
|
77
78
|
<div class="detail-status-line">
|
|
78
79
|
<StatusPill status={account.status} />
|