tuxevil-rotator 3.7.1 → 3.8.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/CHANGELOG.md +21 -0
- package/README.md +4 -0
- package/package.json +2 -1
- package/src/auto-routing.ts +370 -0
- package/src/compat.ts +419 -51
- package/src/config-defaults.ts +13 -0
- package/src/dashboard.ts +2 -2
- package/src/db-store.ts +9 -3
- package/src/fetch-with-retry.ts +71 -0
- package/src/key-auth.ts +15 -15
- package/src/onboarding.ts +174 -2
- package/src/providers/adapter.ts +1 -0
- package/src/providers/google-antigravity/forward.ts +38 -5
- package/src/providers/google-antigravity/translators.ts +2 -1
- package/src/providers/ollama/forward.ts +5 -2
- package/src/providers/openai-codex/compat.ts +95 -12
- package/src/providers/openai-codex/forward.ts +5 -2
- package/src/providers/opencode-zen/forward.ts +36 -4
- package/src/providers/registry.ts +12 -1
- package/src/proxy.ts +138 -24
- package/src/rate-limit-parser.ts +29 -0
- package/src/response-headers.ts +21 -0
- package/src/rotator.ts +233 -62
- package/src/stream-guards.ts +85 -0
- package/src/token-encryption.ts +91 -0
- package/src/types.ts +23 -0
- package/src/validators.ts +38 -0
package/src/compat.ts
CHANGED
|
@@ -10,11 +10,19 @@ import {
|
|
|
10
10
|
type CompressionStats,
|
|
11
11
|
} from "./compression/index.js";
|
|
12
12
|
import { idempotencyManager } from "./idempotency.js";
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
authenticateVirtualKey,
|
|
15
|
+
isVirtualKeyModelAllowed,
|
|
16
|
+
sendAuthErrorResponse,
|
|
17
|
+
} from "./key-auth.js";
|
|
14
18
|
import { logSpend } from "./spend-logger.js";
|
|
15
19
|
import { hashKey } from "./virtual-keys.js";
|
|
16
20
|
import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
|
|
17
21
|
import { logger, redactSensitive } from "./logger.js";
|
|
22
|
+
import {
|
|
23
|
+
createStreamIdleGuard,
|
|
24
|
+
waitForResponseDrain,
|
|
25
|
+
} from "./stream-guards.js";
|
|
18
26
|
import type { AccountRotator } from "./rotator.js";
|
|
19
27
|
import {
|
|
20
28
|
withRotation,
|
|
@@ -96,6 +104,11 @@ import {
|
|
|
96
104
|
getCodexModels,
|
|
97
105
|
} from "./providers/openai-codex/catalog.js";
|
|
98
106
|
import { serveCodexChat, serveCodexResponses } from "./providers/openai-codex/compat.js";
|
|
107
|
+
import {
|
|
108
|
+
selectAutoRoutingTarget,
|
|
109
|
+
type AutoRoutingCatalogEntry,
|
|
110
|
+
type AutoRoutingRoute,
|
|
111
|
+
} from "./auto-routing.js";
|
|
99
112
|
|
|
100
113
|
function isCodexModelForRotator(rotator: AccountRotator, model: string): boolean {
|
|
101
114
|
if (isCodexRequestModel(model)) return true;
|
|
@@ -107,6 +120,109 @@ function isCodexModelForRotator(rotator: AccountRotator, model: string): boolean
|
|
|
107
120
|
}
|
|
108
121
|
}
|
|
109
122
|
|
|
123
|
+
function isAutoModel(model: string): boolean {
|
|
124
|
+
return model.trim().toLowerCase() === "auto";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function authorizeResolvedAutoModel(
|
|
128
|
+
res: ServerResponse,
|
|
129
|
+
auth: Awaited<ReturnType<typeof authenticateVirtualKey>>,
|
|
130
|
+
model: string,
|
|
131
|
+
): boolean {
|
|
132
|
+
if (isVirtualKeyModelAllowed(auth.key, model)) return true;
|
|
133
|
+
sendAuthErrorResponse(res, {
|
|
134
|
+
authenticated: false,
|
|
135
|
+
key: auth.key,
|
|
136
|
+
rawKey: auth.rawKey,
|
|
137
|
+
error: `Model '${model}' is not allowed for this Virtual Key`,
|
|
138
|
+
statusCode: 403,
|
|
139
|
+
});
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function buildAutoRoutingCatalog(
|
|
144
|
+
rotator: AccountRotator,
|
|
145
|
+
route: AutoRoutingRoute,
|
|
146
|
+
): AutoRoutingCatalogEntry[] {
|
|
147
|
+
const catalog: AutoRoutingCatalogEntry[] = getEffectiveAntigravityModels()
|
|
148
|
+
.filter((model) => !["whisper-1", "proactive-observer", "proactive-observer-v10", "models/proactive-observer-v10"].includes(model.id.toLowerCase()))
|
|
149
|
+
.map((model) => ({
|
|
150
|
+
providerId: "google-antigravity",
|
|
151
|
+
modelId: model.id,
|
|
152
|
+
contextWindow: model.ctx,
|
|
153
|
+
multimodal: model.multimodal,
|
|
154
|
+
tools: model.tools,
|
|
155
|
+
reasoning: model.isThinking,
|
|
156
|
+
family: model.family,
|
|
157
|
+
}));
|
|
158
|
+
if (route === "gemini") return catalog;
|
|
159
|
+
|
|
160
|
+
const codexCatalog = new Map(getCodexModels().map((model) => [model.id, model]));
|
|
161
|
+
for (const modelId of route === "anthropic" ? [] : rotator.getCodexModels?.() ?? []) {
|
|
162
|
+
const model = codexCatalog.get(modelId);
|
|
163
|
+
catalog.push({
|
|
164
|
+
providerId: "openai-codex",
|
|
165
|
+
modelId,
|
|
166
|
+
contextWindow: model?.contextWindow ?? 1_050_000,
|
|
167
|
+
multimodal: model?.multimodal ?? true,
|
|
168
|
+
tools: model?.tools ?? true,
|
|
169
|
+
reasoning: model?.reasoning ?? true,
|
|
170
|
+
family: "openai-codex",
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
for (const modelId of rotator.getOllamaModels?.() ?? []) {
|
|
174
|
+
catalog.push({
|
|
175
|
+
providerId: "ollama",
|
|
176
|
+
modelId,
|
|
177
|
+
contextWindow: 128_000,
|
|
178
|
+
multimodal: false,
|
|
179
|
+
tools: true,
|
|
180
|
+
reasoning: false,
|
|
181
|
+
responses: true,
|
|
182
|
+
family: "ollama-cloud",
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
for (const model of OPENCODE_ZEN_CATALOG) {
|
|
186
|
+
catalog.push({
|
|
187
|
+
providerId: OPENCODE_ZEN_PROVIDER_ID,
|
|
188
|
+
modelId: model.id,
|
|
189
|
+
contextWindow: model.contextWindow,
|
|
190
|
+
multimodal: false,
|
|
191
|
+
tools: true,
|
|
192
|
+
reasoning: false,
|
|
193
|
+
responses: isOpenCodeZenResponsesModel(model.id),
|
|
194
|
+
family: "opencode-zen",
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return catalog;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function resolveAutoModel(
|
|
201
|
+
rotator: AccountRotator,
|
|
202
|
+
route: AutoRoutingRoute,
|
|
203
|
+
input: unknown,
|
|
204
|
+
): Promise<{
|
|
205
|
+
model: string;
|
|
206
|
+
providerId: string;
|
|
207
|
+
mode: "typesafe" | "deterministic";
|
|
208
|
+
confidence?: number;
|
|
209
|
+
reason: string;
|
|
210
|
+
} | null> {
|
|
211
|
+
const selection = await selectAutoRoutingTarget(
|
|
212
|
+
rotator,
|
|
213
|
+
buildAutoRoutingCatalog(rotator, route),
|
|
214
|
+
{ route, input, requestedModel: "auto" },
|
|
215
|
+
);
|
|
216
|
+
if (!selection) return null;
|
|
217
|
+
return {
|
|
218
|
+
model: selection.candidate.modelId,
|
|
219
|
+
providerId: selection.candidate.providerId,
|
|
220
|
+
mode: selection.mode,
|
|
221
|
+
confidence: selection.confidence,
|
|
222
|
+
reason: selection.reason,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
110
226
|
export {
|
|
111
227
|
isRecord,
|
|
112
228
|
sanitizeGeminiSchema,
|
|
@@ -146,6 +262,11 @@ const compatLogger = logger.child("compat");
|
|
|
146
262
|
|
|
147
263
|
const VALIDATION_LOG_MAX_CHARS = 200;
|
|
148
264
|
|
|
265
|
+
export interface CompatStreamOptions {
|
|
266
|
+
idleTimeoutMs?: number;
|
|
267
|
+
backpressureTimeoutMs?: number;
|
|
268
|
+
}
|
|
269
|
+
|
|
149
270
|
export function logValidationFailure(scope: string, payload: unknown): void {
|
|
150
271
|
const truncated = redactSensitive(JSON.stringify(payload));
|
|
151
272
|
const clipped =
|
|
@@ -208,6 +329,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
208
329
|
let thinkingText = "";
|
|
209
330
|
let inputTokens = 0;
|
|
210
331
|
let outputTokens = 0;
|
|
332
|
+
let cachedTokens: number | undefined;
|
|
211
333
|
let responseId: string | undefined;
|
|
212
334
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
213
335
|
let toolCallIndex = 0;
|
|
@@ -225,6 +347,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
225
347
|
if (isRecord(parsed.usage)) {
|
|
226
348
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
227
349
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
350
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
351
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
352
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
353
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
354
|
+
}
|
|
228
355
|
}
|
|
229
356
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
230
357
|
const choice = parsed.choices[0];
|
|
@@ -276,6 +403,11 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
276
403
|
if (isRecord(parsed.usage)) {
|
|
277
404
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
278
405
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
406
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
407
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
408
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
409
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
410
|
+
}
|
|
279
411
|
}
|
|
280
412
|
if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
|
|
281
413
|
const choice = parsed.choices[0];
|
|
@@ -314,6 +446,7 @@ export function parseOpenAiJson(raw: string): CompatCompletion {
|
|
|
314
446
|
thinkingText,
|
|
315
447
|
inputTokens,
|
|
316
448
|
outputTokens,
|
|
449
|
+
cachedTokens,
|
|
317
450
|
responseId,
|
|
318
451
|
toolCalls: Array.from(toolCallsMap.values()),
|
|
319
452
|
};
|
|
@@ -324,6 +457,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
324
457
|
let thinkingText = "";
|
|
325
458
|
let inputTokens = 0;
|
|
326
459
|
let outputTokens = 0;
|
|
460
|
+
let cachedTokens: number | undefined;
|
|
327
461
|
let responseId: string | undefined;
|
|
328
462
|
let upstreamFinishReason: string | undefined;
|
|
329
463
|
const toolCallsMap = new Map<string, OpenAIToolCall>();
|
|
@@ -395,6 +529,10 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
395
529
|
inputTokens = usage.promptTokenCount;
|
|
396
530
|
if (typeof usage.candidatesTokenCount === "number")
|
|
397
531
|
outputTokens = usage.candidatesTokenCount;
|
|
532
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
533
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
534
|
+
if (typeof usage.cached_tokens === "number")
|
|
535
|
+
cachedTokens = usage.cached_tokens;
|
|
398
536
|
if (typeof usage.input_tokens === "number")
|
|
399
537
|
inputTokens = usage.input_tokens;
|
|
400
538
|
if (typeof usage.output_tokens === "number")
|
|
@@ -445,6 +583,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
|
|
|
445
583
|
thinkingText: thinkingText || undefined,
|
|
446
584
|
inputTokens,
|
|
447
585
|
outputTokens,
|
|
586
|
+
cachedTokens,
|
|
448
587
|
responseId,
|
|
449
588
|
toolCalls,
|
|
450
589
|
finishReason: upstreamFinishReason,
|
|
@@ -592,7 +731,7 @@ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
|
|
592
731
|
}
|
|
593
732
|
}
|
|
594
733
|
|
|
595
|
-
async function streamCompatSse(
|
|
734
|
+
export async function streamCompatSse(
|
|
596
735
|
body: unknown,
|
|
597
736
|
req: IncomingMessage,
|
|
598
737
|
res: ServerResponse,
|
|
@@ -602,6 +741,7 @@ async function streamCompatSse(
|
|
|
602
741
|
rotator?: AccountRotator,
|
|
603
742
|
compressionStats?: CompressionStats | null,
|
|
604
743
|
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
744
|
+
options: CompatStreamOptions = {},
|
|
605
745
|
): Promise<CompatCompletion> {
|
|
606
746
|
const nodeStream = Readable.fromWeb(
|
|
607
747
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -609,6 +749,7 @@ async function streamCompatSse(
|
|
|
609
749
|
let text = "";
|
|
610
750
|
let inputTokens = 0;
|
|
611
751
|
let outputTokens = 0;
|
|
752
|
+
let cachedTokens: number | undefined;
|
|
612
753
|
const streamStartMs = Date.now();
|
|
613
754
|
let firstByteMs: number | undefined;
|
|
614
755
|
let responseId: string | undefined;
|
|
@@ -629,6 +770,11 @@ async function streamCompatSse(
|
|
|
629
770
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
630
771
|
accountLabel: context?.label,
|
|
631
772
|
model,
|
|
773
|
+
requestedModel: context?.requestedModel,
|
|
774
|
+
selectedProvider: context?.providerId,
|
|
775
|
+
modelSelection: context?.selectionMode,
|
|
776
|
+
selectionConfidence: context?.selectionConfidence,
|
|
777
|
+
selectionReason: context?.selectionReason,
|
|
632
778
|
ttfbMs: Date.now() - (context?.requestStartMs ?? streamStartMs),
|
|
633
779
|
healthScore: context?.account?.healthScore,
|
|
634
780
|
routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
|
|
@@ -754,6 +900,11 @@ async function streamCompatSse(
|
|
|
754
900
|
if (isRecord(parsed.usage)) {
|
|
755
901
|
if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
|
|
756
902
|
if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
|
|
903
|
+
if (isRecord(parsed.usage.prompt_tokens_details) && typeof parsed.usage.prompt_tokens_details.cached_tokens === "number") {
|
|
904
|
+
cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
|
|
905
|
+
} else if (typeof parsed.usage.cached_tokens === "number") {
|
|
906
|
+
cachedTokens = parsed.usage.cached_tokens;
|
|
907
|
+
}
|
|
757
908
|
}
|
|
758
909
|
|
|
759
910
|
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
@@ -938,12 +1089,17 @@ async function streamCompatSse(
|
|
|
938
1089
|
};
|
|
939
1090
|
req.once("close", closeUpstreamForClient);
|
|
940
1091
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
1092
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
1093
|
+
streamError = error.message;
|
|
1094
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
1095
|
+
}, options.idleTimeoutMs);
|
|
941
1096
|
|
|
942
1097
|
try {
|
|
943
1098
|
for await (const chunk of nodeStream) {
|
|
944
1099
|
if (reqClosed) {
|
|
945
1100
|
break;
|
|
946
1101
|
}
|
|
1102
|
+
idleGuard.reset();
|
|
947
1103
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
948
1104
|
const str = chunk.toString();
|
|
949
1105
|
tailBuffer += str;
|
|
@@ -1105,6 +1261,10 @@ async function streamCompatSse(
|
|
|
1105
1261
|
inputTokens = usage.promptTokenCount;
|
|
1106
1262
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1107
1263
|
outputTokens = usage.candidatesTokenCount;
|
|
1264
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
1265
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
1266
|
+
if (typeof usage.cached_tokens === "number")
|
|
1267
|
+
cachedTokens = usage.cached_tokens;
|
|
1108
1268
|
if (typeof usage.input_tokens === "number")
|
|
1109
1269
|
inputTokens = usage.input_tokens;
|
|
1110
1270
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1114,15 +1274,18 @@ async function streamCompatSse(
|
|
|
1114
1274
|
// Ignore malformed JSON chunks
|
|
1115
1275
|
}
|
|
1116
1276
|
}
|
|
1277
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1117
1278
|
}
|
|
1118
1279
|
} catch (err) {
|
|
1119
1280
|
if (!reqClosed) {
|
|
1120
|
-
streamError
|
|
1281
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1121
1282
|
compatLogger.warn(
|
|
1122
1283
|
`Stream read error: ${streamError}`,
|
|
1123
1284
|
);
|
|
1285
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1124
1286
|
}
|
|
1125
1287
|
} finally {
|
|
1288
|
+
idleGuard.clear();
|
|
1126
1289
|
req.off("close", closeUpstreamForClient);
|
|
1127
1290
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1128
1291
|
}
|
|
@@ -1145,7 +1308,21 @@ async function streamCompatSse(
|
|
|
1145
1308
|
// Emit a usage chunk so agents (hermes, openwebui, etc.) can display token statistics
|
|
1146
1309
|
if (inputTokens > 0 || outputTokens > 0) {
|
|
1147
1310
|
res.write(
|
|
1148
|
-
`data: ${JSON.stringify({
|
|
1311
|
+
`data: ${JSON.stringify({
|
|
1312
|
+
id,
|
|
1313
|
+
object: "chat.completion.chunk",
|
|
1314
|
+
created,
|
|
1315
|
+
model,
|
|
1316
|
+
choices: [],
|
|
1317
|
+
usage: {
|
|
1318
|
+
prompt_tokens: inputTokens,
|
|
1319
|
+
completion_tokens: outputTokens,
|
|
1320
|
+
total_tokens: inputTokens + outputTokens,
|
|
1321
|
+
...(cachedTokens !== undefined
|
|
1322
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
1323
|
+
: {}),
|
|
1324
|
+
},
|
|
1325
|
+
})}\n\n`,
|
|
1149
1326
|
);
|
|
1150
1327
|
}
|
|
1151
1328
|
res.write("data: [DONE]\n\n");
|
|
@@ -1170,7 +1347,17 @@ async function streamCompatSse(
|
|
|
1170
1347
|
: "end_turn";
|
|
1171
1348
|
// message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
|
|
1172
1349
|
res.write(
|
|
1173
|
-
`event: message_delta\ndata: ${JSON.stringify({
|
|
1350
|
+
`event: message_delta\ndata: ${JSON.stringify({
|
|
1351
|
+
type: "message_delta",
|
|
1352
|
+
delta: { stop_reason: anthropicStopReason, stop_sequence: null },
|
|
1353
|
+
usage: {
|
|
1354
|
+
input_tokens: inputTokens,
|
|
1355
|
+
output_tokens: outputTokens,
|
|
1356
|
+
...(cachedTokens !== undefined
|
|
1357
|
+
? { cache_read_input_tokens: cachedTokens }
|
|
1358
|
+
: {}),
|
|
1359
|
+
},
|
|
1360
|
+
})}\n\n`,
|
|
1174
1361
|
);
|
|
1175
1362
|
res.write(
|
|
1176
1363
|
`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
|
|
@@ -1214,6 +1401,9 @@ async function streamCompatSse(
|
|
|
1214
1401
|
prompt_tokens: inputTokens,
|
|
1215
1402
|
completion_tokens: outputTokens,
|
|
1216
1403
|
total_tokens: inputTokens + outputTokens,
|
|
1404
|
+
...(cachedTokens !== undefined
|
|
1405
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
1406
|
+
: {}),
|
|
1217
1407
|
},
|
|
1218
1408
|
}
|
|
1219
1409
|
: {
|
|
@@ -1237,13 +1427,20 @@ async function streamCompatSse(
|
|
|
1237
1427
|
: upstreamFinishReason === "MAX_TOKENS"
|
|
1238
1428
|
? "max_tokens"
|
|
1239
1429
|
: "end_turn",
|
|
1240
|
-
usage: {
|
|
1430
|
+
usage: {
|
|
1431
|
+
input_tokens: inputTokens,
|
|
1432
|
+
output_tokens: outputTokens,
|
|
1433
|
+
...(cachedTokens !== undefined
|
|
1434
|
+
? { cache_read_input_tokens: cachedTokens }
|
|
1435
|
+
: {}),
|
|
1436
|
+
},
|
|
1241
1437
|
};
|
|
1242
1438
|
|
|
1243
1439
|
return {
|
|
1244
1440
|
text,
|
|
1245
1441
|
inputTokens,
|
|
1246
1442
|
outputTokens,
|
|
1443
|
+
cachedTokens,
|
|
1247
1444
|
firstByteMs,
|
|
1248
1445
|
responseId,
|
|
1249
1446
|
toolCalls: collectedToolCalls,
|
|
@@ -1253,7 +1450,7 @@ async function streamCompatSse(
|
|
|
1253
1450
|
};
|
|
1254
1451
|
}
|
|
1255
1452
|
|
|
1256
|
-
async function streamResponsesSse(
|
|
1453
|
+
export async function streamResponsesSse(
|
|
1257
1454
|
body: unknown,
|
|
1258
1455
|
req: IncomingMessage,
|
|
1259
1456
|
res: ServerResponse,
|
|
@@ -1265,6 +1462,7 @@ async function streamResponsesSse(
|
|
|
1265
1462
|
rotator?: AccountRotator,
|
|
1266
1463
|
compressionStats?: CompressionStats | null,
|
|
1267
1464
|
upstream: "google" | "ollama" | "opencode-zen" = "google",
|
|
1465
|
+
options: CompatStreamOptions = {},
|
|
1268
1466
|
): Promise<CompatCompletion> {
|
|
1269
1467
|
const nodeStream = Readable.fromWeb(
|
|
1270
1468
|
body as import("node:stream/web").ReadableStream,
|
|
@@ -1273,6 +1471,7 @@ async function streamResponsesSse(
|
|
|
1273
1471
|
let thinkingText = "";
|
|
1274
1472
|
let inputTokens = 0;
|
|
1275
1473
|
let outputTokens = 0;
|
|
1474
|
+
let cachedTokens: number | undefined;
|
|
1276
1475
|
const streamStartMs = Date.now();
|
|
1277
1476
|
let firstByteMs: number | undefined;
|
|
1278
1477
|
const toolCalls: OpenAIToolCall[] = [];
|
|
@@ -1296,10 +1495,19 @@ async function streamResponsesSse(
|
|
|
1296
1495
|
};
|
|
1297
1496
|
req.once("close", closeUpstreamForClient);
|
|
1298
1497
|
responseEvents.once?.("close", closeUpstreamForClient);
|
|
1498
|
+
const idleGuard = createStreamIdleGuard((error) => {
|
|
1499
|
+
streamError = error.message;
|
|
1500
|
+
if (!nodeStream.destroyed) nodeStream.destroy(error);
|
|
1501
|
+
}, options.idleTimeoutMs);
|
|
1299
1502
|
|
|
1300
1503
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
1301
1504
|
accountLabel: context?.label,
|
|
1302
1505
|
model: request.model,
|
|
1506
|
+
requestedModel: context?.requestedModel,
|
|
1507
|
+
selectedProvider: context?.providerId,
|
|
1508
|
+
modelSelection: context?.selectionMode,
|
|
1509
|
+
selectionConfidence: context?.selectionConfidence,
|
|
1510
|
+
selectionReason: context?.selectionReason,
|
|
1303
1511
|
ttfbMs: Date.now() - (context?.requestStartMs ?? streamStartMs),
|
|
1304
1512
|
healthScore: context?.account?.healthScore,
|
|
1305
1513
|
routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
|
|
@@ -1402,6 +1610,19 @@ async function streamResponsesSse(
|
|
|
1402
1610
|
if (typeof usage.completion_tokens === "number") outputTokens = usage.completion_tokens;
|
|
1403
1611
|
if (typeof usage.input_tokens === "number") inputTokens = usage.input_tokens;
|
|
1404
1612
|
if (typeof usage.output_tokens === "number") outputTokens = usage.output_tokens;
|
|
1613
|
+
if (
|
|
1614
|
+
isRecord(usage.input_tokens_details) &&
|
|
1615
|
+
typeof usage.input_tokens_details.cached_tokens === "number"
|
|
1616
|
+
) {
|
|
1617
|
+
cachedTokens = usage.input_tokens_details.cached_tokens;
|
|
1618
|
+
} else if (
|
|
1619
|
+
isRecord(usage.prompt_tokens_details) &&
|
|
1620
|
+
typeof usage.prompt_tokens_details.cached_tokens === "number"
|
|
1621
|
+
) {
|
|
1622
|
+
cachedTokens = usage.prompt_tokens_details.cached_tokens;
|
|
1623
|
+
} else if (typeof usage.cached_tokens === "number") {
|
|
1624
|
+
cachedTokens = usage.cached_tokens;
|
|
1625
|
+
}
|
|
1405
1626
|
}
|
|
1406
1627
|
if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
|
|
1407
1628
|
const choice = parsed.choices[0];
|
|
@@ -1660,6 +1881,7 @@ async function streamResponsesSse(
|
|
|
1660
1881
|
if (reqClosed) {
|
|
1661
1882
|
break;
|
|
1662
1883
|
}
|
|
1884
|
+
idleGuard.reset();
|
|
1663
1885
|
if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
|
|
1664
1886
|
tailBuffer += chunk.toString();
|
|
1665
1887
|
let newlineIdx;
|
|
@@ -1849,6 +2071,10 @@ async function streamResponsesSse(
|
|
|
1849
2071
|
inputTokens = usage.promptTokenCount;
|
|
1850
2072
|
if (typeof usage.candidatesTokenCount === "number")
|
|
1851
2073
|
outputTokens = usage.candidatesTokenCount;
|
|
2074
|
+
if (typeof usage.cachedContentTokenCount === "number")
|
|
2075
|
+
cachedTokens = usage.cachedContentTokenCount;
|
|
2076
|
+
if (typeof usage.cached_tokens === "number")
|
|
2077
|
+
cachedTokens = usage.cached_tokens;
|
|
1852
2078
|
if (typeof usage.input_tokens === "number")
|
|
1853
2079
|
inputTokens = usage.input_tokens;
|
|
1854
2080
|
if (typeof usage.output_tokens === "number")
|
|
@@ -1858,15 +2084,18 @@ async function streamResponsesSse(
|
|
|
1858
2084
|
// Ignore malformed JSON chunks
|
|
1859
2085
|
}
|
|
1860
2086
|
}
|
|
2087
|
+
await waitForResponseDrain(res, options.backpressureTimeoutMs);
|
|
1861
2088
|
}
|
|
1862
2089
|
} catch (err) {
|
|
1863
2090
|
if (!reqClosed) {
|
|
1864
|
-
streamError
|
|
2091
|
+
streamError ??= redactSensitive(String(err)).slice(0, 200);
|
|
1865
2092
|
compatLogger.warn(
|
|
1866
2093
|
`Responses stream read error: ${streamError}`,
|
|
1867
2094
|
);
|
|
2095
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
1868
2096
|
}
|
|
1869
2097
|
} finally {
|
|
2098
|
+
idleGuard.clear();
|
|
1870
2099
|
req.off("close", closeUpstreamForClient);
|
|
1871
2100
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1872
2101
|
}
|
|
@@ -1876,6 +2105,7 @@ async function streamResponsesSse(
|
|
|
1876
2105
|
thinkingText: thinkingText || undefined,
|
|
1877
2106
|
inputTokens,
|
|
1878
2107
|
outputTokens,
|
|
2108
|
+
cachedTokens,
|
|
1879
2109
|
firstByteMs,
|
|
1880
2110
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
1881
2111
|
streamError,
|
|
@@ -1889,6 +2119,9 @@ async function streamResponsesSse(
|
|
|
1889
2119
|
prompt_tokens: inputTokens,
|
|
1890
2120
|
completion_tokens: outputTokens,
|
|
1891
2121
|
total_tokens: inputTokens + outputTokens,
|
|
2122
|
+
...(cachedTokens !== undefined
|
|
2123
|
+
? { prompt_tokens_details: { cached_tokens: cachedTokens } }
|
|
2124
|
+
: {}),
|
|
1892
2125
|
},
|
|
1893
2126
|
},
|
|
1894
2127
|
};
|
|
@@ -2002,9 +2235,9 @@ async function completeResponsesViaRotator(
|
|
|
2002
2235
|
context,
|
|
2003
2236
|
rotator,
|
|
2004
2237
|
options?.compressionStats,
|
|
2005
|
-
isOpenCodeZenResponsesModel(body.model)
|
|
2238
|
+
body.providerId === OPENCODE_ZEN_PROVIDER_ID || isOpenCodeZenResponsesModel(body.model)
|
|
2006
2239
|
? "opencode-zen"
|
|
2007
|
-
: (rotator?.getOllamaModels?.() ?? []).includes(body.model)
|
|
2240
|
+
: body.providerId === "ollama" || (rotator?.getOllamaModels?.() ?? []).includes(body.model)
|
|
2008
2241
|
? "ollama"
|
|
2009
2242
|
: "google",
|
|
2010
2243
|
);
|
|
@@ -2079,7 +2312,7 @@ async function completeViaRotator(
|
|
|
2079
2312
|
compressionStats?: CompressionStats | null;
|
|
2080
2313
|
}> {
|
|
2081
2314
|
const ollamaModels = rotator?.getOllamaModels?.() ?? [];
|
|
2082
|
-
const isOllamaUpstream = (model: string): boolean => ollamaModels.includes(model);
|
|
2315
|
+
const isOllamaUpstream = (model: string): boolean => body.providerId === "ollama" || ollamaModels.includes(model);
|
|
2083
2316
|
const cfg = typeof rotator?.getConfig === "function" ? rotator.getConfig() : undefined;
|
|
2084
2317
|
const enabled = cfg?.idempotencyEnabled === true;
|
|
2085
2318
|
const windowMs = cfg?.idempotencyWindowMs ?? 2000;
|
|
@@ -2099,7 +2332,7 @@ async function completeViaRotator(
|
|
|
2099
2332
|
async (response, context) => {
|
|
2100
2333
|
if (streamMode === "none") {
|
|
2101
2334
|
const raw = await response.text();
|
|
2102
|
-
const completion = isOpenCodeZenModel(body.model)
|
|
2335
|
+
const completion = body.providerId === OPENCODE_ZEN_PROVIDER_ID || isOpenCodeZenModel(body.model)
|
|
2103
2336
|
? parseOpenAiJson(raw)
|
|
2104
2337
|
: isOllamaUpstream(body.model)
|
|
2105
2338
|
? parseOllamaNdjson(raw)
|
|
@@ -2126,12 +2359,14 @@ async function completeViaRotator(
|
|
|
2126
2359
|
response.body,
|
|
2127
2360
|
req,
|
|
2128
2361
|
res,
|
|
2129
|
-
body.displayModel
|
|
2362
|
+
body.displayModel?.toLowerCase() === "auto"
|
|
2363
|
+
? body.model
|
|
2364
|
+
: body.displayModel || body.model,
|
|
2130
2365
|
streamMode,
|
|
2131
2366
|
context,
|
|
2132
2367
|
rotator,
|
|
2133
2368
|
options?.compressionStats,
|
|
2134
|
-
isOpenCodeZenModel(body.model)
|
|
2369
|
+
body.providerId === OPENCODE_ZEN_PROVIDER_ID || isOpenCodeZenModel(body.model)
|
|
2135
2370
|
? "opencode-zen"
|
|
2136
2371
|
: isOllamaUpstream(body.model)
|
|
2137
2372
|
? "ollama"
|
|
@@ -2657,16 +2892,37 @@ export async function handleGeminiGenerateContent(
|
|
|
2657
2892
|
error: { message: "Model path is required", status: "INVALID_ARGUMENT" },
|
|
2658
2893
|
});
|
|
2659
2894
|
|
|
2660
|
-
const
|
|
2895
|
+
const autoRequested = isAutoModel(model);
|
|
2896
|
+
const auth = await authenticateVirtualKey(req, autoRequested ? undefined : model);
|
|
2661
2897
|
if (!auth.authenticated) {
|
|
2662
2898
|
sendAuthErrorResponse(res, auth);
|
|
2663
2899
|
return;
|
|
2664
2900
|
}
|
|
2665
2901
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
2666
2902
|
|
|
2903
|
+
const autoSelection = autoRequested
|
|
2904
|
+
? await resolveAutoModel(rotator, "gemini", parsed)
|
|
2905
|
+
: null;
|
|
2906
|
+
if (autoRequested && !autoSelection) {
|
|
2907
|
+
return writeJson(res, 503, {
|
|
2908
|
+
error: { message: "No compatible model is currently available", status: "UNAVAILABLE" },
|
|
2909
|
+
});
|
|
2910
|
+
}
|
|
2911
|
+
if (autoSelection && !authorizeResolvedAutoModel(res, auth, autoSelection.model)) return;
|
|
2912
|
+
const selectedModel = autoSelection?.model ?? model;
|
|
2913
|
+
|
|
2667
2914
|
const body: RequestBody = {
|
|
2668
|
-
model,
|
|
2915
|
+
model: selectedModel,
|
|
2669
2916
|
project: "",
|
|
2917
|
+
...(autoRequested
|
|
2918
|
+
? {
|
|
2919
|
+
displayModel: model,
|
|
2920
|
+
providerId: autoSelection?.providerId,
|
|
2921
|
+
selectionMode: autoSelection?.mode,
|
|
2922
|
+
selectionConfidence: autoSelection?.confidence,
|
|
2923
|
+
selectionReason: autoSelection?.reason,
|
|
2924
|
+
}
|
|
2925
|
+
: {}),
|
|
2670
2926
|
request: {
|
|
2671
2927
|
contents: Array.isArray(parsed.contents) ? parsed.contents : [],
|
|
2672
2928
|
systemInstruction: parsed.systemInstruction,
|
|
@@ -2700,7 +2956,12 @@ export async function handleGeminiGenerateContent(
|
|
|
2700
2956
|
const ttfbMs = result.completion.firstByteMs ?? totalMs;
|
|
2701
2957
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
2702
2958
|
accountLabel: result.context?.label,
|
|
2703
|
-
model: model,
|
|
2959
|
+
model: autoRequested ? result.context?.selectedModel ?? selectedModel : model,
|
|
2960
|
+
requestedModel: result.context?.requestedModel,
|
|
2961
|
+
selectedProvider: result.context?.providerId,
|
|
2962
|
+
modelSelection: result.context?.selectionMode,
|
|
2963
|
+
selectionConfidence: result.context?.selectionConfidence,
|
|
2964
|
+
selectionReason: result.context?.selectionReason,
|
|
2704
2965
|
latencyMs: totalMs,
|
|
2705
2966
|
ttfbMs,
|
|
2706
2967
|
inputTokens: result.completion.inputTokens,
|
|
@@ -2726,6 +2987,9 @@ export async function handleGeminiGenerateContent(
|
|
|
2726
2987
|
candidatesTokenCount: result.completion.outputTokens,
|
|
2727
2988
|
totalTokenCount:
|
|
2728
2989
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
2990
|
+
...(result.completion.cachedTokens !== undefined
|
|
2991
|
+
? { cachedContentTokenCount: result.completion.cachedTokens }
|
|
2992
|
+
: {}),
|
|
2729
2993
|
},
|
|
2730
2994
|
}, rotatorHeaders);
|
|
2731
2995
|
}
|
|
@@ -2758,19 +3022,39 @@ export async function handleOpenAIChatCompletions(
|
|
|
2758
3022
|
},
|
|
2759
3023
|
});
|
|
2760
3024
|
|
|
2761
|
-
const
|
|
3025
|
+
const requestedModel = validation.value.model;
|
|
3026
|
+
const autoRequested = isAutoModel(requestedModel);
|
|
3027
|
+
const auth = await authenticateVirtualKey(req, autoRequested ? undefined : requestedModel);
|
|
2762
3028
|
if (!auth.authenticated) {
|
|
2763
3029
|
sendAuthErrorResponse(res, auth);
|
|
2764
3030
|
return;
|
|
2765
3031
|
}
|
|
2766
3032
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
2767
3033
|
|
|
2768
|
-
|
|
2769
|
-
await
|
|
3034
|
+
const autoSelection = autoRequested
|
|
3035
|
+
? await resolveAutoModel(rotator, "openai-chat", validation.value)
|
|
3036
|
+
: null;
|
|
3037
|
+
if (autoRequested && !autoSelection) {
|
|
3038
|
+
return writeJson(res, 503, {
|
|
3039
|
+
error: { message: "No compatible model is currently available", type: "upstream_error" },
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
if (autoSelection && !authorizeResolvedAutoModel(res, auth, autoSelection.model)) return;
|
|
3043
|
+
const routedRequest = autoSelection
|
|
3044
|
+
? { ...validation.value, model: autoSelection.model }
|
|
3045
|
+
: validation.value;
|
|
3046
|
+
|
|
3047
|
+
if (isCodexModelForRotator(rotator, routedRequest.model)) {
|
|
3048
|
+
await serveCodexChat(req, res, rotator, routedRequest, {
|
|
2770
3049
|
callType: "chat_completion",
|
|
2771
3050
|
apiKeyHash,
|
|
2772
3051
|
requesterIp: req.socket?.remoteAddress || null,
|
|
2773
3052
|
rawRequest: validation.value,
|
|
3053
|
+
providerId: autoSelection?.providerId,
|
|
3054
|
+
requestedModel: autoRequested ? requestedModel : undefined,
|
|
3055
|
+
selectionMode: autoSelection?.mode,
|
|
3056
|
+
selectionConfidence: autoSelection?.confidence,
|
|
3057
|
+
selectionReason: autoSelection?.reason,
|
|
2774
3058
|
});
|
|
2775
3059
|
return;
|
|
2776
3060
|
}
|
|
@@ -2780,19 +3064,28 @@ export async function handleOpenAIChatCompletions(
|
|
|
2780
3064
|
rotator?.getConfig?.()?.compressionMode,
|
|
2781
3065
|
);
|
|
2782
3066
|
const compRes = applyPromptCompression(
|
|
2783
|
-
|
|
3067
|
+
routedRequest.messages,
|
|
2784
3068
|
compMode,
|
|
2785
|
-
{ model:
|
|
3069
|
+
{ model: routedRequest.model },
|
|
2786
3070
|
);
|
|
2787
3071
|
const chatReq = compRes.stats
|
|
2788
|
-
? { ...
|
|
2789
|
-
:
|
|
3072
|
+
? { ...routedRequest, messages: compRes.messages }
|
|
3073
|
+
: routedRequest;
|
|
2790
3074
|
|
|
2791
3075
|
const started = Date.now();
|
|
2792
|
-
const streamMode =
|
|
2793
|
-
const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model)
|
|
3076
|
+
const streamMode = routedRequest.stream ? "openai" : "none";
|
|
3077
|
+
const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model) || autoSelection?.providerId === OPENCODE_ZEN_PROVIDER_ID
|
|
2794
3078
|
? { project: "", model: chatReq.model, request: chatReq, requestType: "openai-chat" }
|
|
2795
|
-
: (rotator?.getOllamaModels?.().includes(chatReq.model)
|
|
3079
|
+
: (autoSelection?.providerId === "ollama" || rotator?.getOllamaModels?.().includes(chatReq.model)
|
|
3080
|
+
? openAIToOllamaBody(chatReq)
|
|
3081
|
+
: openAIToAntigravityBody(chatReq));
|
|
3082
|
+
if (autoSelection) {
|
|
3083
|
+
bodyToForward.displayModel = requestedModel;
|
|
3084
|
+
bodyToForward.providerId = autoSelection.providerId;
|
|
3085
|
+
bodyToForward.selectionMode = autoSelection.mode;
|
|
3086
|
+
bodyToForward.selectionConfidence = autoSelection.confidence;
|
|
3087
|
+
bodyToForward.selectionReason = autoSelection.reason;
|
|
3088
|
+
}
|
|
2796
3089
|
const result = await completeViaRotator(
|
|
2797
3090
|
req,
|
|
2798
3091
|
res,
|
|
@@ -2838,7 +3131,12 @@ export async function handleOpenAIChatCompletions(
|
|
|
2838
3131
|
const ttfbMs = result.completion.firstByteMs ?? totalMs;
|
|
2839
3132
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
2840
3133
|
accountLabel: result.context?.label,
|
|
2841
|
-
model:
|
|
3134
|
+
model: autoRequested ? result.context?.selectedModel ?? routedRequest.model : requestedModel,
|
|
3135
|
+
requestedModel: result.context?.requestedModel,
|
|
3136
|
+
selectedProvider: result.context?.providerId,
|
|
3137
|
+
modelSelection: result.context?.selectionMode,
|
|
3138
|
+
selectionConfidence: result.context?.selectionConfidence,
|
|
3139
|
+
selectionReason: result.context?.selectionReason,
|
|
2842
3140
|
latencyMs: totalMs,
|
|
2843
3141
|
ttfbMs,
|
|
2844
3142
|
inputTokens: result.completion.inputTokens,
|
|
@@ -2852,7 +3150,7 @@ export async function handleOpenAIChatCompletions(
|
|
|
2852
3150
|
id: `chatcmpl-${started.toString(36)}`,
|
|
2853
3151
|
object: "chat.completion",
|
|
2854
3152
|
created: Math.floor(started / 1000),
|
|
2855
|
-
model:
|
|
3153
|
+
model: autoRequested ? result.context?.selectedModel ?? routedRequest.model : requestedModel,
|
|
2856
3154
|
choices: [
|
|
2857
3155
|
{
|
|
2858
3156
|
index: 0,
|
|
@@ -2879,6 +3177,9 @@ export async function handleOpenAIChatCompletions(
|
|
|
2879
3177
|
completion_tokens: result.completion.outputTokens,
|
|
2880
3178
|
total_tokens:
|
|
2881
3179
|
result.completion.inputTokens + result.completion.outputTokens,
|
|
3180
|
+
...(result.completion.cachedTokens !== undefined
|
|
3181
|
+
? { prompt_tokens_details: { cached_tokens: result.completion.cachedTokens } }
|
|
3182
|
+
: {}),
|
|
2882
3183
|
},
|
|
2883
3184
|
}, rotatorHeaders);
|
|
2884
3185
|
}
|
|
@@ -2911,26 +3212,46 @@ export async function handleOpenAIResponsesCreate(
|
|
|
2911
3212
|
},
|
|
2912
3213
|
});
|
|
2913
3214
|
|
|
2914
|
-
const
|
|
3215
|
+
const requestedModel = validation.value.model;
|
|
3216
|
+
const autoRequested = isAutoModel(requestedModel);
|
|
3217
|
+
const auth = await authenticateVirtualKey(req, autoRequested ? undefined : requestedModel);
|
|
2915
3218
|
if (!auth.authenticated) {
|
|
2916
3219
|
sendAuthErrorResponse(res, auth);
|
|
2917
3220
|
return;
|
|
2918
3221
|
}
|
|
2919
3222
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
2920
3223
|
|
|
2921
|
-
|
|
2922
|
-
await
|
|
3224
|
+
const autoSelection = autoRequested
|
|
3225
|
+
? await resolveAutoModel(rotator, "openai-responses", validation.value)
|
|
3226
|
+
: null;
|
|
3227
|
+
if (autoRequested && !autoSelection) {
|
|
3228
|
+
return writeJson(res, 503, {
|
|
3229
|
+
error: { message: "No compatible model is currently available", type: "upstream_error" },
|
|
3230
|
+
});
|
|
3231
|
+
}
|
|
3232
|
+
if (autoSelection && !authorizeResolvedAutoModel(res, auth, autoSelection.model)) return;
|
|
3233
|
+
const routedValidation = autoSelection
|
|
3234
|
+
? { ...validation.value, model: autoSelection.model }
|
|
3235
|
+
: validation.value;
|
|
3236
|
+
|
|
3237
|
+
if (isCodexModelForRotator(rotator, routedValidation.model)) {
|
|
3238
|
+
await serveCodexResponses(req, res, rotator, routedValidation, {
|
|
2923
3239
|
callType: "responses",
|
|
2924
3240
|
apiKeyHash,
|
|
2925
3241
|
requesterIp: req.socket?.remoteAddress || null,
|
|
2926
3242
|
rawRequest: validation.value,
|
|
3243
|
+
providerId: autoSelection?.providerId,
|
|
3244
|
+
requestedModel: autoRequested ? requestedModel : undefined,
|
|
3245
|
+
selectionMode: autoSelection?.mode,
|
|
3246
|
+
selectionConfidence: autoSelection?.confidence,
|
|
3247
|
+
selectionReason: autoSelection?.reason,
|
|
2927
3248
|
});
|
|
2928
3249
|
return;
|
|
2929
3250
|
}
|
|
2930
3251
|
|
|
2931
3252
|
let converted: ResponsesConversionResult;
|
|
2932
3253
|
try {
|
|
2933
|
-
converted = convertResponsesToChatRequest(
|
|
3254
|
+
converted = convertResponsesToChatRequest(routedValidation);
|
|
2934
3255
|
} catch {
|
|
2935
3256
|
return writeJson(res, 400, {
|
|
2936
3257
|
error: {
|
|
@@ -2955,16 +3276,25 @@ export async function handleOpenAIResponsesCreate(
|
|
|
2955
3276
|
? { ...converted.chatRequest, messages: compRes.messages }
|
|
2956
3277
|
: converted.chatRequest;
|
|
2957
3278
|
|
|
2958
|
-
const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model)
|
|
3279
|
+
const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model) || autoSelection?.providerId === OPENCODE_ZEN_PROVIDER_ID
|
|
2959
3280
|
? { project: "", model: chatRequest.model, request: chatRequest, requestType: "openai-responses" }
|
|
2960
|
-
: (rotator?.getOllamaModels?.().includes(chatRequest.model)
|
|
3281
|
+
: (autoSelection?.providerId === "ollama" || rotator?.getOllamaModels?.().includes(chatRequest.model)
|
|
3282
|
+
? openAIToOllamaBody(chatRequest)
|
|
3283
|
+
: openAIToAntigravityBody(chatRequest));
|
|
3284
|
+
if (autoSelection) {
|
|
3285
|
+
requestBody.displayModel = requestedModel;
|
|
3286
|
+
requestBody.providerId = autoSelection.providerId;
|
|
3287
|
+
requestBody.selectionMode = autoSelection.mode;
|
|
3288
|
+
requestBody.selectionConfidence = autoSelection.confidence;
|
|
3289
|
+
requestBody.selectionReason = autoSelection.reason;
|
|
3290
|
+
}
|
|
2961
3291
|
requestBody.requestId = responseId;
|
|
2962
3292
|
|
|
2963
3293
|
if (validation.value.store !== false) {
|
|
2964
3294
|
const expiresAt = Date.now() + 6 * 60 * 60 * 1000;
|
|
2965
3295
|
setStoredResponse(responseId, {
|
|
2966
3296
|
response: buildResponsesResponse(
|
|
2967
|
-
|
|
3297
|
+
routedValidation,
|
|
2968
3298
|
responseId,
|
|
2969
3299
|
createdAt,
|
|
2970
3300
|
{ text: "", inputTokens: 0, outputTokens: 0, toolCalls: [] },
|
|
@@ -2985,7 +3315,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
2985
3315
|
req,
|
|
2986
3316
|
res,
|
|
2987
3317
|
rotator,
|
|
2988
|
-
|
|
3318
|
+
routedValidation,
|
|
2989
3319
|
requestBody,
|
|
2990
3320
|
responseId,
|
|
2991
3321
|
converted.previousResponseId,
|
|
@@ -3009,7 +3339,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
3009
3339
|
}
|
|
3010
3340
|
if (validation.value.store !== false) {
|
|
3011
3341
|
const responseObject = buildResponsesResponse(
|
|
3012
|
-
|
|
3342
|
+
routedValidation,
|
|
3013
3343
|
responseId,
|
|
3014
3344
|
createdAt,
|
|
3015
3345
|
result.completion,
|
|
@@ -3051,7 +3381,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
3051
3381
|
}
|
|
3052
3382
|
|
|
3053
3383
|
const responseObject = buildResponsesResponse(
|
|
3054
|
-
|
|
3384
|
+
routedValidation,
|
|
3055
3385
|
responseId,
|
|
3056
3386
|
createdAt,
|
|
3057
3387
|
result.completion,
|
|
@@ -3072,7 +3402,12 @@ export async function handleOpenAIResponsesCreate(
|
|
|
3072
3402
|
const ttfbMs = result.completion.firstByteMs ?? totalMs;
|
|
3073
3403
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
3074
3404
|
accountLabel: result.context?.label,
|
|
3075
|
-
model:
|
|
3405
|
+
model: autoRequested ? result.context?.selectedModel ?? routedValidation.model : requestedModel,
|
|
3406
|
+
requestedModel: result.context?.requestedModel,
|
|
3407
|
+
selectedProvider: result.context?.providerId,
|
|
3408
|
+
modelSelection: result.context?.selectionMode,
|
|
3409
|
+
selectionConfidence: result.context?.selectionConfidence,
|
|
3410
|
+
selectionReason: result.context?.selectionReason,
|
|
3076
3411
|
latencyMs: totalMs,
|
|
3077
3412
|
ttfbMs,
|
|
3078
3413
|
inputTokens: result.completion.inputTokens,
|
|
@@ -3184,34 +3519,59 @@ export async function handleAnthropicMessages(
|
|
|
3184
3519
|
},
|
|
3185
3520
|
});
|
|
3186
3521
|
|
|
3187
|
-
const
|
|
3522
|
+
const requestedModel = validation.value.model;
|
|
3523
|
+
const autoRequested = isAutoModel(requestedModel);
|
|
3524
|
+
const auth = await authenticateVirtualKey(req, autoRequested ? undefined : requestedModel);
|
|
3188
3525
|
if (!auth.authenticated) {
|
|
3189
3526
|
sendAuthErrorResponse(res, auth);
|
|
3190
3527
|
return;
|
|
3191
3528
|
}
|
|
3192
3529
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
3193
3530
|
|
|
3531
|
+
const autoSelection = autoRequested
|
|
3532
|
+
? await resolveAutoModel(rotator, "anthropic", validation.value)
|
|
3533
|
+
: null;
|
|
3534
|
+
if (autoRequested && !autoSelection) {
|
|
3535
|
+
return writeJson(res, 503, {
|
|
3536
|
+
type: "error",
|
|
3537
|
+
error: { type: "overloaded_error", message: "No compatible model is currently available" },
|
|
3538
|
+
});
|
|
3539
|
+
}
|
|
3540
|
+
if (autoSelection && !authorizeResolvedAutoModel(res, auth, autoSelection.model)) return;
|
|
3541
|
+
const routedValidation = autoSelection
|
|
3542
|
+
? { ...validation.value, model: autoSelection.model }
|
|
3543
|
+
: validation.value;
|
|
3544
|
+
|
|
3194
3545
|
const compMode = parseCompressionMode(
|
|
3195
3546
|
req.headers["x-rotator-compression"],
|
|
3196
3547
|
rotator?.getConfig?.()?.compressionMode,
|
|
3197
3548
|
);
|
|
3198
3549
|
const compRes = applyPromptCompression(
|
|
3199
|
-
|
|
3550
|
+
routedValidation.messages as ChatMessage[],
|
|
3200
3551
|
compMode,
|
|
3201
|
-
{ model:
|
|
3552
|
+
{ model: routedValidation.model },
|
|
3202
3553
|
);
|
|
3203
3554
|
const anthropicReq = compRes.stats
|
|
3204
3555
|
? {
|
|
3205
|
-
...
|
|
3206
|
-
messages: compRes.messages as typeof
|
|
3556
|
+
...routedValidation,
|
|
3557
|
+
messages: compRes.messages as typeof routedValidation.messages,
|
|
3207
3558
|
}
|
|
3208
|
-
:
|
|
3559
|
+
: routedValidation;
|
|
3209
3560
|
|
|
3210
3561
|
const started = Date.now();
|
|
3211
|
-
const streamMode =
|
|
3212
|
-
const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model)
|
|
3562
|
+
const streamMode = routedValidation.stream ? "anthropic" : "none";
|
|
3563
|
+
const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model) || autoSelection?.providerId === OPENCODE_ZEN_PROVIDER_ID
|
|
3213
3564
|
? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq), requestType: "anthropic" }
|
|
3214
|
-
: (rotator?.getOllamaModels?.().includes(anthropicReq.model)
|
|
3565
|
+
: (autoSelection?.providerId === "ollama" || rotator?.getOllamaModels?.().includes(anthropicReq.model)
|
|
3566
|
+
? anthropicToOllamaBody(anthropicReq)
|
|
3567
|
+
: anthropicToAntigravityBody(anthropicReq));
|
|
3568
|
+
if (autoSelection) {
|
|
3569
|
+
bodyToForward.displayModel = requestedModel;
|
|
3570
|
+
bodyToForward.providerId = autoSelection.providerId;
|
|
3571
|
+
bodyToForward.selectionMode = autoSelection.mode;
|
|
3572
|
+
bodyToForward.selectionConfidence = autoSelection.confidence;
|
|
3573
|
+
bodyToForward.selectionReason = autoSelection.reason;
|
|
3574
|
+
}
|
|
3215
3575
|
const result = await completeViaRotator(
|
|
3216
3576
|
req,
|
|
3217
3577
|
res,
|
|
@@ -3278,7 +3638,12 @@ export async function handleAnthropicMessages(
|
|
|
3278
3638
|
const ttfbMs = result.completion.firstByteMs ?? totalMs;
|
|
3279
3639
|
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
3280
3640
|
accountLabel: result.context?.label,
|
|
3281
|
-
model:
|
|
3641
|
+
model: autoRequested ? result.context?.selectedModel ?? routedValidation.model : requestedModel,
|
|
3642
|
+
requestedModel: result.context?.requestedModel,
|
|
3643
|
+
selectedProvider: result.context?.providerId,
|
|
3644
|
+
modelSelection: result.context?.selectionMode,
|
|
3645
|
+
selectionConfidence: result.context?.selectionConfidence,
|
|
3646
|
+
selectionReason: result.context?.selectionReason,
|
|
3282
3647
|
latencyMs: totalMs,
|
|
3283
3648
|
ttfbMs,
|
|
3284
3649
|
inputTokens: result.completion.inputTokens,
|
|
@@ -3292,13 +3657,16 @@ export async function handleAnthropicMessages(
|
|
|
3292
3657
|
id: `msg_${started.toString(36)}`,
|
|
3293
3658
|
type: "message",
|
|
3294
3659
|
role: "assistant",
|
|
3295
|
-
model:
|
|
3660
|
+
model: autoRequested ? result.context?.selectedModel ?? routedValidation.model : requestedModel,
|
|
3296
3661
|
content: contentBlocks,
|
|
3297
3662
|
stop_reason: stopReason,
|
|
3298
3663
|
stop_sequence: null,
|
|
3299
3664
|
usage: {
|
|
3300
3665
|
input_tokens: result.completion.inputTokens,
|
|
3301
3666
|
output_tokens: result.completion.outputTokens,
|
|
3667
|
+
...(result.completion.cachedTokens !== undefined
|
|
3668
|
+
? { cache_read_input_tokens: result.completion.cachedTokens }
|
|
3669
|
+
: {}),
|
|
3302
3670
|
},
|
|
3303
3671
|
}, rotatorHeaders);
|
|
3304
3672
|
}
|