tuxevil-rotator 4.4.8 → 4.5.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 (58) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +3 -1
  3. package/package.json +1 -1
  4. package/plugins/opencode-discovery/index.mjs +50 -21
  5. package/src/access-probe.ts +1 -1
  6. package/src/account-store.ts +14 -2
  7. package/src/audio-transcription.ts +1 -0
  8. package/src/auto-model-access.ts +22 -0
  9. package/src/compat/model-specs.ts +7 -0
  10. package/src/compat/schema-sanitizer.ts +420 -287
  11. package/src/compat.ts +110 -66
  12. package/src/config-defaults.ts +7 -0
  13. package/src/fetch-with-retry.ts +294 -16
  14. package/src/idempotency.ts +3 -1
  15. package/src/model-access-api.ts +9 -1
  16. package/src/model-access.ts +2 -2
  17. package/src/notification-poller.ts +9 -1
  18. package/src/provider-catalog-evidence.ts +18 -1
  19. package/src/providers/adapter.ts +10 -0
  20. package/src/providers/credential-helpers.ts +34 -0
  21. package/src/providers/google-antigravity/aicode-eligibility.ts +256 -0
  22. package/src/providers/google-antigravity/aicode-forward.ts +381 -0
  23. package/src/providers/google-antigravity/aicode.ts +478 -0
  24. package/src/providers/google-antigravity/catalog.ts +6 -0
  25. package/src/providers/google-antigravity/code-assist.ts +53 -41
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +72 -7
  27. package/src/providers/google-antigravity/forward.ts +309 -86
  28. package/src/providers/google-antigravity/index.ts +122 -4
  29. package/src/providers/google-antigravity/oauth.ts +22 -12
  30. package/src/providers/google-antigravity/quota.ts +781 -34
  31. package/src/providers/google-antigravity/translators.ts +55 -46
  32. package/src/providers/google-antigravity/twin-payload.ts +231 -0
  33. package/src/providers/ollama/quota.ts +6 -4
  34. package/src/providers/openai-codex/compat.ts +11 -2
  35. package/src/providers/openai-codex/quota.ts +2 -1
  36. package/src/providers/opencode-zen/catalog.ts +159 -13
  37. package/src/providers/opencode-zen/discovery.ts +50 -0
  38. package/src/providers/opencode-zen/index.ts +7 -2
  39. package/src/providers/opencode-zen/quota.ts +14 -1
  40. package/src/proxy.ts +570 -87
  41. package/src/quota-pools.ts +76 -1
  42. package/src/rate-limit-parser.ts +239 -19
  43. package/src/rotator.ts +848 -297
  44. package/src/stream-guards.ts +87 -1
  45. package/src/telemetry.ts +17 -3
  46. package/src/types.ts +184 -9
  47. package/src/validators.ts +3 -0
  48. package/src/web/lib/accounts.ts +2 -0
  49. package/src/web/lib/attention.ts +19 -0
  50. package/src/web/lib/models.ts +6 -1
  51. package/src/web/lib/status.ts +22 -4
  52. package/src/web/pages/AccountDetail.tsx +49 -2
  53. package/src/web/pages/Accounts.tsx +38 -3
  54. package/src/web/pages/ModelAccess.tsx +4 -0
  55. package/src/web/pages/Models.tsx +2 -1
  56. package/src/web/pages/Overview.tsx +15 -1
  57. package/src/web/styles/app.css +73 -3
  58. package/tools/telemetry-receiver/receiver.js +523 -266
package/src/compat.ts CHANGED
@@ -4,6 +4,7 @@ import { classifyAccessObservation } from "./access-evidence.js";
4
4
  import { getCachedOllamaContextWindow } from "./providers/ollama/context-window.js";
5
5
  import type { IncomingMessage, ServerResponse } from "node:http";
6
6
  import { Readable } from "node:stream";
