tuxevil-rotator 3.6.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/compat.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  type RotationAttemptContext,
24
24
  type RotationOutcome,
25
25
  } from "./proxy.js";
26
+ import { getEffortRouting } from "./types.js";
26
27
  import {
27
28
  isRecord,
28
29
  sanitizeGeminiSchema,
@@ -516,7 +517,7 @@ function recordCompatOutcome(
516
517
  },
517
518
  ): void {
518
519
  const ttfbMs = completion?.firstByteMs ?? totalMs;
519
- rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
520
+ rotator.recordLatency(context.displayModelKey, ttfbMs, totalMs);
520
521
  rotator.recordRequestLog({
521
522
  model: context.displayModelKey,
522
523
  account: context.label,
@@ -1802,7 +1803,7 @@ async function completeResponsesViaRotator(
1802
1803
  );
1803
1804
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1804
1805
  rotator.recordTokenUsage(
1805
- body.displayModel || body.model,
1806
+ context.displayModelKey,
1806
1807
  completion.inputTokens,
1807
1808
  completion.outputTokens,
1808
1809
  );
@@ -1898,7 +1899,7 @@ async function completeViaRotator(
1898
1899
  : parseAntigravitySse(raw);
1899
1900
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1900
1901
  rotator.recordTokenUsage(
1901
- body.displayModel || body.model,
1902
+ context.displayModelKey,
1902
1903
  completion.inputTokens,
1903
1904
  completion.outputTokens,
1904
1905
  );
@@ -1931,7 +1932,7 @@ async function completeViaRotator(
1931
1932
  );
1932
1933
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1933
1934
  rotator.recordTokenUsage(
1934
- body.displayModel || body.model,
1935
+ context.displayModelKey,
1935
1936
  completion.inputTokens,
1936
1937
  completion.outputTokens,
1937
1938
  );
@@ -2123,6 +2124,22 @@ const MODEL_CATALOG = [
2123
2124
  multimodal: false,
2124
2125
  tools: true,
2125
2126
  },
2127
+ {
2128
+ id: "models/proactive-observer-v10",
2129
+ family: "proactive-observer",
2130
+ ctx: 1048576,
2131
+ quotaPool: "gemini",
2132
+ multimodal: true,
2133
+ tools: false,
2134
+ },
2135
+ {
2136
+ id: "whisper-1",
2137
+ family: "proactive-observer",
2138
+ ctx: 1048576,
2139
+ quotaPool: "gemini",
2140
+ multimodal: true,
2141
+ tools: false,
2142
+ },
2126
2143
  ] as const;
2127
2144
 
2128
2145
  export interface OpenAIModelCatalogEntry {
@@ -2181,9 +2198,69 @@ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2181
2198
  isThinking: spec.isThinking,
2182
2199
  });
2183
2200
  }
2201
+
2184
2202
  return result;
2185
2203
  }
2186
2204
 
