tuxevil-rotator 3.10.0 → 4.0.0
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 +52 -0
- package/README.md +22 -12
- package/package.json +8 -4
- package/src/admin-auth.ts +233 -3
- package/src/dashboard-app.ts +257 -0
- package/src/dashboard-live.ts +654 -0
- package/src/dashboard-types.ts +192 -0
- package/src/dashboard.ts +165 -732
- package/src/db-store.ts +43 -0
- package/src/exposure.ts +21 -1
- package/src/providers/opencode-zen/catalog.ts +2 -0
- package/src/providers/opencode-zen/forward.ts +18 -15
- package/src/providers/opencode-zen/login.ts +2 -1
- package/src/providers/opencode-zen/quota.ts +2 -1
- package/src/proxy.ts +71 -25
- package/src/rotator.ts +30 -30
- package/src/settings-repository.ts +7 -0
- package/src/types.ts +2 -0
- package/src/web/app.tsx +765 -0
- package/src/web/components/charts.tsx +338 -0
- package/src/web/components/command.tsx +279 -0
- package/src/web/components/icons.tsx +357 -0
- package/src/web/components/overlays.tsx +432 -0
- package/src/web/components/ui.tsx +421 -0
- package/src/web/lib/accounts.ts +109 -0
- package/src/web/lib/attention.ts +219 -0
- package/src/web/lib/colors.ts +103 -0
- package/src/web/lib/format.ts +113 -0
- package/src/web/lib/mask.ts +92 -0
- package/src/web/lib/pools.ts +199 -0
- package/src/web/lib/status.ts +242 -0
- package/src/web/lib/usage.ts +296 -0
- package/src/web/main.tsx +16 -0
- package/src/web/nav.ts +28 -0
- package/src/web/pages/AccountDetail.tsx +346 -0
- package/src/web/pages/Accounts.tsx +581 -0
- package/src/web/pages/Keys.tsx +431 -0
- package/src/web/pages/Overview.tsx +600 -0
- package/src/web/pages/Requests.tsx +644 -0
- package/src/web/pages/Settings.tsx +546 -0
- package/src/web/pages/Usage.tsx +346 -0
- package/src/web/pages/shared.ts +36 -0
- package/src/web/state/actions.ts +211 -0
- package/src/web/state/api.ts +273 -0
- package/src/web/state/prefs.ts +19 -0
- package/src/web/state/router.ts +92 -0
- package/src/web/state/store.ts +266 -0
- package/src/web/styles/app.css +5043 -0
- package/src/web/tsconfig.json +14 -0
- package/src/static/dashboard-keys.js +0 -535
- package/src/static/dashboard-logs.js +0 -800
- package/src/static/dashboard.css +0 -2741
- package/src/static/dashboard.js +0 -3334
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
// Data shaping and the live stream behind the dashboard (/api/dashboard/*).
|
|
2
|
+
//
|
|
3
|
+
// The rotator exposes one large StatusResponse. The dashboard splits it:
|
|
4
|
+
// a small overview snapshot, live request/event tails, and history fetched
|
|
5
|
+
// per view. The stream sends only what changed since the previous tick.
|
|
6
|
+
|
|
7
|
+
import type { ServerResponse } from "node:http";
|
|
8
|
+
import {
|
|
9
|
+
getModelPricing,
|
|
10
|
+
type StatusResponse,
|
|
11
|
+
type TokenBucket,
|
|
12
|
+
type TokenUsageData,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
import type {
|
|
15
|
+
AccountsPatch,
|
|
16
|
+
ActivityResponse,
|
|
17
|
+
DashboardAccount,
|
|
18
|
+
DashboardOverview,
|
|
19
|
+
DashboardRoutingDiagnostics,
|
|
20
|
+
DashboardSnapshot,
|
|
21
|
+
DashboardStreamMessage,
|
|
22
|
+
DashboardTokenBucket,
|
|
23
|
+
LiveEvent,
|
|
24
|
+
LiveRequest,
|
|
25
|
+
ModelPrice,
|
|
26
|
+
OverviewSection,
|
|
27
|
+
TrafficMinute,
|
|
28
|
+
UsageBucket,
|
|
29
|
+
UsageRange,
|
|
30
|
+
UsageResponse,
|
|
31
|
+
} from "./dashboard-types.js";
|
|
32
|
+
import { USAGE_RANGES } from "./dashboard-types.js";
|
|
33
|
+
|
|
34
|
+
const MINUTE = 60_000;
|
|
35
|
+
const HOUR = 60 * MINUTE;
|
|
36
|
+
const DAY = 24 * HOUR;
|
|
37
|
+
|
|
38
|
+
/** Round countdown-derived timestamps so ms jitter does not look like change. */
|
|
39
|
+
function absoluteFrom(now: number, remainingMs: number): number | null {
|
|
40
|
+
if (!(remainingMs > 0)) return null;
|
|
41
|
+
return Math.round((now + remainingMs) / 1000) * 1000;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function tokenBucketAt(
|
|
45
|
+
now: number,
|
|
46
|
+
bucket: {
|
|
47
|
+
enabled: boolean;
|
|
48
|
+
tokens: number;
|
|
49
|
+
capacity: number;
|
|
50
|
+
nextRefillInMs: number;
|
|
51
|
+
},
|
|
52
|
+
): DashboardTokenBucket {
|
|
53
|
+
return {
|
|
54
|
+
enabled: bucket.enabled,
|
|
55
|
+
tokens: Math.round(bucket.tokens * 10) / 10,
|
|
56
|
+
capacity: bucket.capacity,
|
|
57
|
+
nextRefillAt: absoluteFrom(now, bucket.nextRefillInMs),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Parse a rotator bucket period ("2026-04-28T12:05", "…T12", "2026-04-28") as UTC. */
|
|
62
|
+
export function periodStart(period: string): number {
|
|
63
|
+
if (period.length === 16) return Date.parse(`${period}:00Z`);
|
|
64
|
+
if (period.length === 13) return Date.parse(`${period}:00:00Z`);
|
|
65
|
+
if (period.length === 10) return Date.parse(`${period}T00:00:00Z`);
|
|
66
|
+
if (period.length === 7) return Date.parse(`${period}-01T00:00:00Z`);
|
|
67
|
+
return NaN;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function periodSpan(period: string): number {
|
|
71
|
+
if (period.length === 16) return MINUTE;
|
|
72
|
+
if (period.length === 13) return HOUR;
|
|
73
|
+
if (period.length === 10) return DAY;
|
|
74
|
+
return Infinity;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function trafficFor(
|
|
78
|
+
tokenUsage: TokenUsageData | undefined,
|
|
79
|
+
now: number,
|
|
80
|
+
): { traffic: TrafficMinute[]; byModel: Record<string, number> } {
|
|
81
|
+
const firstMinute = Math.floor(now / MINUTE) * MINUTE - 59 * MINUTE;
|
|
82
|
+
const traffic: TrafficMinute[] = Array.from({ length: 60 }, (_, i) => ({
|
|
83
|
+
start: firstMinute + i * MINUTE,
|
|
84
|
+
requests: 0,
|
|
85
|
+
tokens: 0,
|
|
86
|
+
}));
|
|
87
|
+
const byModel: Record<string, number> = {};
|
|
88
|
+
for (const bucket of tokenUsage?.minutes ?? []) {
|
|
89
|
+
const start = periodStart(bucket.period);
|
|
90
|
+
const index = Math.round((start - firstMinute) / MINUTE);
|
|
91
|
+
if (!(index >= 0 && index < 60)) continue;
|
|
92
|
+
traffic[index].requests += bucket.requests || 0;
|
|
93
|
+
traffic[index].tokens +=
|
|
94
|
+
(bucket.inputTokens || 0) + (bucket.outputTokens || 0);
|
|
95
|
+
for (const [model, totals] of Object.entries(bucket.byModel || {})) {
|
|
96
|
+
byModel[model] = (byModel[model] || 0) + (totals.requests || 0);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { traffic, byModel };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function buildOverview(
|
|
103
|
+
status: StatusResponse,
|
|
104
|
+
now: number,
|
|
105
|
+
capabilities: { database: boolean },
|
|
106
|
+
): DashboardOverview {
|
|
107
|
+
const accounts: DashboardAccount[] = (status.accounts || []).map(
|
|
108
|
+
(account) => ({
|
|
109
|
+
...account,
|
|
110
|
+
tokenBucket: tokenBucketAt(
|
|
111
|
+
now,
|
|
112
|
+
account.tokenBucket || {
|
|
113
|
+
enabled: false,
|
|
114
|
+
tokens: 0,
|
|
115
|
+
capacity: 0,
|
|
116
|
+
nextRefillInMs: 0,
|
|
117
|
+
},
|
|
118
|
+
),
|
|
119
|
+
}),
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
const routingDiagnostics: Record<string, DashboardRoutingDiagnostics> = {};
|
|
123
|
+
for (const [key, diag] of Object.entries(status.routingDiagnostics || {})) {
|
|
124
|
+
routingDiagnostics[key] = {
|
|
125
|
+
...diag,
|
|
126
|
+
accounts: (diag.accounts || []).map((entry) => ({
|
|
127
|
+
...entry,
|
|
128
|
+
tokenBucket: tokenBucketAt(now, entry.tokenBucket),
|
|
129
|
+
})),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const breakers = status.circuitBreakers || { model: {}, project: {} };
|
|
134
|
+
const untilMap = (
|
|
135
|
+
source: Record<string, { until: number }> | undefined,
|
|
136
|
+
): Record<string, number> => {
|
|
137
|
+
const out: Record<string, number> = {};
|
|
138
|
+
for (const [key, value] of Object.entries(source || {})) {
|
|
139
|
+
if (value.until > now) out[key] = value.until;
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const health = status.routingHealth;
|
|
145
|
+
const { nextRetryIn, ...healthRest } = health || {
|
|
146
|
+
state: "stopped" as const,
|
|
147
|
+
reason: "",
|
|
148
|
+
nextRetryIn: 0,
|
|
149
|
+
availableCount: 0,
|
|
150
|
+
readyCount: 0,
|
|
151
|
+
activeCount: 0,
|
|
152
|
+
cooldownCount: 0,
|
|
153
|
+
busyCount: 0,
|
|
154
|
+
flaggedCount: 0,
|
|
155
|
+
disabledCount: 0,
|
|
156
|
+
errorCount: 0,
|
|
157
|
+
};
|
|
158
|
+
const { traffic, byModel } = trafficFor(status.tokenUsage, now);
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
generatedAt: now,
|
|
162
|
+
version: status.version,
|
|
163
|
+
proxyPort: status.proxyPort,
|
|
164
|
+
startedAt: Math.round((now - (status.uptime || 0)) / 1000) * 1000,
|
|
165
|
+
requestsPerRotation: status.requestsPerRotation,
|
|
166
|
+
maxConcurrentRequestsPerAccount: status.maxConcurrentRequestsPerAccount,
|
|
167
|
+
totalRequestsAllAccounts: status.totalRequestsAllAccounts,
|
|
168
|
+
activeAccounts: status.activeAccounts || {},
|
|
169
|
+
accounts,
|
|
170
|
+
protectivePause: {
|
|
171
|
+
until:
|
|
172
|
+
(status.protectivePauseRemaining || 0) > 0
|
|
173
|
+
? status.protectivePauseUntil
|
|
174
|
+
: 0,
|
|
175
|
+
reason: status.protectivePauseReason ?? null,
|
|
176
|
+
},
|
|
177
|
+
operatorControls: status.operatorControls || {
|
|
178
|
+
allowFreshWindowStarts: true,
|
|
179
|
+
autoWarmupEnabled: false,
|
|
180
|
+
},
|
|
181
|
+
security: status.security || {
|
|
182
|
+
adminTokenConfigured: false,
|
|
183
|
+
warning: null,
|
|
184
|
+
bindHost: "0.0.0.0",
|
|
185
|
+
},
|
|
186
|
+
routingHealth: {
|
|
187
|
+
...healthRest,
|
|
188
|
+
nextRetryAt: absoluteFrom(now, nextRetryIn),
|
|
189
|
+
},
|
|
190
|
+
routingDiagnostics,
|
|
191
|
+
circuitBreakers: {
|
|
192
|
+
model: untilMap(breakers.model),
|
|
193
|
+
project: untilMap(breakers.project),
|
|
194
|
+
},
|
|
195
|
+
predictions: status.predictions || {},
|
|
196
|
+
modelTierAccess: status.modelTierAccess ?? null,
|
|
197
|
+
updateInfo: status.updateInfo ?? null,
|
|
198
|
+
notifications: status.notifications ?? [],
|
|
199
|
+
hostedOAuthConfigured: Boolean(status.hostedOAuthConfigured),
|
|
200
|
+
capabilities,
|
|
201
|
+
usage: {
|
|
202
|
+
totalRequests: status.tokenUsage?.totalRequests ?? 0,
|
|
203
|
+
totalInputTokens: status.tokenUsage?.totalInputTokens ?? 0,
|
|
204
|
+
totalOutputTokens: status.tokenUsage?.totalOutputTokens ?? 0,
|
|
205
|
+
savingsUsd: status.tokenUsage?.savings?.totalUsd ?? 0,
|
|
206
|
+
},
|
|
207
|
+
traffic,
|
|
208
|
+
recentRequestsByModel: byModel,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ── Live hub ────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
const REQUEST_RING = 200;
|
|
215
|
+
const EVENT_RING = 100;
|
|
216
|
+
|
|
217
|
+
function requestKey(entry: {
|
|
218
|
+
timestamp: number;
|
|
219
|
+
model: string;
|
|
220
|
+
account: string;
|
|
221
|
+
statusCode: number;
|
|
222
|
+
totalMs: number;
|
|
223
|
+
}): string {
|
|
224
|
+
return `${entry.timestamp}|${entry.model}|${entry.account}|${entry.statusCode}|${entry.totalMs}`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function eventKey(entry: {
|
|
228
|
+
timestamp: number;
|
|
229
|
+
source: string;
|
|
230
|
+
level: string;
|
|
231
|
+
message: string;
|
|
232
|
+
}): string {
|
|
233
|
+
return `${entry.timestamp}|${entry.source}|${entry.level}|${entry.message}`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export interface DashboardLiveHubOptions {
|
|
237
|
+
getStatus: () => StatusResponse;
|
|
238
|
+
capabilities: () => { database: boolean };
|
|
239
|
+
now?: () => number;
|
|
240
|
+
/** Throttle for change-triggered pushes. */
|
|
241
|
+
throttleMs?: number;
|
|
242
|
+
/** Background tick while clients are connected. */
|
|
243
|
+
tickMs?: number;
|
|
244
|
+
heartbeatMs?: number;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Keeps the last broadcast state and turns each new status into the smallest
|
|
249
|
+
* set of stream messages: changed overview sections, changed accounts, and
|
|
250
|
+
* requests/events not seen before.
|
|
251
|
+
*/
|
|
252
|
+
export class DashboardLiveHub {
|
|
253
|
+
private readonly clients = new Set<ServerResponse>();
|
|
254
|
+
private overview: DashboardOverview | null = null;
|
|
255
|
+
private sectionJson = new Map<OverviewSection, string>();
|
|
256
|
+
private accountJson = new Map<string, string>();
|
|
257
|
+
private accountOrder: string[] = [];
|
|
258
|
+
private requests: LiveRequest[] = [];
|
|
259
|
+
private events: LiveEvent[] = [];
|
|
260
|
+
private seenRequests = new Set<string>();
|
|
261
|
+
private seenEvents = new Set<string>();
|
|
262
|
+
private nextId = 1;
|
|
263
|
+
private throttleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
264
|
+
private tickTimer: ReturnType<typeof setInterval> | null = null;
|
|
265
|
+
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
266
|
+
private readonly now: () => number;
|
|
267
|
+
|
|
268
|
+
constructor(private readonly options: DashboardLiveHubOptions) {
|
|
269
|
+
this.now = options.now ?? Date.now;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
get clientCount(): number {
|
|
273
|
+
return this.clients.size;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Advance the baseline (pushing diffs to connected clients) and return it. */
|
|
277
|
+
snapshot(): DashboardSnapshot {
|
|
278
|
+
this.broadcast(this.collect());
|
|
279
|
+
return {
|
|
280
|
+
overview: this.overview!,
|
|
281
|
+
requests: this.requests.slice(),
|
|
282
|
+
events: this.events.slice(),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Compute stream messages for the current rotator state. */
|
|
287
|
+
collect(): DashboardStreamMessage[] {
|
|
288
|
+
const status = this.options.getStatus();
|
|
289
|
+
const next = buildOverview(status, this.now(), this.options.capabilities());
|
|
290
|
+
const messages: DashboardStreamMessage[] = [];
|
|
291
|
+
const first = this.overview === null;
|
|
292
|
+
|
|
293
|
+
const sections: Partial<Pick<DashboardOverview, OverviewSection>> = {};
|
|
294
|
+
let sectionChanged = false;
|
|
295
|
+
for (const key of Object.keys(next) as Array<keyof DashboardOverview>) {
|
|
296
|
+
// generatedAt changes every tick and carries no information of its own.
|
|
297
|
+
if (key === "accounts" || key === "generatedAt") continue;
|
|
298
|
+
const json = JSON.stringify(next[key]);
|
|
299
|
+
if (this.sectionJson.get(key) !== json) {
|
|
300
|
+
this.sectionJson.set(key, json);
|
|
301
|
+
(sections as Record<string, unknown>)[key] = next[key];
|
|
302
|
+
sectionChanged = true;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (sectionChanged && !first) {
|
|
306
|
+
messages.push({
|
|
307
|
+
type: "overview",
|
|
308
|
+
data: { ...sections, generatedAt: next.generatedAt },
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const patch: AccountsPatch = { upsert: [], remove: [] };
|
|
313
|
+
const seen = new Set<string>();
|
|
314
|
+
for (const account of next.accounts) {
|
|
315
|
+
seen.add(account.email);
|
|
316
|
+
const json = JSON.stringify(account);
|
|
317
|
+
if (this.accountJson.get(account.email) !== json) {
|
|
318
|
+
this.accountJson.set(account.email, json);
|
|
319
|
+
patch.upsert.push(account);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
for (const email of this.accountJson.keys()) {
|
|
323
|
+
if (!seen.has(email)) {
|
|
324
|
+
this.accountJson.delete(email);
|
|
325
|
+
patch.remove.push(email);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const order = next.accounts.map((a) => a.email);
|
|
329
|
+
if (order.join("\n") !== this.accountOrder.join("\n")) {
|
|
330
|
+
this.accountOrder = order;
|
|
331
|
+
patch.order = order;
|
|
332
|
+
}
|
|
333
|
+
if (
|
|
334
|
+
!first &&
|
|
335
|
+
(patch.upsert.length > 0 || patch.remove.length > 0 || patch.order)
|
|
336
|
+
) {
|
|
337
|
+
messages.push({ type: "accounts", data: patch });
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
this.overview = next;
|
|
341
|
+
|
|
342
|
+
const freshRequests = this.absorbRequests(status);
|
|
343
|
+
if (freshRequests.length > 0 && !first) {
|
|
344
|
+
messages.push({ type: "requests", data: freshRequests });
|
|
345
|
+
}
|
|
346
|
+
const freshEvents = this.absorbEvents(status);
|
|
347
|
+
if (freshEvents.length > 0 && !first) {
|
|
348
|
+
messages.push({ type: "events", data: freshEvents });
|
|
349
|
+
}
|
|
350
|
+
return messages;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private absorbRequests(status: StatusResponse): LiveRequest[] {
|
|
354
|
+
const log = status.requestLog || [];
|
|
355
|
+
const fresh: LiveRequest[] = [];
|
|
356
|
+
// requestLog is newest first; assign ids oldest first.
|
|
357
|
+
for (let i = log.length - 1; i >= 0; i--) {
|
|
358
|
+
const key = requestKey(log[i]);
|
|
359
|
+
if (this.seenRequests.has(key)) continue;
|
|
360
|
+
this.seenRequests.add(key);
|
|
361
|
+
fresh.unshift({ ...log[i], id: this.nextId++ });
|
|
362
|
+
}
|
|
363
|
+
if (fresh.length > 0) {
|
|
364
|
+
this.requests = fresh.concat(this.requests).slice(0, REQUEST_RING);
|
|
365
|
+
if (this.seenRequests.size > REQUEST_RING * 2) {
|
|
366
|
+
this.seenRequests = new Set(log.map(requestKey));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return fresh;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private absorbEvents(status: StatusResponse): LiveEvent[] {
|
|
373
|
+
const recent = status.recentEvents || [];
|
|
374
|
+
const fresh: LiveEvent[] = [];
|
|
375
|
+
for (let i = recent.length - 1; i >= 0; i--) {
|
|
376
|
+
const key = eventKey(recent[i]);
|
|
377
|
+
if (this.seenEvents.has(key)) continue;
|
|
378
|
+
this.seenEvents.add(key);
|
|
379
|
+
fresh.unshift({ ...recent[i], id: this.nextId++ });
|
|
380
|
+
}
|
|
381
|
+
if (fresh.length > 0) {
|
|
382
|
+
this.events = fresh.concat(this.events).slice(0, EVENT_RING);
|
|
383
|
+
if (this.seenEvents.size > EVENT_RING * 2) {
|
|
384
|
+
this.seenEvents = new Set(recent.map(eventKey));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return fresh;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
addClient(res: ServerResponse): void {
|
|
391
|
+
res.writeHead(200, {
|
|
392
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
393
|
+
"Cache-Control": "no-cache, no-store",
|
|
394
|
+
Connection: "keep-alive",
|
|
395
|
+
"X-Accel-Buffering": "no",
|
|
396
|
+
});
|
|
397
|
+
res.write("retry: 3000\n\n");
|
|
398
|
+
const snapshot = this.snapshot();
|
|
399
|
+
this.clients.add(res);
|
|
400
|
+
this.write(res, { type: "snapshot", data: snapshot });
|
|
401
|
+
res.on("close", () => {
|
|
402
|
+
this.clients.delete(res);
|
|
403
|
+
if (this.clients.size === 0) this.stopTimers();
|
|
404
|
+
});
|
|
405
|
+
this.startTimers();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Called when rotator state changes; pushes at most once per throttle. */
|
|
409
|
+
schedule(): void {
|
|
410
|
+
if (this.clients.size === 0 || this.throttleTimer) return;
|
|
411
|
+
this.throttleTimer = setTimeout(() => {
|
|
412
|
+
this.throttleTimer = null;
|
|
413
|
+
this.tick();
|
|
414
|
+
}, this.options.throttleMs ?? 1000);
|
|
415
|
+
this.throttleTimer.unref?.();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
tick(): void {
|
|
419
|
+
if (this.clients.size === 0) return;
|
|
420
|
+
this.broadcast(this.collect());
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
close(): void {
|
|
424
|
+
this.stopTimers();
|
|
425
|
+
if (this.throttleTimer) clearTimeout(this.throttleTimer);
|
|
426
|
+
this.throttleTimer = null;
|
|
427
|
+
for (const client of this.clients) {
|
|
428
|
+
try {
|
|
429
|
+
client.end();
|
|
430
|
+
} catch {
|
|
431
|
+
// already closed
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
this.clients.clear();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private broadcast(messages: DashboardStreamMessage[]): void {
|
|
438
|
+
for (const message of messages) {
|
|
439
|
+
for (const client of this.clients) this.write(client, message);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
private write(res: ServerResponse, message: DashboardStreamMessage): void {
|
|
444
|
+
try {
|
|
445
|
+
res.write(`event: ${message.type}\ndata: ${JSON.stringify(message.data)}\n\n`);
|
|
446
|
+
} catch {
|
|
447
|
+
this.clients.delete(res);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
private startTimers(): void {
|
|
452
|
+
if (!this.tickTimer) {
|
|
453
|
+
this.tickTimer = setInterval(() => this.tick(), this.options.tickMs ?? 5000);
|
|
454
|
+
this.tickTimer.unref?.();
|
|
455
|
+
}
|
|
456
|
+
if (!this.heartbeatTimer) {
|
|
457
|
+
this.heartbeatTimer = setInterval(() => {
|
|
458
|
+
for (const client of this.clients) {
|
|
459
|
+
try {
|
|
460
|
+
client.write(": ping\n\n");
|
|
461
|
+
} catch {
|
|
462
|
+
this.clients.delete(client);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}, this.options.heartbeatMs ?? 25_000);
|
|
466
|
+
this.heartbeatTimer.unref?.();
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private stopTimers(): void {
|
|
471
|
+
if (this.tickTimer) clearInterval(this.tickTimer);
|
|
472
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
473
|
+
this.tickTimer = null;
|
|
474
|
+
this.heartbeatTimer = null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ── Usage history ───────────────────────────────────────────────────────
|
|
479
|
+
|
|
480
|
+
interface RangeWindow {
|
|
481
|
+
windowMs: number;
|
|
482
|
+
/** Largest bucket span that still fits inside one chart bar. */
|
|
483
|
+
maxSpan: number;
|
|
484
|
+
/** Roll minute buckets into UTC hours to keep long ranges small. */
|
|
485
|
+
rollMinutes: boolean;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Margins cover aligning bars to the viewer's local clock.
|
|
489
|
+
const RANGE_WINDOWS: Record<UsageRange, RangeWindow> = {
|
|
490
|
+
"1h": { windowMs: HOUR + 2 * MINUTE, maxSpan: MINUTE, rollMinutes: false },
|
|
491
|
+
"6h": { windowMs: 6 * HOUR + 10 * MINUTE, maxSpan: MINUTE, rollMinutes: false },
|
|
492
|
+
"24h": { windowMs: 25 * HOUR, maxSpan: HOUR, rollMinutes: false },
|
|
493
|
+
"7d": { windowMs: 8 * DAY, maxSpan: DAY, rollMinutes: true },
|
|
494
|
+
"30d": { windowMs: 31 * DAY, maxSpan: DAY, rollMinutes: true },
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
export function isUsageRange(value: unknown): value is UsageRange {
|
|
498
|
+
return (USAGE_RANGES as readonly unknown[]).includes(value);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function toUsageBucket(bucket: TokenBucket): UsageBucket | null {
|
|
502
|
+
const start = periodStart(bucket.period);
|
|
503
|
+
const span = periodSpan(bucket.period);
|
|
504
|
+
if (!Number.isFinite(start) || !Number.isFinite(span)) return null;
|
|
505
|
+
const byModel: UsageBucket["byModel"] = {};
|
|
506
|
+
for (const [model, totals] of Object.entries(bucket.byModel || {})) {
|
|
507
|
+
byModel[model] = {
|
|
508
|
+
inputTokens: totals.inputTokens || 0,
|
|
509
|
+
outputTokens: totals.outputTokens || 0,
|
|
510
|
+
requests: totals.requests || 0,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
return {
|
|
514
|
+
start,
|
|
515
|
+
span,
|
|
516
|
+
inputTokens: bucket.inputTokens || 0,
|
|
517
|
+
outputTokens: bucket.outputTokens || 0,
|
|
518
|
+
requests: bucket.requests || 0,
|
|
519
|
+
byModel,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function addInto(target: UsageBucket, source: UsageBucket): void {
|
|
524
|
+
target.inputTokens += source.inputTokens;
|
|
525
|
+
target.outputTokens += source.outputTokens;
|
|
526
|
+
target.requests += source.requests;
|
|
527
|
+
for (const [model, totals] of Object.entries(source.byModel)) {
|
|
528
|
+
const dst = (target.byModel[model] ??= {
|
|
529
|
+
inputTokens: 0,
|
|
530
|
+
outputTokens: 0,
|
|
531
|
+
requests: 0,
|
|
532
|
+
});
|
|
533
|
+
dst.inputTokens += totals.inputTokens;
|
|
534
|
+
dst.outputTokens += totals.outputTokens;
|
|
535
|
+
dst.requests += totals.requests;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export function buildUsage(
|
|
540
|
+
tokenUsage: TokenUsageData | undefined,
|
|
541
|
+
latency: StatusResponse["latencyStats"] | undefined,
|
|
542
|
+
range: UsageRange,
|
|
543
|
+
now: number,
|
|
544
|
+
): UsageResponse {
|
|
545
|
+
const window = RANGE_WINDOWS[range];
|
|
546
|
+
const from = now - window.windowMs;
|
|
547
|
+
const sources = [
|
|
548
|
+
...(tokenUsage?.minutes ?? []),
|
|
549
|
+
...(tokenUsage?.hours ?? []),
|
|
550
|
+
...(tokenUsage?.days ?? []),
|
|
551
|
+
];
|
|
552
|
+
const rolled = new Map<number, UsageBucket>();
|
|
553
|
+
const buckets: UsageBucket[] = [];
|
|
554
|
+
for (const raw of sources) {
|
|
555
|
+
const bucket = toUsageBucket(raw);
|
|
556
|
+
if (!bucket || bucket.span > window.maxSpan) continue;
|
|
557
|
+
if (bucket.start + bucket.span <= from || bucket.start > now) continue;
|
|
558
|
+
if (window.rollMinutes && bucket.span === MINUTE) {
|
|
559
|
+
const hourStart = Math.floor(bucket.start / HOUR) * HOUR;
|
|
560
|
+
let hour = rolled.get(hourStart);
|
|
561
|
+
if (!hour) {
|
|
562
|
+
hour = {
|
|
563
|
+
start: hourStart,
|
|
564
|
+
span: HOUR,
|
|
565
|
+
inputTokens: 0,
|
|
566
|
+
outputTokens: 0,
|
|
567
|
+
requests: 0,
|
|
568
|
+
byModel: {},
|
|
569
|
+
};
|
|
570
|
+
rolled.set(hourStart, hour);
|
|
571
|
+
buckets.push(hour);
|
|
572
|
+
}
|
|
573
|
+
addInto(hour, bucket);
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
buckets.push(bucket);
|
|
577
|
+
}
|
|
578
|
+
buckets.sort((a, b) => a.start - b.start || a.span - b.span);
|
|
579
|
+
|
|
580
|
+
const pricing: Record<string, ModelPrice> = {};
|
|
581
|
+
for (const bucket of buckets) {
|
|
582
|
+
for (const model of Object.keys(bucket.byModel)) {
|
|
583
|
+
if (model in pricing) continue;
|
|
584
|
+
const price = getModelPricing(model);
|
|
585
|
+
if (price) {
|
|
586
|
+
pricing[model] = {
|
|
587
|
+
inputPer1M: price.inputPer1M,
|
|
588
|
+
outputPer1M: price.outputPer1M,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
return {
|
|
595
|
+
range,
|
|
596
|
+
generatedAt: now,
|
|
597
|
+
buckets,
|
|
598
|
+
pricing,
|
|
599
|
+
allTime: {
|
|
600
|
+
inputTokens: tokenUsage?.totalInputTokens ?? 0,
|
|
601
|
+
outputTokens: tokenUsage?.totalOutputTokens ?? 0,
|
|
602
|
+
requests: tokenUsage?.totalRequests ?? 0,
|
|
603
|
+
savingsUsd: tokenUsage?.savings?.totalUsd ?? 0,
|
|
604
|
+
},
|
|
605
|
+
latency: latency ?? {},
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
export function buildActivity(
|
|
610
|
+
tokenUsage: TokenUsageData | undefined,
|
|
611
|
+
now: number,
|
|
612
|
+
): ActivityResponse {
|
|
613
|
+
// 60 local days plus an alignment margin; the rotator keeps hour buckets
|
|
614
|
+
// this long (KEEP_HOURS_MS in rotator.ts).
|
|
615
|
+
const from = now - 61 * DAY;
|
|
616
|
+
const hours = new Map<number, number>();
|
|
617
|
+
for (const raw of [...(tokenUsage?.minutes ?? []), ...(tokenUsage?.hours ?? [])]) {
|
|
618
|
+
const start = periodStart(raw.period);
|
|
619
|
+
if (!Number.isFinite(start) || start < from || start > now) continue;
|
|
620
|
+
if (!(raw.requests > 0)) continue;
|
|
621
|
+
const hour = Math.floor(start / HOUR) * HOUR;
|
|
622
|
+
hours.set(hour, (hours.get(hour) || 0) + raw.requests);
|
|
623
|
+
}
|
|
624
|
+
return {
|
|
625
|
+
generatedAt: now,
|
|
626
|
+
hours: [...hours.entries()].sort((a, b) => a[0] - b[0]),
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
export function tokenUsageCsv(tokenUsage: TokenUsageData | undefined): string {
|
|
631
|
+
const lines = ["Tier,Period,Model,InputTokens,OutputTokens,Requests"];
|
|
632
|
+
for (const tier of ["months", "days", "hours", "minutes"] as const) {
|
|
633
|
+
for (const bucket of tokenUsage?.[tier] ?? []) {
|
|
634
|
+
for (const [model, totals] of Object.entries(bucket.byModel || {})) {
|
|
635
|
+
// A leading = + - @ would run as a formula in a spreadsheet.
|
|
636
|
+
const text = /^[=+\-@\t\r]/.test(model) ? `'${model}` : model;
|
|
637
|
+
const safeModel = /[",\r\n]/.test(text)
|
|
638
|
+
? `"${text.replace(/"/g, '""')}"`
|
|
639
|
+
: text;
|
|
640
|
+
lines.push(
|
|
641
|
+
[
|
|
642
|
+
tier,
|
|
643
|
+
bucket.period,
|
|
644
|
+
safeModel,
|
|
645
|
+
totals.inputTokens,
|
|
646
|
+
totals.outputTokens,
|
|
647
|
+
totals.requests,
|
|
648
|
+
].join(","),
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return lines.join("\n") + "\n";
|
|
654
|
+
}
|