tuxevil-rotator 3.7.0 → 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 +26 -0
- package/README.md +8 -3
- package/package.json +1 -1
- package/src/compat.ts +342 -15
- package/src/fetch-with-retry.ts +71 -0
- package/src/providers/adapter.ts +10 -0
- package/src/providers/credential-helpers.ts +12 -1
- 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/ollama/index.ts +5 -3
- package/src/providers/ollama/quota-poll-store.ts +14 -6
- package/src/providers/ollama/quota.ts +31 -5
- package/src/providers/openai-codex/compat.ts +62 -7
- package/src/providers/openai-codex/forward.ts +53 -2
- package/src/providers/openai-codex/index.ts +26 -2
- package/src/providers/openai-codex/quota.ts +32 -6
- package/src/providers/opencode-zen/catalog.ts +15 -4
- package/src/providers/opencode-zen/forward.ts +739 -16
- package/src/providers/opencode-zen/quota.ts +1 -1
- package/src/providers/registry.ts +2 -0
- package/src/proxy.ts +40 -5
- package/src/rate-limit-parser.ts +29 -0
- package/src/rotator.ts +216 -71
- package/src/static/dashboard.css +1 -0
- package/src/static/dashboard.js +14 -15
- package/src/stream-guards.ts +85 -0
- package/src/telemetry.ts +1 -1
- package/src/types.ts +21 -23
- package/tools/telemetry-receiver/receiver.js +12 -11
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,
|
|
@@ -73,7 +77,11 @@ import {
|
|
|
73
77
|
anthropicToOllamaBody,
|
|
74
78
|
parseOllamaNdjson,
|
|
75
79
|
} from "./providers/ollama/translators.js";
|
|
76
|
-
import {
|
|
80
|
+
import {
|
|
81
|
+
OPENCODE_ZEN_CATALOG,
|
|
82
|
+
isOpenCodeZenModel,
|
|
83
|
+
isOpenCodeZenResponsesModel,
|
|
84
|
+
} from "./providers/opencode-zen/catalog.js";
|
|
77
85
|
import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
|
|
78
86
|
import type {
|
|
79
87
|
ChatMessage,
|
|
@@ -142,6 +150,11 @@ const compatLogger = logger.child("compat");
|
|
|
142
150
|
|
|
143
151
|
const VALIDATION_LOG_MAX_CHARS = 200;
|
|
144
152
|
|
|
153
|
+
export interface CompatStreamOptions {
|
|
154
|
+
idleTimeoutMs?: number;
|
|
155
|
+
backpressureTimeoutMs?: number;
|
|
156
|
+
}
|
|
157
|
+
|
|
145
158
|
export function logValidationFailure(scope: string, payload: unknown): void {
|
|
146
159
|
const truncated = redactSensitive(JSON.stringify(payload));
|
|
147
160
|
const clipped =
|
|
@@ -204,6 +217,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
204
217
|
let thinkingText = "";
|
|
205
218
|
let inputTokens = 0;
|
|
206
219
|
let outputTokens = 0;
|
|
220
|
+
let cachedTokens: number | undefined;
|
|
207
221
|
let responseId: string | undefined;
|
|
208
222
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
209
223
|
let toolCallIndex = 0;
|
|
@@ -221,6 +235,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
221
235
|
if (isRecord(parsed.usage)) {
|
|
222
236
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
223
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
|
+
}
|
|
224
243
|
}
|
|
225
244
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
226
245
|
const choice = parsed.choices[0];
|
|
@@ -272,6 +291,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
272
291
|
if (isRecord(parsed.usage)) {
|
|
273
292
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
274
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
|
+
}
|
|
275
299
|
}
|
|
276
300
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
277
301
|
const choice = parsed.choices[0];
|
|
@@ -310,6 +334,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
310
334
|
thinkingText,
|
|
311
335
|
inputTokens,
|
|
312
336
|
outputTokens,
|
|
337
|
+
cachedTokens,
|
|
313
338
|
responseId,
|
|
314
339
|
toolCalls: Array.from(toolCallsMap.values()),
|
|
315
340
|
};
|
|
@@ -320,6 +345,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
320
345
|
let thinkingText = "";
|
|
321
346
|
let inputTokens = 0;
|
|
322
347
|
let outputTokens = 0;
|
|
348
|
+
let cachedTokens: number | undefined;
|
|
323
349
|
let responseId: string | undefined;
|
|
324
350
|
let upstreamFinishReason: string | undefined;
|
|
325
351
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
@@ -391,6 +417,10 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
391
417
|
inputTokens = usage.promptTokenCount;
|
|
392
418
|
if (typeof usage.candidatesTokenCount === "number")
|
|
393
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;
|
|
394
424
|
if (typeof usage.input_tokens === "number")
|
|
395
425
|
inputTokens = usage.input_tokens;
|
|
396
426
|
if (typeof usage.output_tokens === "number")
|
|
@@ -441,6 +471,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
441
471
|
thinkingText: thinkingText || undefined,
|
|
442
472
|
inputTokens,
|
|
443
473
|
outputTokens,
|
|
474
|
+
cachedTokens,
|
|
444
475
|
responseId,
|
|
445
476
|
toolCalls,
|
|
446
477
|
finishReason: upstreamFinishReason,
|
|
@@ -588,7 +619,7 @@ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
|
|
588
619
|
}
|
|
589
620
|
}
|
|
590
621
|
|
|
591
|
-
async function streamCompatSse(
|
|
622
|
+
export async function streamCompatSse(
|
|
592
623
|
body: unknown,
|
|
593
624
|
req: IncomingMessage,
|
|
594
625
|
res: ServerResponse,
|
|
@@ -598,6 +629,7 @@ async function streamCompatSse(
|
|
|
598
629
|
rotator?: AccountRotator,
|
|
599
630
|
compressionStats?: CompressionStats | null,
|
|
600
631
|
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
632
|
+
options: CompatStreamOptions = {},
|
|
601
633
|
): Promise<CompatCompletion> {
|
|
602
634
|
const nodeStream = Readable.fromWeb(
|
|
603
635
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -605,6 +637,7 @@ async function streamCompatSse(
|
|
|
605
637
|
let text = "";
|
|
606
638
|
let inputTokens = 0;
|
|
607
639
|
let outputTokens = 0;
|
|
640
|
+
let cachedTokens: number | undefined;
|
|
608
641
|
const streamStartMs = Date.now();
|
|
609
642
|
let firstByteMs: number | undefined;
|
|
610
643
|
let responseId: string | undefined;
|
|
@@ -750,6 +783,11 @@ async function streamCompatSse(
|
|
|
750
783
|
if (isRecord(parsed.usage)) {
|
|
751
784
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
752
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
|
+
}
|
|
753
791
|
}
|
|
754
792
|
|
|
755
793
|
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
@@ -934,12 +972,17 @@ async function streamCompatSse(
|
|
|
934
972
|
};
|
|
935
973
|
req.once("close", closeUpstreamForClient);
|
|
936
974
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
975
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
976
|
+
streamError = error.message;
|
|
977
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
978
|
+
}, options.idleTimeoutMs);
|
|
937
979
|
|
|
938
980
|
try {
|
|
939
981
|
for await (const chunk of nodeStream) {
|
|
940
982
|
if (reqClosed) {
|
|
941
983
|
break;
|
|
942
984
|
}
|
|
985
|
+
idleGuard.reset();
|
|
943
986
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
944
987
|
const str = chunk.toString();
|
|
945
988
|
tailBuffer += str;
|
|
@@ -1101,6 +1144,10 @@ async function streamCompatSse(
|
|
|
1101
1144
|
inputTokens = usage.promptTokenCount;
|
|
1102
1145
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1103
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;
|
|
1104
1151
|
if (typeof usage.input_tokens === "number")
|
|
1105
1152
|
inputTokens = usage.input_tokens;
|
|
1106
1153
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1110,15 +1157,18 @@ async function streamCompatSse(
|
|
|
1110
1157
|
// Ignore malformed JSON chunks
|
|
1111
1158
|
}
|
|
1112
1159
|
}
|
|
1160
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1113
1161
|
}
|
|
1114
1162
|
} catch (err) {
|
|
1115
1163
|
if (!reqClosed) {
|
|
1116
|
-
streamError
|
|
1164
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1117
1165
|
compatLogger.warn(
|
|
1118
1166
|
`Stream read error: ${streamError}`,
|
|
1119
1167
|
);
|
|
1168
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1120
1169
|
}
|
|
1121
1170
|
} finally {
|
|
1171
|
+
idleGuard.clear();
|
|
1122
1172
|
req.off("close", closeUpstreamForClient);
|
|
1123
1173
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1124
1174
|
}
|
|
@@ -1141,7 +1191,21 @@ async function streamCompatSse(
|
|
|
1141
1191
|
// Emit a usage chunk so agents (hermes, openwebui, etc.) can display token statistics
|
|
1142
1192
|
if (inputTokens > 0 || outputTokens > 0) {
|
|
1143
1193
|
res.write(
|
|
1144
|
-
`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`,
|
|
1145
1209
|
);
|
|
1146
1210
|
}
|
|
1147
1211
|
res.write("data: [DONE]\n\n");
|
|
@@ -1166,7 +1230,17 @@ async function streamCompatSse(
|
|
|
1166
1230
|
: "end_turn";
|
|
1167
1231
|
// message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
|
|
1168
1232
|
res.write(
|
|
1169
|
-
`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`,
|
|
1170
1244
|
);
|
|
1171
1245
|
res.write(
|
|
1172
1246
|
`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
|
|
@@ -1210,6 +1284,9 @@ async function streamCompatSse(
|
|
|
1210
1284
|
prompt_tokens: inputTokens,
|
|
1211
1285
|
completion_tokens: outputTokens,
|
|
1212
1286
|
total_tokens: inputTokens + outputTokens,
|
|
1287
|
+
...(cachedTokens !== undefined
|
|
1288
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
1289
|
+
: {}),
|
|
1213
1290
|
},
|
|
1214
1291
|
}
|
|
1215
1292
|
: {
|
|
@@ -1233,13 +1310,20 @@ async function streamCompatSse(
|
|
|
1233
1310
|
: upstreamFinishReason === "MAX_TOKENS"
|
|
1234
1311
|
? "max_tokens"
|
|
1235
1312
|
: "end_turn",
|
|
1236
|
-
usage: {
|
|
1313
|
+
usage: {
|
|
1314
|
+
input_tokens: inputTokens,
|
|
1315
|
+
output_tokens: outputTokens,
|
|
1316
|
+
...(cachedTokens !== undefined
|
|
1317
|
+
? { cache_read_input_tokens: cachedTokens }
|
|
1318
|
+
: {}),
|
|
1319
|
+
},
|
|
1237
1320
|
};
|
|
1238
1321
|
|
|
1239
1322
|
return {
|
|
1240
1323
|
text,
|
|
1241
1324
|
inputTokens,
|
|
1242
1325
|
outputTokens,
|
|
1326
|
+
cachedTokens,
|
|
1243
1327
|
firstByteMs,
|
|
1244
1328
|
responseId,
|
|
1245
1329
|
toolCalls: collectedToolCalls,
|
|
@@ -1249,7 +1333,7 @@ async function streamCompatSse(
|
|
|
1249
1333
|
};
|
|
1250
1334
|
}
|
|
1251
1335
|
|
|
1252
|
-
async function streamResponsesSse(
|
|
1336
|
+
export async function streamResponsesSse(
|
|
1253
1337
|
body: unknown,
|
|
1254
1338
|
req: IncomingMessage,
|
|
1255
1339
|
res: ServerResponse,
|
|
@@ -1260,7 +1344,8 @@ async function streamResponsesSse(
|
|
|
1260
1344
|
context?: RotationAttemptContext,
|
|
1261
1345
|
rotator?: AccountRotator,
|
|
1262
1346
|
compressionStats?: CompressionStats | null,
|
|
1263
|
-
upstream: "google" | "ollama" = "google",
|
|
1347
|
+
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
1348
|
+
options: CompatStreamOptions = {},
|
|
1264
1349
|
): Promise<CompatCompletion> {
|
|
1265
1350
|
const nodeStream = Readable.fromWeb(
|
|
1266
1351
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -1269,6 +1354,7 @@ async function streamResponsesSse(
|
|
|
1269
1354
|
let thinkingText = "";
|
|
1270
1355
|
let inputTokens = 0;
|
|
1271
1356
|
let outputTokens = 0;
|
|
1357
|
+
let cachedTokens: number | undefined;
|
|
1272
1358
|
const streamStartMs = Date.now();
|
|
1273
1359
|
let firstByteMs: number | undefined;
|
|
1274
1360
|
const toolCalls: OpenAIToolCall[] = [];
|
|
@@ -1281,6 +1367,7 @@ async function streamResponsesSse(
|
|
|
1281
1367
|
let reasoningDone = false;
|
|
1282
1368
|
let reqClosed = false;
|
|
1283
1369
|
let streamError: string | undefined;
|
|
1370
|
+
let upstreamFinishReason: string | undefined;
|
|
1284
1371
|
const closeUpstreamForClient = (): void => {
|
|
1285
1372
|
reqClosed = true;
|
|
1286
1373
|
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
@@ -1291,6 +1378,10 @@ async function streamResponsesSse(
|
|
|
1291
1378
|
};
|
|
1292
1379
|
req.once("close", closeUpstreamForClient);
|
|
1293
1380
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
1381
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
1382
|
+
streamError = error.message;
|
|
1383
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
1384
|
+
}, options.idleTimeoutMs);
|
|
1294
1385
|
|
|
1295
1386
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
1296
1387
|
accountLabel: context?.label,
|
|
@@ -1339,6 +1430,213 @@ async function streamResponsesSse(
|
|
|
1339
1430
|
),
|
|
1340
1431
|
});
|
|
1341
1432
|
|
|
1433
|
+
interface OpenCodeStreamingToolState {
|
|
1434
|
+
id: string;
|
|
1435
|
+
name: string;
|
|
1436
|
+
arguments: string;
|
|
1437
|
+
itemId: string;
|
|
1438
|
+
outputIndex: number;
|
|
1439
|
+
}
|
|
1440
|
+
const openCodeStreamingTools = new Map<number, OpenCodeStreamingToolState>();
|
|
1441
|
+
const closeReasoning = (): void => {
|
|
1442
|
+
if (reasoningOutputIndex === -1 || reasoningDone) return;
|
|
1443
|
+
reasoningDone = true;
|
|
1444
|
+
writeResponsesEvent(res, {
|
|
1445
|
+
type: "response.reasoning_summary_text.done",
|
|
1446
|
+
item_id: reasoningItemId,
|
|
1447
|
+
output_index: reasoningOutputIndex,
|
|
1448
|
+
summary_index: 0,
|
|
1449
|
+
text: thinkingText,
|
|
1450
|
+
});
|
|
1451
|
+
writeResponsesEvent(res, {
|
|
1452
|
+
type: "response.output_item.done",
|
|
1453
|
+
output_index: reasoningOutputIndex,
|
|
1454
|
+
item: {
|
|
1455
|
+
id: reasoningItemId,
|
|
1456
|
+
type: "reasoning",
|
|
1457
|
+
status: "completed",
|
|
1458
|
+
summary: [{ type: "summary_text", text: thinkingText }],
|
|
1459
|
+
},
|
|
1460
|
+
});
|
|
1461
|
+
};
|
|
1462
|
+
const ensureMessage = (): void => {
|
|
1463
|
+
if (messageOutputIndex !== -1) return;
|
|
1464
|
+
messageOutputIndex = nextOutputIndex++;
|
|
1465
|
+
messageItemId = makeCompatId("msg");
|
|
1466
|
+
writeResponsesEvent(res, {
|
|
1467
|
+
type: "response.output_item.added",
|
|
1468
|
+
output_index: messageOutputIndex,
|
|
1469
|
+
item: {
|
|
1470
|
+
id: messageItemId,
|
|
1471
|
+
type: "message",
|
|
1472
|
+
status: "in_progress",
|
|
1473
|
+
role: "assistant",
|
|
1474
|
+
content: [{ type: "output_text", text: "", annotations: [] }],
|
|
1475
|
+
},
|
|
1476
|
+
});
|
|
1477
|
+
};
|
|
1478
|
+
const emitOpenCodeZenLine = (line: string): void => {
|
|
1479
|
+
if (!line.startsWith("data:")) return;
|
|
1480
|
+
const payload = line.slice(5).trim();
|
|
1481
|
+
if (!payload || payload === "[DONE]") return;
|
|
1482
|
+
try {
|
|
1483
|
+
const parsed = JSON.parse(payload) as Record<string, unknown>;
|
|
1484
|
+
if (!isRecord(parsed)) return;
|
|
1485
|
+
const usage = isRecord(parsed.usage) ? parsed.usage : null;
|
|
1486
|
+
if (usage) {
|
|
1487
|
+
if (typeof usage.prompt_tokens === "number") inputTokens = usage.prompt_tokens;
|
|
1488
|
+
if (typeof usage.completion_tokens === "number") outputTokens = usage.completion_tokens;
|
|
1489
|
+
if (typeof usage.input_tokens === "number") inputTokens = usage.input_tokens;
|
|
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
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
1506
|
+
const choice = parsed.choices[0];
|
|
1507
|
+
if (!isRecord(choice)) return;
|
|
1508
|
+
if (typeof choice.finish_reason === "string" && choice.finish_reason) {
|
|
1509
|
+
upstreamFinishReason = choice.finish_reason;
|
|
1510
|
+
}
|
|
1511
|
+
const delta = isRecord(choice.delta) ? choice.delta : {};
|
|
1512
|
+
const reasoningDelta = typeof delta.reasoning_content === "string"
|
|
1513
|
+
? delta.reasoning_content
|
|
1514
|
+
: "";
|
|
1515
|
+
if (reasoningDelta) {
|
|
1516
|
+
if (reasoningOutputIndex === -1) {
|
|
1517
|
+
reasoningOutputIndex = nextOutputIndex++;
|
|
1518
|
+
reasoningItemId = makeCompatId("rs");
|
|
1519
|
+
writeResponsesEvent(res, {
|
|
1520
|
+
type: "response.output_item.added",
|
|
1521
|
+
output_index: reasoningOutputIndex,
|
|
1522
|
+
item: {
|
|
1523
|
+
id: reasoningItemId,
|
|
1524
|
+
type: "reasoning",
|
|
1525
|
+
status: "in_progress",
|
|
1526
|
+
summary: [],
|
|
1527
|
+
},
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
thinkingText += reasoningDelta;
|
|
1531
|
+
writeResponsesEvent(res, {
|
|
1532
|
+
type: "response.reasoning_summary_text.delta",
|
|
1533
|
+
item_id: reasoningItemId,
|
|
1534
|
+
output_index: reasoningOutputIndex,
|
|
1535
|
+
summary_index: 0,
|
|
1536
|
+
delta: reasoningDelta,
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
const contentDelta = typeof delta.content === "string" ? delta.content : "";
|
|
1541
|
+
if (contentDelta) {
|
|
1542
|
+
closeReasoning();
|
|
1543
|
+
ensureMessage();
|
|
1544
|
+
text += contentDelta;
|
|
1545
|
+
writeResponsesEvent(res, {
|
|
1546
|
+
type: "response.output_text.delta",
|
|
1547
|
+
item_id: messageItemId,
|
|
1548
|
+
output_index: messageOutputIndex,
|
|
1549
|
+
content_index: 0,
|
|
1550
|
+
delta: contentDelta,
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
1555
|
+
for (const rawToolCall of delta.tool_calls) {
|
|
1556
|
+
if (!isRecord(rawToolCall) || !isRecord(rawToolCall.function)) continue;
|
|
1557
|
+
const index = typeof rawToolCall.index === "number"
|
|
1558
|
+
? rawToolCall.index
|
|
1559
|
+
: openCodeStreamingTools.size;
|
|
1560
|
+
const fn = rawToolCall.function;
|
|
1561
|
+
const name = typeof fn.name === "string" && fn.name ? fn.name : "unknown";
|
|
1562
|
+
const args = typeof fn.arguments === "string" ? fn.arguments : "";
|
|
1563
|
+
let state = openCodeStreamingTools.get(index);
|
|
1564
|
+
if (!state) {
|
|
1565
|
+
closeReasoning();
|
|
1566
|
+
const id = typeof rawToolCall.id === "string" && rawToolCall.id
|
|
1567
|
+
? rawToolCall.id
|
|
1568
|
+
: `call_${Date.now().toString(36)}_${toolCallIndex++}`;
|
|
1569
|
+
state = {
|
|
1570
|
+
id,
|
|
1571
|
+
name,
|
|
1572
|
+
arguments: "",
|
|
1573
|
+
itemId: makeCompatId("fc"),
|
|
1574
|
+
outputIndex: nextOutputIndex++,
|
|
1575
|
+
};
|
|
1576
|
+
openCodeStreamingTools.set(index, state);
|
|
1577
|
+
toolCalls.push({
|
|
1578
|
+
id,
|
|
1579
|
+
type: "function",
|
|
1580
|
+
function: { name, arguments: "" },
|
|
1581
|
+
});
|
|
1582
|
+
writeResponsesEvent(res, {
|
|
1583
|
+
type: "response.output_item.added",
|
|
1584
|
+
output_index: state.outputIndex,
|
|
1585
|
+
item: {
|
|
1586
|
+
id: state.itemId,
|
|
1587
|
+
type: "function_call",
|
|
1588
|
+
status: "in_progress",
|
|
1589
|
+
call_id: state.id,
|
|
1590
|
+
name: state.name,
|
|
1591
|
+
arguments: "",
|
|
1592
|
+
},
|
|
1593
|
+
});
|
|
1594
|
+
} else if (name !== "unknown") {
|
|
1595
|
+
state.name = name;
|
|
1596
|
+
const call = toolCalls.find((candidate) => candidate.id === state?.id);
|
|
1597
|
+
if (call) call.function.name = name;
|
|
1598
|
+
}
|
|
1599
|
+
if (args) {
|
|
1600
|
+
state.arguments += args;
|
|
1601
|
+
const call = toolCalls.find((candidate) => candidate.id === state?.id);
|
|
1602
|
+
if (call) call.function.arguments = state.arguments;
|
|
1603
|
+
writeResponsesEvent(res, {
|
|
1604
|
+
type: "response.function_call_arguments.delta",
|
|
1605
|
+
item_id: state.itemId,
|
|
1606
|
+
output_index: state.outputIndex,
|
|
1607
|
+
delta: args,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
} catch {
|
|
1613
|
+
// Ignore malformed compatibility chunks; the normal stream finaliser
|
|
1614
|
+
// still returns a valid Responses envelope when possible.
|
|
1615
|
+
}
|
|
1616
|
+
};
|
|
1617
|
+
const closeOpenCodeTools = (): void => {
|
|
1618
|
+
for (const state of openCodeStreamingTools.values()) {
|
|
1619
|
+
writeResponsesEvent(res, {
|
|
1620
|
+
type: "response.function_call_arguments.done",
|
|
1621
|
+
item_id: state.itemId,
|
|
1622
|
+
output_index: state.outputIndex,
|
|
1623
|
+
arguments: state.arguments,
|
|
1624
|
+
});
|
|
1625
|
+
writeResponsesEvent(res, {
|
|
1626
|
+
type: "response.output_item.done",
|
|
1627
|
+
output_index: state.outputIndex,
|
|
1628
|
+
item: {
|
|
1629
|
+
id: state.itemId,
|
|
1630
|
+
type: "function_call",
|
|
1631
|
+
status: "completed",
|
|
1632
|
+
call_id: state.id,
|
|
1633
|
+
name: state.name,
|
|
1634
|
+
arguments: state.arguments,
|
|
1635
|
+
},
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
};
|
|
1639
|
+
|
|
1342
1640
|
let tailBuffer = "";
|
|
1343
1641
|
const emitOllamaLine = (line: string): void => {
|
|
1344
1642
|
try {
|
|
@@ -1461,6 +1759,7 @@ async function streamResponsesSse(
|
|
|
1461
1759
|
if (reqClosed) {
|
|
1462
1760
|
break;
|
|
1463
1761
|
}
|
|
1762
|
+
idleGuard.reset();
|
|
1464
1763
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
1465
1764
|
tailBuffer += chunk.toString();
|
|
1466
1765
|
let newlineIdx;
|
|
@@ -1471,6 +1770,10 @@ async function streamResponsesSse(
|
|
|
1471
1770
|
if (line) emitOllamaLine(line);
|
|
1472
1771
|
continue;
|
|
1473
1772
|
}
|
|
1773
|
+
if (upstream === "opencode-zen") {
|
|
1774
|
+
emitOpenCodeZenLine(line);
|
|
1775
|
+
continue;
|
|
1776
|
+
}
|
|
1474
1777
|
if (!line.startsWith("data:")) continue;
|
|
1475
1778
|
const payload = line.slice(5).trim();
|
|
1476
1779
|
if (!payload || payload === "[DONE]") continue;
|
|
@@ -1646,6 +1949,10 @@ async function streamResponsesSse(
|
|
|
1646
1949
|
inputTokens = usage.promptTokenCount;
|
|
1647
1950
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1648
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;
|
|
1649
1956
|
if (typeof usage.input_tokens === "number")
|
|
1650
1957
|
inputTokens = usage.input_tokens;
|
|
1651
1958
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1655,15 +1962,18 @@ async function streamResponsesSse(
|
|
|
1655
1962
|
// Ignore malformed JSON chunks
|
|
1656
1963
|
}
|
|
1657
1964
|
}
|
|
1965
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1658
1966
|
}
|
|
1659
1967
|
} catch (err) {
|
|
1660
1968
|
if (!reqClosed) {
|
|
1661
|
-
streamError
|
|
1969
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1662
1970
|
compatLogger.warn(
|
|
1663
1971
|
`Responses stream read error: ${streamError}`,
|
|
1664
1972
|
);
|
|
1973
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1665
1974
|
}
|
|
1666
1975
|
} finally {
|
|
1976
|
+
idleGuard.clear();
|
|
1667
1977
|
req.off("close", closeUpstreamForClient);
|
|
1668
1978
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1669
1979
|
}
|
|
@@ -1673,9 +1983,11 @@ async function streamResponsesSse(
|
|
|
1673
1983
|
thinkingText: thinkingText || undefined,
|
|
1674
1984
|
inputTokens,
|
|
1675
1985
|
outputTokens,
|
|
1986
|
+
cachedTokens,
|
|
1676
1987
|
firstByteMs,
|
|
1677
1988
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
1678
1989
|
streamError,
|
|
1990
|
+
finishReason: upstreamFinishReason,
|
|
1679
1991
|
rawResponse: {
|
|
1680
1992
|
id: responseId,
|
|
1681
1993
|
object: "response",
|
|
@@ -1685,6 +1997,9 @@ async function streamResponsesSse(
|
|
|
1685
1997
|
prompt_tokens: inputTokens,
|
|
1686
1998
|
completion_tokens: outputTokens,
|
|
1687
1999
|
total_tokens: inputTokens + outputTokens,
|
|
2000
|
+
...(cachedTokens !== undefined
|
|
2001
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
2002
|
+
: {}),
|
|
1688
2003
|
},
|
|
1689
2004
|
},
|
|
1690
2005
|
};
|
|
@@ -1715,6 +2030,7 @@ async function streamResponsesSse(
|
|
|
1715
2030
|
},
|
|
1716
2031
|
});
|
|
1717
2032
|
}
|
|
2033
|
+
if (upstream === "opencode-zen") closeOpenCodeTools();
|
|
1718
2034
|
if (messageOutputIndex !== -1) {
|
|
1719
2035
|
writeResponsesEvent(res, {
|
|
1720
2036
|
type: "response.output_text.done",
|
|
@@ -1797,9 +2113,11 @@ async function completeResponsesViaRotator(
|
|
|
1797
2113
|
context,
|
|
1798
2114
|
rotator,
|
|
1799
2115
|
options?.compressionStats,
|
|
1800
|
-
(
|
|
1801
|
-
? "
|
|
1802
|
-
:
|
|
2116
|
+
isOpenCodeZenResponsesModel(body.model)
|
|
2117
|
+
? "opencode-zen"
|
|
2118
|
+
: (rotator?.getOllamaModels?.() ?? []).includes(body.model)
|
|
2119
|
+
? "ollama"
|
|
2120
|
+
: "google",
|
|
1803
2121
|
);
|
|
1804
2122
|
if (completion.inputTokens > 0 || completion.outputTokens > 0) {
|
|
1805
2123
|
rotator.recordTokenUsage(
|
|
@@ -2519,6 +2837,9 @@ export async function handleGeminiGenerateContent(
|
|
|
2519
2837
|
candidatesTokenCount: result.completion.outputTokens,
|
|
2520
2838
|
totalTokenCount:
|
|
2521
2839
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
2840
|
+
...(result.completion.cachedTokens !== undefined
|
|
2841
|
+
? { cachedContentTokenCount: result.completion.cachedTokens }
|
|
2842
|
+
: {}),
|
|
2522
2843
|
},
|
|
2523
2844
|
}, rotatorHeaders);
|
|
2524
2845
|
}
|
|
@@ -2584,7 +2905,7 @@ export async function handleOpenAIChatCompletions(
|
|
|
2584
2905
|
const started = Date.now();
|
|
2585
2906
|
const streamMode = validation.value.stream ? "openai" : "none";
|
|
2586
2907
|
const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model)
|
|
2587
|
-
? { project: "", model: chatReq.model, request: chatReq }
|
|
2908
|
+
? { project: "", model: chatReq.model, request: chatReq, requestType: "openai-chat" }
|
|
2588
2909
|
: (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq));
|
|
2589
2910
|
const result = await completeViaRotator(
|
|
2590
2911
|
req,
|
|
@@ -2672,6 +2993,9 @@ export async function handleOpenAIChatCompletions(
|
|
|
2672
2993
|
completion_tokens: result.completion.outputTokens,
|
|
2673
2994
|
total_tokens:
|
|
2674
2995
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
2996
|
+
...(result.completion.cachedTokens !== undefined
|
|
2997
|
+
? { prompt_tokens_details: { cached_tokens: result.completion.cachedTokens } }
|
|
2998
|
+
: {}),
|
|
2675
2999
|
},
|
|
2676
3000
|
}, rotatorHeaders);
|
|
2677
3001
|
}
|
|
@@ -2749,7 +3073,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
2749
3073
|
: converted.chatRequest;
|
|
2750
3074
|
|
|
2751
3075
|
const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model)
|
|
2752
|
-
? { project: "", model: chatRequest.model, request: chatRequest }
|
|
3076
|
+
? { project: "", model: chatRequest.model, request: chatRequest, requestType: "openai-responses" }
|
|
2753
3077
|
: (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
|
|
2754
3078
|
requestBody.requestId = responseId;
|
|
2755
3079
|
|
|
@@ -3003,7 +3327,7 @@ export async function handleAnthropicMessages(
|
|
|
3003
3327
|
const started = Date.now();
|
|
3004
3328
|
const streamMode = validation.value.stream ? "anthropic" : "none";
|
|
3005
3329
|
const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model)
|
|
3006
|
-
? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq) }
|
|
3330
|
+
? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq), requestType: "anthropic" }
|
|
3007
3331
|
: (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq));
|
|
3008
3332
|
const result = await completeViaRotator(
|
|
3009
3333
|
req,
|
|
@@ -3092,6 +3416,9 @@ export async function handleAnthropicMessages(
|
|
|
3092
3416
|
usage: {
|
|
3093
3417
|
input_tokens: result.completion.inputTokens,
|
|
3094
3418
|
output_tokens: result.completion.outputTokens,
|
|
3419
|
+
...(result.completion.cachedTokens !== undefined
|
|
3420
|
+
? { cache_read_input_tokens: result.completion.cachedTokens }
|
|
3421
|
+
: {}),
|
|
3095
3422
|
},
|
|
3096
3423
|
}, rotatorHeaders);
|
|
3097
3424
|
}
|