2205
+ function getOpenAIAntigravityModels(): CompatModelEntry[] {
2206
+ const result = getEffectiveAntigravityModels();
2207
+ const rules = getEffortRouting();
2208
+ if (!rules || Object.keys(rules).length === 0) {
2209
+ return result;
2210
+ }
2211
+
2212
+ const successfulAliases: Array<{
2213
+ alias: string;
2214
+ representative: CompatModelEntry;
2215
+ }> = [];
2216
+ const hiddenTargetIds = new Set<string>();
2217
+ const successfulAliasNames = new Set<string>();
2218
+
2219
+ for (const [alias, rule] of Object.entries(rules)) {
2220
+ const defaultEffortKey = rule.defaultEffort;
2221
+ const defaultTargetId = rule.targets[defaultEffortKey];
2222
+ if (!defaultTargetId) {
2223
+ compatLogger.warn(
2224
+ `Effort routing alias "${alias}" default effort "${defaultEffortKey}" target not found; skipping catalog swap`,
2225
+ );
2226
+ continue;
2227
+ }
2228
+ const representative = result.find(
2229
+ (m) => m.id.toLowerCase() === defaultTargetId.toLowerCase(),
2230
+ );
2231
+ if (!representative) {
2232
+ compatLogger.warn(
2233
+ `Effort routing alias "${alias}" default target "${defaultTargetId}" absent from catalog; skipping catalog swap`,
2234
+ );
2235
+ continue;
2236
+ }
2237
+ successfulAliases.push({ alias, representative });
2238
+ successfulAliasNames.add(alias.toLowerCase());
2239
+ for (const targetId of Object.values(rule.targets)) {
2240
+ hiddenTargetIds.add(targetId.toLowerCase());
2241
+ }
2242
+ }
2243
+
2244
+ if (successfulAliases.length === 0) {
2245
+ return result;
2246
+ }
2247
+
2248
+ const filtered = result.filter(
2249
+ (m) =>
2250
+ !hiddenTargetIds.has(m.id.toLowerCase()) &&
2251
+ !successfulAliasNames.has(m.id.toLowerCase()),
2252
+ );
2253
+
2254
+ for (const { alias, representative } of successfulAliases) {
2255
+ filtered.push({
2256
+ ...representative,
2257
+ id: alias,
2258
+ });
2259
+ }
2260
+
2261
+ return filtered;
2262
+ }
2263
+
2187
2264
  /**
2188
2265
  * Build the OpenAI-compatible `/v1/models` catalog for the proxy.
2189
2266
  *
@@ -2193,7 +2270,7 @@ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2193
2270
  export function buildOpenAIModelCatalog(
2194
2271
  rotator?: AccountRotator,
2195
2272
  ): OpenAIModelCatalogEntry[] {
2196
- const catalog: OpenAIModelCatalogEntry[] = getEffectiveAntigravityModels().map(
2273
+ const catalog: OpenAIModelCatalogEntry[] = getOpenAIAntigravityModels().map(
2197
2274
  ({
2198
2275
  id,
2199
2276
  ctx,
@@ -56,6 +56,8 @@ export function applyConfigDefaults(config: Config): Config {
56
56
  streamRecoveryMaxRetries: safeStreamRecoveryMaxRetries(config.streamRecoveryMaxRetries),
57
57
  compressionMode: config.compressionMode ?? "off",
58
58
  modelSpecs: config.modelSpecs,
59
+ modelAliases: config.modelAliases,
60
+ effortRouting: config.effortRouting,
59
61
  accounts: config.accounts ? config.accounts.map((account) => ({
60
62
  ...normalizeAccountConfig(account),
61
63
  tier: account.tier || "unknown",
package/src/index.ts CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  loadResponsesStore,
20
20
  flushResponsesStore,
21
21
  } from "./compat.js";
22
- import { setModelAliasesOverride } from "./types.js";
22
+ import { setModelAliasesOverride, setEffortRoutingOverride } from "./types.js";
23
23
  import { readTextFile, writeTextFileAtomic } from "./storage.js";
24
24
  import { initDb, isDbConfigured } from "./db-store.js";
25
25
  import { runKeyMigrations } from "./key-migrations.js";
@@ -211,6 +211,7 @@ export async function main(): Promise<void> {
211
211
  warnIfInsecureTelemetryEndpoint();
212
212
  setModelSpecsOverride(config.modelSpecs ?? null);
213
213
  setModelAliasesOverride(config.modelAliases ?? null);
214
+ setEffortRoutingOverride(config.effortRouting ?? null);
214
215
  void loadResponsesStore();
215
216
 
216
217
  const rotator = new AccountRotator(config);
@@ -29,9 +29,7 @@ import {
29
29
 
30
30
  type GoogleModelInfo = GoogleQuotaResponse["models"][string];
31
31
  type GoogleModelInfoWithQuota = GoogleModelInfo & {
32
- quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]> & {
33
- remainingFraction: number;
34
- };
32
+ quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]>;
35
33
  };
36
34
 
37
35
  function hasUsableQuotaInfo(
@@ -39,10 +37,58 @@ function hasUsableQuotaInfo(
39
37
  ): info is GoogleModelInfoWithQuota {
40
38
  if (!info?.quotaInfo) return false;
41
39
  const remaining = info.quotaInfo.remainingFraction;
42
- return typeof remaining === "number" &&
43
- Number.isFinite(remaining) &&
44
- remaining >= 0 &&
45
- remaining <= 1;
40
+ if (remaining === undefined) {
41
+ // Google omits remainingFraction for active quota windows. A resetTime
42
+ // without a fraction is the partial shape used by the legacy parser.
43
+ return typeof info.quotaInfo.resetTime === "string" &&
44
+ info.quotaInfo.resetTime.trim().length > 0;
45
+ }
46
+ return typeof remaining === "number" && Number.isFinite(remaining) &&
47
+ remaining >= 0 && remaining <= 1;
48
+ }
49
+
50
+ function getRemainingFraction(info: GoogleModelInfoWithQuota): number {
51
+ const remaining = info.quotaInfo.remainingFraction;
52
+ return typeof remaining === "number" && Number.isFinite(remaining) &&
53
+ remaining >= 0 && remaining <= 1
54
+ ? remaining
55
+ : 0;
56
+ }
57
+
58
+ function applyActiveCooldown(
59
+ quota: ModelQuota,
60
+ cooldownUntil: number | undefined,
61
+ now: number,
62
+ ): void {
63
+ if (!cooldownUntil || !Number.isFinite(cooldownUntil) || cooldownUntil <= now) {
64
+ return;
65
+ }
66
+ const advertisedReset = quota.resetTime
67
+ ? new Date(quota.resetTime).getTime()
68
+ : 0;
69
+ const resetAt = Math.max(
70
+ cooldownUntil,
71
+ Number.isFinite(advertisedReset) && advertisedReset > now ? advertisedReset : 0,
72
+ );
73
+ quota.percentRemaining = 0;
74
+ quota.resetTime = new Date(resetAt).toISOString();
75
+ quota.timerType = resetAt - now < 6 * 60 * 60 * 1000 ? "5h" : "7d";
76
+ }
77
+
78
+ function getActiveCooldownForPool(
79
+ account: AccountRuntime,
80
+ poolKey: string,
81
+ ): number | undefined {
82
+ let cooldownUntil = account.cooldownsByModel[poolKey] ?? 0;
83
+ for (const [modelKey, deadline] of Object.entries(account.cooldownsByModel)) {
84
+ if (
85
+ modelKey !== poolKey &&
86
+ dynamicCatalog.resolveQuotaPool(modelKey) === poolKey
87
+ ) {
88
+ cooldownUntil = Math.max(cooldownUntil, deadline);
89
+ }
90
+ }
91
+ return cooldownUntil || undefined;
46
92
  }
47
93
 
48
94
  /**
@@ -57,29 +103,33 @@ export function extractQuotas(
57
103
  const now = Date.now();
58
104
 
59
105
  for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
60
- let modelInfo: GoogleModelInfoWithQuota | undefined;
106
+ const candidates: GoogleModelInfoWithQuota[] = [];
61
107
  for (const candidate of [config.key, ...config.altKeys]) {
62
108
  const info = data.models[candidate];
63
109
  if (hasUsableQuotaInfo(info)) {
64
- modelInfo = info;
65
- break;
110
+ candidates.push(info);
66
111
  }
67
112
  }
68
113
 
69
- if (!modelInfo) {
70
- for (const [modelKey, info] of Object.entries(data.models)) {
71
- if (
72
- DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
73
- hasUsableQuotaInfo(info)
74
- ) {
75
- modelInfo = info;
76
- break;
77
- }
114
+ for (const [modelKey, info] of Object.entries(data.models)) {
115
+ if (
116
+ ![config.key, ...config.altKeys].includes(modelKey) &&
117
+ DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
118
+ hasUsableQuotaInfo(info)
119
+ ) {
120
+ candidates.push(info);
78
121
  }
79
122
  }
80
123
 
124
+ // A shared pool is usable only as far as its most exhausted model. Google
125
+ // may report one sibling at 100% while the model we route to is exhausted.
126
+ const modelInfo = candidates.sort(
127
+ (a, b) => getRemainingFraction(a) - getRemainingFraction(b) ||
128
+ Number(Boolean(b.quotaInfo.resetTime)) -
129
+ Number(Boolean(a.quotaInfo.resetTime)),
130
+ )[0];
81
131
  if (modelInfo?.quotaInfo) {
82
- const remainingFraction = modelInfo.quotaInfo.remainingFraction;
132
+ const remainingFraction = getRemainingFraction(modelInfo);
83
133
  // Google can publish a nominal reset for an untouched pool; no usage means
84
134
  // there is no active quota window yet.
85
135
  const resetTime =
@@ -207,7 +257,32 @@ export async function fetchProviderQuota(
207
257
  fresh.forEach(
208
258
  (q) => ((q as { providerId?: string }).providerId = "google-antigravity"),
209
259
  );
210
- account.quota = sortQuotaPools([...otherProviders, ...fresh]);
260
+ const freshKeys = new Set(fresh.map((quota) => quota.modelKey));
261
+ const previousGooglePools = oldQuota.filter(
262
+ (q) => (q as { providerId?: string }).providerId === DEFAULT_PROVIDER &&
263
+ !freshKeys.has(q.modelKey),
264
+ );
265
+ for (const quota of [...previousGooglePools, ...fresh]) {
266
+ if (
267
+ freshKeys.has(quota.modelKey) &&
268
+ quota.percentRemaining === 0 &&
269
+ quota.resetTime
270
+ ) {
271
+ // A newly reported exhausted window is authoritative; the poll
272
+ // reconciler will persist its reset time instead of stale local state.
273
+ continue;
274
+ }
275
+ applyActiveCooldown(
276
+ quota,
277
+ getActiveCooldownForPool(account, quota.modelKey),
278
+ Date.now(),
279
+ );
280
+ }
281
+ account.quota = sortQuotaPools([
282
+ ...otherProviders,
283
+ ...previousGooglePools,
284
+ ...fresh,
285
+ ]);
211
286
  account.lastQuotaPoll = Date.now();
212
287
 
213
288
  // Stash the provider-local poll log for the rotator to emit as a
@@ -1,5 +1,5 @@
1
1
  import { logger, redactSensitive } from "../../logger.js";
2
- import { applyModelAlias } from "../../types.js";
2
+ import { applyModelAlias, getEffortRoutingRule } from "../../types.js";
3
3
  import type { RequestBody } from "../../proxy.js";
4
4
  import {
5
5
  isRecord,
@@ -136,7 +136,7 @@ export interface OpenAIChatCompletionRequest {
136
136
  tools?: OpenAITool[];
137
137
  tool_choice?: unknown;
138
138
  /** OpenAI-style reasoning effort. Mapped to Gemini thinkingLevel. */
