tuxevil-rotator 3.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,1169 @@
1
+ // Web dashboard for monitoring account rotation status
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { join, dirname } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import type { IncomingMessage, ServerResponse } from "node:http";
7
+ import type { Config } from "./types.js";
8
+ import type { AccountRotator } from "./rotator.js";
9
+ import { readLimitedBody } from "./body-limit.js";
10
+ import {
11
+ generateVirtualKey,
12
+ listVirtualKeys,
13
+ getVirtualKeyByHash,
14
+ updateVirtualKey,
15
+ deleteVirtualKey,
16
+ } from "./virtual-keys.js";
17
+ import { getSpendLogs, getDailySpendSummary, getSpendByKey } from "./spend-logger.js";
18
+ import { logger } from "./logger.js";
19
+
20
+ const dashboardLogger = logger.child("dashboard");
21
+
22
+ const __dirname = dirname(fileURLToPath(import.meta.url));
23
+
24
+ // Static assets are read once at startup and served via dedicated routes.
25
+ const DASHBOARD_CSS = readFileSync(
26
+ join(__dirname, "static", "dashboard.css"),
27
+ "utf-8",
28
+ );
29
+ const DASHBOARD_JS = readFileSync(
30
+ join(__dirname, "static", "dashboard.js"),
31
+ "utf-8",
32
+ );
33
+ const DASHBOARD_KEYS_JS = readFileSync(
34
+ join(__dirname, "static", "dashboard-keys.js"),
35
+ "utf-8",
36
+ );
37
+ const DASHBOARD_LOGS_JS = readFileSync(
38
+ join(__dirname, "static", "dashboard-logs.js"),
39
+ "utf-8",
40
+ );
41
+
42
+ export function serveDashboard(res: ServerResponse): void {
43
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
44
+ res.end(DASHBOARD_HTML);
45
+ }
46
+
47
+ export function serveStaticCss(res: ServerResponse): void {
48
+ res.writeHead(200, {
49
+ "Content-Type": "text/css; charset=utf-8",
50
+ "Cache-Control": "public, max-age=3600",
51
+ });
52
+ res.end(DASHBOARD_CSS);
53
+ }
54
+
55
+ export function serveStaticJs(res: ServerResponse): void {
56
+ res.writeHead(200, {
57
+ "Content-Type": "application/javascript; charset=utf-8",
58
+ "Cache-Control": "public, max-age=3600",
59
+ });
60
+ res.end(DASHBOARD_JS);
61
+ }
62
+
63
+ export function serveStaticKeysJs(res: ServerResponse): void {
64
+ res.writeHead(200, {
65
+ "Content-Type": "application/javascript; charset=utf-8",
66
+ "Cache-Control": "public, max-age=3600",
67
+ });
68
+ res.end(DASHBOARD_KEYS_JS);
69
+ }
70
+
71
+ export function serveStaticLogsJs(res: ServerResponse): void {
72
+ res.writeHead(200, {
73
+ "Content-Type": "application/javascript; charset=utf-8",
74
+ "Cache-Control": "public, max-age=3600",
75
+ });
76
+ res.end(DASHBOARD_LOGS_JS);
77
+ }
78
+
79
+ export function serveDashboardKeys(res: ServerResponse): void {
80
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
81
+ res.end(DASHBOARD_KEYS_HTML);
82
+ }
83
+
84
+ export function serveDashboardLogs(res: ServerResponse): void {
85
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
86
+ res.end(DASHBOARD_LOGS_HTML);
87
+ }
88
+
89
+ export function serveStatusApi(
90
+ res: ServerResponse,
91
+ rotator: AccountRotator,
92
+ ): void {
93
+ res.writeHead(200, {
94
+ "Content-Type": "application/json",
95
+ "Cache-Control": "no-store",
96
+ });
97
+ res.end(JSON.stringify(rotator.getStatus()));
98
+ }
99
+
100
+ export function serveConfigApi(
101
+ res: ServerResponse,
102
+ rotator: AccountRotator,
103
+ ): void {
104
+ res.writeHead(200, {
105
+ "Content-Type": "application/json",
106
+ "Cache-Control": "no-store",
107
+ });
108
+ res.end(JSON.stringify(rotator.getConfig()));
109
+ }
110
+
111
+ export function serveConfigExportApi(
112
+ res: ServerResponse,
113
+ rotator: AccountRotator,
114
+ ): void {
115
+ res.writeHead(200, {
116
+ "Content-Type": "application/json",
117
+ "Content-Disposition":
118
+ 'attachment; filename="tuxevil-rotator-config.json"',
119
+ });
120
+ res.end(JSON.stringify(rotator.getConfig(), null, 2));
121
+ }
122
+
123
+ export async function serveConfigImportApi(
124
+ res: ServerResponse,
125
+ rotator: AccountRotator,
126
+ config: Config,
127
+ ): Promise<void> {
128
+ await rotator.replaceConfig(config);
129
+ res.writeHead(200, { "Content-Type": "application/json" });
130
+ res.end(
131
+ JSON.stringify({ ok: true, importedAccounts: config.accounts.length }),
132
+ );
133
+ }
134
+
135
+ export async function serveEnableApi(
136
+ res: ServerResponse,
137
+ rotator: AccountRotator,
138
+ email: string,
139
+ ): Promise<void> {
140
+ const ok = await rotator.enableAccount(email);
141
+ res.writeHead(ok ? 200 : 409, { "Content-Type": "application/json" });
142
+ res.end(JSON.stringify({ ok, email }));
143
+ }
144
+
145
+ export async function serveDisableApi(
146
+ res: ServerResponse,
147
+ rotator: AccountRotator,
148
+ email: string,
149
+ ): Promise<void> {
150
+ const ok = await rotator.disableAccount(email);
151
+ res.writeHead(ok ? 200 : 404, { "Content-Type": "application/json" });
152
+ res.end(JSON.stringify({ ok, email }));
153
+ }
154
+
155
+ export async function serveQuarantineApi(
156
+ res: ServerResponse,
157
+ rotator: AccountRotator,
158
+ email: string,
159
+ ): Promise<void> {
160
+ const ok = await rotator.quarantineAccount(email);
161
+ res.writeHead(ok ? 200 : 404, { "Content-Type": "application/json" });
162
+ res.end(JSON.stringify({ ok, email }));
163
+ }
164
+
165
+ export async function serveRestoreApi(
166
+ res: ServerResponse,
167
+ rotator: AccountRotator,
168
+ email: string,
169
+ ): Promise<void> {
170
+ const ok = await rotator.restoreAccount(email);
171
+ res.writeHead(ok ? 200 : 404, { "Content-Type": "application/json" });
172
+ res.end(JSON.stringify({ ok, email }));
173
+ }
174
+
175
+ export async function serveRemoveAccountApi(
176
+ res: ServerResponse,
177
+ rotator: AccountRotator,
178
+ email: string,
179
+ ): Promise<void> {
180
+ const ok = await rotator.removeAccount(email);
181
+ res.writeHead(ok ? 200 : 400, { "Content-Type": "application/json" });
182
+ res.end(JSON.stringify({ ok, email }));
183
+ }
184
+
185
+ export async function serveSetTierApi(
186
+ res: ServerResponse,
187
+ rotator: AccountRotator,
188
+ email: string,
189
+ tier: string,
190
+ ): Promise<void> {
191
+ const ok = await rotator.setAccountTier(email, tier);
192
+ res.writeHead(ok ? 200 : 400, { "Content-Type": "application/json" });
193
+ res.end(JSON.stringify({ ok, email, tier }));
194
+ }
195
+
196
+ export async function serveFreshWindowStartsApi(
197
+ res: ServerResponse,
198
+ rotator: AccountRotator,
199
+ enabled: boolean,
200
+ ): Promise<void> {
201
+ const changed = await rotator.setAllowFreshWindowStarts(enabled);
202
+ res.writeHead(200, { "Content-Type": "application/json" });
203
+ res.end(
204
+ JSON.stringify({ ok: true, changed, allowFreshWindowStarts: enabled }),
205
+ );
206
+ }
207
+
208
+ export async function serveAccountFreshWindowStartsApi(
209
+ res: ServerResponse,
210
+ rotator: AccountRotator,
211
+ email: string,
212
+ enabled: boolean,
213
+ ): Promise<void> {
214
+ const ok = await rotator.setAccountAllowFreshWindowStartsOverride(email, enabled);
215
+ res.writeHead(ok ? 200 : 404, { "Content-Type": "application/json" });
216
+ res.end(
217
+ JSON.stringify({ ok, email, allowFreshWindowStartsOverride: enabled }),
218
+ );
219
+ }
220
+
221
+ export function serveClearInFlightApi(
222
+ res: ServerResponse,
223
+ rotator: AccountRotator,
224
+ email: string,
225
+ modelKey?: string,
226
+ ): void {
227
+ const ok = rotator.clearInFlightRequests(email, modelKey);
228
+ res.writeHead(ok ? 200 : 404, { "Content-Type": "application/json" });
229
+ res.end(JSON.stringify({ ok, email, modelKey }));
230
+ }
231
+
232
+ export async function serveClearBreakerApi(
233
+ res: ServerResponse,
234
+ rotator: AccountRotator,
235
+ modelKey?: string,
236
+ ): Promise<void> {
237
+ if (modelKey) {
238
+ await rotator.clearModelBreaker(modelKey);
239
+ } else {
240
+ await rotator.clearAllBreakers();
241
+ }
242
+ res.writeHead(200, { "Content-Type": "application/json" });
243
+ res.end(JSON.stringify({ ok: true }));
244
+ }
245
+
246
+ export function serveKickstartApi(
247
+ res: ServerResponse,
248
+ rotator: AccountRotator,
249
+ email: string,
250
+ modelKey?: string,
251
+ ): void {
252
+ if (modelKey) {
253
+ rotator.kickstartTimerForAccount(email, modelKey).then((result) => {
254
+ res.writeHead(200, { "Content-Type": "application/json" });
255
+ res.end(JSON.stringify(result));
256
+ }).catch((err) => {
257
+ res.writeHead(500, { "Content-Type": "application/json" });
258
+ res.end(JSON.stringify({ ok: false, error: String(err) }));
259
+ });
260
+ } else {
261
+ rotator.kickstartAllFreshTimers(email).then((result) => {
262
+ res.writeHead(200, { "Content-Type": "application/json" });
263
+ res.end(JSON.stringify(result));
264
+ }).catch((err) => {
265
+ res.writeHead(500, { "Content-Type": "application/json" });
266
+ res.end(JSON.stringify({ ok: false, error: String(err), results: [] }));
267
+ });
268
+ }
269
+ }
270
+
271
+ export async function serveAutoWarmupApi(
272
+ res: ServerResponse,
273
+ rotator: AccountRotator,
274
+ enabled: boolean,
275
+ ): Promise<void> {
276
+ const changed = await rotator.setAutoWarmup(enabled);
277
+ res.writeHead(200, { "Content-Type": "application/json" });
278
+ res.end(JSON.stringify({ ok: true, changed, autoWarmupEnabled: enabled }));
279
+ }
280
+
281
+ // ── Virtual Keys & Spend Logging REST API ────────────────────────────
282
+
283
+ export async function serveGenerateVirtualKeyApi(
284
+ req: IncomingMessage,
285
+ res: ServerResponse,
286
+ ): Promise<void> {
287
+ try {
288
+ const rawBody = await readLimitedBody(req);
289
+ const parsed = rawBody.length > 0 ? JSON.parse(rawBody.toString("utf-8")) : {};
290
+ if (!parsed.alias || typeof parsed.alias !== "string") {
291
+ res.writeHead(400, { "Content-Type": "application/json" });
292
+ res.end(JSON.stringify({ ok: false, error: "Field 'alias' is required" }));
293
+ return;
294
+ }
295
+ const created = await generateVirtualKey({
296
+ alias: parsed.alias,
297
+ userId: parsed.userId,
298
+ models: parsed.models,
299
+ metadata: parsed.metadata,
300
+ createdBy: parsed.createdBy || "admin",
301
+ });
302
+ res.writeHead(201, { "Content-Type": "application/json" });
303
+ res.end(JSON.stringify({ ok: true, ...created }));
304
+ } catch (err) {
305
+ dashboardLogger.error(`Failed to generate virtual key: ${err}`);
306
+ res.writeHead(500, { "Content-Type": "application/json" });
307
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
308
+ }
309
+ }
310
+
311
+ export async function serveListVirtualKeysApi(
312
+ res: ServerResponse,
313
+ ): Promise<void> {
314
+ try {
315
+ const keys = await listVirtualKeys();
316
+ res.writeHead(200, { "Content-Type": "application/json" });
317
+ res.end(JSON.stringify({ ok: true, keys }));
318
+ } catch (err) {
319
+ dashboardLogger.error(`Failed to list virtual keys: ${err}`);
320
+ res.writeHead(500, { "Content-Type": "application/json" });
321
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
322
+ }
323
+ }
324
+
325
+ export async function serveGetVirtualKeyApi(
326
+ res: ServerResponse,
327
+ tokenHash: string,
328
+ ): Promise<void> {
329
+ try {
330
+ const key = await getVirtualKeyByHash(tokenHash);
331
+ if (!key) {
332
+ res.writeHead(404, { "Content-Type": "application/json" });
333
+ res.end(JSON.stringify({ ok: false, error: "Virtual key not found" }));
334
+ return;
335
+ }
336
+ res.writeHead(200, { "Content-Type": "application/json" });
337
+ res.end(JSON.stringify({ ok: true, key }));
338
+ } catch (err) {
339
+ dashboardLogger.error(`Failed to get virtual key: ${err}`);
340
+ res.writeHead(500, { "Content-Type": "application/json" });
341
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
342
+ }
343
+ }
344
+
345
+ export async function serveUpdateVirtualKeyApi(
346
+ req: IncomingMessage,
347
+ res: ServerResponse,
348
+ tokenHash: string,
349
+ ): Promise<void> {
350
+ try {
351
+ const rawBody = await readLimitedBody(req);
352
+ const updates = rawBody.length > 0 ? JSON.parse(rawBody.toString("utf-8")) : {};
353
+ const updated = await updateVirtualKey(tokenHash, updates);
354
+ if (!updated) {
355
+ res.writeHead(404, { "Content-Type": "application/json" });
356
+ res.end(JSON.stringify({ ok: false, error: "Virtual key not found" }));
357
+ return;
358
+ }
359
+ res.writeHead(200, { "Content-Type": "application/json" });
360
+ res.end(JSON.stringify({ ok: true, key: updated }));
361
+ } catch (err) {
362
+ dashboardLogger.error(`Failed to update virtual key: ${err}`);
363
+ res.writeHead(500, { "Content-Type": "application/json" });
364
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
365
+ }
366
+ }
367
+
368
+ export async function serveDeleteVirtualKeyApi(
369
+ res: ServerResponse,
370
+ tokenHash: string,
371
+ ): Promise<void> {
372
+ try {
373
+ const deleted = await deleteVirtualKey(tokenHash);
374
+ if (!deleted) {
375
+ res.writeHead(404, { "Content-Type": "application/json" });
376
+ res.end(JSON.stringify({ ok: false, error: "Virtual key not found" }));
377
+ return;
378
+ }
379
+ res.writeHead(200, { "Content-Type": "application/json" });
380
+ res.end(JSON.stringify({ ok: true, message: "Virtual key deleted" }));
381
+ } catch (err) {
382
+ dashboardLogger.error(`Failed to delete virtual key: ${err}`);
383
+ res.writeHead(500, { "Content-Type": "application/json" });
384
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
385
+ }
386
+ }
387
+
388
+ export async function serveGetSpendLogsApi(
389
+ req: IncomingMessage,
390
+ res: ServerResponse,
391
+ ): Promise<void> {
392
+ try {
393
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
394
+ const keyHash = url.searchParams.get("keyHash") || undefined;
395
+ const model = url.searchParams.get("model") || undefined;
396
+ const status = url.searchParams.get("status") || undefined;
397
+ const startDate = url.searchParams.get("startDate") || undefined;
398
+ const endDate = url.searchParams.get("endDate") || undefined;
399
+ const limit = url.searchParams.has("limit")
400
+ ? parseInt(url.searchParams.get("limit")!, 10)
401
+ : 50;
402
+ const offset = url.searchParams.has("offset")
403
+ ? parseInt(url.searchParams.get("offset")!, 10)
404
+ : 0;
405
+
406
+ const result = await getSpendLogs({
407
+ apiKeyHash: keyHash,
408
+ model,
409
+ status,
410
+ startDate,
411
+ endDate,
412
+ limit,
413
+ offset,
414
+ });
415
+ res.writeHead(200, { "Content-Type": "application/json" });
416
+ res.end(JSON.stringify({ ok: true, ...result }));
417
+ } catch (err) {
418
+ dashboardLogger.error(`Failed to get spend logs: ${err}`);
419
+ res.writeHead(500, { "Content-Type": "application/json" });
420
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
421
+ }
422
+ }
423
+
424
+ export async function serveGetSpendSummaryApi(
425
+ req: IncomingMessage,
426
+ res: ServerResponse,
427
+ ): Promise<void> {
428
+ try {
429
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
430
+ const keyHash = url.searchParams.get("keyHash") || undefined;
431
+ const startDate = url.searchParams.get("startDate") || undefined;
432
+ const endDate = url.searchParams.get("endDate") || undefined;
433
+
434
+ const summary = await getDailySpendSummary({
435
+ apiKeyHash: keyHash,
436
+ startDate,
437
+ endDate,
438
+ });
439
+ res.writeHead(200, { "Content-Type": "application/json" });
440
+ res.end(JSON.stringify({ ok: true, summary }));
441
+ } catch (err) {
442
+ dashboardLogger.error(`Failed to get spend summary: ${err}`);
443
+ res.writeHead(500, { "Content-Type": "application/json" });
444
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
445
+ }
446
+ }
447
+
448
+ export async function serveGetSpendByKeyApi(
449
+ req: IncomingMessage,
450
+ res: ServerResponse,
451
+ ): Promise<void> {
452
+ try {
453
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
454
+ const apiKeyHash = url.searchParams.get("apiKeyHash") || undefined;
455
+ const model = url.searchParams.get("model") || undefined;
456
+ const status = url.searchParams.get("status") || undefined;
457
+ const startDate = url.searchParams.get("startDate") || undefined;
458
+ const endDate = url.searchParams.get("endDate") || undefined;
459
+
460
+ const byKey = await getSpendByKey({ apiKeyHash, model, status, startDate, endDate });
461
+ res.writeHead(200, { "Content-Type": "application/json" });
462
+ res.end(JSON.stringify({ ok: true, byKey }));
463
+ } catch (err) {
464
+ dashboardLogger.error(`Failed to get spend by key: ${err}`);
465
+ res.writeHead(500, { "Content-Type": "application/json" });
466
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
467
+ }
468
+ }
469
+
470
+ function renderAppShell(opts: {
471
+ title: string;
472
+ activeTab: "accounts" | "keys" | "logs";
473
+ contentHtml: string;
474
+ scriptSrc: string;
475
+ }): string {
476
+ const pageTitle = opts.title === "Tuxevil Rotator" ? opts.title : (opts.title + " — Tuxevil Rotator");
477
+ return `<!DOCTYPE html>
478
+ <html lang="en">
479
+ <head>
480
+ <meta charset="utf-8">
481
+ <meta name="viewport" content="width=device-width, initial-scale=1">
482
+ <title>${pageTitle}</title>
483
+ <link rel="stylesheet" href="/static/dashboard.css">
484
+ </head>
485
+ <body class="${opts.activeTab}-page">
486
+
487
+ <div class="update-banner" id="updateBanner">
488
+ <span class="update-badge" id="updateBadgeLabel">NEW</span>
489
+ <div class="update-message" id="updateMessage"></div>
490
+ <div class="update-banner-actions" id="updateActions"></div>
491
+ </div>
492
+
493
+ <div class="notif-container" id="notifContainer"></div>
494
+
495
+ <div class="header">
496
+ <div class="header-main">
497
+ <div class="header-title-row">
498
+ <div class="header-brand-group">
499
+ <h1>Tuxevil Rotator</h1>
500
+ <span class="header-version" id="headerVersion">v--</span>
501
+ <button id="maskBtn" class="mask-btn" onclick="toggleMask()">PII: Visible</button>
502
+ </div>
503
+
504
+ <nav class="header-nav-bar" id="appNav">
505
+ <a class="header-nav-tab ${opts.activeTab === "accounts" ? "active" : ""}" id="navAccounts" href="/dashboard">
506
+ <svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
507
+ Accounts
508
+ </a>
509
+ <a class="header-nav-tab ${opts.activeTab === "keys" ? "active" : ""}" id="navKeys" href="/dashboard/keys">
510
+ <svg viewBox="0 0 24 24"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
511
+ Virtual Keys
512
+ </a>
513
+ <a class="header-nav-tab ${opts.activeTab === "logs" ? "active" : ""}" id="navLogs" href="/dashboard/logs">
514
+ <svg viewBox="0 0 24 24"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
515
+ Spend Logs
516
+ </a>
517
+ </nav>
518
+ </div>
519
+ <div class="header-stats">
520
+ Uptime: <span id="uptime">--</span> |
521
+ Port: <span id="port">--</span> |
522
+ Rotation: <span id="rotation">--</span> reqs |
523
+ Updated: <span id="lastRefresh">--</span> |
524
+ Requests: <span id="totalRequests">0</span>
525
+ </div>
526
+ </div>
527
+ <div class="header-actions">
528
+ <button class="header-icon-btn attention" id="attentionBtn" onclick="openModal('attentionModal')" title="Attention Needed" aria-label="Open attention needed">
529
+ <svg viewBox="0 0 24 24"><path d="M12 8v5"/><path d="M12 17.5h.01"/><path d="M10.3 3.8 2.9 17a2 2 0 0 0 1.75 3h14.7A2 2 0 0 0 21.1 17L13.7 3.8a2 2 0 0 0-3.4 0Z"/></svg>
530
+ <span class="header-icon-badge attention" id="attentionBadge" style="display:none">0</span>
531
+ </button>
532
+
533
+ <button class="header-icon-btn heart-beat" id="kofiBtn" onclick="openModal('donationModal')" title="Support the Project" aria-label="Support the project">
534
+ <svg viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
535
+ </button>
536
+
537
+ <a class="header-icon-btn website-btn" id="websiteBtn" href="https://tuxevil.com" target="_blank" title="tuxevil.com" aria-label="Visit tuxevil.com">
538
+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
539
+ </a>
540
+ </div>
541
+ </div>
542
+
543
+ <script>
544
+ (function(){
545
+ var urlParams = new URLSearchParams(window.location.search);
546
+ var t = urlParams.get("token") || localStorage.getItem("rotatorAdminToken");
547
+ var mask = urlParams.has("mask");
548
+ if (t || mask) {
549
+ ["navAccounts", "navKeys", "navLogs"].forEach(function(id) {
550
+ var el = document.getElementById(id);
551
+ if (el && el.getAttribute("href")) {
552
+ var base = el.getAttribute("href").split("?")[0];
553
+ var params = new URLSearchParams();
554
+ if (t) params.set("token", t);
555
+ if (mask) params.set("mask", "1");
556
+ el.href = base + "?" + params.toString();
557
+ }
558
+ });
559
+ }
560
+ })();
561
+ </script>
562
+
563
+ ${opts.contentHtml}
564
+
565
+ <div class="modal" id="attentionModal" onclick="closeModal(event, 'attentionModal')">
566
+ <div class="modal-card" onclick="event.stopPropagation()">
567
+ <div class="modal-header">
568
+ <strong>Attention Needed</strong>
569
+ <button class="modal-close" onclick="closeModal(null, 'attentionModal')" aria-label="Close attention modal">×</button>
570
+ </div>
571
+ <div id="attentionPanel"></div>
572
+ </div>
573
+ </div>
574
+
575
+ <div class="modal" id="donationModal" onclick="closeModal(event, 'donationModal')">
576
+ <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 500px;">
577
+ <div class="modal-header">
578
+ <strong>Support the Project</strong>
579
+ <button class="modal-close" onclick="closeModal(null, 'donationModal')" aria-label="Close support modal">x</button>
580
+ </div>
581
+ <div style="padding: 16px; font-size: 0.95rem; line-height: 1.5; color: var(--text);">
582
+ <p style="margin-bottom:12px;">If this tool has helped you save money on AI API costs, consider supporting its continued development.</p>
583
+ <div style="display:flex;flex-direction:column;gap:16px;margin-bottom:20px;">
584
+ <a href="https://ko-fi.com/tuxevil" target="_blank" style="display:inline-flex;flex-direction:column;align-items:center;background-color:#FF5E5B;color:white;padding:12px 24px;border-radius:6px;text-decoration:none;transition:opacity 0.2s;width:100%;box-sizing:border-box;text-align:center;" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'">
585
+ <span style="font-weight:bold;font-size:1.1rem;">Support on Ko-fi</span>
586
+ <span style="font-size:0.85rem;margin-top:4px;opacity:0.85;">ko-fi.com/tuxevil</span>
587
+ </a>
588
+ <div style="width:100%; padding:14px; border: 1px solid var(--border); border-radius: 8px; background: rgba(255,255,255,0.02); box-sizing: border-box;">
589
+ <p style="margin-bottom:10px;font-weight:bold;color:var(--accent);font-size:0.95rem;">Free ways to support</p>
590
+ <ul style="margin-left:18px; font-size:0.85rem; color:var(--text-dim); line-height:1.7; list-style:none; padding:0;">
591
+ <li style="margin-bottom:6px;margin-left:0;">&#11088; <a href="https://github.com/tuxevil/tuxevil-rotator" target="_blank" style="color:var(--accent);text-decoration:underline;">Star the project on GitHub</a> — helps with visibility</li>
592
+ <li style="margin-bottom:6px;margin-left:0;">&#128027; <a href="https://github.com/tuxevil/tuxevil-rotator/issues" target="_blank" style="color:var(--accent);text-decoration:underline;">Report bugs & contribute</a> — open issues or submit PRs</li>
593
+ <li style="margin-bottom:0;margin-left:0;">&#128227; Share the project with colleagues or communities who might find it useful</li>
594
+ </ul>
595
+ </div>
596
+ </div>
597
+ <div style="text-align: center;">
598
+ <button class="btn-secondary" onclick="hideDonationModalPermanently()">Dismiss</button>
599
+ </div>
600
+ </div>
601
+ </div>
602
+ </div>
603
+
604
+ <footer class="app-footer">
605
+ <div class="app-footer-inner">
606
+ <span class="app-footer-brand">Tuxevil Rotator</span>
607
+ <span class="app-footer-sep"></span>
608
+ <a href="https://tuxevil.com" target="_blank">tuxevil.com</a>
609
+ <span class="app-footer-sep"></span>
610
+ <a href="https://github.com/tuxevil/tuxevil-rotator" target="_blank">GitHub</a>
611
+ </div>
612
+ </footer>
613
+
614
+ <script src="${opts.scriptSrc}"></script>
615
+ </body>
616
+ </html>`;
617
+ }
618
+
619
+ const DASHBOARD_HTML = renderAppShell({
620
+ title: "Tuxevil Rotator",
621
+ activeTab: "accounts",
622
+ scriptSrc: "/static/dashboard.js",
623
+ contentHtml: `
624
+ <div class="accounts-dashboard">
625
+ <div class="dashboard-intro">
626
+ <div>
627
+ <div class="dashboard-kicker">Operations / Account fleet</div>
628
+ <h2>Keep the fleet moving.</h2>
629
+ <p>Scan routing health, quota windows and account actions from one focused control room.</p>
630
+ </div>
631
+ <div class="dashboard-intro-actions">
632
+ <span class="dashboard-live-chip"><span class="dashboard-live-dot"></span>Live polling</span>
633
+ <button class="btn-secondary dashboard-refresh-btn" onclick="refresh()">Refresh now</button>
634
+ </div>
635
+ </div>
636
+
637
+ <div class="view-toggle-bar">
638
+ <button class="view-tab active" id="viewTabGrid" onclick="switchView('grid')">⊞ Grid</button>
639
+ <button class="view-tab" id="viewTabList" onclick="switchView('list')">☰ List</button>
640
+ </div>
641
+
642
+ <div class="routing-panel state-stopped" id="routingHealth"></div>
643
+
644
+ <div class="routing-panel" id="tokenUsagePanel" style="margin-top:12px">
645
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px">
646
+ <strong style="min-width:max-content">Token Usage</strong>
647
+ <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
648
+ <div id="tokenTotals" style="font-family:JetBrains Mono,monospace;font-size:0.85rem;color:var(--text-dim);margin-right:12px"></div>
649
+ <button class="btn-secondary btn-sm" onclick="exportData('csv')" title="Export CSV" style="padding:2px 6px">CSV</button>
650
+ <button class="btn-secondary btn-sm" onclick="exportData('json')" title="Export JSON" style="padding:2px 6px;margin-right:8px">JSON</button>
651
+ <div style="width:1px;height:16px;background:var(--border);margin-right:8px"></div>
652
+ <button class="btn-secondary btn-sm" onclick="setTokenView('1h')" id="tbtn-1h">1h</button>
653
+ <button class="btn-secondary btn-sm" onclick="setTokenView('2h')" id="tbtn-2h">2h</button>
654
+ <button class="btn-secondary btn-sm" onclick="setTokenView('4h')" id="tbtn-4h">4h</button>
655
+ <button class="btn-secondary btn-sm" onclick="setTokenView('8h')" id="tbtn-8h">8h</button>
656
+ <button class="btn-secondary btn-sm" onclick="setTokenView('12h')" id="tbtn-12h">12h</button>
657
+ <button class="btn-secondary btn-sm" onclick="setTokenView('1d')" id="tbtn-1d">1d</button>
658
+ <button class="btn-secondary btn-sm" onclick="setTokenView('7d')" id="tbtn-7d">7d</button>
659
+ <button class="btn-secondary btn-sm" onclick="setTokenView('1m')" id="tbtn-1m">1m</button>
660
+ </div>
661
+ </div>
662
+ <div id="tokenChart" style="width:100%;overflow-x:auto"></div>
663
+ <div id="tokenLegend" style="margin-top:8px;display:flex;gap:16px;flex-wrap:wrap;font-size:0.8rem"></div>
664
+ </div>
665
+
666
+ <div class="routing-panel" id="latencyPanel" style="margin-top:12px;display:none">
667
+ <strong>Latency (last 200 requests)</strong>
668
+ <div id="latencyGrid" style="margin-top:8px"></div>
669
+ </div>
670
+
671
+ <div class="routing-panel" id="forecastPanel" style="margin-top:12px;display:none">
672
+ <strong>Quota Forecast</strong>
673
+ <div id="forecastGrid" style="margin-top:8px"></div>
674
+ </div>
675
+
676
+ <div class="routing-panel" id="benchmarkPanel" style="margin-top:12px">
677
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
678
+ <div>
679
+ <strong>Account Benchmark</strong>
680
+ <div id="benchmarkStatus" style="color:var(--text-dim);font-size:0.8rem;margin-top:4px">Measure active account performance without persisting results.</div>
681
+ </div>
682
+ <button class="btn-secondary" id="benchmarkBtn" onclick="runBenchmark()">Benchmark Active Accounts</button>
683
+ </div>
684
+ <div id="benchmarkResults" style="margin-top:12px;overflow-x:auto"></div>
685
+ </div>
686
+
687
+ <div class="accounts-grid" id="accounts"></div>
688
+
689
+ <div class="list-panel" id="listPanel" style="display:none">
690
+ <div class="list-toolbar">
691
+ <span class="list-toolbar-label">Installations</span>
692
+ <input class="list-search" id="listSearch" placeholder="Search…" oninput="renderListView()" />
693
+ <button class="list-sort-btn" id="lsort-requests" onclick="setListSort('requests')">Requests ↕</button>
694
+ <button class="list-sort-btn" id="lsort-quota" onclick="setListSort('quota')">Quota ↕</button>
695
+ <button class="list-sort-btn" id="lsort-tokens" onclick="setListSort('tokens')">Tokens ↕</button>
696
+ <button class="list-sort-btn" id="lsort-status" onclick="setListSort('status')">Status ↕</button>
697
+ </div>
698
+ <div id="listTableWrap"></div>
699
+ </div>
700
+
701
+ <div class="routing-panel" id="heatmapPanel" style="margin-top:12px;display:none">
702
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
703
+ <strong>Activity Heatmap (last 60d)</strong>
704
+ <span style="color:var(--text-dim);font-size:0.75rem">rows: hour · cols: day</span>
705
+ </div>
706
+ <div id="heatmapGrid"></div>
707
+ </div>
708
+
709
+ <div class="routing-panel" id="requestLogPanel" style="margin-top:12px;display:none">
710
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
711
+ <strong>Request Log</strong>
712
+ <div style="display:flex;gap:6px">
713
+ <input id="logFilterModel" placeholder="model" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:100px" />
714
+ <input id="logFilterAccount" placeholder="account" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:100px" />
715
+ <input id="logFilterStatus" placeholder="status" style="background:var(--card-bg);border:1px solid var(--border);color:var(--text);padding:2px 6px;border-radius:4px;font-size:0.75rem;width:60px" />
716
+ </div>
717
+ </div>
718
+ <div id="requestLogGrid" style="max-height:320px;overflow-y:auto"></div>
719
+ </div>
720
+
721
+ <div class="events-panel" id="recentEventsPanel" style="display:none"></div>
722
+
723
+ </div>
724
+
725
+ <div class="modal" id="configEditorModal" onclick="closeModal(event, 'configEditorModal')">
726
+ <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 960px; width: min(960px, 92vw);">
727
+ <div class="modal-header">
728
+ <strong>Config Editor</strong>
729
+ <button class="modal-close" onclick="closeModal(null, 'configEditorModal')" aria-label="Close config editor modal">×</button>
730
+ </div>
731
+ <div style="padding:16px;">
732
+ <div style="display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px">
733
+ <div id="configEditorStatus" style="font-size:12px;color:var(--text-dim)"></div>
734
+ <div style="display:flex;gap:8px;flex-wrap:wrap">
735
+ <button class="btn-secondary" onclick="loadConfigEditor()">Reload</button>
736
+ <button class="btn-secondary" onclick="saveConfigEditor()">Save</button>
737
+ <button class="btn-secondary" onclick="exportConfig()">Export</button>
738
+ <button class="btn-secondary" onclick="importConfigPrompt()">Import</button>
739
+ <button class="btn-secondary" onclick="window.location.href='/login' + (ADMIN_TOKEN ? ('?token=' + encodeURIComponent(ADMIN_TOKEN)) : '')">Hosted Login</button>
740
+ </div>
741
+ </div>
742
+ <textarea id="configEditor" spellcheck="false" style="width:100%;min-height:420px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:8px;color:var(--text);padding:12px;font-family:'JetBrains Mono', monospace;font-size:12px;line-height:1.5"></textarea>
743
+ <div style="margin-top:8px;font-size:12px;color:var(--text-dim)">routingPolicy: timer-first, tier-first, quota-first, hybrid, sequential-quota o sticky-quota. Las políticas quota-aware evitan la rotación por contador; sticky-quota vuelve a la cuenta preferida después de un cooldown.</div>
744
+ </div>
745
+ </div>
746
+ </div>
747
+
748
+ <div class="modal" id="routingInspectorModal" onclick="closeModal(event, 'routingInspectorModal')">
749
+ <div class="modal-card" onclick="event.stopPropagation()" style="max-width: 1100px; width: min(1100px, 94vw);">
750
+ <div class="modal-header">
751
+ <strong>Routing Inspector</strong>
752
+ <button class="modal-close" onclick="closeModal(null, 'routingInspectorModal')" aria-label="Close routing inspector modal">×</button>
753
+ </div>
754
+ <div id="routingInspectorPanel" style="padding:16px;"></div>
755
+ </div>
756
+ </div>
757
+ `,
758
+ });
759
+
760
+ const DASHBOARD_KEYS_HTML = renderAppShell({
761
+ title: "Virtual Keys",
762
+ activeTab: "keys",
763
+ scriptSrc: "/static/dashboard-keys.js",
764
+ contentHtml: `
765
+ <div class="keys-workspace">
766
+ <div class="workspace-intro">
767
+ <div>
768
+ <div class="workspace-kicker">Access / Credentials</div>
769
+ <h2>Virtual Keys &amp; Access Control</h2>
770
+ <p>Manage API credentials, agent assignments, and per-model authorization rules from one operator workspace.</p>
771
+ </div>
772
+ <div class="workspace-intro-actions">
773
+ <span class="workspace-live-chip"><span class="workspace-live-dot"></span>Registry live</span>
774
+ <button class="btn-modal-submit workspace-primary-action" onclick="showGenerateModal()" style="display:inline-flex;align-items:center;gap:8px">
775
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
776
+ Generate Virtual Key
777
+ </button>
778
+ </div>
779
+ </div>
780
+
781
+ <div class="stats-summary-grid keys-stats">
782
+ <div class="summary-card">
783
+ <div class="summary-card-header">
784
+ <span>Total Credentials</span>
785
+ <div class="summary-card-icon">
786
+ <svg viewBox="0 0 24 24"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
787
+ </div>
788
+ </div>
789
+ <div class="summary-card-value" id="statTotalKeys">0</div>
790
+ <div class="summary-card-sub">Registered virtual keys</div>
791
+ </div>
792
+
793
+ <div class="summary-card">
794
+ <div class="summary-card-header">
795
+ <span>Active Keys</span>
796
+ <div class="summary-card-icon" style="background:rgba(52,211,153,0.1);color:var(--green)">
797
+ <svg viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
798
+ </div>
799
+ </div>
800
+ <div class="summary-card-value" id="statActiveKeys" style="color:var(--green)">0</div>
801
+ <div class="summary-card-sub">Authorized for requests</div>
802
+ </div>
803
+
804
+ <div class="summary-card">
805
+ <div class="summary-card-header">
806
+ <span>Blocked Keys</span>
807
+ <div class="summary-card-icon" style="background:rgba(248,113,113,0.1);color:var(--red)">
808
+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
809
+ </div>
810
+ </div>
811
+ <div class="summary-card-value" id="statBlockedKeys" style="color:var(--red)">0</div>
812
+ <div class="summary-card-sub">Revoked access</div>
813
+ </div>
814
+
815
+ <div class="summary-card">
816
+ <div class="summary-card-header">
817
+ <span>Supported Models</span>
818
+ <div class="summary-card-icon" style="background:rgba(96,165,250,0.1);color:var(--blue)">
819
+ <svg viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
820
+ </div>
821
+ </div>
822
+ <div class="summary-card-value" id="statAvailableModels">12</div>
823
+ <div class="summary-card-sub">Gemini, Claude, GPT-OSS</div>
824
+ </div>
825
+ </div>
826
+
827
+ <div class="list-panel keys-list-panel">
828
+ <div class="list-toolbar keys-list-toolbar">
829
+ <span class="list-toolbar-label">Virtual Keys</span>
830
+ <div class="filter-input-group" style="width:260px">
831
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
832
+ <input id="keySearchInput" placeholder="Search alias, key name, user..." oninput="renderKeys()">
833
+ </div>
834
+ <div class="filter-input-group" style="width:140px">
835
+ <select id="keyStatusFilter" onchange="renderKeys()">
836
+ <option value="all">All Statuses</option>
837
+ <option value="active">Active Only</option>
838
+ <option value="blocked">Blocked Only</option>
839
+ </select>
840
+ </div>
841
+ </div>
842
+
843
+ <div style="overflow-x:auto">
844
+ <table class="compact-table">
845
+ <thead>
846
+ <tr>
847
+ <th>Key Alias &amp; Name</th>
848
+ <th>User ID</th>
849
+ <th>Allowed Models</th>
850
+ <th>Status</th>
851
+ <th>Last Active</th>
852
+ <th style="width:110px;text-align:right">Actions</th>
853
+ </tr>
854
+ </thead>
855
+ <tbody id="keysTbody"></tbody>
856
+ </table>
857
+ </div>
858
+ </div>
859
+ </div>
860
+
861
+ <div id="keyModal" class="modal" onclick="if(event.target===this) hideModal()">
862
+ <div class="modal-card" onclick="event.stopPropagation()" style="max-width:640px;display:flex;flex-direction:column;max-height:90vh;overflow:hidden">
863
+ <div class="modal-header">
864
+ <div class="modal-title-group">
865
+ <div class="modal-icon">
866
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>
867
+ </div>
868
+ <div>
869
+ <h3 id="modalTitle" class="modal-title">Generate Virtual Key</h3>
870
+ <p id="modalSubtitle" class="modal-subtitle">Configure key access and model restrictions</p>
871
+ </div>
872
+ </div>
873
+ <button class="modal-close-btn" onclick="hideModal()" type="button" aria-label="Close">&times;</button>
874
+ </div>
875
+
876
+ <div class="modal-body" style="overflow-y:auto;flex:1">
877
+ <div class="form-grid">
878
+ <div class="form-group">
879
+ <label class="form-label" for="keyFormAlias">Key Alias <span class="req">*</span></label>
880
+ <input id="keyFormAlias" class="form-input" placeholder="e.g. cursor-agent" autofocus>
881
+ </div>
882
+ <div class="form-group">
883
+ <label class="form-label" for="keyFormUserId">User ID <span class="opt">(optional)</span></label>
884
+ <input id="keyFormUserId" class="form-input" placeholder="e.g. seba">
885
+ </div>
886
+ </div>
887
+
888
+ <div id="modelCheckboxes" class="models-section">
889
+ <div class="models-header">
890
+ <div>
891
+ <span class="form-label">Allowed Models</span>
892
+ <span class="models-badge" id="modelsCountBadge">All models allowed</span>
893
+ </div>
894
+ <div class="models-actions">
895
+ <button class="pill-btn" onclick="selectAllModels()" type="button">Select All</button>
896
+ <button class="pill-btn" onclick="selectNoModels()" type="button">Clear All</button>
897
+ </div>
898
+ </div>
899
+
900
+ <div class="model-grid">
901
+ <div class="model-category">
902
+ <div class="cat-title">Gemini 3.1 Pro</div>
903
+ <div class="cat-grid">
904
+ <label class="model-card"><input type="checkbox" value="gemini-3.1-pro-low" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.1-pro-low</span></label>
905
+ <label class="model-card"><input type="checkbox" value="gemini-3.1-pro-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.1-pro-high</span></label>
906
+ </div>
907
+ </div>
908
+ <div class="model-category">
909
+ <div class="cat-title">Gemini 3.5 Flash</div>
910
+ <div class="cat-grid">
911
+ <label class="model-card"><input type="checkbox" value="gemini-3.5-flash-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.5-flash-medium</span></label>
912
+ <label class="model-card"><input type="checkbox" value="gemini-3.5-flash-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.5-flash-high</span></label>
913
+ <label class="model-card"><input type="checkbox" value="gemini-3-flash" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3-flash</span></label>
914
+ </div>
915
+ </div>
916
+ <div class="model-category">
917
+ <div class="cat-title">Gemini 3.6 Flash</div>
918
+ <div class="cat-grid">
919
+ <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-low" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-low</span></label>
920
+ <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-medium</span></label>
921
+ <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-high" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-high</span></label>
922
+ <label class="model-card"><input type="checkbox" value="gemini-3.6-flash-tiered" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gemini-3.6-flash-tiered</span></label>
923
+ </div>
924
+ </div>
925
+ <div class="model-category">
926
+ <div class="cat-title">Claude</div>
927
+ <div class="cat-grid">
928
+ <label class="model-card"><input type="checkbox" value="claude-sonnet-4-6" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">claude-sonnet-4-6</span></label>
929
+ <label class="model-card"><input type="checkbox" value="claude-opus-4-6-thinking" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">claude-opus-4-6-thinking</span></label>
930
+ </div>
931
+ </div>
932
+ <div class="model-category">
933
+ <div class="cat-title">GPT-OSS</div>
934
+ <div class="cat-grid">
935
+ <label class="model-card"><input type="checkbox" value="gpt-oss-120b-medium" class="modelCb" onchange="updateModelsCountBadge()"><span class="model-name">gpt-oss-120b-medium</span></label>
936
+ </div>
937
+ </div>
938
+ </div>
939
+ </div>
940
+
941
+ <div id="keyFormError" class="modal-error"></div>
942
+
943
+ <div id="generatedKeyResult" class="generated-key-box" style="display:none">
944
+ <div class="key-warn-header">
945
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
946
+ Save this key now — it won't be shown again!
947
+ </div>
948
+ <div class="raw" id="generatedRawKey"></div>
949
+ <button id="copyKeyBtn" class="btn-secondary" onclick="copyRawKey()" style="margin-top:8px" type="button">Copy Key</button>
950
+ </div>
951
+ </div>
952
+
953
+ <div class="modal-footer">
954
+ <button class="btn-modal-cancel" onclick="hideModal()" type="button">Cancel</button>
955
+ <button class="btn-modal-submit" onclick="submitKeyForm()" id="submitKeyBtn" type="button">Generate Key</button>
956
+ </div>
957
+ </div>
958
+ </div>
959
+ `,
960
+ });
961
+
962
+ const DASHBOARD_LOGS_HTML = renderAppShell({
963
+ title: "Spend Logs",
964
+ activeTab: "logs",
965
+ scriptSrc: "/static/dashboard-logs.js",
966
+ contentHtml: `
967
+ <div class="logs-workspace">
968
+ <div class="workspace-intro">
969
+ <div>
970
+ <div class="workspace-kicker">Observability / Spend telemetry</div>
971
+ <h2>Spend Logs &amp; Usage Analytics</h2>
972
+ <p>Trace request cost, token flow, latency, and payload context through a focused audit console.</p>
973
+ </div>
974
+ <div class="workspace-intro-actions">
975
+ <span class="workspace-live-chip"><span class="workspace-live-dot"></span>Live audit</span>
976
+ <button class="btn-secondary workspace-refresh-action" onclick="loadLogs(0)">Refresh logs</button>
977
+ </div>
978
+ </div>
979
+
980
+ <div class="stats-summary-grid logs-stats">
981
+ <div class="summary-card">
982
+ <div class="summary-card-header">
983
+ <span>Total Requests</span>
984
+ <div class="summary-card-icon">
985
+ <svg viewBox="0 0 24 24"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
986
+ </div>
987
+ </div>
988
+ <div class="summary-card-value" id="statLogRequests">0</div>
989
+ <div class="summary-card-sub" id="statLogRequestsSub">Logged requests</div>
990
+ </div>
991
+
992
+ <div class="summary-card">
993
+ <div class="summary-card-header">
994
+ <span>Prompt Tokens</span>
995
+ <div class="summary-card-icon" style="background:rgba(124,92,252,0.1);color:var(--accent)">
996
+ <svg viewBox="0 0 24 24"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>
997
+ </div>
998
+ </div>
999
+ <div class="summary-card-value" id="statLogPromptTokens">0</div>
1000
+ <div class="summary-card-sub">Input tokens processed</div>
1001
+ </div>
1002
+
1003
+ <div class="summary-card">
1004
+ <div class="summary-card-header">
1005
+ <span>Completion Tokens</span>
1006
+ <div class="summary-card-icon" style="background:rgba(52,211,153,0.1);color:var(--green)">
1007
+ <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
1008
+ </div>
1009
+ </div>
1010
+ <div class="summary-card-value" id="statLogCompletionTokens" style="color:var(--green)">0</div>
1011
+ <div class="summary-card-sub">Output tokens generated</div>
1012
+ </div>
1013
+
1014
+ <div class="summary-card">
1015
+ <div class="summary-card-header">
1016
+ <span>Est. Cost</span>
1017
+ <div class="summary-card-icon" style="background:rgba(59,130,246,0.1);color:#3b82f6">
1018
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
1019
+ </div>
1020
+ </div>
1021
+ <div class="summary-card-value" id="statLogCost" style="color:#3b82f6">$0.000000</div>
1022
+ <div class="summary-card-sub">Estimated USD cost</div>
1023
+ </div>
1024
+
1025
+ <div class="summary-card">
1026
+ <div class="summary-card-header">
1027
+ <span>Avg Latency</span>
1028
+ <div class="summary-card-icon" style="background:rgba(251,191,36,0.1);color:var(--yellow)">
1029
+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
1030
+ </div>
1031
+ </div>
1032
+ <div class="summary-card-value" id="statLogAvgLatency" style="color:var(--yellow)">--</div>
1033
+ <div class="summary-card-sub">Average round-trip duration</div>
1034
+ </div>
1035
+ </div>
1036
+
1037
+ <div id="byKeySummary" class="logs-by-key-summary"></div>
1038
+
1039
+ <div class="filter-panel logs-filter-panel">
1040
+ <div class="logs-filter-heading">
1041
+ <div>
1042
+ <span class="logs-filter-kicker">Query console</span>
1043
+ <strong>Filter request history</strong>
1044
+ </div>
1045
+ <span>Use filters to narrow the audit window, then expand any row for payload context.</span>
1046
+ </div>
1047
+ <div class="multiselect-container" id="keyMultiselectContainer">
1048
+ <div class="multiselect-trigger" id="keyMultiselectTrigger" onclick="toggleMultiselect(event, 'key')">
1049
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
1050
+ <span class="multiselect-label" id="keyMultiselectLabel">All Keys</span>
1051
+ <svg class="multiselect-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
1052
+ </div>
1053
+ <div class="multiselect-menu" id="keyMultiselectMenu" style="display:none">
1054
+ <div class="multiselect-header">
1055
+ <input type="text" class="multiselect-search" id="keySearchInput" placeholder="Search keys..." onclick="event.stopPropagation()" oninput="filterMultiselectOptions('key')">
1056
+ <div class="multiselect-actions">
1057
+ <button type="button" class="multiselect-action-btn" onclick="selectAllMultiselect('key')">Select All</button>
1058
+ <button type="button" class="multiselect-action-btn" onclick="clearMultiselect('key')">Clear</button>
1059
+ </div>
1060
+ </div>
1061
+ <div class="multiselect-options" id="keyMultiselectOptions">
1062
+ <div style="padding:8px;color:var(--text-dim);font-size:12px;text-align:center">Loading keys...</div>
1063
+ </div>
1064
+ </div>
1065
+ </div>
1066
+
1067
+ <div class="multiselect-container" id="modelMultiselectContainer">
1068
+ <div class="multiselect-trigger" id="modelMultiselectTrigger" onclick="toggleMultiselect(event, 'model')">
1069
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
1070
+ <span class="multiselect-label" id="modelMultiselectLabel">All Models</span>
1071
+ <svg class="multiselect-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
1072
+ </div>
1073
+ <div class="multiselect-menu" id="modelMultiselectMenu" style="display:none">
1074
+ <div class="multiselect-header">
1075
+ <input type="text" class="multiselect-search" id="modelSearchInput" placeholder="Search models..." onclick="event.stopPropagation()" oninput="filterMultiselectOptions('model')">
1076
+ <div class="multiselect-actions">
1077
+ <button type="button" class="multiselect-action-btn" onclick="selectAllMultiselect('model')">Select All</button>
1078
+ <button type="button" class="multiselect-action-btn" onclick="clearMultiselect('model')">Clear</button>
1079
+ </div>
1080
+ </div>
1081
+ <div class="multiselect-options" id="modelMultiselectOptions">
1082
+ <div style="padding:8px;color:var(--text-dim);font-size:12px;text-align:center">Loading models...</div>
1083
+ </div>
1084
+ </div>
1085
+ </div>
1086
+
1087
+ <div class="filter-input-group" style="width:150px">
1088
+ <select id="filterStatus">
1089
+ <option value="">All Statuses</option>
1090
+ <option value="success">Success (200)</option>
1091
+ <option value="failure">Failure / Error</option>
1092
+ </select>
1093
+ </div>
1094
+
1095
+ <div class="filter-input-group" style="width:150px">
1096
+ <input id="filterStartDate" type="date" title="From Date">
1097
+ </div>
1098
+
1099
+ <div class="filter-input-group" style="width:150px">
1100
+ <input id="filterEndDate" type="date" title="To Date">
1101
+ </div>
1102
+
1103
+ <button class="pill-btn" onclick="applyFilters()" style="background:var(--accent);color:#fff;border:none;padding:7px 14px;font-weight:600;cursor:pointer">Apply</button>
1104
+ <button class="pill-btn" onclick="resetFilters()" style="padding:7px 12px;cursor:pointer">Reset</button>
1105
+
1106
+ <div class="filter-input-group" style="width:160px;margin-left:auto">
1107
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;height:14px;color:var(--text-dim)"><path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
1108
+ <select id="autoRefreshSelect" onchange="changeAutoRefresh(this.value)" title="Auto Refresh">
1109
+ <option value="0">Auto-refresh: Off</option>
1110
+ <option value="5">Auto-refresh: 5s</option>
1111
+ <option value="10">Auto-refresh: 10s</option>
1112
+ <option value="30">Auto-refresh: 30s</option>
1113
+ <option value="60">Auto-refresh: 60s</option>
1114
+ </select>
1115
+ </div>
1116
+
1117
+ <div class="col-picker-container" style="position:relative">
1118
+ <button class="pill-btn" onclick="toggleColumnPicker(event)" type="button" style="display:inline-flex;align-items:center;gap:6px;padding:7px 12px;cursor:pointer">
1119
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>
1120
+ <span>Columns</span>
1121
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
1122
+ </button>
1123
+ <div id="colPickerMenu" class="col-picker-menu" style="display:none" onclick="event.stopPropagation()">
1124
+ <div class="col-picker-header">
1125
+ <span>Visible Columns</span>
1126
+ <button type="button" class="col-picker-reset" onclick="resetColumns()">Reset</button>
1127
+ </div>
1128
+ <div class="col-picker-list">
1129
+ <label class="col-picker-item"><input type="checkbox" data-col="time" checked onchange="toggleColumn('time')"> Time</label>
1130
+ <label class="col-picker-item"><input type="checkbox" data-col="key" checked onchange="toggleColumn('key')"> Key / Agent</label>
1131
+ <label class="col-picker-item"><input type="checkbox" data-col="model" checked onchange="toggleColumn('model')"> Model</label>
1132
+ <label class="col-picker-item"><input type="checkbox" data-col="type" checked onchange="toggleColumn('type')"> Call Type</label>
1133
+ <label class="col-picker-item"><input type="checkbox" data-col="status" checked onchange="toggleColumn('status')"> Status</label>
1134
+ <label class="col-picker-item"><input type="checkbox" data-col="tokens" checked onchange="toggleColumn('tokens')"> Tokens (In / Out)</label>
1135
+ <label class="col-picker-item"><input type="checkbox" data-col="cost" checked onchange="toggleColumn('cost')"> Est. Cost</label>
1136
+ <label class="col-picker-item"><input type="checkbox" data-col="duration" checked onchange="toggleColumn('duration')"> Duration</label>
1137
+ <label class="col-picker-item"><input type="checkbox" data-col="ttfb" checked onchange="toggleColumn('ttfb')"> TTFB</label>
1138
+ <label class="col-picker-item"><input type="checkbox" data-col="ip" checked onchange="toggleColumn('ip')"> IP Address</label>
1139
+ </div>
1140
+ </div>
1141
+ </div>
1142
+ </div>
1143
+
1144
+ <div class="list-panel logs-list-panel">
1145
+ <div style="overflow-x:auto">
1146
+ <table id="logsTable" class="compact-table">
1147
+ <thead>
1148
+ <tr>
1149
+ <th class="col-time">Time</th>
1150
+ <th class="col-key">Key / Agent</th>
1151
+ <th class="col-model">Model</th>
1152
+ <th class="col-type">Call Type</th>
1153
+ <th class="col-status">Status</th>
1154
+ <th class="col-tokens">Tokens (In / Out)</th>
1155
+ <th class="col-cost">Est. Cost</th>
1156
+ <th class="col-duration">Duration</th>
1157
+ <th class="col-ttfb">TTFB</th>
1158
+ <th class="col-ip">IP</th>
1159
+ </tr>
1160
+ </thead>
1161
+ <tbody id="logsBody"></tbody>
1162
+ </table>
1163
+ </div>
1164
+ </div>
1165
+
1166
+ <div id="pagination" class="logs-pagination" style="margin-top:16px;display:flex;justify-content:center;align-items:center;gap:8px;font-size:0.85rem"></div>
1167
+ </div>
1168
+ `,
1169
+ });