7
+ import { StringDecoder } from "node:string_decoder";
7
8
  import {
8
9
  type CompressionHeaderOptions,
9
10
  buildRotatorResponseHeaders,
@@ -26,10 +27,12 @@ import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
26
27
  import { logger, redactSensitive } from "./logger.js";
27
28
  import {
28
29
  createStreamIdleGuard,
30
+ startSseKeepalive,
29
31
  waitForResponseDrain,
30
32
  } from "./stream-guards.js";
31
33
  import type { AccountRotator } from "./rotator.js";
32
34
  import {
35
+ attachClientAbortController,
33
36
  withRotation,
34
37
  flattenHeaders,
35
38
  type RequestBody,
@@ -343,6 +346,7 @@ const VALIDATION_LOG_MAX_CHARS = 200;
343
346
  export interface CompatStreamOptions {
344
347
  idleTimeoutMs?: number;
345
348
  backpressureTimeoutMs?: number;
349
+ keepaliveIntervalMs?: number;
346
350
  }
347
351
 
348
352
  export function logValidationFailure(scope: string, payload: unknown): void {
@@ -888,6 +892,10 @@ export async function streamCompatSse(
888
892
  "X-Accel-Buffering": "no",
889
893
  ...rotatorHeaders,
890
894
  });
895
+ const stopKeepalive = startSseKeepalive(
896
+ res,
897
+ options.keepaliveIntervalMs ?? rotator?.getConfig?.()?.sseKeepaliveIntervalMs,
898
+ );
891
899
 
892
900
  if (format === "openai") {
893
901
  res.write(
@@ -1200,31 +1208,19 @@ export async function streamCompatSse(
1200
1208
  if (!nodeStream.destroyed) nodeStream.destroy(error);
1201
1209
  }, options.idleTimeoutMs);
1202
1210
 
1203
- try {
1204
- for await (const chunk of nodeStream) {
1205
- if (reqClosed) {
1206
- break;
1207
- }
1208
- idleGuard.reset();
1209
- if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
1210
- const str = chunk.toString();
1211
- tailBuffer += str;
1212
- let newlineIdx;
1213
- while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
1214
- const line = tailBuffer.slice(0, newlineIdx).trim();
1215
- tailBuffer = tailBuffer.slice(newlineIdx + 1);
1216
-
1217
- if (upstream === "ollama") {
1218
- if (line) emitOllamaLine(line);
1219
- continue;
1220
- }
1221
- if (upstream === "opencode-zen") {
1222
- if (line) emitOpenAiSseLine(line);
1223
- continue;
1224
- }
1225
- if (!line.startsWith("data:")) continue;
1226
- const payload = line.slice(5).trim();
1227
- if (!payload || payload === "[DONE]") continue;
1211
+ const decoder = new StringDecoder("utf8");
1212
+ const processCompatLine = (line: string): void => {
1213
+ if (upstream === "ollama") {
1214
+ if (line) emitOllamaLine(line);
1215
+ return;
1216
+ }
1217
+ if (upstream === "opencode-zen") {
1218
+ if (line) emitOpenAiSseLine(line);
1219
+ return;
1220
+ }
1221
+ if (!line.startsWith("data:")) return;
1222
+ const payload = line.slice(5).trim();
1223
+ if (!payload || payload === "[DONE]") return;
1228
1224
 
1229
1225
  try {
1230
1226
  const parsed = JSON.parse(payload) as Record<string, unknown>;
@@ -1380,9 +1376,35 @@ export async function streamCompatSse(
1380
1376
  } catch {
1381
1377
  // Ignore malformed JSON chunks
1382
1378
  }
1379
+ };
1380
+
1381
+ try {
1382
+ for await (const chunk of nodeStream) {
1383
+ if (reqClosed) {
1384
+ break;
1385
+ }
1386
+ idleGuard.reset();
1387
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
1388
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
1389
+ tailBuffer += decoder.write(buf);
1390
+ let newlineIdx;
1391
+ while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
1392
+ const line = tailBuffer.slice(0, newlineIdx).trim();
1393
+ tailBuffer = tailBuffer.slice(newlineIdx + 1);
1394
+ processCompatLine(line);
1383
1395
  }
1384
1396
  await waitForResponseDrain(res, options.backpressureTimeoutMs);
1385
1397
  }
1398
+ if (!reqClosed) {
1399
+ tailBuffer += decoder.end();
1400
+ if (tailBuffer.length > 0) {
1401
+ for (const rawLine of tailBuffer.split("\n")) {
1402
+ const line = rawLine.trim();
1403
+ if (line) processCompatLine(line);
1404
+ }
1405
+ tailBuffer = "";
1406
+ }
1407
+ }
1386
1408
  } catch (err) {
1387
1409
  if (!reqClosed) {
1388
1410
  streamError ??= redactSensitive(String(err)).slice(0, 200);
@@ -1393,6 +1415,7 @@ export async function streamCompatSse(
1393
1415
  }
1394
1416
  } finally {
1395
1417
  idleGuard.clear();
1418
+ stopKeepalive();
1396
1419
  req.off("close", closeUpstreamForClient);
1397
1420
  responseEvents.off?.("close", closeUpstreamForClient);
1398
1421
  }
@@ -1634,6 +1657,10 @@ export async function streamResponsesSse(
1634
1657
  "X-Accel-Buffering": "no",
1635
1658
  ...rotatorHeaders,
1636
1659
  });
1660
+ const stopKeepalive = startSseKeepalive(
1661
+ res,
1662
+ options.keepaliveIntervalMs ?? rotator?.getConfig?.()?.sseKeepaliveIntervalMs,
1663
+ );
1637
1664
  const emptyCompletion: CompatCompletion = {
1638
1665
  text: "",
1639
1666
  thinkingText: undefined,
@@ -1988,29 +2015,19 @@ export async function streamResponsesSse(
1988
2015
  // Ignore malformed NDJSON lines
1989
2016
  }
1990
2017
  };
1991
- try {
1992
- for await (const chunk of nodeStream) {
1993
- if (reqClosed) {
1994
- break;
1995
- }
1996
- idleGuard.reset();
1997
- if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
1998
- tailBuffer += chunk.toString();
1999
- let newlineIdx;
2000
- while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
2001
- const line = tailBuffer.slice(0, newlineIdx).trim();
2002
- tailBuffer = tailBuffer.slice(newlineIdx + 1);
2003
- if (upstream === "ollama") {
2004
- if (line) emitOllamaLine(line);
2005
- continue;
2006
- }
2007
- if (upstream === "opencode-zen") {
2008
- emitOpenCodeZenLine(line);
2009
- continue;
2010
- }
2011
- if (!line.startsWith("data:")) continue;
2012
- const payload = line.slice(5).trim();
2013
- if (!payload || payload === "[DONE]") continue;
2018
+ const decoder = new StringDecoder("utf8");
2019
+ const processResponsesLine = (line: string): void => {
2020
+ if (upstream === "ollama") {
2021
+ if (line) emitOllamaLine(line);
2022
+ return;
2023
+ }
2024
+ if (upstream === "opencode-zen") {
2025
+ emitOpenCodeZenLine(line);
2026
+ return;
2027
+ }
2028
+ if (!line.startsWith("data:")) return;
2029
+ const payload = line.slice(5).trim();
2030
+ if (!payload || payload === "[DONE]") return;
2014
2031
  try {
2015
2032
  const parsed = JSON.parse(payload) as Record<string, unknown>;
2016
2033
  const response = isRecord(parsed.response) ? parsed.response : parsed;
@@ -2196,9 +2213,35 @@ export async function streamResponsesSse(
2196
2213
  } catch {
2197
2214
  // Ignore malformed JSON chunks
2198
2215
  }
2216
+ };
2217
+
2218
+ try {
2219
+ for await (const chunk of nodeStream) {
2220
+ if (reqClosed) {
2221
+ break;
2222
+ }
2223
+ idleGuard.reset();
2224
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
2225
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
2226
+ tailBuffer += decoder.write(buf);
2227
+ let newlineIdx;
2228
+ while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
2229
+ const line = tailBuffer.slice(0, newlineIdx).trim();
2230
+ tailBuffer = tailBuffer.slice(newlineIdx + 1);
2231
+ processResponsesLine(line);
2199
2232
  }
2200
2233
  await waitForResponseDrain(res, options.backpressureTimeoutMs);
2201
2234
  }
2235
+ if (!reqClosed) {
2236
+ tailBuffer += decoder.end();
2237
+ if (tailBuffer.length > 0) {
2238
+ for (const rawLine of tailBuffer.split("\n")) {
2239
+ const line = rawLine.trim();
2240
+ if (line) processResponsesLine(line);
2241
+ }
2242
+ tailBuffer = "";
2243
+ }
2244
+ }
2202
2245
  } catch (err) {
2203
2246
  if (!reqClosed) {
2204
2247
  streamError ??= redactSensitive(String(err)).slice(0, 200);
@@ -2209,6 +2252,7 @@ export async function streamResponsesSse(
2209
2252
  }
2210
2253
  } finally {
2211
2254
  idleGuard.clear();
2255
+ stopKeepalive();
2212
2256
  req.off("close", closeUpstreamForClient);
2213
2257
  responseEvents.off?.("close", closeUpstreamForClient);
2214
2258
  }
@@ -2328,10 +2372,7 @@ async function completeResponsesViaRotator(
2328
2372
  }> {
2329
2373
  const startedAt = Date.now();
2330
2374
  const createdAt = Math.floor(Date.now() / 1000);
2331
- const controller = new AbortController();
2332
- const abort = (): void => controller.abort();
2333
- req.once("aborted", abort);
2334
- if (typeof res.once === "function") res.once("close", abort);
2375
+ const { controller, cleanup } = attachClientAbortController(req, res);
2335
2376
  const outcome = await withRotation(
2336
2377
  rotator,
2337
2378
  body.model,
@@ -2370,7 +2411,7 @@ async function completeResponsesViaRotator(
2370
2411
  return completion;
2371
2412
  },
2372
2413
  controller.signal,
2373
- );
2414
+ ).finally(cleanup);
2374
2415
  if (!outcome.ok) {
2375
2416
  recordCompatFailure(rotator, body, outcome, startedAt, options);
2376
2417
  return {
@@ -2392,6 +2433,18 @@ async function completeResponsesViaRotator(
2392
2433
  };
2393
2434
  }
2394
2435
 
2436
+ function logCompatFailure(
2437
+ providerName: "OpenAI" | "Anthropic",
2438
+ status: number,
2439
+ model: string,
2440
+ ): void {
2441
+ const summary =
2442
+ status === 499
2443
+ ? `${providerName} compat request aborted before completion status=499`
2444
+ : `${providerName} compat upstream failed status=${status}`;
2445
+ compatLogger.warn(`${summary} model=${model}`);
2446
+ }
2447
+
2395
2448
  class NonOkOutcomeError extends Error {
2396
2449
  constructor(public outcome: RotationOutcome<CompatCompletion>) {
2397
2450
  super("Non-ok rotation outcome");
@@ -2427,11 +2480,7 @@ async function completeViaRotator(
2427
2480
  const enabled = cfg?.idempotencyEnabled === true;
2428
2481
  const windowMs = cfg?.idempotencyWindowMs ?? 2000;
2429
2482
  const shouldDedup = enabled && streamMode === "none" && !idempotencyManager.isOptedOut(req);
2430
- const controller = new AbortController();
2431
- const abort = (): void => controller.abort();
2432
- req.once("aborted", abort);
2433
- if (typeof res.once === "function") res.once("close", abort);
2434
- if (req.aborted || res.destroyed) abort();
2483
+ const { controller, cleanup } = attachClientAbortController(req, res);
2435
2484
 
2436
2485
  const runWithRotation = () =>
2437
2486
  withRotation(
@@ -2553,8 +2602,7 @@ async function completeViaRotator(
2553
2602
  outcome = await runWithRotation();
2554
2603
  }
2555
2604
  } finally {
2556
- req.off("aborted", abort);
2557
- if (typeof res.off === "function") res.off("close", abort);
2605
+ cleanup();
2558
2606
  }
2559
2607
 
2560
2608
  if (!outcome.ok) {
@@ -3383,9 +3431,7 @@ async function handleChatCompletions(
3383
3431
  return;
3384
3432
  }
3385
3433
  if (result.status !== 200) {
3386
- compatLogger.warn(
3387
- `OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
3388
- );
3434
+ logCompatFailure("OpenAI", result.status, validation.value.model);
3389
3435
  if (!res.headersSent) {
3390
3436
  const retrySec = extractRetryAfterSeconds(result.errorText);
3391
3437
  const headers: Record<string, string> = retrySec ? { "Retry-After": String(retrySec) } : {};
@@ -3895,9 +3941,7 @@ export async function handleAnthropicMessages(
3895
3941
  },
3896
3942
  );
3897
3943
  if (result.status !== 200) {
3898
- compatLogger.warn(
3899
- `Anthropic compat upstream failed status=${result.status} model=${validation.value.model}`,
3900
- );
3944
+ logCompatFailure("Anthropic", result.status, validation.value.model);
3901
3945
  if (!res.headersSent) {
3902
3946
  const retrySec = extractRetryAfterSeconds(result.errorText);
3903
3947
  const headers: Record<string, string> = retrySec ? { "Retry-After": String(retrySec) } : {};
@@ -1,5 +1,6 @@
1
1
  import { rotatorEnv } from "./env.js";
2
2
  import { normalizeAccountConfig } from "./config-normalize.js";
3
+ import { DEFAULT_SSE_KEEPALIVE_INTERVAL_MS } from "./stream-guards.js";
3
4
  import {
4
5
  DEFAULT_QUOTA_POLL_INTERVAL_MS,
5
6
  MAX_QUOTA_POLL_INTERVAL_MS,
@@ -19,6 +20,11 @@ function safeQuotaPollIntervalMs(value: number | undefined): number {
19
20
  return Math.floor(value);
20
21
  }
21
22
 
23
+ function safeSseKeepaliveIntervalMs(value: number | undefined): number {
24
+ if (value === undefined || !Number.isFinite(value) || value < 0) return DEFAULT_SSE_KEEPALIVE_INTERVAL_MS;
25
+ return Math.floor(value);
26
+ }
27
+
22
28
  function safeStreamRecoveryMaxRetries(value: number | undefined): number {
23
29
  if (value === undefined || !Number.isInteger(value) || value < 0) return 2;
24
30
  return value;
@@ -55,6 +61,7 @@ export function applyConfigDefaults(config: Config): Config {
55
61
  idempotencyEnabled: config.idempotencyEnabled ?? true,
56
62
  idempotencyWindowMs: config.idempotencyWindowMs ?? 2000,
57
63
  streamRecoveryMaxRetries: safeStreamRecoveryMaxRetries(config.streamRecoveryMaxRetries),
64
+ sseKeepaliveIntervalMs: safeSseKeepaliveIntervalMs(config.sseKeepaliveIntervalMs),
58
65
  compressionMode: config.compressionMode ?? "off",
59
66
  modelSpecs: config.modelSpecs,
60
67
  modelAliases: config.modelAliases,