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,696 @@
1
+ import randomBytes from "node:crypto";
2
+ import { MODEL_PRICING, type SpendLog, type DailySpend } from "./types.js";
3
+ import { isDbConfigured, queryDb } from "./db-store.js";
4
+ import { rotatorEnv } from "./env.js";
5
+
6
+ const FLUSH_INTERVAL_MS = 5_000;
7
+ const MAX_QUEUE_SIZE = 50;
8
+ const DEFAULT_KEY_HASH_LABEL = "unauthenticated";
9
+
10
+ const storeMessagesConfig =
11
+ rotatorEnv("LOG_MESSAGES") !== "false" &&
12
+ rotatorEnv("LOG_MESSAGES") !== "0";
13
+
14
+ const storeResponsesConfig =
15
+ rotatorEnv("LOG_RESPONSES") !== "false" &&
16
+ rotatorEnv("LOG_RESPONSES") !== "0";
17
+
18
+ let queue: SpendLog[] = [];
19
+ let flushTimer: ReturnType<typeof setTimeout> | null = null;
20
+ let isFlushing = false;
21
+
22
+ export function generateRequestId(): string {
23
+ return `req_${Date.now().toString(36)}_${randomBytes.randomBytes(8).toString("hex")}`;
24
+ }
25
+
26
+ /**
27
+ * Enqueue a request log for async DB persistence & aggregation.
28
+ */
29
+ export function logSpend(
30
+ log: Omit<SpendLog, "requestId" | "totalTokens"> & {
31
+ requestId?: string;
32
+ totalTokens?: number;
33
+ },
34
+ ): void {
35
+ const pricing = MODEL_PRICING[log.model] || { inputPer1M: 0, outputPer1M: 0 };
36
+ const promptTokens = Math.max(0, log.promptTokens || 0);
37
+ const completionTokens = Math.max(0, log.completionTokens || 0);
38
+ const promptCostUsd = (promptTokens / 1_000_000) * (pricing.inputPer1M || 0);
39
+ const completionCostUsd = (completionTokens / 1_000_000) * (pricing.outputPer1M || 0);
40
+ const totalCostUsd = promptCostUsd + completionCostUsd;
41
+
42
+ const enrichedMetadata: Record<string, unknown> = {
43
+ ...(log.metadata || {}),
44
+ costBreakdown: {
45
+ promptCostUsd,
46
+ completionCostUsd,
47
+ totalCostUsd,
48
+ inputRatePer1M: pricing.inputPer1M || 0,
49
+ outputRatePer1M: pricing.outputPer1M || 0,
50
+ },
51
+ };
52
+
53
+ const fullLog: SpendLog = {
54
+ requestId: log.requestId || generateRequestId(),
55
+ apiKeyHash: log.apiKeyHash || null,
56
+ model: log.model,
57
+ accountEmail: log.accountEmail || null,
58
+ callType: log.callType,
59
+ status: log.status,
60
+ promptTokens,
61
+ completionTokens,
62
+ totalTokens: Math.max(0, log.totalTokens || promptTokens + completionTokens),
63
+ startTime: log.startTime,
64
+ endTime: log.endTime,
65
+ ttfbMs: log.ttfbMs ?? null,
66
+ durationMs: Math.max(0, log.durationMs || 0),
67
+ requestMessages: storeMessagesConfig ? sanitizePayload(log.requestMessages) : null,
68
+ responseContent: storeResponsesConfig ? sanitizePayload(log.responseContent) : null,
69
+ metadata: enrichedMetadata,
70
+ requesterIp: log.requesterIp || null,
71
+ createdAt: new Date().toISOString(),
72
+ };
73
+
74
+ queue.push(fullLog);
75
+
76
+ if (queue.length >= MAX_QUEUE_SIZE) {
77
+ void flushSpendLogs();
78
+ } else {
79
+ scheduleFlush();
80
+ }
81
+ }
82
+
83
+ function scheduleFlush(): void {
84
+ if (flushTimer) return;
85
+ flushTimer = setTimeout(() => {
86
+ flushTimer = null;
87
+ void flushSpendLogs();
88
+ }, FLUSH_INTERVAL_MS);
89
+ flushTimer.unref();
90
+ }
91
+
92
+ function sanitizePayload(payload: unknown): unknown {
93
+ if (!payload) return null;
94
+ try {
95
+ const cleaned = cleanValue(payload);
96
+ const str = JSON.stringify(cleaned);
97
+ if (str.length > 512 * 1024) {
98
+ return {
99
+ _truncated: true,
100
+ originalLengthBytes: str.length,
101
+ previewText: str.slice(0, 50000) + "\n... [payload truncated at 50,000 characters]",
102
+ };
103
+ }
104
+ return cleaned;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ function cleanValue(val: unknown, depth = 0): unknown {
111
+ if (depth > 20) return "[Max Depth Reached]";
112
+ if (typeof val === "string") {
113
+ if (val.startsWith("data:") && val.includes(";base64,")) {
114
+ const parts = val.split(";base64,");
115
+ const b64Len = parts[1] ? parts[1].length : 0;
116
+ return `${parts[0]};base64,[data truncated: ${Math.round((b64Len * 0.75) / 1024)}KB]`;
117
+ }
118
+ if (val.length > 2000 && !val.includes(" ") && /^[A-Za-z0-9+/=]+$/.test(val.slice(0, 100))) {
119
+ return `[base64 data truncated: ${Math.round((val.length * 0.75) / 1024)}KB]`;
120
+ }
121
+ return val;
122
+ }
123
+ if (Array.isArray(val)) {
124
+ return val.map((item) => cleanValue(item, depth + 1));
125
+ }
126
+ if (val && typeof val === "object") {
127
+ const obj: Record<string, unknown> = {};
128
+ for (const [k, v] of Object.entries(val as Record<string, unknown>)) {
129
+ obj[k] = cleanValue(v, depth + 1);
130
+ }
131
+ return obj;
132
+ }
133
+ return val;
134
+ }
135
+
136
+ /**
137
+ * Flush accumulated spend logs to database.
138
+ */
139
+ export async function flushSpendLogs(): Promise<void> {
140
+ if (isFlushing || queue.length === 0 || !isDbConfigured()) return;
141
+ isFlushing = true;
142
+
143
+ const logsToFlush = queue;
144
+ queue = [];
145
+
146
+ try {
147
+ for (const log of logsToFlush) {
148
+ // 1. Insert detailed spend log
149
+ await queryDb(
150
+ `INSERT INTO rotator_spend_logs (
151
+ request_id, api_key_hash, model, account_email, call_type, status,
152
+ prompt_tokens, completion_tokens, total_tokens, start_time, end_time,
153
+ ttfb_ms, duration_ms, request_messages, response_content, metadata,
154
+ requester_ip, created_at
155
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
156
+ ON CONFLICT (request_id) DO NOTHING`,
157
+ [
158
+ log.requestId,
159
+ log.apiKeyHash,
160
+ log.model,
161
+ log.accountEmail,
162
+ log.callType,
163
+ log.status,
164
+ log.promptTokens,
165
+ log.completionTokens,
166
+ log.totalTokens,
167
+ log.startTime,
168
+ log.endTime,
169
+ log.ttfbMs,
170
+ log.durationMs,
171
+ log.requestMessages ? JSON.stringify(log.requestMessages) : null,
172
+ log.responseContent ? JSON.stringify(log.responseContent) : null,
173
+ JSON.stringify(log.metadata || {}),
174
+ log.requesterIp,
175
+ log.createdAt || new Date().toISOString(),
176
+ ],
177
+ );
178
+
179
+ // 2. Upsert daily aggregation
180
+ const dateStr = log.startTime.slice(0, 10); // YYYY-MM-DD
181
+ const keyHashForDaily = log.apiKeyHash || DEFAULT_KEY_HASH_LABEL;
182
+ const isSuccess = log.status === "success" ? 1 : 0;
183
+ const isFail = log.status === "failure" ? 1 : 0;
184
+
185
+ await queryDb(
186
+ `INSERT INTO rotator_daily_spend (
187
+ api_key_hash, model, date, prompt_tokens, completion_tokens,
188
+ total_requests, successful_requests, failed_requests, total_duration_ms
189
+ ) VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8)
190
+ ON CONFLICT (api_key_hash, model, date) DO UPDATE SET
191
+ prompt_tokens = rotator_daily_spend.prompt_tokens + EXCLUDED.prompt_tokens,
192
+ completion_tokens = rotator_daily_spend.completion_tokens + EXCLUDED.completion_tokens,
193
+ total_requests = rotator_daily_spend.total_requests + 1,
194
+ successful_requests = rotator_daily_spend.successful_requests + EXCLUDED.successful_requests,
195
+ failed_requests = rotator_daily_spend.failed_requests + EXCLUDED.failed_requests,
196
+ total_duration_ms = rotator_daily_spend.total_duration_ms + EXCLUDED.total_duration_ms`,
197
+ [
198
+ keyHashForDaily,
199
+ log.model,
200
+ dateStr,
201
+ log.promptTokens,
202
+ log.completionTokens,
203
+ isSuccess,
204
+ isFail,
205
+ log.durationMs,
206
+ ],
207
+ );
208
+ }
209
+ } catch (err) {
210
+ console.error("Failed to flush spend logs to database:", err);
211
+ // Put unfetched items back in queue if flush failed
212
+ queue = [...logsToFlush, ...queue];
213
+ } finally {
214
+ isFlushing = false;
215
+ }
216
+ }
217
+
218
+ export function calculateCost(model: string, promptTokens: number, completionTokens: number): number {
219
+ let pricing = MODEL_PRICING[model];
220
+ if (!pricing) {
221
+ const lower = model.toLowerCase();
222
+ if (lower.includes("opus")) {
223
+ pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
224
+ } else if (lower.includes("sonnet")) {
225
+ pricing = MODEL_PRICING["claude-sonnet-4-6"];
226
+ } else if (lower.includes("3.6-flash")) {
227
+ pricing = MODEL_PRICING["gemini-3.6-flash-high"];
228
+ } else if (lower.includes("3.5-flash")) {
229
+ pricing = MODEL_PRICING["gemini-3.5-flash-high"];
230
+ } else if (lower.includes("flash")) {
231
+ pricing = MODEL_PRICING["gemini-3-flash"];
232
+ } else if (lower.includes("pro")) {
233
+ pricing = MODEL_PRICING["gemini-3.1-pro"];
234
+ }
235
+ }
236
+ if (!pricing) return 0;
237
+ const inputCost = (promptTokens / 1_000_000) * pricing.inputPer1M;
238
+ const outputCost = (completionTokens / 1_000_000) * pricing.outputPer1M;
239
+ return Number((inputCost + outputCost).toFixed(6));
240
+ }
241
+
242
+ // ── Dashboard Query API Functions ────────────────────────────────────
243
+
244
+ export interface SpendFilterOptions {
245
+ apiKeyHash?: string | string[];
246
+ model?: string | string[];
247
+ status?: string;
248
+ startDate?: string;
249
+ endDate?: string;
250
+ }
251
+
252
+ export interface GetSpendLogsOptions extends SpendFilterOptions {
253
+ limit?: number;
254
+ offset?: number;
255
+ }
256
+
257
+ export interface SpendSummary {
258
+ totalRequests: number;
259
+ promptTokens: number;
260
+ completionTokens: number;
261
+ avgLatencyMs: number;
262
+ totalCost: number;
263
+ }
264
+
265
+ function buildWhereClause(options: SpendFilterOptions = {}): {
266
+ whereClause: string;
267
+ params: unknown[];
268
+ } {
269
+ const conditions: string[] = [];
270
+ const params: unknown[] = [];
271
+
272
+ if (options.apiKeyHash) {
273
+ const rawKeys = Array.isArray(options.apiKeyHash)
274
+ ? options.apiKeyHash
275
+ : String(options.apiKeyHash).split(",").map((s) => s.trim()).filter(Boolean);
276
+
277
+ if (rawKeys.length > 0) {
278
+ const keyOrConditions: string[] = [];
279
+ for (const kVal of rawKeys) {
280
+ if (kVal === "unauthenticated") {
281
+ keyOrConditions.push(`(l.api_key_hash = 'unauthenticated' OR l.api_key_hash IS NULL OR l.api_key_hash = '')`);
282
+ } else {
283
+ const safeKVal = kVal.replace(/[\\%_]/g, "\\$&");
284
+ const searchVal = `%${safeKVal}%`;
285
+ params.push(kVal, searchVal);
286
+ const p1 = params.length - 1;
287
+ const p2 = params.length;
288
+ keyOrConditions.push(
289
+ `(l.api_key_hash = $${p1} OR k.key_alias ILIKE $${p2} OR k.key_name ILIKE $${p2})`,
290
+ );
291
+ }
292
+ }
293
+ if (keyOrConditions.length > 0) {
294
+ conditions.push(`(${keyOrConditions.join(" OR ")})`);
295
+ }
296
+ }
297
+ }
298
+ if (options.model) {
299
+ const rawModels = Array.isArray(options.model)
300
+ ? options.model
301
+ : String(options.model).split(",").map((s) => s.trim()).filter(Boolean);
302
+
303
+ if (rawModels.length > 0) {
304
+ const modelConds: string[] = [];
305
+ for (const m of rawModels) {
306
+ const safeM = m.replace(/[\\%_]/g, "\\$&");
307
+ params.push(`${safeM}%`);
308
+ modelConds.push(`l.model ILIKE $${params.length}`);
309
+ }
310
+ conditions.push(`(${modelConds.join(" OR ")})`);
311
+ }
312
+ }
313
+ if (options.status) {
314
+ params.push(options.status);
315
+ conditions.push(`l.status = $${params.length}`);
316
+ }
317
+ if (options.startDate) {
318
+ params.push(options.startDate);
319
+ conditions.push(`l.created_at >= $${params.length}::timestamptz`);
320
+ }
321
+ if (options.endDate) {
322
+ params.push(options.endDate);
323
+ conditions.push(`l.created_at <= ($${params.length}::date + INTERVAL '1 day')`);
324
+ }
325
+
326
+ const whereClause =
327
+ conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
328
+ return { whereClause, params };
329
+ }
330
+
331
+ export async function getSpendLogs(
332
+ options: GetSpendLogsOptions = {},
333
+ ): Promise<{ logs: SpendLog[]; total: number; summary: SpendSummary }> {
334
+ const emptySummary: SpendSummary = {
335
+ totalRequests: 0,
336
+ promptTokens: 0,
337
+ completionTokens: 0,
338
+ avgLatencyMs: 0,
339
+ totalCost: 0,
340
+ };
341
+
342
+ if (!isDbConfigured()) return { logs: [], total: 0, summary: emptySummary };
343
+
344
+ const limit = Math.min(100, Math.max(1, options.limit || 50));
345
+ const offset = Math.max(0, options.offset || 0);
346
+
347
+ const { whereClause, params } = buildWhereClause(options);
348
+
349
+ try {
350
+ const aggRes = await queryDb<{
351
+ count: string;
352
+ prompt_tokens: string;
353
+ completion_tokens: string;
354
+ total_duration_ms: string;
355
+ count_duration: string;
356
+ }>(
357
+ `SELECT
358
+ COUNT(*)::text as count,
359
+ COALESCE(SUM(l.prompt_tokens), 0)::text as prompt_tokens,
360
+ COALESCE(SUM(l.completion_tokens), 0)::text as completion_tokens,
361
+ COALESCE(SUM(l.duration_ms), 0)::text as total_duration_ms,
362
+ COUNT(l.duration_ms)::text as count_duration
363
+ FROM rotator_spend_logs l
364
+ LEFT JOIN rotator_virtual_keys k ON l.api_key_hash = k.token_hash
365
+ ${whereClause}`,
366
+ params,
367
+ );
368
+
369
+ const aggRow = aggRes.rows[0];
370
+ const total = parseInt(aggRow?.count || "0", 10);
371
+ const promptTokens = parseInt(aggRow?.prompt_tokens || "0", 10);
372
+ const completionTokens = parseInt(aggRow?.completion_tokens || "0", 10);
373
+ const totalDurationMs = parseInt(aggRow?.total_duration_ms || "0", 10);
374
+ const countDuration = parseInt(aggRow?.count_duration || "0", 10);
375
+ const avgLatencyMs = countDuration > 0 ? Math.round(totalDurationMs / countDuration) : 0;
376
+
377
+ const byModelRes = await queryDb<{
378
+ model: string;
379
+ prompt_tokens: string;
380
+ completion_tokens: string;
381
+ }>(
382
+ `SELECT
383
+ l.model,
384
+ COALESCE(SUM(l.prompt_tokens), 0)::text as prompt_tokens,
385
+ COALESCE(SUM(l.completion_tokens), 0)::text as completion_tokens
386
+ FROM rotator_spend_logs l
387
+ LEFT JOIN rotator_virtual_keys k ON l.api_key_hash = k.token_hash
388
+ ${whereClause}
389
+ GROUP BY l.model`,
390
+ params,
391
+ );
392
+
393
+ let totalCost = 0;
394
+ for (const mRow of byModelRes.rows) {
395
+ const pTok = parseInt(mRow.prompt_tokens || "0", 10);
396
+ const cTok = parseInt(mRow.completion_tokens || "0", 10);
397
+ totalCost += calculateCost(mRow.model, pTok, cTok);
398
+ }
399
+ totalCost = Number(totalCost.toFixed(6));
400
+
401
+ const summary: SpendSummary = {
402
+ totalRequests: total,
403
+ promptTokens,
404
+ completionTokens,
405
+ avgLatencyMs,
406
+ totalCost,
407
+ };
408
+
409
+ const queryParams = [...params, limit, offset];
410
+ const logsRes = await queryDb(
411
+ `SELECT l.*, k.key_alias, k.key_name
412
+ FROM rotator_spend_logs l
413
+ LEFT JOIN rotator_virtual_keys k ON l.api_key_hash = k.token_hash
414
+ ${whereClause}
415
+ ORDER BY l.created_at DESC
416
+ LIMIT $${queryParams.length - 1} OFFSET $${queryParams.length}`,
417
+ queryParams,
418
+ );
419
+
420
+ const logs: SpendLog[] = logsRes.rows.map((row) => {
421
+ const model = String(row.model);
422
+ const promptTokens = Number(row.prompt_tokens || 0);
423
+ const completionTokens = Number(row.completion_tokens || 0);
424
+ return {
425
+ requestId: String(row.request_id),
426
+ apiKeyHash: row.api_key_hash ? String(row.api_key_hash) : null,
427
+ keyAlias: row.key_alias ? String(row.key_alias) : null,
428
+ keyName: row.key_name ? String(row.key_name) : null,
429
+ model,
430
+ accountEmail: row.account_email ? String(row.account_email) : null,
431
+ callType: String(row.call_type),
432
+ status: (row.status as "success" | "failure") || "success",
433
+ promptTokens,
434
+ completionTokens,
435
+ totalTokens: Number(row.total_tokens || 0),
436
+ cost: calculateCost(model, promptTokens, completionTokens),
437
+ startTime: new Date(row.start_time as string | Date).toISOString(),
438
+ endTime: new Date(row.end_time as string | Date).toISOString(),
439
+ ttfbMs: row.ttfb_ms !== null ? Number(row.ttfb_ms) : null,
440
+ durationMs: Number(row.duration_ms || 0),
441
+ requestMessages: row.request_messages || null,
442
+ responseContent: row.response_content || null,
443
+ metadata:
444
+ row.metadata && typeof row.metadata === "object"
445
+ ? (row.metadata as Record<string, unknown>)
446
+ : {},
447
+ requesterIp: row.requester_ip ? String(row.requester_ip) : null,
448
+ createdAt: new Date(row.created_at as string | Date).toISOString(),
449
+ };
450
+ });
451
+
452
+ return { logs, total, summary };
453
+ } catch (err) {
454
+ console.error("Failed to query spend logs:", err);
455
+ return { logs: [], total: 0, summary: emptySummary };
456
+ }
457
+ }
458
+
459
+ export async function getDailySpendSummary(options: {
460
+ apiKeyHash?: string;
461
+ startDate?: string;
462
+ endDate?: string;
463
+ }): Promise<DailySpend[]> {
464
+ if (!isDbConfigured()) return [];
465
+
466
+ const conditions: string[] = [];
467
+ const params: unknown[] = [];
468
+
469
+ if (options.apiKeyHash) {
470
+ params.push(options.apiKeyHash);
471
+ conditions.push(`api_key_hash = $${params.length}`);
472
+ }
473
+ if (options.startDate) {
474
+ params.push(options.startDate);
475
+ conditions.push(`date >= $${params.length}::date`);
476
+ }
477
+ if (options.endDate) {
478
+ params.push(options.endDate);
479
+ conditions.push(`date <= $${params.length}::date`);
480
+ }
481
+
482
+ const whereClause =
483
+ conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
484
+
485
+ try {
486
+ const res = await queryDb(
487
+ `SELECT * FROM rotator_daily_spend ${whereClause} ORDER BY date DESC, total_requests DESC`,
488
+ params,
489
+ );
490
+
491
+ return res.rows.map((row) => ({
492
+ apiKeyHash: row.api_key_hash ? String(row.api_key_hash) : null,
493
+ model: String(row.model),
494
+ date: new Date(row.date as string | Date).toISOString().slice(0, 10),
495
+ promptTokens: Number(row.prompt_tokens || 0),
496
+ completionTokens: Number(row.completion_tokens || 0),
497
+ totalRequests: Number(row.total_requests || 0),
498
+ successfulRequests: Number(row.successful_requests || 0),
499
+ failedRequests: Number(row.failed_requests || 0),
500
+ totalDurationMs: Number(row.total_duration_ms || 0),
501
+ }));
502
+ } catch (err) {
503
+ console.error("Failed to get daily spend summary:", err);
504
+ return [];
505
+ }
506
+ }
507
+
508
+ // ── Spend by Key Aggregation ────────────────────────────────────────
509
+
510
+ export interface SpendByKey {
511
+ apiKeyHash: string;
512
+ keyAlias?: string | null;
513
+ keyName?: string | null;
514
+ totalRequests: number;
515
+ totalPromptTokens: number;
516
+ totalCompletionTokens: number;
517
+ totalDurationMs: number;
518
+ avgDurationMs: number;
519
+ totalCost: number;
520
+ firstSeen: string | null;
521
+ lastSeen: string | null;
522
+ }
523
+
524
+ export async function getSpendByKey(
525
+ options: SpendFilterOptions = {},
526
+ ): Promise<SpendByKey[]> {
527
+ if (!isDbConfigured()) return [];
528
+
529
+ const { whereClause, params } = buildWhereClause(options);
530
+
531
+ try {
532
+ const res = await queryDb(
533
+ `SELECT
534
+ COALESCE(NULLIF(l.api_key_hash, ''), 'unauthenticated') as api_key_hash,
535
+ k.key_alias,
536
+ k.key_name,
537
+ l.model,
538
+ COUNT(*)::int as total_requests,
539
+ COALESCE(SUM(l.prompt_tokens), 0)::bigint as total_prompt_tokens,
540
+ COALESCE(SUM(l.completion_tokens), 0)::bigint as total_completion_tokens,
541
+ COALESCE(SUM(l.duration_ms), 0)::bigint as total_duration_ms,
542
+ MIN(l.created_at) as first_seen,
543
+ MAX(l.created_at) as last_seen
544
+ FROM rotator_spend_logs l
545
+ LEFT JOIN rotator_virtual_keys k ON l.api_key_hash = k.token_hash
546
+ ${whereClause}
547
+ GROUP BY COALESCE(NULLIF(l.api_key_hash, ''), 'unauthenticated'), k.key_alias, k.key_name, l.model`,
548
+ params,
549
+ );
550
+
551
+ const map = new Map<
552
+ string,
553
+ {
554
+ apiKeyHash: string;
555
+ keyAlias: string | null;
556
+ keyName: string | null;
557
+ totalRequests: number;
558
+ totalPromptTokens: number;
559
+ totalCompletionTokens: number;
560
+ totalDurationMs: number;
561
+ totalCost: number;
562
+ firstSeen: string | null;
563
+ lastSeen: string | null;
564
+ }
565
+ >();
566
+
567
+ for (const row of res.rows) {
568
+ const hash = String(row.api_key_hash);
569
+ const prompt = Number(row.total_prompt_tokens || 0);
570
+ const completion = Number(row.total_completion_tokens || 0);
571
+ const cost = calculateCost(String(row.model), prompt, completion);
572
+
573
+ const firstSeenIso = row.first_seen ? new Date(row.first_seen as string | Date).toISOString() : null;
574
+ const lastSeenIso = row.last_seen ? new Date(row.last_seen as string | Date).toISOString() : null;
575
+
576
+ const existing = map.get(hash) || {
577
+ apiKeyHash: hash,
578
+ keyAlias: row.key_alias ? String(row.key_alias) : null,
579
+ keyName: row.key_name ? String(row.key_name) : null,
580
+ totalRequests: 0,
581
+ totalPromptTokens: 0,
582
+ totalCompletionTokens: 0,
583
+ totalDurationMs: 0,
584
+ totalCost: 0,
585
+ firstSeen: firstSeenIso,
586
+ lastSeen: lastSeenIso,
587
+ };
588
+
589
+ existing.totalRequests += Number(row.total_requests || 0);
590
+ existing.totalPromptTokens += prompt;
591
+ existing.totalCompletionTokens += completion;
592
+ existing.totalDurationMs += Number(row.total_duration_ms || 0);
593
+ existing.totalCost += cost;
594
+
595
+ if (firstSeenIso && (!existing.firstSeen || firstSeenIso < existing.firstSeen)) {
596
+ existing.firstSeen = firstSeenIso;
597
+ }
598
+ if (lastSeenIso && (!existing.lastSeen || lastSeenIso > existing.lastSeen)) {
599
+ existing.lastSeen = lastSeenIso;
600
+ }
601
+
602
+ map.set(hash, existing);
603
+ }
604
+
605
+ const resultList: SpendByKey[] = Array.from(map.values()).map((item) => {
606
+ const avgDurationMs = item.totalRequests > 0 ? item.totalDurationMs / item.totalRequests : 0;
607
+ return {
608
+ apiKeyHash: item.apiKeyHash,
609
+ keyAlias: item.keyAlias,
610
+ keyName: item.keyName,
611
+ totalRequests: item.totalRequests,
612
+ totalPromptTokens: item.totalPromptTokens,
613
+ totalCompletionTokens: item.totalCompletionTokens,
614
+ totalDurationMs: item.totalDurationMs,
615
+ avgDurationMs,
616
+ totalCost: Number(item.totalCost.toFixed(6)),
617
+ firstSeen: item.firstSeen,
618
+ lastSeen: item.lastSeen,
619
+ };
620
+ });
621
+
622
+ resultList.sort((a, b) => b.totalPromptTokens + b.totalCompletionTokens - (a.totalPromptTokens + a.totalCompletionTokens));
623
+ return resultList;
624
+ } catch (err) {
625
+ console.error("Failed to get spend by key:", err);
626
+ return [];
627
+ }
628
+ }
629
+
630
+ // ── Retention Policy ─────────────────────────────────────────────────
631
+
632
+ const DEFAULT_LOG_RETENTION_DAYS = 30;
633
+ const DAILY_RETENTION_DAYS = 90;
634
+ const RETENTION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
635
+
636
+ let retentionTimer: ReturnType<typeof setTimeout> | null = null;
637
+
638
+ function getLogRetentionDays(): number {
639
+ const env = rotatorEnv("LOG_RETENTION_DAYS");
640
+ if (env) {
641
+ const n = parseInt(env, 10);
642
+ if (!isNaN(n) && n > 0) return n;
643
+ }
644
+ return DEFAULT_LOG_RETENTION_DAYS;
645
+ }
646
+
647
+ async function runRetentionCleanup(): Promise<void> {
648
+ if (!isDbConfigured()) return;
649
+
650
+ const logDays = getLogRetentionDays();
651
+
652
+ try {
653
+ const logRes = await queryDb<{ deleted: string }>(
654
+ `WITH deleted AS (
655
+ DELETE FROM rotator_spend_logs WHERE created_at < NOW() - ($1 || ' days')::interval
656
+ RETURNING request_id
657
+ )
658
+ SELECT COUNT(*)::text as deleted FROM deleted`,
659
+ [String(logDays)],
660
+ );
661
+ const dailyRes = await queryDb<{ deleted: string }>(
662
+ `WITH deleted AS (
663
+ DELETE FROM rotator_daily_spend WHERE date < CURRENT_DATE - ($1 || ' days')::interval
664
+ RETURNING id
665
+ )
666
+ SELECT COUNT(*)::text as deleted FROM deleted`,
667
+ [String(DAILY_RETENTION_DAYS)],
668
+ );
669
+
670
+ const logDeleted = parseInt(logRes.rows[0]?.deleted || "0", 10);
671
+ const dailyDeleted = parseInt(dailyRes.rows[0]?.deleted || "0", 10);
672
+
673
+ if (logDeleted > 0 || dailyDeleted > 0) {
674
+ console.log(
675
+ `[retention] Cleaned ${logDeleted} spend logs (${logDays}d policy) and ${dailyDeleted} daily aggregates (${DAILY_RETENTION_DAYS}d policy)`,
676
+ );
677
+ }
678
+ } catch (err) {
679
+ console.error("Retention cleanup failed:", err);
680
+ }
681
+ }
682
+
683
+ export function startRetentionCleanup(): void {
684
+ void runRetentionCleanup();
685
+ retentionTimer = setInterval(() => {
686
+ void runRetentionCleanup();
687
+ }, RETENTION_CHECK_INTERVAL_MS);
688
+ retentionTimer.unref();
689
+ }
690
+
691
+ export function stopRetentionCleanup(): void {
692
+ if (retentionTimer) {
693
+ clearInterval(retentionTimer);
694
+ retentionTimer = null;
695
+ }
696
+ }