139
- reasoning_effort?: string;
139
+ reasoning_effort?: unknown;
140
140
  [key: string]: unknown;
141
141
  }
142
142
 
@@ -893,7 +893,7 @@ export function isTieredEffortModel(modelId: string): boolean {
893
893
  * semantics and never emits an invalid upstream enum.
894
894
  */
895
895
  export function mapTieredReasoningEffortToThinkingLevel(
896
- effort: string | undefined,
896
+ effort: unknown,
897
897
  modelId: string,
898
898
  ): "LOW" | "MEDIUM" | "HIGH" | undefined {
899
899
  if (!isTieredEffortModel(modelId)) return undefined;
@@ -910,9 +910,35 @@ export function mapTieredReasoningEffortToThinkingLevel(
910
910
  }
911
911
  }
912
912
 
913
+ export function resolveEffortAliasModel(
914
+ requestedModel: string,
915
+ effort: unknown,
916
+ ): string | null {
917
+ const rule = getEffortRoutingRule(requestedModel);
918
+ if (!rule) return null;
919
+ const key = typeof effort === "string" ? effort.trim().toLowerCase() : "";
920
+ if (key && Object.hasOwn(rule.targets, key)) return rule.targets[key];
921
+ if (effort !== undefined) {
922
+ const supplied = typeof effort === "string"
923
+ ? JSON.stringify(effort.length > 40 ? `${effort.slice(0, 40)}…` : effort)
924
+ : `<${effort === null ? "null" : typeof effort}>`;
925
+ compatLogger.debug(
926
+ `Unrecognized effort ${supplied} for alias "${requestedModel.trim().toLowerCase()}", falling back to default`,
927
+ );
928
+ }
929
+ return Object.hasOwn(rule.targets, rule.defaultEffort)
930
+ ? rule.targets[rule.defaultEffort]
931
+ : null;
932
+ }
933
+
913
934
  export function openAIToAntigravityBody(
914
935
  input: OpenAIChatCompletionRequest,
915
936
  ): RequestBody {
937
+ const requestedModel = input.model;
938
+ const effortTarget =
939
+ resolveEffortAliasModel(requestedModel, input.reasoning_effort) ??
940
+ requestedModel;
941
+
916
942
  const systemParts: string[] = [];
917
943
  const conversationMessages = input.messages.filter((msg) => {
918
944
  if (msg.role === "system" || msg.role === "developer") {
@@ -926,8 +952,8 @@ export function openAIToAntigravityBody(
926
952
  return true;
927
953
  });
928
954
 
929
- const isClaude = /^claude-/i.test(input.model);
930
- const isThinking = isThinkingModel(input.model);
955
+ const isClaude = /^claude-/i.test(effortTarget);
956
+ const isThinking = isThinkingModel(effortTarget);
931
957
  const isGeminiThinking = !isClaude && isThinking;
932
958
 
933
959
  const contents: GeminiContent[] = [];
@@ -1206,13 +1232,13 @@ export function openAIToAntigravityBody(
1206
1232
  ? convertToolChoiceToGemini(input.tool_choice)
1207
1233
  : undefined;
1208
1234
 
1209
- const modelSpec = getModelSpec(input.model);
1210
- const modelFamily = getModelFamily(input.model);
1235
+ const modelSpec = getModelSpec(effortTarget);
1236
+ const modelFamily = getModelFamily(effortTarget);
1211
1237
  let maxOutputTokens =
1212
1238
  typeof input.max_tokens === "number" ? input.max_tokens : undefined;
1213
1239
  if (maxOutputTokens && maxOutputTokens > modelSpec.maxOutputTokens) {
1214
1240
  compatLogger.debug(
1215
- `Capping ${input.model} maxOutputTokens ${maxOutputTokens} → ${modelSpec.maxOutputTokens}`,
1241
+ `Capping ${effortTarget} maxOutputTokens ${maxOutputTokens} → ${modelSpec.maxOutputTokens}`,
1216
1242
  );
1217
1243
  maxOutputTokens = modelSpec.maxOutputTokens;
1218
1244
  }
@@ -1247,7 +1273,7 @@ export function openAIToAntigravityBody(
1247
1273
  tb === -1
1248
1274
  ? mapTieredReasoningEffortToThinkingLevel(
1249
1275
  input.reasoning_effort,
1250
- input.model,
1276
+ effortTarget,
1251
1277
  )
1252
1278
  : undefined;
1253
1279
  if (tieredThinkingLevel) {
@@ -1324,12 +1350,12 @@ export function openAIToAntigravityBody(
1324
1350
  if (geminiTools.length > 0) request.tools = geminiTools;
1325
1351
  if (geminiToolConfig) request.toolConfig = geminiToolConfig;
1326
1352
 
1327
- const mappedModel = applyModelAlias(input.model);
1353
+ const mappedModel = applyModelAlias(effortTarget);
1328
1354
 
1329
1355
  return {
1330
1356
  project: "compat-placeholder",
1331
1357
  model: mappedModel,
1332
- displayModel: input.model,
1358
+ displayModel: requestedModel,
1333
1359
  userAgent: "antigravity",
1334
1360
  requestType: "agent",
1335
1361
  request,
package/src/proxy.ts CHANGED
@@ -12,6 +12,8 @@ import {
12
12
  } from "node:http";
13
13
  import { Readable } from "node:stream";
14
14
  import {
15
+ classifyEffortRoutingModel,
16
+ getEffortRoutingRule,
15
17
  resolveQuotaModelKey,
16
18
  resolveDisplayModelKey,
17
19
  } from "./types.js";
@@ -108,6 +110,12 @@ export function providerAdapterForModel(
108
110
  ollamaModels: new Set(rotator?.getOllamaModels?.() ?? []),
109
111
  codexModels: new Set(rotator?.getCodexModels?.() ?? []),
110
112
  };
113
+ const effortRoutingKind = classifyEffortRoutingModel(model);
114
+ if (effortRoutingKind && context.ollamaModels.has(model)) {
115
+ proxyLogger.warn(
116
+ `Effort routing ${effortRoutingKind} "${model}" matches a live Ollama model; live provider dispatch wins`,
117
+ );
118
+ }
111
119
  const matched = findProviderForModel(model, context);
112
120
  if (matched) return matched;
113
121
  }
@@ -133,11 +141,20 @@ function routingModelKey(rotator: AccountRotator, model: string): string {
133
141
  return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
134
142
  }
135
143
 
136
- function observedModelKey(rotator: AccountRotator, model: string): string {
144
+ function observedModelKey(
145
+ rotator: AccountRotator,
146
+ displayModel: string,
147
+ effectiveModel?: string,
148
+ ): string {
149
+ const rule = getEffortRoutingRule(displayModel);
150
+ const observedModel = effectiveModel && rule ? effectiveModel : displayModel;
137
151
  const resolver = (rotator as unknown as {
138
152
  resolveObservedModelKey?: (value: string) => string;
139
153
  }).resolveObservedModelKey;
140
- return resolver?.call(rotator, model) ?? resolveDisplayModelKey(model);
154
+ return (
155
+ resolver?.call(rotator, observedModel) ??
156
+ resolveDisplayModelKey(displayModel, effectiveModel)
157
+ );
141
158
  }
142
159
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
143
160
  import { startNotificationPoller } from "./notification-poller.js";
@@ -153,6 +170,10 @@ import {
153
170
  serveGeminiModels,
154
171
  serveOpenAIModels,
155
172
  } from "./compat.js";
173
+ import {
174
+ handleOpenAIAudioTranscriptions,
175
+ handleAudioWebSocket,
176
+ } from "./audio-transcription.js";
156
177
  import { applyConfigDefaults } from "./account-store.js";
157
178
  import {
158
179
  classifyRateLimitReason,
@@ -1180,7 +1201,11 @@ export async function withRotation<T>(
1180
1201
 
1181
1202
  const label = account.config.label || account.config.email;
1182
1203
  const modelKey = routingModelKey(rotator, model);
1183
- const displayModelKey = observedModelKey(rotator, body.displayModel || model);
1204
+ const displayModelKey = observedModelKey(
1205
+ rotator,
1206
+ body.displayModel || model,
1207
+ body.model,
1208
+ );
1184
1209
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1185
1210
  const requestStartMs = Date.now();
1186
1211
  let accountReleased = false;
@@ -1208,8 +1233,13 @@ export async function withRotation<T>(
1208
1233
  );
1209
1234
 
1210
1235
  try {
1211
- const jitterMs = rotator.getSafetyJitterMs(account);
1212
- const globalDelayMs = rotator.getGlobalDelayMs();
1236
+ const skipJitter = Boolean(
1237
+ originalHeaders &&
1238
+ (originalHeaders["x-skip-safety-jitter"] === "true" ||
1239
+ originalHeaders["x-live-request"] === "true"),
1240
+ );
1241
+ const jitterMs = skipJitter ? 0 : rotator.getSafetyJitterMs(account);
1242
+ const globalDelayMs = skipJitter ? 0 : rotator.getGlobalDelayMs();
1213
1243
  const totalDelayMs = jitterMs + globalDelayMs;
1214
1244
  if (totalDelayMs > 0) {
1215
1245
  if (jitterMs > 0) {
@@ -1661,8 +1691,9 @@ async function handleProxyRequest(
1661
1691
  };
1662
1692
 
1663
1693
  try {
1664
- const jitterMs = rotator.getSafetyJitterMs(account);
1665
- const globalDelayMs = rotator.getGlobalDelayMs();
1694
+ const skipJitter = req.headers["x-skip-safety-jitter"] === "true" || req.headers["x-live-request"] === "true";
1695
+ const jitterMs = skipJitter ? 0 : rotator.getSafetyJitterMs(account);
1696
+ const globalDelayMs = skipJitter ? 0 : rotator.getGlobalDelayMs();
1666
1697
  const totalDelayMs = jitterMs + globalDelayMs;
1667
1698
  if (totalDelayMs > 0) {
1668
1699
  if (jitterMs > 0) {
@@ -2037,6 +2068,17 @@ export function startProxy(
2037
2068
  const url = req.url || "";
2038
2069
  const pathname = url.split("?")[0];
2039
2070
 
2071
+ // CORS headers for API consumers (e.g. MindWhisperAI, local frontends)
2072
+ res.setHeader("Access-Control-Allow-Origin", "*");
2073
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
2074
+ res.setHeader("Access-Control-Allow-Headers", "*");
2075
+
2076
+ if (method === "OPTIONS") {
2077
+ res.writeHead(204);
2078
+ res.end();
2079
+ return;
2080
+ }
2081
+
2040
2082
  if (method === "GET" && (pathname === "/" || pathname === "/dashboard")) {
2041
2083
  if (!requireAdmin(req, res)) return;
2042
2084
  trackFeature("dashboard");
@@ -2454,6 +2496,23 @@ export function startProxy(
2454
2496
  return;
2455
2497
  }
2456
2498
 
2499
+ if (method === "POST" && pathname === "/v1/audio/transcriptions") {
2500
+ handleOpenAIAudioTranscriptions(req, res).catch((err) => {
2501
+ log(`Audio transcription error: ${err}`, rotator, "error");
2502
+ if (!res.headersSent)
2503
+ res.writeHead(500, { "Content-Type": "application/json" });
2504
+ res.end(
2505
+ JSON.stringify({
2506
+ error: {
2507
+ message: "Internal audio transcription error",
2508
+ type: "server_error",
2509
+ },
2510
+ }),
2511
+ );
2512
+ });
2513
+ return;
2514
+ }
2515
+
2457
2516
  if (method === "POST" && pathname === "/v1/responses") {
2458
2517
  handleOpenAIResponsesCreate(req, res, rotator).catch((err) => {
2459
2518
  log(`OpenAI responses compat error: ${err}`, rotator, "error");
@@ -2576,9 +2635,26 @@ export function startProxy(
2576
2635
  res.end(JSON.stringify({ error: "Not found" }));
2577
2636
  });
2578
2637
 
2638
+ server.on("upgrade", (req, socket) => {
2639
+ const url = req.url || "";
2640
+ const pathname = url.split("?")[0];
2641
+ if (
2642
+ pathname === "/ws" ||
2643
+ pathname === "/ws/audio" ||
2644
+ pathname === "/v1/audio/transcriptions/stream" ||
2645
+ pathname === "/v1/listen" ||
2646
+ pathname.startsWith("/ws/")
2647
+ ) {
2648
+ handleAudioWebSocket(req, socket).catch(() => socket.destroy());
2649
+ return;
2650
+ }
2651
+ socket.destroy();
2652
+ });
2653
+
2579
2654
  server.listen(port, bindHost, () => {
2580
2655
  log(`Listening on ${bindHost}:${port}`, rotator);
2581
2656
  log(`Dashboard: http://localhost:${port}/dashboard`, rotator);
2657
+ log(`Audio Stream WS: ws://localhost:${port}/ws`, rotator);
2582
2658
  log(`Hosted login: http://localhost:${port}/login`, rotator);
2583
2659
  });
2584
2660
  return server;
package/src/rotator.ts CHANGED
@@ -1443,23 +1443,12 @@ export class AccountRotator {
1443
1443
  ): AccountStatus["status"] {
1444
1444
  const defaultCooldownActive =
1445
1445
  (account.cooldownsByModel.__default__ ?? 0) > now;
1446
- const knownPools = new Set(account.quota.map((quota) => quota.modelKey));
1447
- for (const [modelKey, cooldownUntil] of Object.entries(
1448
- account.cooldownsByModel,
1449
- )) {
1450
- if (modelKey !== "__default__" && cooldownUntil > now) {
1451
- knownPools.add(modelKey);
1452
- }
1453
- }
1454
- const allKnownPoolsCooling =
1455
- knownPools.size > 0 &&
1456
- [...knownPools].every(
1457
- (modelKey) => (account.cooldownsByModel[modelKey] ?? 0) > now,
1458
- );
1459
1446
  if (account.flagged) return "flagged";
1460
1447
  if (account.disabled) return "disabled";
1461
1448
  if (account.consecutiveErrors > 0 && !account.disabled) return "error";
1462
- if (defaultCooldownActive || allKnownPoolsCooling) return "cooldown";
1449
+ // Pool cooldowns stay visible in cooldownsByModel but must not make the
1450
+ // whole account unavailable for unrelated quota pools.
1451
+ if (defaultCooldownActive) return "cooldown";
1463
1452
  if (this.isDailySafetyStopped(account, now)) return "exhausted";
1464
1453
  if (activeForModels.length > 0) return "active";
1465
1454
  return "ready";
@@ -1948,6 +1937,14 @@ export class AccountRotator {
1948
1937
  this.requestWaiterWakeAt = wakeAt;
1949
1938
  this.requestWaiterWakeTimer = setTimeout(() => {
1950
1939
  this.requestWaiterWakeTimer = null;
1940
+ if (this.requestWaiters.length === 0) {
1941
+ this.requestWaiterWakeAt = 0;
1942
+ return;
1943
+ }
1944
+ if (Date.now() < wakeAt) {
1945
+ this.scheduleRequestWaiterWake(wakeAt);
1946
+ return;
1947
+ }
1951
1948
  this.requestWaiterWakeAt = 0;
1952
1949
  this.requestWaiterDrain();
1953
1950
  }, Math.max(1, wakeAt - Date.now()));
@@ -2991,6 +2988,21 @@ export class AccountRotator {
2991
2988
  account.cooldownsByModel[modelKey] = now + cooldownMs;
2992
2989
  account.quotaExhaustedAt = now;
2993
2990
 
2991
+ // Keep the dashboard aligned with provider truth. The quota endpoint can
2992
+ // report an untouched 100% pool while generation has already exhausted it.
2993
+ if (modelKey !== "__default__" && cooldownMs > 0) {
2994
+ const quota = account.quota.find(
2995
+ (candidate) =>
2996
+ candidate.modelKey === modelKey &&
2997
+ candidate.providerId === DEFAULT_PROVIDER,
2998
+ );
2999
+ if (quota) {
3000
+ quota.percentRemaining = 0;
3001
+ quota.resetTime = new Date(now + cooldownMs).toISOString();
3002
+ quota.timerType = cooldownMs < 6 * 60 * 60 * 1000 ? "5h" : "7d";
3003
+ }
3004
+ }
3005
+
2994
3006
  const errorDetail = errorText ? ` | ${errorText}` : "";
2995
3007
  this.log(
2996
3008
  `${account.config.label || account.config.email} [${modelKey}]: EXHAUSTED, cooldown ${Math.ceil(cooldownMs / 1000)}s${errorDetail}`,
@@ -4466,6 +4478,19 @@ export class AccountRotator {
4466
4478
  const upstreamModel = target.upstreamModel;
4467
4479
  const poolKey = target.poolKey;
4468
4480
 
4481
+ const activeCooldown = Math.max(
4482
+ account.cooldownsByModel[poolKey] ?? 0,
4483
+ account.cooldownsByModel.__default__ ?? 0,
4484
+ );
4485
+ if (activeCooldown > Date.now()) {
4486
+ return {
4487
+ ok: false,
4488
+ status: 429,
4489
+ upstreamModel,
4490
+ error: `quota cooldown active for ${Math.ceil((activeCooldown - Date.now()) / 1000)}s`,
4491
+ };
4492
+ }
4493
+
4469
4494
  const controller = new AbortController();
4470
4495
  const timeout = setTimeout(() => controller.abort(), 15_000);
4471
4496