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
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [3.7.2] - 2026-09-16
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Cached token usage propagation**: Google Antigravity cached prompt usage is now preserved as OpenAI `prompt_tokens_details.cached_tokens` and Anthropic `cache_read_input_tokens` across the compatibility layer ([#34](https://github.com/tuxevil/tuxevil-rotator/pull/34) by [@toRolex](https://github.com/toRolex)).
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Native Gemini usage reporting**: Native `generateContent` responses now expose `cachedContentTokenCount` when Google reports cached prompt tokens.
|
|
14
|
+
- **OpenCode Zen Responses usage**: Cached input tokens now survive JSON and SSE translation through Chat and Responses compatibility paths, with regression coverage.
|
|
15
|
+
|
|
5
16
|
## [3.7.1] - 2026-09-12
|
|
6
17
|
|
|
7
18
|
### Added
|
package/README.md
CHANGED
|
@@ -53,6 +53,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
53
53
|
|
|
54
54
|
## Current Model Update
|
|
55
55
|
|
|
56
|
+
- **Cached Token Usage Propagation**: Google Antigravity cached prompt usage is preserved as `cachedContentTokenCount` for native Gemini responses and as cache-read details across OpenAI, Anthropic, and OpenCode Zen Responses compatibility routes. ([PR #34](https://github.com/tuxevil/tuxevil-rotator/pull/34) by [@toRolex](https://github.com/toRolex); follow-up compatibility fixes included in [v3.7.2](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.2))
|
|
56
57
|
- **OpenCode Zen catalog sync**: Added `big-pickle` and removed the retired `deepseek-v4-flash-free` and `hy3-free` entries; `muse-spark-1.3-contributor-free` is now routed through the Responses endpoint with full Chat, Responses, and Anthropic surface compatibility. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
57
58
|
- **Tier-first routing under concurrency**: Concurrent least-loaded account selection now enforces tier priority, and persisted lower-tier assignments are re-evaluated while idle. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
58
59
|
- **Codex kickstart lifecycle**: Unstarted Codex quota timers are kicked off on startup and stale kickstart responses are drained to avoid blocking subsequent requests. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
@@ -358,6 +359,7 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
358
359
|
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, effort-based model routing, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28), [PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32))
|
|
359
360
|
- **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
|
|
360
361
|
- **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
|
|
362
|
+
- **[@toRolex](https://github.com/toRolex)** (Rolex) — Added cached prompt-token extraction from Google Antigravity/Cloud Code usage and mapped it to OpenAI and Anthropic compatibility responses, with focused regression tests. ([PR #34](https://github.com/tuxevil/tuxevil-rotator/pull/34))
|
|
361
363
|
- **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, account-scoped dynamic Antigravity discovery and routing, dynamic catalog and quota-safety hardening, persistent dynamic model ownership across restarts, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, Ollama kickstart routing for multi-provider accounts, and OpenAI-compatible audio transcription plus bidirectional live WebSocket streaming through the local Antigravity observer model. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26), [PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29), [PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30), [PR #31](https://github.com/tuxevil/tuxevil-rotator/pull/31), [PR #33](https://github.com/tuxevil/tuxevil-rotator/pull/33))
|
|
362
364
|
|
|
363
365
|
## Development
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "3.7.
|
|
3
|
+
"version": "3.7.2",
|
|
4
4
|
"description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/src/compat.ts
CHANGED
|
@@ -15,6 +15,10 @@ import { logSpend } from "./spend-logger.js";
|
|
|
15
15
|
import { hashKey } from "./virtual-keys.js";
|
|
16
16
|
import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
|
|
17
17
|
import { logger, redactSensitive } from "./logger.js";
|
|
18
|
+
import {
|
|
19
|
+
createStreamIdleGuard,
|
|
20
|
+
waitForResponseDrain,
|
|
21
|
+
} from "./stream-guards.js";
|
|
18
22
|
import type { AccountRotator } from "./rotator.js";
|
|
19
23
|
import {
|
|
20
24
|
withRotation,
|
|
@@ -146,6 +150,11 @@ const compatLogger = logger.child("compat");
|
|
|
146
150
|
|
|
147
151
|
const VALIDATION_LOG_MAX_CHARS = 200;
|
|
148
152
|
|
|
153
|
+
export interface CompatStreamOptions {
|
|
154
|
+
idleTimeoutMs?: number;
|
|
155
|
+
backpressureTimeoutMs?: number;
|
|
156
|
+
}
|
|
157
|
+
|
|
149
158
|
export function logValidationFailure(scope: string, payload: unknown): void {
|
|
150
159
|
const truncated = redactSensitive(JSON.stringify(payload));
|
|
151
160
|
const clipped =
|
|
@@ -208,6 +217,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
208
217
|
let thinkingText = "";
|
|
209
218
|
let inputTokens = 0;
|
|
210
219
|
let outputTokens = 0;
|
|
220
|
+
let cachedTokens: number | undefined;
|
|
211
221
|
let responseId: string | undefined;
|
|
212
222
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
213
223
|
let toolCallIndex = 0;
|
|
@@ -225,6 +235,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
225
235
|
if (isRecord(parsed.usage)) {
|
|
226
236
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
227
237
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
238
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
239
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
240
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
241
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
242
|
+
}
|
|
228
243
|
}
|
|
229
244
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
230
245
|
const choice = parsed.choices[0];
|
|
@@ -276,6 +291,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
276
291
|
if (isRecord(parsed.usage)) {
|
|
277
292
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
278
293
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
294
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
295
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
296
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
297
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
298
|
+
}
|
|
279
299
|
}
|
|
280
300
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
281
301
|
const choice = parsed.choices[0];
|
|
@@ -314,6 +334,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
314
334
|
thinkingText,
|
|
315
335
|
inputTokens,
|
|
316
336
|
outputTokens,
|
|
337
|
+
cachedTokens,
|
|
317
338
|
responseId,
|
|
318
339
|
toolCalls: Array.from(toolCallsMap.values()),
|
|
319
340
|
};
|
|
@@ -324,6 +345,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
324
345
|
let thinkingText = "";
|
|
325
346
|
let inputTokens = 0;
|
|
326
347
|
let outputTokens = 0;
|
|
348
|
+
let cachedTokens: number | undefined;
|
|
327
349
|
let responseId: string | undefined;
|
|
328
350
|
let upstreamFinishReason: string | undefined;
|
|
329
351
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
@@ -395,6 +417,10 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
395
417
|
inputTokens = usage.promptTokenCount;
|
|
396
418
|
if (typeof usage.candidatesTokenCount === "number")
|
|
397
419
|
outputTokens = usage.candidatesTokenCount;
|
|
420
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
421
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
422
|
+
if (typeof usage.cached_tokens === "number")
|
|
423
|
+
cachedTokens = usage.cached_tokens;
|
|
398
424
|
if (typeof usage.input_tokens === "number")
|
|
399
425
|
inputTokens = usage.input_tokens;
|
|
400
426
|
if (typeof usage.output_tokens === "number")
|
|
@@ -445,6 +471,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
445
471
|
thinkingText: thinkingText || undefined,
|
|
446
472
|
inputTokens,
|
|
447
473
|
outputTokens,
|
|
474
|
+
cachedTokens,
|
|
448
475
|
responseId,
|
|
449
476
|
toolCalls,
|
|
450
477
|
finishReason: upstreamFinishReason,
|
|
@@ -592,7 +619,7 @@ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
|
|
592
619
|
}
|
|
593
620
|
}
|
|
594
621
|
|
|
595
|
-
async function streamCompatSse(
|
|
622
|
+
export async function streamCompatSse(
|
|
596
623
|
body: unknown,
|
|
597
624
|
req: IncomingMessage,
|
|
598
625
|
res: ServerResponse,
|
|
@@ -602,6 +629,7 @@ async function streamCompatSse(
|
|
|
602
629
|
rotator?: AccountRotator,
|
|
603
630
|
compressionStats?: CompressionStats | null,
|
|
604
631
|
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
632
|
+
options: CompatStreamOptions = {},
|
|
605
633
|
): Promise<CompatCompletion> {
|
|
606
634
|
const nodeStream = Readable.fromWeb(
|
|
607
635
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -609,6 +637,7 @@ async function streamCompatSse(
|
|
|
609
637
|
let text = "";
|
|
610
638
|
let inputTokens = 0;
|
|
611
639
|
let outputTokens = 0;
|
|
640
|
+
let cachedTokens: number | undefined;
|
|
612
641
|
const streamStartMs = Date.now();
|
|
613
642
|
let firstByteMs: number | undefined;
|
|
614
643
|
let responseId: string | undefined;
|
|
@@ -754,6 +783,11 @@ async function streamCompatSse(
|
|
|
754
783
|
if (isRecord(parsed.usage)) {
|
|
755
784
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
756
785
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
786
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
787
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
788
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
789
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
790
|
+
}
|
|
757
791
|
}
|
|
758
792
|
|
|
759
793
|
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
@@ -938,12 +972,17 @@ async function streamCompatSse(
|
|
|
938
972
|
};
|
|
939
973
|
req.once("close", closeUpstreamForClient);
|
|
940
974
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
975
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
976
|
+
streamError = error.message;
|
|
977
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
978
|
+
}, options.idleTimeoutMs);
|
|
941
979
|
|
|
942
980
|
try {
|
|
943
981
|
for await (const chunk of nodeStream) {
|
|
944
982
|
if (reqClosed) {
|
|
945
983
|
break;
|
|
946
984
|
}
|
|
985
|
+
idleGuard.reset();
|
|
947
986
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
948
987
|
const str = chunk.toString();
|
|
949
988
|
tailBuffer += str;
|
|
@@ -1105,6 +1144,10 @@ async function streamCompatSse(
|
|
|
1105
1144
|
inputTokens = usage.promptTokenCount;
|
|
1106
1145
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1107
1146
|
outputTokens = usage.candidatesTokenCount;
|
|
1147
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
1148
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
1149
|
+
if (typeof usage.cached_tokens === "number")
|
|
1150
|
+
cachedTokens = usage.cached_tokens;
|
|
1108
1151
|
if (typeof usage.input_tokens === "number")
|
|
1109
1152
|
inputTokens = usage.input_tokens;
|
|
1110
1153
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1114,15 +1157,18 @@ async function streamCompatSse(
|
|
|
1114
1157
|
// Ignore malformed JSON chunks
|
|
1115
1158
|
}
|
|
1116
1159
|
}
|
|
1160
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1117
1161
|
}
|
|
1118
1162
|
} catch (err) {
|
|
1119
1163
|
if (!reqClosed) {
|
|
1120
|
-
streamError
|
|
1164
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1121
1165
|
compatLogger.warn(
|
|
1122
1166
|
`Stream read error: ${streamError}`,
|
|
1123
1167
|
);
|
|
1168
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1124
1169
|
}
|
|
1125
1170
|
} finally {
|
|
1171
|
+
idleGuard.clear();
|
|
1126
1172
|
req.off("close", closeUpstreamForClient);
|
|
1127
1173
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1128
1174
|
}
|
|
@@ -1145,7 +1191,21 @@ async function streamCompatSse(
|
|
|
1145
1191
|
// Emit a usage chunk so agents (hermes, openwebui, etc.) can display token statistics
|
|
1146
1192
|
if (inputTokens > 0 || outputTokens > 0) {
|
|
1147
1193
|
res.write(
|
|
1148
|
-
`data: ${JSON.stringify({
|
|
1194
|
+
`data: ${JSON.stringify({
|
|
1195
|
+
id,
|
|
1196
|
+
object: "chat.completion.chunk",
|
|
1197
|
+
created,
|
|
1198
|
+
model,
|
|
1199
|
+
choices: [],
|
|
1200
|
+
usage: {
|
|
1201
|
+
prompt_tokens: inputTokens,
|
|
1202
|
+
completion_tokens: outputTokens,
|
|
1203
|
+
total_tokens: inputTokens + outputTokens,
|
|
1204
|
+
...(cachedTokens !== undefined
|
|
1205
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
1206
|
+
: {}),
|
|
1207
|
+
},
|
|
1208
|
+
})}\n\n`,
|
|
1149
1209
|
);
|
|
1150
1210
|
}
|
|
1151
1211
|
res.write("data: [DONE]\n\n");
|
|
@@ -1170,7 +1230,17 @@ async function streamCompatSse(
|
|
|
1170
1230
|
: "end_turn";
|
|
1171
1231
|
// message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
|
|
1172
1232
|
res.write(
|
|
1173
|
-
`event: message_delta\ndata: ${JSON.stringify({
|
|
1233
|
+
`event: message_delta\ndata: ${JSON.stringify({
|
|
1234
|
+
type: "message_delta",
|
|
1235
|
+
delta: { stop_reason: anthropicStopReason, stop_sequence: null },
|
|
1236
|
+
usage: {
|
|
1237
|
+
input_tokens: inputTokens,
|
|
1238
|
+
output_tokens: outputTokens,
|
|
1239
|
+
...(cachedTokens !== undefined
|
|
1240
|
+
? { cache_read_input_tokens: cachedTokens }
|
|
1241
|
+
: {}),
|
|
1242
|
+
},
|
|
1243
|
+
})}\n\n`,
|
|
1174
1244
|
);
|
|
1175
1245
|
res.write(
|
|
1176
1246
|
`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
|
|
@@ -1214,6 +1284,9 @@ async function streamCompatSse(
|
|
|
1214
1284
|
prompt_tokens: inputTokens,
|
|
1215
1285
|
completion_tokens: outputTokens,
|
|
1216
1286
|
total_tokens: inputTokens + outputTokens,
|
|
1287
|
+
...(cachedTokens !== undefined
|
|
1288
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
1289
|
+
: {}),
|
|
1217
1290
|
},
|
|
1218
1291
|
}
|
|
1219
1292
|
: {
|
|
@@ -1237,13 +1310,20 @@ async function streamCompatSse(
|
|
|
1237
1310
|
: upstreamFinishReason === "MAX_TOKENS"
|
|
1238
1311
|
? "max_tokens"
|
|
1239
1312
|
: "end_turn",
|
|
1240
|
-
usage: {
|
|
1313
|
+
usage: {
|
|
1314
|
+
input_tokens: inputTokens,
|
|
1315
|
+
output_tokens: outputTokens,
|
|
1316
|
+
...(cachedTokens !== undefined
|
|
1317
|
+
? { cache_read_input_tokens: cachedTokens }
|
|
1318
|
+
: {}),
|
|
1319
|
+
},
|
|
1241
1320
|
};
|
|
1242
1321
|
|
|
1243
1322
|
return {
|
|
1244
1323
|
text,
|
|
1245
1324
|
inputTokens,
|
|
1246
1325
|
outputTokens,
|
|
1326
|
+
cachedTokens,
|
|
1247
1327
|
firstByteMs,
|
|
1248
1328
|
responseId,
|
|
1249
1329
|
toolCalls: collectedToolCalls,
|
|
@@ -1253,7 +1333,7 @@ async function streamCompatSse(
|
|
|
1253
1333
|
};
|
|
1254
1334
|
}
|
|
1255
1335
|
|
|
1256
|
-
async function streamResponsesSse(
|
|
1336
|
+
export async function streamResponsesSse(
|
|
1257
1337
|
body: unknown,
|
|
1258
1338
|
req: IncomingMessage,
|
|
1259
1339
|
res: ServerResponse,
|
|
@@ -1265,6 +1345,7 @@ async function streamResponsesSse(
|
|
|
1265
1345
|
rotator?: AccountRotator,
|
|
1266
1346
|
compressionStats?: CompressionStats | null,
|
|
1267
1347
|
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
1348
|
+
options: CompatStreamOptions = {},
|
|
1268
1349
|
): Promise<CompatCompletion> {
|
|
1269
1350
|
const nodeStream = Readable.fromWeb(
|
|
1270
1351
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -1273,6 +1354,7 @@ async function streamResponsesSse(
|
|
|
1273
1354
|
let thinkingText = "";
|
|
1274
1355
|
let inputTokens = 0;
|
|
1275
1356
|
let outputTokens = 0;
|
|
1357
|
+
let cachedTokens: number | undefined;
|
|
1276
1358
|
const streamStartMs = Date.now();
|
|
1277
1359
|
let firstByteMs: number | undefined;
|
|
1278
1360
|
const toolCalls: OpenAIToolCall[] = [];
|
|
@@ -1296,6 +1378,10 @@ async function streamResponsesSse(
|
|
|
1296
1378
|
};
|
|
1297
1379
|
req.once("close", closeUpstreamForClient);
|
|
1298
1380
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
1381
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
1382
|
+
streamError = error.message;
|
|
1383
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
1384
|
+
}, options.idleTimeoutMs);
|
|
1299
1385
|
|
|
1300
1386
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
1301
1387
|
accountLabel: context?.label,
|
|
@@ -1402,6 +1488,19 @@ async function streamResponsesSse(
|
|
|
1402
1488
|
if (typeof usage.completion_tokens === "number") outputTokens = usage.completion_tokens;
|
|
1403
1489
|
if (typeof usage.input_tokens === "number") inputTokens = usage.input_tokens;
|
|
1404
1490
|
if (typeof usage.output_tokens === "number") outputTokens = usage.output_tokens;
|
|
1491
|
+
if (
|
|
1492
|
+
isRecord(usage.input_tokens_details) &&
|
|
1493
|
+
typeof usage.input_tokens_details.cached_tokens === "number"
|
|
1494
|
+
) {
|
|
1495
|
+
cachedTokens = usage.input_tokens_details.cached_tokens;
|
|
1496
|
+
} else if (
|
|
1497
|
+
isRecord(usage.prompt_tokens_details) &&
|
|
1498
|
+
typeof usage.prompt_tokens_details.cached_tokens === "number"
|
|
1499
|
+
) {
|
|
1500
|
+
cachedTokens = usage.prompt_tokens_details.cached_tokens;
|
|
1501
|
+
} else if (typeof usage.cached_tokens === "number") {
|
|
1502
|
+
cachedTokens = usage.cached_tokens;
|
|
1503
|
+
}
|
|
1405
1504
|
}
|
|
1406
1505
|
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
1407
1506
|
const choice = parsed.choices[0];
|
|
@@ -1660,6 +1759,7 @@ async function streamResponsesSse(
|
|
|
1660
1759
|
if (reqClosed) {
|
|
1661
1760
|
break;
|
|
1662
1761
|
}
|
|
1762
|
+
idleGuard.reset();
|
|
1663
1763
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
1664
1764
|
tailBuffer += chunk.toString();
|
|
1665
1765
|
let newlineIdx;
|
|
@@ -1849,6 +1949,10 @@ async function streamResponsesSse(
|
|
|
1849
1949
|
inputTokens = usage.promptTokenCount;
|
|
1850
1950
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1851
1951
|
outputTokens = usage.candidatesTokenCount;
|
|
1952
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
1953
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
1954
|
+
if (typeof usage.cached_tokens === "number")
|
|
1955
|
+
cachedTokens = usage.cached_tokens;
|
|
1852
1956
|
if (typeof usage.input_tokens === "number")
|
|
1853
1957
|
inputTokens = usage.input_tokens;
|
|
1854
1958
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1858,15 +1962,18 @@ async function streamResponsesSse(
|
|
|
1858
1962
|
// Ignore malformed JSON chunks
|
|
1859
1963
|
}
|
|
1860
1964
|
}
|
|
1965
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1861
1966
|
}
|
|
1862
1967
|
} catch (err) {
|
|
1863
1968
|
if (!reqClosed) {
|
|
1864
|
-
streamError
|
|
1969
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1865
1970
|
compatLogger.warn(
|
|
1866
1971
|
`Responses stream read error: ${streamError}`,
|
|
1867
1972
|
);
|
|
1973
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1868
1974
|
}
|
|
1869
1975
|
} finally {
|
|
1976
|
+
idleGuard.clear();
|
|
1870
1977
|
req.off("close", closeUpstreamForClient);
|
|
1871
1978
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1872
1979
|
}
|
|
@@ -1876,6 +1983,7 @@ async function streamResponsesSse(
|
|
|
1876
1983
|
thinkingText: thinkingText || undefined,
|
|
1877
1984
|
inputTokens,
|
|
1878
1985
|
outputTokens,
|
|
1986
|
+
cachedTokens,
|
|
1879
1987
|
firstByteMs,
|
|
1880
1988
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
1881
1989
|
streamError,
|
|
@@ -1889,6 +1997,9 @@ async function streamResponsesSse(
|
|
|
1889
1997
|
prompt_tokens: inputTokens,
|
|
1890
1998
|
completion_tokens: outputTokens,
|
|
1891
1999
|
total_tokens: inputTokens + outputTokens,
|
|
2000
|
+
...(cachedTokens !== undefined
|
|
2001
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
2002
|
+
: {}),
|
|
1892
2003
|
},
|
|
1893
2004
|
},
|
|
1894
2005
|
};
|
|
@@ -2726,6 +2837,9 @@ export async function handleGeminiGenerateContent(
|
|
|
2726
2837
|
candidatesTokenCount: result.completion.outputTokens,
|
|
2727
2838
|
totalTokenCount:
|
|
2728
2839
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
2840
|
+
...(result.completion.cachedTokens !== undefined
|
|
2841
|
+
? { cachedContentTokenCount: result.completion.cachedTokens }
|
|
2842
|
+
: {}),
|
|
2729
2843
|
},
|
|
2730
2844
|
}, rotatorHeaders);
|
|
2731
2845
|
}
|
|
@@ -2879,6 +2993,9 @@ export async function handleOpenAIChatCompletions(
|
|
|
2879
2993
|
completion_tokens: result.completion.outputTokens,
|
|
2880
2994
|
total_tokens:
|
|
2881
2995
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
2996
|
+
...(result.completion.cachedTokens !== undefined
|
|
2997
|
+
? { prompt_tokens_details: { cached_tokens: result.completion.cachedTokens } }
|
|
2998
|
+
: {}),
|
|
2882
2999
|
},
|
|
2883
3000
|
}, rotatorHeaders);
|
|
2884
3001
|
}
|
|
@@ -3299,6 +3416,9 @@ export async function handleAnthropicMessages(
|
|
|
3299
3416
|
usage: {
|
|
3300
3417
|
input_tokens: result.completion.inputTokens,
|
|
3301
3418
|
output_tokens: result.completion.outputTokens,
|
|
3419
|
+
...(result.completion.cachedTokens !== undefined
|
|
3420
|
+
? { cache_read_input_tokens: result.completion.cachedTokens }
|
|
3421
|
+
: {}),
|
|
3302
3422
|
},
|
|
3303
3423
|
}, rotatorHeaders);
|
|
3304
3424
|
}
|
package/src/fetch-with-retry.ts
CHANGED
|
@@ -15,6 +15,23 @@ export interface FetchWithRetryOptions extends RequestInit {
|
|
|
15
15
|
export type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
|
|
16
16
|
|
|
17
17
|
export const DEFAULT_RETRY_STATUSES = [408, 429, 500, 502, 503, 504] as const;
|
|
18
|
+
export const DEFAULT_HEADERS_TIMEOUT_MS = 30_000;
|
|
19
|
+
|
|
20
|
+
/** Raised when an upstream accepts a request but never sends response headers. */
|
|
21
|
+
export class UpstreamHeadersTimeoutError extends Error {
|
|
22
|
+
readonly code = "UND_ERR_HEADERS_TIMEOUT";
|
|
23
|
+
|
|
24
|
+
constructor(timeoutMs: number) {
|
|
25
|
+
super(`upstream response headers timeout after ${timeoutMs}ms`);
|
|
26
|
+
this.name = "UpstreamHeadersTimeoutError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface FetchWithHeadersTimeoutOptions extends RequestInit {
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
fetchImpl?: typeof fetch;
|
|
33
|
+
dispatcher?: Dispatcher;
|
|
34
|
+
}
|
|
18
35
|
|
|
19
36
|
export function isRetryableStatus(status: number, retryStatuses: readonly number[] = DEFAULT_RETRY_STATUSES): boolean {
|
|
20
37
|
return retryStatuses.includes(status);
|
|
@@ -22,6 +39,7 @@ export function isRetryableStatus(status: number, retryStatuses: readonly number
|
|
|
22
39
|
|
|
23
40
|
export function isRetryableFetchError(error: unknown): boolean {
|
|
24
41
|
if (error instanceof DOMException && error.name === "AbortError") return true;
|
|
42
|
+
if (error instanceof UpstreamHeadersTimeoutError) return true;
|
|
25
43
|
return error instanceof TypeError;
|
|
26
44
|
}
|
|
27
45
|
|
|
@@ -47,6 +65,59 @@ function createTimeoutSignal(timeoutMs: number | undefined, inputSignal: AbortSi
|
|
|
47
65
|
return AbortSignal.any([inputSignal, timeoutSignal]);
|
|
48
66
|
}
|
|
49
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Fetch a response while bounding only the time spent waiting for its headers.
|
|
70
|
+
* Once headers arrive, the caller owns the response body and its stream-level
|
|
71
|
+
* idle/backpressure guards continue to apply.
|
|
72
|
+
*/
|
|
73
|
+
export async function fetchWithHeadersTimeout(
|
|
74
|
+
input: RequestInfo | URL,
|
|
75
|
+
options: FetchWithHeadersTimeoutOptions = {},
|
|
76
|
+
): Promise<Response> {
|
|
77
|
+
const {
|
|
78
|
+
timeoutMs = DEFAULT_HEADERS_TIMEOUT_MS,
|
|
79
|
+
fetchImpl = fetch,
|
|
80
|
+
dispatcher,
|
|
81
|
+
signal: inputSignal,
|
|
82
|
+
...init
|
|
83
|
+
} = options;
|
|
84
|
+
|
|
85
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
86
|
+
return fetchImpl(input, {
|
|
87
|
+
...init,
|
|
88
|
+
dispatcher,
|
|
89
|
+
signal: inputSignal,
|
|
90
|
+
} as RequestInitWithDispatcher);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const timeoutController = new AbortController();
|
|
94
|
+
let timedOut = false;
|
|
95
|
+
const timeout = setTimeout(() => {
|
|
96
|
+
timedOut = true;
|
|
97
|
+
timeoutController.abort();
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
const requestSignal = inputSignal
|
|
100
|
+
? AbortSignal.any([inputSignal, timeoutController.signal])
|
|
101
|
+
: timeoutController.signal;
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
return await fetchImpl(input, {
|
|
105
|
+
...init,
|
|
106
|
+
dispatcher,
|
|
107
|
+
signal: requestSignal,
|
|
108
|
+
} as RequestInitWithDispatcher);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
// A client cancellation must retain its original error and must not cause
|
|
111
|
+
// the rotator to retry work the client no longer wants.
|
|
112
|
+
if (timedOut && !inputSignal?.aborted) {
|
|
113
|
+
throw new UpstreamHeadersTimeoutError(timeoutMs);
|
|
114
|
+
}
|
|
115
|
+
throw error;
|
|
116
|
+
} finally {
|
|
117
|
+
clearTimeout(timeout);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
50
121
|
/**
|
|
51
122
|
* Fetch wrapper for non-streaming calls. Retries only transport failures and explicit retryable statuses.
|
|
52
123
|
* Do not use for streaming responses: retrying streams can duplicate upstream work.
|
package/src/providers/adapter.ts
CHANGED
|
@@ -15,7 +15,10 @@ import { logger } from "../../logger.js";
|
|
|
15
15
|
import type { TokenUsage } from "../adapter.js";
|
|
16
16
|
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
17
17
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
18
|
-
import
|
|
18
|
+
import {
|
|
19
|
+
fetchWithHeadersTimeout,
|
|
20
|
+
type RequestInitWithDispatcher,
|
|
21
|
+
} from "../../fetch-with-retry.js";
|
|
19
22
|
|
|
20
23
|
const forwardLogger = logger.child("google-forward");
|
|
21
24
|
|
|
@@ -53,8 +56,18 @@ function findUsageInJson(
|
|
|
53
56
|
: typeof usageMetadata.outputTokenCount === "number"
|
|
54
57
|
? usageMetadata.outputTokenCount
|
|
55
58
|
: 0;
|
|
59
|
+
const cached =
|
|
60
|
+
typeof usageMetadata.cachedContentTokenCount === "number"
|
|
61
|
+
? usageMetadata.cachedContentTokenCount
|
|
62
|
+
: typeof usageMetadata.cached_tokens === "number"
|
|
63
|
+
? usageMetadata.cached_tokens
|
|
64
|
+
: undefined;
|
|
56
65
|
if (input > 0 || output > 0)
|
|
57
|
-
return {
|
|
66
|
+
return {
|
|
67
|
+
inputTokens: input,
|
|
68
|
+
outputTokens: output,
|
|
69
|
+
...(cached !== undefined ? { cachedTokens: cached } : {}),
|
|
70
|
+
};
|
|
58
71
|
}
|
|
59
72
|
// OpenAI / Anthropic format
|
|
60
73
|
const usage = value.usage;
|
|
@@ -71,8 +84,21 @@ function findUsageInJson(
|
|
|
71
84
|
: typeof usage.output_tokens === "number"
|
|
72
85
|
? usage.output_tokens
|
|
73
86
|
: 0;
|
|
87
|
+
const cached =
|
|
88
|
+
isRecord(usage.prompt_tokens_details) &&
|
|
89
|
+
typeof usage.prompt_tokens_details.cached_tokens === "number"
|
|
90
|
+
? usage.prompt_tokens_details.cached_tokens
|
|
91
|
+
: typeof usage.cached_tokens === "number"
|
|
92
|
+
? usage.cached_tokens
|
|
93
|
+
: typeof usage.cache_read_input_tokens === "number"
|
|
94
|
+
? usage.cache_read_input_tokens
|
|
95
|
+
: undefined;
|
|
74
96
|
if (input > 0 || output > 0)
|
|
75
|
-
return {
|
|
97
|
+
return {
|
|
98
|
+
inputTokens: input,
|
|
99
|
+
outputTokens: output,
|
|
100
|
+
...(cached !== undefined ? { cachedTokens: cached } : {}),
|
|
101
|
+
};
|
|
76
102
|
}
|
|
77
103
|
// Recurse into common nesting locations.
|
|
78
104
|
for (const key of ["candidates", "output", "response", "message"]) {
|
|
@@ -381,7 +407,7 @@ export async function forwardRequest(
|
|
|
381
407
|
? AbortSignal.any([controller.signal, signal])
|
|
382
408
|
: signal ?? controller?.signal;
|
|
383
409
|
|
|
384
|
-
const response = await
|
|
410
|
+
const response = await fetchWithHeadersTimeout(url, {
|
|
385
411
|
method: "POST",
|
|
386
412
|
headers: forwardHeaders,
|
|
387
413
|
body: requestBody,
|
|
@@ -178,6 +178,7 @@ export interface CompatCompletion {
|
|
|
178
178
|
thinkingText?: string; // Gemini thought blocks (thought: true), emitted as reasoning_content
|
|
179
179
|
inputTokens: number;
|
|
180
180
|
outputTokens: number;
|
|
181
|
+
cachedTokens?: number;
|
|
181
182
|
firstByteMs?: number;
|
|
182
183
|
responseId?: string;
|
|
183
184
|
toolCalls?: OpenAIToolCall[];
|
|
@@ -1683,7 +1684,7 @@ export function responseUsageFromCompletion(
|
|
|
1683
1684
|
): Record<string, unknown> {
|
|
1684
1685
|
return {
|
|
1685
1686
|
input_tokens: completion.inputTokens,
|
|
1686
|
-
input_tokens_details: { cached_tokens: 0 },
|
|
1687
|
+
input_tokens_details: { cached_tokens: completion.cachedTokens ?? 0 },
|
|
1687
1688
|
output_tokens: completion.outputTokens,
|
|
1688
1689
|
output_tokens_details: { reasoning_tokens: 0 },
|
|
1689
1690
|
total_tokens: completion.inputTokens + completion.outputTokens,
|
|
@@ -18,7 +18,10 @@ import {
|
|
|
18
18
|
} from "../google-antigravity/translators.js";
|
|
19
19
|
import type { StreamAccumulator, TokenUsage } from "../adapter.js";
|
|
20
20
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
21
|
-
import
|
|
21
|
+
import {
|
|
22
|
+
fetchWithHeadersTimeout,
|
|
23
|
+
type RequestInitWithDispatcher,
|
|
24
|
+
} from "../../fetch-with-retry.js";
|
|
22
25
|
|
|
23
26
|
const OLLAMA_BENCHMARK_MODEL = "gpt-oss:20b";
|
|
24
27
|
|
|
@@ -146,7 +149,7 @@ export async function forwardRequest(
|
|
|
146
149
|
delete forwardHeaders["content-length"];
|
|
147
150
|
|
|
148
151
|
const endpoint = OLLAMA_CHAT_ENDPOINTS[0] || "https://ollama.com/api/chat";
|
|
149
|
-
const response = await
|
|
152
|
+
const response = await fetchWithHeadersTimeout(endpoint, {
|
|
150
153
|
method: "POST",
|
|
151
154
|
headers: forwardHeaders,
|
|
152
155
|
body: requestBody,
|