tuxevil-rotator 3.7.1 → 3.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +2 -0
- package/package.json +1 -1
- package/src/compat.ts +127 -7
- package/src/fetch-with-retry.ts +71 -0
- package/src/providers/adapter.ts +1 -0
- package/src/providers/google-antigravity/forward.ts +30 -4
- package/src/providers/google-antigravity/translators.ts +2 -1
- package/src/providers/ollama/forward.ts +5 -2
- package/src/providers/openai-codex/compat.ts +62 -7
- package/src/providers/openai-codex/forward.ts +5 -2
- package/src/providers/opencode-zen/forward.ts +36 -4
- package/src/proxy.ts +40 -5
- package/src/rate-limit-parser.ts +29 -0
- package/src/rotator.ts +130 -34
- package/src/stream-guards.ts +85 -0
|
@@ -11,6 +11,11 @@ import type { AccountRotator } from "../../rotator.js";
|
|
|
11
11
|
import type { OpenAIChatCompletionRequest, OpenAIResponsesRequest, CompatCompletion, OpenAIToolCall } from "../google-antigravity/translators.js";
|
|
12
12
|
import { buildRotatorResponseHeaders } from "../../response-headers.js";
|
|
13
13
|
import { logSpend } from "../../spend-logger.js";
|
|
14
|
+
import { redactSensitive } from "../../logger.js";
|
|
15
|
+
import {
|
|
16
|
+
createStreamIdleGuard,
|
|
17
|
+
waitForResponseDrain,
|
|
18
|
+
} from "../../stream-guards.js";
|
|
14
19
|
import {
|
|
15
20
|
buildCodexPayload,
|
|
16
21
|
createCodexStreamAccumulator,
|
|
@@ -384,16 +389,31 @@ async function pipeNativeResponses(
|
|
|
384
389
|
const accumulator = createCodexStreamAccumulator();
|
|
385
390
|
const streamStartMs = Date.now();
|
|
386
391
|
let firstByteMs: number | undefined;
|
|
392
|
+
let streamError: string | undefined;
|
|
387
393
|
const close = (): void => { if (!stream.destroyed) stream.destroy(); };
|
|
388
394
|
req.once("close", close);
|
|
395
|
+
res.once("close", close);
|
|
396
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
397
|
+
streamError = error.message;
|
|
398
|
+
if (!stream.destroyed) stream.destroy(error);
|
|
399
|
+
});
|
|
389
400
|
try {
|
|
390
401
|
for await (const chunk of stream) {
|
|
402
|
+
idleGuard.reset();
|
|
391
403
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
392
404
|
accumulator.append(chunk.toString());
|
|
393
405
|
if (!res.writableEnded) res.write(chunk);
|
|
406
|
+
await waitForResponseDrain(res);
|
|
407
|
+
}
|
|
408
|
+
} catch (error) {
|
|
409
|
+
streamError ??= redactSensitive(String(error)).slice(0, 200);
|
|
410
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
411
|
+
res.write(`event: error\ndata: ${JSON.stringify({ type: "error", error: { code: "stream_error", message: streamError } })}\n\n`);
|
|
394
412
|
}
|
|
395
413
|
} finally {
|
|
414
|
+
idleGuard.clear();
|
|
396
415
|
req.off("close", close);
|
|
416
|
+
res.off("close", close);
|
|
397
417
|
if (!res.writableEnded) res.end();
|
|
398
418
|
}
|
|
399
419
|
const usage = accumulator.final();
|
|
@@ -402,6 +422,7 @@ async function pipeNativeResponses(
|
|
|
402
422
|
inputTokens: usage?.inputTokens ?? 0,
|
|
403
423
|
outputTokens: usage?.outputTokens ?? 0,
|
|
404
424
|
firstByteMs,
|
|
425
|
+
streamError,
|
|
405
426
|
};
|
|
406
427
|
}
|
|
407
428
|
|
|
@@ -432,8 +453,14 @@ async function pipeCodexAsChat(
|
|
|
432
453
|
let toolIndex = 0;
|
|
433
454
|
const streamStartMs = Date.now();
|
|
434
455
|
let firstByteMs: number | undefined;
|
|
456
|
+
let streamError: string | undefined;
|
|
435
457
|
const close = (): void => { if (!stream.destroyed) stream.destroy(); };
|
|
436
458
|
req.once("close", close);
|
|
459
|
+
res.once("close", close);
|
|
460
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
461
|
+
streamError = error.message;
|
|
462
|
+
if (!stream.destroyed) stream.destroy(error);
|
|
463
|
+
});
|
|
437
464
|
const handle = (payload: string, event: string): void => {
|
|
438
465
|
let data: Record<string, unknown>;
|
|
439
466
|
try { data = JSON.parse(payload) as Record<string, unknown>; } catch { return; }
|
|
@@ -454,6 +481,7 @@ async function pipeCodexAsChat(
|
|
|
454
481
|
};
|
|
455
482
|
try {
|
|
456
483
|
for await (const chunk of stream) {
|
|
484
|
+
idleGuard.reset();
|
|
457
485
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
458
486
|
buffer += chunk.toString();
|
|
459
487
|
let newline = buffer.indexOf("\n");
|
|
@@ -464,12 +492,25 @@ async function pipeCodexAsChat(
|
|
|
464
492
|
else if (line.startsWith("data:")) handle(line.slice(5).trim(), eventName);
|
|
465
493
|
newline = buffer.indexOf("\n");
|
|
466
494
|
}
|
|
495
|
+
await waitForResponseDrain(res);
|
|
496
|
+
}
|
|
497
|
+
} catch (error) {
|
|
498
|
+
streamError ??= redactSensitive(String(error)).slice(0, 200);
|
|
499
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
500
|
+
res.write(`data: ${JSON.stringify({ error: { message: streamError, type: "server_error" } })}\n\n`);
|
|
501
|
+
res.end("data: [DONE]\n\n");
|
|
467
502
|
}
|
|
468
|
-
} finally {
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
503
|
+
} finally {
|
|
504
|
+
idleGuard.clear();
|
|
505
|
+
req.off("close", close);
|
|
506
|
+
res.off("close", close);
|
|
507
|
+
}
|
|
508
|
+
if (!streamError && !res.writableEnded) {
|
|
509
|
+
emitChatChunk(res, model, id, {}, toolIndex > 0 ? "tool_calls" : "stop");
|
|
510
|
+
if (inputTokens > 0 || outputTokens > 0) emitChatChunk(res, model, id, {}, null, { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens });
|
|
511
|
+
res.end("data: [DONE]\n\n");
|
|
512
|
+
}
|
|
513
|
+
return { text: "", inputTokens, outputTokens, firstByteMs, streamError };
|
|
473
514
|
}
|
|
474
515
|
|
|
475
516
|
export async function serveCodexResponses(
|
|
@@ -489,7 +530,14 @@ export async function serveCodexResponses(
|
|
|
489
530
|
if (request.stream) {
|
|
490
531
|
const completion = await pipeNativeResponses(response, req, res, context, request.model);
|
|
491
532
|
recordCodexTokenUsage(rotator, request.model, completion);
|
|
492
|
-
recordCodexOutcome(
|
|
533
|
+
recordCodexOutcome(
|
|
534
|
+
rotator,
|
|
535
|
+
body,
|
|
536
|
+
context,
|
|
537
|
+
completion.streamError ? 502 : response.status,
|
|
538
|
+
completion,
|
|
539
|
+
options,
|
|
540
|
+
);
|
|
493
541
|
return completion;
|
|
494
542
|
}
|
|
495
543
|
const raw = await response.text();
|
|
@@ -529,7 +577,14 @@ export async function serveCodexChat(
|
|
|
529
577
|
if (request.stream) {
|
|
530
578
|
const completion = await pipeCodexAsChat(response, req, res, request.model, context);
|
|
531
579
|
recordCodexTokenUsage(rotator, request.model, completion);
|
|
532
|
-
recordCodexOutcome(
|
|
580
|
+
recordCodexOutcome(
|
|
581
|
+
rotator,
|
|
582
|
+
body,
|
|
583
|
+
context,
|
|
584
|
+
completion.streamError ? 502 : response.status,
|
|
585
|
+
completion,
|
|
586
|
+
options,
|
|
587
|
+
);
|
|
533
588
|
return completion;
|
|
534
589
|
}
|
|
535
590
|
const raw = await response.text();
|
|
@@ -2,7 +2,10 @@ import type { AccountRuntime, ProviderCredential } from "../../types.js";
|
|
|
2
2
|
import type { ForwardedResponse, RequestBody } from "../../proxy.js";
|
|
3
3
|
import type { StreamAccumulator, TokenUsage } from "../adapter.js";
|
|
4
4
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
5
|
-
import
|
|
5
|
+
import {
|
|
6
|
+
fetchWithHeadersTimeout,
|
|
7
|
+
type RequestInitWithDispatcher,
|
|
8
|
+
} from "../../fetch-with-retry.js";
|
|
6
9
|
import { getCodexAccountId, getCodexCredential, getCodexTokenState } from "./credentials.js";
|
|
7
10
|
import { DEFAULT_CODEX_BASE_URL, CODEX_PROVIDER_ID } from "./oauth.js";
|
|
8
11
|
|
|
@@ -148,7 +151,7 @@ export async function forwardCodexRequest(
|
|
|
148
151
|
signal?: AbortSignal,
|
|
149
152
|
): Promise<ForwardedResponse> {
|
|
150
153
|
const payload = buildCodexPayload(body);
|
|
151
|
-
const response = await
|
|
154
|
+
const response = await fetchWithHeadersTimeout(codexResponsesEndpoint(), {
|
|
152
155
|
method: "POST",
|
|
153
156
|
headers: forwardHeaders(originalHeaders, account, payload),
|
|
154
157
|
body: JSON.stringify(payload),
|
|
@@ -5,7 +5,10 @@ import type { AccountRuntime } from "../../types.js";
|
|
|
5
5
|
import type { ForwardedResponse, RequestBody } from "../../proxy.js";
|
|
6
6
|
import type { StreamAccumulator, TokenUsage } from "../adapter.js";
|
|
7
7
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
8
|
-
import
|
|
8
|
+
import {
|
|
9
|
+
fetchWithHeadersTimeout,
|
|
10
|
+
type RequestInitWithDispatcher,
|
|
11
|
+
} from "../../fetch-with-retry.js";
|
|
9
12
|
import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
|
|
10
13
|
import {
|
|
11
14
|
isOpenCodeZenResponsesModel,
|
|
@@ -282,7 +285,7 @@ export async function forwardRequest(
|
|
|
282
285
|
forwardHeaders["Accept"] = payload.stream === true ? "text/event-stream" : "application/json";
|
|
283
286
|
|
|
284
287
|
const endpoint = usesResponses ? OPENCODE_ZEN_RESPONSES_URL : OPENCODE_ZEN_CHAT_URL;
|
|
285
|
-
const response = await
|
|
288
|
+
const response = await fetchWithHeadersTimeout(endpoint, {
|
|
286
289
|
method: "POST",
|
|
287
290
|
headers: forwardHeaders,
|
|
288
291
|
body: JSON.stringify(payload),
|
|
@@ -406,6 +409,7 @@ function responseCompletionFromRecord(
|
|
|
406
409
|
thinkingText: thinkingText || undefined,
|
|
407
410
|
inputTokens: usage?.inputTokens ?? 0,
|
|
408
411
|
outputTokens: usage?.outputTokens ?? 0,
|
|
412
|
+
cachedTokens: usage?.cachedTokens,
|
|
409
413
|
responseId: typeof value.id === "string" ? value.id : undefined,
|
|
410
414
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
411
415
|
rawResponse,
|
|
@@ -483,6 +487,7 @@ export class OpenCodeZenResponsesStreamParser {
|
|
|
483
487
|
thinkingText: this.thinkingText || undefined,
|
|
484
488
|
inputTokens: this.usage?.inputTokens ?? 0,
|
|
485
489
|
outputTokens: this.usage?.outputTokens ?? 0,
|
|
490
|
+
cachedTokens: this.usage?.cachedTokens,
|
|
486
491
|
responseId: this.responseId,
|
|
487
492
|
toolCalls: this.toolCalls.size > 0 ? Array.from(this.toolCalls.values()) : undefined,
|
|
488
493
|
streamError: this.streamError,
|
|
@@ -496,6 +501,9 @@ export class OpenCodeZenResponsesStreamParser {
|
|
|
496
501
|
input_tokens: this.usage.inputTokens,
|
|
497
502
|
output_tokens: this.usage.outputTokens,
|
|
498
503
|
total_tokens: this.usage.inputTokens + this.usage.outputTokens,
|
|
504
|
+
...(this.usage.cachedTokens !== undefined
|
|
505
|
+
? { input_tokens_details: { cached_tokens: this.usage.cachedTokens } }
|
|
506
|
+
: {}),
|
|
499
507
|
}
|
|
500
508
|
: undefined,
|
|
501
509
|
},
|
|
@@ -641,7 +649,7 @@ function openCodeZenChatChunk(
|
|
|
641
649
|
id: string,
|
|
642
650
|
model: string,
|
|
643
651
|
delta: Record<string, unknown>,
|
|
644
|
-
usage?: Record<string,
|
|
652
|
+
usage?: Record<string, unknown>,
|
|
645
653
|
): string {
|
|
646
654
|
return `data: ${JSON.stringify({
|
|
647
655
|
id,
|
|
@@ -681,6 +689,9 @@ function updateToOpenCodeZenChatSse(
|
|
|
681
689
|
prompt_tokens: update.usage.inputTokens,
|
|
682
690
|
completion_tokens: update.usage.outputTokens,
|
|
683
691
|
total_tokens: update.usage.inputTokens + update.usage.outputTokens,
|
|
692
|
+
...(update.usage.cachedTokens !== undefined
|
|
693
|
+
? { prompt_tokens_details: { cached_tokens: update.usage.cachedTokens } }
|
|
694
|
+
: {}),
|
|
684
695
|
});
|
|
685
696
|
case "finish":
|
|
686
697
|
return "";
|
|
@@ -774,6 +785,9 @@ function openCodeZenResponsesToChatJson(
|
|
|
774
785
|
prompt_tokens: completion.inputTokens,
|
|
775
786
|
completion_tokens: completion.outputTokens,
|
|
776
787
|
total_tokens: completion.inputTokens + completion.outputTokens,
|
|
788
|
+
...(completion.cachedTokens !== undefined
|
|
789
|
+
? { prompt_tokens_details: { cached_tokens: completion.cachedTokens } }
|
|
790
|
+
: {}),
|
|
777
791
|
},
|
|
778
792
|
};
|
|
779
793
|
}
|
|
@@ -792,9 +806,27 @@ function extractUsageFromRecord(record: Record<string, unknown>): TokenUsage | n
|
|
|
792
806
|
: typeof usage.output_tokens === "number"
|
|
793
807
|
? usage.output_tokens
|
|
794
808
|
: 0;
|
|
809
|
+
const inputTokenDetails = isRecord(usage.input_tokens_details)
|
|
810
|
+
? usage.input_tokens_details
|
|
811
|
+
: null;
|
|
812
|
+
const promptTokenDetails = isRecord(usage.prompt_tokens_details)
|
|
813
|
+
? usage.prompt_tokens_details
|
|
814
|
+
: null;
|
|
815
|
+
const cachedTokens =
|
|
816
|
+
typeof inputTokenDetails?.cached_tokens === "number"
|
|
817
|
+
? inputTokenDetails.cached_tokens
|
|
818
|
+
: typeof promptTokenDetails?.cached_tokens === "number"
|
|
819
|
+
? promptTokenDetails.cached_tokens
|
|
820
|
+
: typeof usage.cached_tokens === "number"
|
|
821
|
+
? usage.cached_tokens
|
|
822
|
+
: undefined;
|
|
795
823
|
|
|
796
824
|
return inputTokens > 0 || outputTokens > 0
|
|
797
|
-
? {
|
|
825
|
+
? {
|
|
826
|
+
inputTokens,
|
|
827
|
+
outputTokens,
|
|
828
|
+
...(cachedTokens !== undefined ? { cachedTokens } : {}),
|
|
829
|
+
}
|
|
798
830
|
: null;
|
|
799
831
|
}
|
|
800
832
|
|
package/src/proxy.ts
CHANGED
|
@@ -183,6 +183,7 @@ import {
|
|
|
183
183
|
import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
|
|
184
184
|
import { logSpend } from "./spend-logger.js";
|
|
185
185
|
import { hashKey } from "./virtual-keys.js";
|
|
186
|
+
import { STREAM_BACKPRESSURE_TIMEOUT_MS } from "./stream-guards.js";
|
|
186
187
|
|
|
187
188
|
const proxyLogger = logger.child("proxy");
|
|
188
189
|
const GENERIC_UPSTREAM_ERROR = "Upstream request failed";
|
|
@@ -334,7 +335,7 @@ export async function classifyUpstreamResponse(
|
|
|
334
335
|
const rateLimitReason = classifyRateLimitReason(errorText, response.status);
|
|
335
336
|
const providerResourceExhausted = rateLimitReason === "quota-exhausted";
|
|
336
337
|
const cooldownMs = providerResourceExhausted
|
|
337
|
-
? providerId === DEFAULT_PROVIDER
|
|
338
|
+
? providerId === DEFAULT_PROVIDER || providerId === "openai-codex"
|
|
338
339
|
? parseRetryAfterMs(
|
|
339
340
|
errorText,
|
|
340
341
|
response.headers,
|
|
@@ -761,7 +762,7 @@ function isFetchTransportError(err: unknown): boolean {
|
|
|
761
762
|
return true;
|
|
762
763
|
}
|
|
763
764
|
if (err && typeof err === "object" && "code" in err) {
|
|
764
|
-
return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(
|
|
765
|
+
return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_SOCKET"].includes(
|
|
765
766
|
String(err.code),
|
|
766
767
|
);
|
|
767
768
|
}
|
|
@@ -815,9 +816,12 @@ async function streamResponseBody(
|
|
|
815
816
|
} | null>((resolve, reject) => {
|
|
816
817
|
let settled = false;
|
|
817
818
|
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
819
|
+
let backpressureTimer: ReturnType<typeof setTimeout> | null = null;
|
|
820
|
+
let waitingForDrain = false;
|
|
818
821
|
|
|
819
822
|
const cleanup = (): void => {
|
|
820
823
|
if (idleTimer) clearTimeout(idleTimer);
|
|
824
|
+
if (backpressureTimer) clearTimeout(backpressureTimer);
|
|
821
825
|
nodeStream.off("data", onData);
|
|
822
826
|
nodeStream.off("end", onEnd);
|
|
823
827
|
nodeStream.off("error", onError);
|
|
@@ -825,6 +829,8 @@ async function streamResponseBody(
|
|
|
825
829
|
req.off("close", onClientClose);
|
|
826
830
|
res.off("close", onResponseClose);
|
|
827
831
|
res.off("error", onResponseError);
|
|
832
|
+
res.off("drain", onDrain);
|
|
833
|
+
waitingForDrain = false;
|
|
828
834
|
};
|
|
829
835
|
|
|
830
836
|
const finish = (reason?: string): void => {
|
|
@@ -861,6 +867,31 @@ async function streamResponseBody(
|
|
|
861
867
|
);
|
|
862
868
|
};
|
|
863
869
|
|
|
870
|
+
const onDrain = (): void => {
|
|
871
|
+
if (!waitingForDrain) return;
|
|
872
|
+
waitingForDrain = false;
|
|
873
|
+
if (backpressureTimer) clearTimeout(backpressureTimer);
|
|
874
|
+
backpressureTimer = null;
|
|
875
|
+
if (!settled && !nodeStream.destroyed) nodeStream.resume();
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
const pauseForBackpressure = (): void => {
|
|
879
|
+
if (waitingForDrain || settled) return;
|
|
880
|
+
waitingForDrain = true;
|
|
881
|
+
nodeStream.pause();
|
|
882
|
+
backpressureTimer = setTimeout(() => {
|
|
883
|
+
backpressureTimer = null;
|
|
884
|
+
if (!waitingForDrain || settled) return;
|
|
885
|
+
const error = new Error(
|
|
886
|
+
`client backpressure timeout after ${Math.round(STREAM_BACKPRESSURE_TIMEOUT_MS / 1000)}s`,
|
|
887
|
+
);
|
|
888
|
+
emitStreamError(error);
|
|
889
|
+
finish(error.message);
|
|
890
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
891
|
+
}, STREAM_BACKPRESSURE_TIMEOUT_MS);
|
|
892
|
+
res.once("drain", onDrain);
|
|
893
|
+
};
|
|
894
|
+
|
|
864
895
|
const resetIdleTimer = (): void => {
|
|
865
896
|
if (idleTimer) clearTimeout(idleTimer);
|
|
866
897
|
idleTimer = setTimeout(() => {
|
|
@@ -882,7 +913,7 @@ async function streamResponseBody(
|
|
|
882
913
|
if (!res.destroyed && !res.writableEnded) {
|
|
883
914
|
if (!res.headersSent) res.writeHead(responseStatus, responseHeaders);
|
|
884
915
|
hasForwardedBytes = true;
|
|
885
|
-
res.write(chunk);
|
|
916
|
+
if (!res.write(chunk)) pauseForBackpressure();
|
|
886
917
|
}
|
|
887
918
|
// Extract usage from any newly-completed SSE events
|
|
888
919
|
if (!firstUsage) {
|
|
@@ -1191,6 +1222,7 @@ export async function withRotation<T>(
|
|
|
1191
1222
|
const maxAttempts = maxRetries + 1;
|
|
1192
1223
|
|
|
1193
1224
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1225
|
+
const admissionStartedMs = Date.now();
|
|
1194
1226
|
const account = await rotator.getActiveAccount(model, signal);
|
|
1195
1227
|
if (!account) {
|
|
1196
1228
|
if (signal?.aborted) {
|
|
@@ -1206,6 +1238,7 @@ export async function withRotation<T>(
|
|
|
1206
1238
|
body.displayModel || model,
|
|
1207
1239
|
body.model,
|
|
1208
1240
|
);
|
|
1241
|
+
const queueWaitMs = Date.now() - admissionStartedMs;
|
|
1209
1242
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1210
1243
|
const requestStartMs = Date.now();
|
|
1211
1244
|
let accountReleased = false;
|
|
@@ -1228,7 +1261,7 @@ export async function withRotation<T>(
|
|
|
1228
1261
|
};
|
|
1229
1262
|
|
|
1230
1263
|
log(
|
|
1231
|
-
`[${requestId}] START account=${label} model=${model} attempt=${attempt + 1}`,
|
|
1264
|
+
`[${requestId}] START account=${label} model=${model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
|
|
1232
1265
|
rotator,
|
|
1233
1266
|
);
|
|
1234
1267
|
|
|
@@ -1634,6 +1667,7 @@ async function handleProxyRequest(
|
|
|
1634
1667
|
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1635
1668
|
const maxAttempts = maxRetries + 1;
|
|
1636
1669
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1670
|
+
const admissionStartedMs = Date.now();
|
|
1637
1671
|
const account = await rotator.getActiveAccount(
|
|
1638
1672
|
body.model,
|
|
1639
1673
|
clientController.signal,
|
|
@@ -1647,6 +1681,7 @@ async function handleProxyRequest(
|
|
|
1647
1681
|
const label = account.config.label || account.config.email;
|
|
1648
1682
|
const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
|
|
1649
1683
|
const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
|
|
1684
|
+
const queueWaitMs = Date.now() - admissionStartedMs;
|
|
1650
1685
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1651
1686
|
let accountReleased = false;
|
|
1652
1687
|
const releaseCurrentAccount = (): void => {
|
|
@@ -1663,7 +1698,7 @@ async function handleProxyRequest(
|
|
|
1663
1698
|
return nextAccount;
|
|
1664
1699
|
};
|
|
1665
1700
|
proxyLog(
|
|
1666
|
-
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
|
|
1701
|
+
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
|
|
1667
1702
|
);
|
|
1668
1703
|
const requestStartMs = Date.now();
|
|
1669
1704
|
const logRequestEnd = (status: string | number, extra = ""): void => {
|
package/src/rate-limit-parser.ts
CHANGED
|
@@ -24,6 +24,8 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
|
|
|
24
24
|
lower.includes("quotaresettimestamp") ||
|
|
25
25
|
lower.includes("resource_exhausted") ||
|
|
26
26
|
lower.includes("resource exhausted") ||
|
|
27
|
+
lower.includes("usage_limit_reached") ||
|
|
28
|
+
lower.includes("usage limit reached") ||
|
|
27
29
|
lower.includes("daily limit") ||
|
|
28
30
|
lower.includes("quota exceeded")
|
|
29
31
|
) {
|
|
@@ -88,6 +90,33 @@ export function parseRetryAfterMs(
|
|
|
88
90
|
if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
|
|
89
91
|
}
|
|
90
92
|
|
|
93
|
+
const codexResetSecondsMatch = errorText.match(
|
|
94
|
+
/["']?resets_in_seconds["']?\s*:\s*["']?(\d+(?:\.\d+)?)/i,
|
|
95
|
+
);
|
|
96
|
+
if (codexResetSecondsMatch?.[1]) {
|
|
97
|
+
const seconds = Number(codexResetSecondsMatch[1]);
|
|
98
|
+
if (Number.isFinite(seconds) && seconds > 0) {
|
|
99
|
+
return Math.ceil(seconds * 1000 + 1000);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const codexResetAtMatch = errorText.match(
|
|
104
|
+
/["']?resets_at["']?\s*:\s*(?:["']([^"']+)["']|(\d{10,13}))/i,
|
|
105
|
+
);
|
|
106
|
+
if (codexResetAtMatch) {
|
|
107
|
+
const rawResetAt = codexResetAtMatch[1] ?? codexResetAtMatch[2];
|
|
108
|
+
const numericResetAt = Number(rawResetAt);
|
|
109
|
+
const resetAt = Number.isFinite(numericResetAt)
|
|
110
|
+
? numericResetAt < 1_000_000_000_000
|
|
111
|
+
? numericResetAt * 1000
|
|
112
|
+
: numericResetAt
|
|
113
|
+
: Date.parse(rawResetAt ?? "");
|
|
114
|
+
if (Number.isFinite(resetAt)) {
|
|
115
|
+
const delta = resetAt - Date.now();
|
|
116
|
+
if (delta > 0) return Math.ceil(delta + 1000);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
91
120
|
const quotaDelayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
|
|
92
121
|
if (quotaDelayMatch) {
|
|
93
122
|
const value = parseFloat(quotaDelayMatch[1]);
|