tuxevil-rotator 3.0.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
package/src/compat.ts ADDED
@@ -0,0 +1,2357 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ import {
4
+ type CompressionHeaderOptions,
5
+ buildRotatorResponseHeaders,
6
+ } from "./response-headers.js";
7
+ import {
8
+ applyPromptCompression,
9
+ parseCompressionMode,
10
+ type CompressionStats,
11
+ } from "./compression/index.js";
12
+ import { idempotencyManager } from "./idempotency.js";
13
+ import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
14
+ import { logSpend } from "./spend-logger.js";
15
+ import { hashKey } from "./virtual-keys.js";
16
+ import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
17
+ import { logger, redactSensitive } from "./logger.js";
18
+ import type { AccountRotator } from "./rotator.js";
19
+ import {
20
+ withRotation,
21
+ flattenHeaders,
22
+ type RequestBody,
23
+ type RotationAttemptContext,
24
+ type RotationOutcome,
25
+ } from "./proxy.js";
26
+ import {
27
+ isRecord,
28
+ sanitizeGeminiSchema,
29
+ sanitizeClaudeViaGeminiSchema,
30
+ } from "./compat/schema-sanitizer.js";
31
+ import {
32
+ DEFAULT_MODEL_SPECS,
33
+ setModelSpecsOverride,
34
+ getActiveModelSpecs,
35
+ getModelFamily,
36
+ getModelSpec,
37
+ isThinkingModel,
38
+ } from "./compat/model-specs.js";
39
+ import type { ModelSpec } from "./compat/model-specs.js";
40
+ import {
41
+ responsesStore,
42
+ makeCompatId,
43
+ getStoredResponse,
44
+ setStoredResponse,
45
+ resetResponsesStoreForTests,
46
+ loadResponsesStore,
47
+ flushResponsesStore,
48
+ cacheThoughtSignature,
49
+ } from "./compat/cache.js";
50
+ import {
51
+ normalizeOpenAIChatCompletionRequest,
52
+ normalizeOpenAIResponsesRequest,
53
+ normalizeAnthropicMessagesRequest,
54
+ convertResponsesToChatRequest,
55
+ openAIToAntigravityBody,
56
+ anthropicToAntigravityBody,
57
+ validateOpenAIChatCompletionRequest,
58
+ validateOpenAIResponsesRequest,
59
+ validateAnthropicMessagesRequest,
60
+ buildResponsesResponse,
61
+ saveResponsesEntry,
62
+ toolArgumentsToObject,
63
+ toolArgumentsToString,
64
+ } from "./providers/google-antigravity/translators.js";
65
+ import {
66
+ openAIToOllamaBody,
67
+ anthropicToOllamaBody,
68
+ parseOllamaNdjson,
69
+ } from "./providers/ollama/translators.js";
70
+ import type {
71
+ ChatMessage,
72
+ OpenAITool,
73
+ OpenAIToolCall,
74
+ OpenAIToolChoice,
75
+ OpenAIChatCompletionRequest,
76
+ OpenAIResponsesRequest,
77
+ AnthropicMessagesRequest,
78
+ CompatCompletion,
79
+ ResponsesConversionResult,
80
+ } from "./providers/google-antigravity/translators.js";
81
+
82
+ export {
83
+ isRecord,
84
+ sanitizeGeminiSchema,
85
+ sanitizeClaudeViaGeminiSchema,
86
+ DEFAULT_MODEL_SPECS,
87
+ setModelSpecsOverride,
88
+ getActiveModelSpecs,
89
+ getModelFamily,
90
+ getModelSpec,
91
+ isThinkingModel,
92
+ resetResponsesStoreForTests,
93
+ loadResponsesStore,
94
+ flushResponsesStore,
95
+ normalizeOpenAIChatCompletionRequest,
96
+ normalizeOpenAIResponsesRequest,
97
+ normalizeAnthropicMessagesRequest,
98
+ openAIToAntigravityBody,
99
+ anthropicToAntigravityBody,
100
+ validateOpenAIChatCompletionRequest,
101
+ validateOpenAIResponsesRequest,
102
+ validateAnthropicMessagesRequest,
103
+ };
104
+ export type {
105
+ ModelSpec,
106
+ ChatMessage,
107
+ OpenAITool,
108
+ OpenAIToolCall,
109
+ OpenAIToolChoice,
110
+ OpenAIChatCompletionRequest,
111
+ OpenAIResponsesRequest,
112
+ AnthropicMessagesRequest,
113
+ CompatCompletion,
114
+ };
115
+
116
+ const compatLogger = logger.child("compat");
117
+
118
+ const VALIDATION_LOG_MAX_CHARS = 200;
119
+
120
+ export function logValidationFailure(scope: string, payload: unknown): void {
121
+ const truncated = redactSensitive(JSON.stringify(payload));
122
+ const clipped =
123
+ truncated.length > VALIDATION_LOG_MAX_CHARS
124
+ ? `${truncated.slice(0, VALIDATION_LOG_MAX_CHARS)}…[+${truncated.length - VALIDATION_LOG_MAX_CHARS} chars]`
125
+ : truncated;
126
+ compatLogger.warn(`${scope}: ${clipped}`);
127
+ }
128
+
129
+ // Interfaces and types have been moved to src/providers/google-antigravity/translators.ts
130
+
131
+ // Response Output types
132
+
133
+ // Cache and stores have been moved to src/compat/cache.ts
134
+
135
+ // Helper and translation functions have been moved to src/providers/google-antigravity/translators.ts
136
+
137
+ export function parseAntigravitySse(raw: string): CompatCompletion {
138
+ let text = "";
139
+ let thinkingText = "";
140
+ let inputTokens = 0;
141
+ let outputTokens = 0;
142
+ let responseId: string | undefined;
143
+ const toolCallsMap = new Map<string, OpenAIToolCall>();
144
+ let toolCallIndex = 0;
145
+
146
+ for (const line of raw.split(/\r?\n/)) {
147
+ if (!line.startsWith("data:")) continue;
148
+ const payload = line.slice(5).trim();
149
+ if (!payload || payload === "[DONE]") continue;
150
+ try {
151
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
152
+ const response = isRecord(parsed.response) ? parsed.response : parsed;
153
+ if (!responseId && typeof response.responseId === "string")
154
+ responseId = response.responseId;
155
+ const candidates = Array.isArray(response.candidates)
156
+ ? response.candidates
157
+ : [];
158
+ for (const candidate of candidates) {
159
+ if (
160
+ !isRecord(candidate) ||
161
+ !isRecord(candidate.content) ||
162
+ !Array.isArray(candidate.content.parts)
163
+ )
164
+ continue;
165
+ for (const part of candidate.content.parts) {
166
+ if (!isRecord(part)) continue;
167
+ if (typeof part.text === "string") {
168
+ // Route thought blocks separately from normal text
169
+ if (part.thought === true) {
170
+ thinkingText += part.text;
171
+ } else {
172
+ text += part.text;
173
+ }
174
+ } else if (isRecord(part.functionCall)) {
175
+ // Gemini functionCall → OpenAI tool_call
176
+ const fc = part.functionCall;
177
+ const name = typeof fc.name === "string" ? fc.name : "unknown";
178
+ const args = fc.args !== undefined ? JSON.stringify(fc.args) : "{}";
179
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
180
+ // Cache thought_signature so we can re-inject it on the next turn
181
+ if (
182
+ typeof part.thoughtSignature === "string" &&
183
+ part.thoughtSignature
184
+ ) {
185
+ cacheThoughtSignature(callId, part.thoughtSignature);
186
+ }
187
+ toolCallsMap.set(name + callId, {
188
+ id: callId,
189
+ type: "function",
190
+ function: { name, arguments: args },
191
+ });
192
+ }
193
+ }
194
+ }
195
+ const usage = isRecord(response.usageMetadata)
196
+ ? response.usageMetadata
197
+ : isRecord(response.usage)
198
+ ? response.usage
199
+ : null;
200
+ if (usage) {
201
+ if (typeof usage.promptTokenCount === "number")
202
+ inputTokens = usage.promptTokenCount;
203
+ if (typeof usage.candidatesTokenCount === "number")
204
+ outputTokens = usage.candidatesTokenCount;
205
+ if (typeof usage.input_tokens === "number")
206
+ inputTokens = usage.input_tokens;
207
+ if (typeof usage.output_tokens === "number")
208
+ outputTokens = usage.output_tokens;
209
+ }
210
+ } catch {
211
+ // Ignore malformed SSE lines from upstream; other chunks may still be valid.
212
+ }
213
+ }
214
+
215
+ let parsedText = text;
216
+
217
+ // Intercept legacy hallucinated format: [Tool call: name(args)]
218
+ const legacyRegex = /\[Tool call:\s*([a-zA-Z0-9_-]+)\(([\s\S]*?)\)\]/g;
219
+ let match;
220
+ while ((match = legacyRegex.exec(parsedText)) !== null) {
221
+ const name = match[1];
222
+ const args = match[2].trim();
223
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
224
+ toolCallsMap.set(name + callId, {
225
+ id: callId,
226
+ type: "function",
227
+ function: { name, arguments: args },
228
+ });
229
+ }
230
+ parsedText = parsedText.replace(legacyRegex, "");
231
+
232
+ // Intercept new hallucinated XML format: <tool_call name="name">args</tool_call>
233
+ const xmlRegex = /<tool_call name="([^"]+)">([\s\S]*?)<\/tool_call>/g;
234
+ while ((match = xmlRegex.exec(parsedText)) !== null) {
235
+ const name = match[1];
236
+ const args = match[2].trim();
237
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
238
+ toolCallsMap.set(name + callId, {
239
+ id: callId,
240
+ type: "function",
241
+ function: { name, arguments: args },
242
+ });
243
+ }
244
+ parsedText = parsedText.replace(xmlRegex, "");
245
+
246
+ parsedText = parsedText.trim();
247
+
248
+ const toolCalls =
249
+ toolCallsMap.size > 0 ? [...toolCallsMap.values()] : undefined;
250
+ return {
251
+ text: parsedText,
252
+ thinkingText: thinkingText || undefined,
253
+ inputTokens,
254
+ outputTokens,
255
+ responseId,
256
+ toolCalls,
257
+ };
258
+ }
259
+
260
+ function getCompressionHeaderOpts(
261
+ stats?: CompressionStats | null,
262
+ ): CompressionHeaderOptions | undefined {
263
+ if (!stats) return undefined;
264
+ return {
265
+ mode: stats.mode,
266
+ savedChars: stats.savedChars,
267
+ savingsPercent: stats.savingsPercent,
268
+ };
269
+ }
270
+
271
+ function writeJson(
272
+ res: ServerResponse,
273
+ status: number,
274
+ payload: unknown,
275
+ headers: Record<string, string> = {},
276
+ ): void {
277
+ res.writeHead(status, { "Content-Type": "application/json", ...headers });
278
+ res.end(JSON.stringify(payload));
279
+ }
280
+
281
+ function writeResponsesEvent(
282
+ res: ServerResponse,
283
+ payload: Record<string, unknown>,
284
+ ): void {
285
+ res.write(`data: ${JSON.stringify(payload)}\n\n`);
286
+ }
287
+
288
+ function writeCompatStreamError(
289
+ res: ServerResponse,
290
+ format: "openai" | "anthropic",
291
+ message: string,
292
+ ): void {
293
+ if (format === "openai") {
294
+ res.write(
295
+ `data: ${JSON.stringify({ error: { message, type: "server_error" } })}\n\n`,
296
+ );
297
+ res.write("data: [DONE]\n\n");
298
+ return;
299
+ }
300
+ res.write(
301
+ `event: error\ndata: ${JSON.stringify({ type: "error", error: { type: "api_error", message } })}\n\n`,
302
+ );
303
+ }
304
+
305
+ function summarizeCompatRequest(body: RequestBody): string {
306
+ const request = isRecord(body.request) ? body.request : {};
307
+ const contents = Array.isArray(request.contents) ? request.contents : [];
308
+ const tools = Array.isArray(request.tools) ? request.tools.length : 0;
309
+ const systemInstruction = isRecord(request.systemInstruction) ? "yes" : "no";
310
+ return `model=${body.model} userAgent=${body.userAgent || "none"} turns=${contents.length} tools=${tools} systemInstruction=${systemInstruction}`;
311
+ }
312
+
313
+ function recordCompatOutcome(
314
+ rotator: AccountRotator,
315
+ body: RequestBody,
316
+ context: RotationAttemptContext,
317
+ statusCode: number,
318
+ completion?: CompatCompletion,
319
+ totalMs = Date.now() - context.requestStartMs,
320
+ options?: {
321
+ callType?: string;
322
+ apiKeyHash?: string | null;
323
+ requesterIp?: string | null;
324
+ rawRequest?: unknown;
325
+ rawResponse?: unknown;
326
+ },
327
+ ): void {
328
+ const ttfbMs = completion?.firstByteMs ?? totalMs;
329
+ rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
330
+ rotator.recordRequestLog({
331
+ model: context.displayModelKey,
332
+ account: context.label,
333
+ statusCode,
334
+ ttfbMs,
335
+ totalMs,
336
+ inputTokens: completion?.inputTokens ?? 0,
337
+ outputTokens: completion?.outputTokens ?? 0,
338
+ });
339
+ logSpend({
340
+ requestId: context.requestId,
341
+ apiKeyHash: options?.apiKeyHash || null,
342
+ model: context.displayModelKey,
343
+ accountEmail: context.label,
344
+ callType: options?.callType || "compat",
345
+ status: statusCode >= 200 && statusCode < 300 ? "success" : "failure",
346
+ promptTokens: completion?.inputTokens ?? 0,
347
+ completionTokens: completion?.outputTokens ?? 0,
348
+ totalTokens: (completion?.inputTokens ?? 0) + (completion?.outputTokens ?? 0),
349
+ startTime: new Date(context.requestStartMs).toISOString(),
350
+ endTime: new Date().toISOString(),
351
+ ttfbMs,
352
+ durationMs: totalMs,
353
+ requestMessages: options?.rawRequest || body.request || body,
354
+ responseContent:
355
+ options?.rawResponse ||
356
+ completion?.rawResponse ||
357
+ (completion?.text ? { text: completion.text } : null),
358
+ requesterIp: options?.requesterIp || null,
359
+ });
360
+ }
361
+
362
+ function recordCompatFailure(
363
+ rotator: AccountRotator,
364
+ body: RequestBody,
365
+ outcome: RotationOutcome<unknown>,
366
+ options?: {
367
+ callType?: string;
368
+ apiKeyHash?: string | null;
369
+ requesterIp?: string | null;
370
+ rawRequest?: unknown;
371
+ rawResponse?: unknown;
372
+ },
373
+ ): void {
374
+ if (outcome.ok || !outcome.context) return;
375
+ recordCompatOutcome(
376
+ rotator,
377
+ body,
378
+ outcome.context,
379
+ outcome.status,
380
+ undefined,
381
+ outcome.totalMs,
382
+ options,
383
+ );
384
+ }
385
+
386
+ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
387
+ try {
388
+ const body = await readLimitedBody(req);
389
+ return JSON.parse(body.toString("utf-8"));
390
+ } catch (err) {
391
+ if (err instanceof PayloadTooLargeError) throw err;
392
+ throw new Error("Invalid JSON body", { cause: err });
393
+ }
394
+ }
395
+
396
+ async function streamCompatSse(
397
+ body: unknown,
398
+ req: IncomingMessage,
399
+ res: ServerResponse,
400
+ model: string,
401
+ format: "openai" | "anthropic",
402
+ context?: RotationAttemptContext,
403
+ rotator?: AccountRotator,
404
+ compressionStats?: CompressionStats | null,
405
+ upstream: "google" | "ollama" = "google",
406
+ ): Promise<CompatCompletion> {
407
+ const nodeStream = Readable.fromWeb(
408
+ body as import("node:stream/web").ReadableStream,
409
+ );
410
+ let text = "";
411
+ let inputTokens = 0;
412
+ let outputTokens = 0;
413
+ const streamStartMs = Date.now();
414
+ let firstByteMs: number | undefined;
415
+ let responseId: string | undefined;
416
+ let toolCallIndex = 0;
417
+
418
+ const created = Math.floor(Date.now() / 1000);
419
+ const id =
420
+ format === "openai"
421
+ ? `chatcmpl-${Date.now().toString(36)}`
422
+ : `msg_${Date.now().toString(36)}`;
423
+
424
+ const openaiToolCalls: OpenAIToolCall[] = [];
425
+ let anthropicActiveBlockIndex = -1;
426
+ let anthropicActiveBlockType: "thinking" | "text" | null = null;
427
+ let anthropicHasToolUse = false;
428
+ const anthropicToolCalls: OpenAIToolCall[] = [];
429
+
430
+ const rotatorHeaders = buildRotatorResponseHeaders({
431
+ accountLabel: context?.label,
432
+ model,
433
+ ttfbMs: Date.now() - (context?.requestStartMs ?? streamStartMs),
434
+ healthScore: context?.account?.healthScore,
435
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
436
+ retries: context?.retries,
437
+ compression: getCompressionHeaderOpts(compressionStats),
438
+ });
439
+
440
+ res.writeHead(200, {
441
+ "Content-Type": "text/event-stream",
442
+ "Cache-Control": "no-cache",
443
+ Connection: "keep-alive",
444
+ "X-Accel-Buffering": "no",
445
+ ...rotatorHeaders,
446
+ });
447
+
448
+ if (format === "openai") {
449
+ res.write(
450
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] })}\n\n`,
451
+ );
452
+ } else if (format === "anthropic") {
453
+ res.write(
454
+ `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id, type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } })}\n\n`,
455
+ );
456
+ }
457
+
458
+ let tailBuffer = "";
459
+ let reqClosed = false;
460
+ let streamError: string | undefined;
461
+ const emitOllamaLine = (line: string): void => {
462
+ try {
463
+ const parsed = JSON.parse(line) as Record<string, unknown>;
464
+ if (parsed.done === true) {
465
+ if (typeof parsed.prompt_eval_count === "number")
466
+ inputTokens = parsed.prompt_eval_count;
467
+ if (typeof parsed.eval_count === "number")
468
+ outputTokens = parsed.eval_count;
469
+ }
470
+ const message = isRecord(parsed.message) ? parsed.message : null;
471
+ if (!message) return;
472
+ const deltaText =
473
+ typeof message.content === "string" ? message.content : "";
474
+ if (deltaText) {
475
+ text += deltaText;
476
+ if (format === "openai") {
477
+ res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { content: deltaText }, finish_reason: null }] })}\n\n`);
478
+ } else {
479
+ if (anthropicActiveBlockType !== "text") {
480
+ if (anthropicActiveBlockType === "thinking") {
481
+ res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`);
482
+ anthropicActiveBlockIndex = 1;
483
+ } else {
484
+ anthropicActiveBlockIndex = 0;
485
+ }
486
+ anthropicActiveBlockType = "text";
487
+ res.write(`event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "text", text: "" } })}\n\n`);
488
+ }
489
+ res.write(`event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "text_delta", text: deltaText } })}\n\n`);
490
+ }
491
+ }
492
+ if (Array.isArray(message.tool_calls)) {
493
+ for (const tc of message.tool_calls) {
494
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
495
+ const name =
496
+ typeof tc.function.name === "string" ? tc.function.name : "unknown";
497
+ const args =
498
+ typeof tc.function.arguments === "string"
499
+ ? tc.function.arguments
500
+ : JSON.stringify(tc.function.arguments ?? {});
501
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
502
+ if (format === "openai") {
503
+ openaiToolCalls.push({
504
+ id: callId,
505
+ type: "function",
506
+ function: { name, arguments: args },
507
+ });
508
+ res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { tool_calls: [{ index: toolCallIndex - 1, id: callId, type: "function", function: { name, arguments: args } }] }, finish_reason: null }] })}\n\n`);
509
+ } else {
510
+ if (anthropicActiveBlockType !== null) {
511
+ res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`);
512
+ anthropicActiveBlockType = null;
513
+ }
514
+ anthropicActiveBlockIndex++;
515
+ anthropicHasToolUse = true;
516
+ anthropicToolCalls.push({
517
+ id: callId,
518
+ type: "function",
519
+ function: { name, arguments: args },
520
+ });
521
+ let parsedInput: unknown;
522
+ try {
523
+ parsedInput = JSON.parse(args);
524
+ } catch {
525
+ parsedInput = {};
526
+ }
527
+ res.write(`event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "tool_use", id: callId, name, input: {} } })}\n\n`);
528
+ res.write(`event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "input_json_delta", partial_json: JSON.stringify(parsedInput) } })}\n\n`);
529
+ res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`);
530
+ }
531
+ }
532
+ }
533
+ } catch {
534
+ // Ignore malformed NDJSON lines
535
+ }
536
+ };
537
+ const closeUpstreamForClient = (): void => {
538
+ reqClosed = true;
539
+ if (!nodeStream.destroyed) nodeStream.destroy();
540
+ };
541
+ const responseEvents = res as {
542
+ once?: (event: "close", listener: () => void) => unknown;
543
+ off?: (event: "close", listener: () => void) => unknown;
544
+ };
545
+ req.once("close", closeUpstreamForClient);
546
+ responseEvents.once?.("close", closeUpstreamForClient);
547
+
548
+ try {
549
+ for await (const chunk of nodeStream) {
550
+ if (reqClosed) {
551
+ break;
552
+ }
553
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
554
+ const str = chunk.toString();
555
+ tailBuffer += str;
556
+ let newlineIdx;
557
+ while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
558
+ const line = tailBuffer.slice(0, newlineIdx).trim();
559
+ tailBuffer = tailBuffer.slice(newlineIdx + 1);
560
+
561
+ if (upstream === "ollama") {
562
+ if (line) emitOllamaLine(line);
563
+ continue;
564
+ }
565
+ if (!line.startsWith("data:")) continue;
566
+ const payload = line.slice(5).trim();
567
+ if (!payload || payload === "[DONE]") continue;
568
+
569
+ try {
570
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
571
+ const response = isRecord(parsed.response) ? parsed.response : parsed;
572
+ if (!responseId && typeof response.responseId === "string")
573
+ responseId = response.responseId;
574
+
575
+ const candidates = Array.isArray(response.candidates)
576
+ ? response.candidates
577
+ : [];
578
+ for (const candidate of candidates) {
579
+ if (
580
+ !isRecord(candidate) ||
581
+ !isRecord(candidate.content) ||
582
+ !Array.isArray(candidate.content.parts)
583
+ )
584
+ continue;
585
+ for (const part of candidate.content.parts) {
586
+ if (!isRecord(part)) continue;
587
+ if (typeof part.text === "string" && part.text) {
588
+ if (part.thought === true) {
589
+ // Thought block → reasoning_content (OpenAI) or thinking_delta (Anthropic)
590
+ if (format === "openai") {
591
+ res.write(
592
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { reasoning_content: part.text }, finish_reason: null }] })}\n\n`,
593
+ );
594
+ } else {
595
+ if (anthropicActiveBlockType !== "thinking") {
596
+ if (anthropicActiveBlockType === "text") {
597
+ res.write(
598
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
599
+ );
600
+ }
601
+ anthropicActiveBlockIndex = 0;
602
+ anthropicActiveBlockType = "thinking";
603
+ res.write(
604
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "thinking", thinking: "" } })}\n\n`,
605
+ );
606
+ }
607
+ res.write(
608
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "thinking_delta", thinking: part.text } })}\n\n`,
609
+ );
610
+ }
611
+ } else {
612
+ text += part.text;
613
+ if (format === "openai") {
614
+ res.write(
615
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { content: part.text }, finish_reason: null }] })}\n\n`,
616
+ );
617
+ } else {
618
+ if (anthropicActiveBlockType !== "text") {
619
+ if (anthropicActiveBlockType === "thinking") {
620
+ res.write(
621
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
622
+ );
623
+ anthropicActiveBlockIndex = 1;
624
+ } else {
625
+ anthropicActiveBlockIndex = 0;
626
+ }
627
+ anthropicActiveBlockType = "text";
628
+ res.write(
629
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "text", text: "" } })}\n\n`,
630
+ );
631
+ }
632
+ res.write(
633
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "text_delta", text: part.text } })}\n\n`,
634
+ );
635
+ }
636
+ }
637
+ } else if (isRecord(part.functionCall)) {
638
+ const fc = part.functionCall;
639
+ const name = typeof fc.name === "string" ? fc.name : "unknown";
640
+ const args =
641
+ fc.args !== undefined ? JSON.stringify(fc.args) : "{}";
642
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
643
+ // Cache thought_signature so we can re-inject it on the next turn
644
+ if (
645
+ typeof part.thoughtSignature === "string" &&
646
+ part.thoughtSignature
647
+ ) {
648
+ cacheThoughtSignature(callId, part.thoughtSignature);
649
+ }
650
+ if (format === "openai") {
651
+ openaiToolCalls.push({
652
+ id: callId,
653
+ type: "function",
654
+ function: { name, arguments: args },
655
+ });
656
+ res.write(
657
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { tool_calls: [{ index: toolCallIndex - 1, id: callId, type: "function", function: { name, arguments: args } }] }, finish_reason: null }] })}\n\n`,
658
+ );
659
+ } else {
660
+ // Close any active text/thinking block before emitting tool_use
661
+ if (anthropicActiveBlockType !== null) {
662
+ res.write(
663
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
664
+ );
665
+ anthropicActiveBlockType = null;
666
+ }
667
+ anthropicActiveBlockIndex++;
668
+ anthropicHasToolUse = true;
669
+ anthropicToolCalls.push({
670
+ id: callId,
671
+ type: "function",
672
+ function: { name, arguments: args },
673
+ });
674
+ let parsedInput: unknown;
675
+ try {
676
+ parsedInput = JSON.parse(args);
677
+ } catch {
678
+ parsedInput = {};
679
+ }
680
+ res.write(
681
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "tool_use", id: callId, name, input: {} } })}\n\n`,
682
+ );
683
+ res.write(
684
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "input_json_delta", partial_json: JSON.stringify(parsedInput) } })}\n\n`,
685
+ );
686
+ res.write(
687
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
688
+ );
689
+ }
690
+ }
691
+ }
692
+ }
693
+ const usage = isRecord(response.usageMetadata)
694
+ ? response.usageMetadata
695
+ : isRecord(response.usage)
696
+ ? response.usage
697
+ : null;
698
+ if (usage) {
699
+ if (typeof usage.promptTokenCount === "number")
700
+ inputTokens = usage.promptTokenCount;
701
+ if (typeof usage.candidatesTokenCount === "number")
702
+ outputTokens = usage.candidatesTokenCount;
703
+ if (typeof usage.input_tokens === "number")
704
+ inputTokens = usage.input_tokens;
705
+ if (typeof usage.output_tokens === "number")
706
+ outputTokens = usage.output_tokens;
707
+ }
708
+ } catch {
709
+ // Ignore malformed JSON chunks
710
+ }
711
+ }
712
+ }
713
+ } catch (err) {
714
+ if (!reqClosed) {
715
+ streamError = redactSensitive(String(err)).slice(0, 200);
716
+ compatLogger.warn(
717
+ `Stream read error: ${streamError}`,
718
+ );
719
+ }
720
+ } finally {
721
+ req.off("close", closeUpstreamForClient);
722
+ responseEvents.off?.("close", closeUpstreamForClient);
723
+ }
724
+
725
+ if (!reqClosed && !res.writableEnded) {
726
+ if (streamError) {
727
+ writeCompatStreamError(res, format, streamError);
728
+ } else if (format === "openai") {
729
+ const openaiFinishReason = toolCallIndex > 0 ? "tool_calls" : "stop";
730
+ res.write(
731
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: {}, finish_reason: openaiFinishReason }] })}\n\n`,
732
+ );
733
+ // Emit a usage chunk so agents (hermes, openwebui, etc.) can display token statistics
734
+ if (inputTokens > 0 || outputTokens > 0) {
735
+ res.write(
736
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [], usage: { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens } })}\n\n`,
737
+ );
738
+ }
739
+ res.write("data: [DONE]\n\n");
740
+ } else {
741
+ if (anthropicActiveBlockType !== null) {
742
+ res.write(
743
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
744
+ );
745
+ }
746
+ const anthropicStopReason = anthropicHasToolUse ? "tool_use" : "end_turn";
747
+ // message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
748
+ res.write(
749
+ `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: anthropicStopReason, stop_sequence: null }, usage: { input_tokens: inputTokens, output_tokens: outputTokens } })}\n\n`,
750
+ );
751
+ res.write(
752
+ `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
753
+ );
754
+ }
755
+ res.end();
756
+ }
757
+
758
+ const collectedToolCalls =
759
+ openaiToolCalls.length > 0
760
+ ? openaiToolCalls
761
+ : anthropicToolCalls.length > 0
762
+ ? anthropicToolCalls
763
+ : undefined;
764
+
765
+ const rawResponse =
766
+ format === "openai"
767
+ ? {
768
+ id,
769
+ object: "chat.completion",
770
+ created,
771
+ model,
772
+ choices: [
773
+ {
774
+ index: 0,
775
+ message: {
776
+ role: "assistant",
777
+ content: text || null,
778
+ ...(collectedToolCalls ? { tool_calls: collectedToolCalls } : {}),
779
+ },
780
+ finish_reason: collectedToolCalls ? "tool_calls" : "stop",
781
+ },
782
+ ],
783
+ usage: {
784
+ prompt_tokens: inputTokens,
785
+ completion_tokens: outputTokens,
786
+ total_tokens: inputTokens + outputTokens,
787
+ },
788
+ }
789
+ : {
790
+ id,
791
+ type: "message",
792
+ role: "assistant",
793
+ model,
794
+ content: [
795
+ ...(text ? [{ type: "text", text }] : []),
796
+ ...(collectedToolCalls
797
+ ? collectedToolCalls.map((tc) => ({
798
+ type: "tool_use",
799
+ id: tc.id,
800
+ name: tc.function.name,
801
+ input: toolArgumentsToObject(tc.function.arguments),
802
+ }))
803
+ : []),
804
+ ],
805
+ stop_reason: anthropicHasToolUse ? "tool_use" : "end_turn",
806
+ usage: { input_tokens: inputTokens, output_tokens: outputTokens },
807
+ };
808
+
809
+ return {
810
+ text,
811
+ inputTokens,
812
+ outputTokens,
813
+ firstByteMs,
814
+ responseId,
815
+ toolCalls: collectedToolCalls,
816
+ rawResponse,
817
+ streamError,
818
+ };
819
+ }
820
+
821
+ async function streamResponsesSse(
822
+ body: unknown,
823
+ req: IncomingMessage,
824
+ res: ServerResponse,
825
+ request: OpenAIResponsesRequest,
826
+ responseId: string,
827
+ previousResponseId: string | null,
828
+ createdAt: number,
829
+ context?: RotationAttemptContext,
830
+ rotator?: AccountRotator,
831
+ compressionStats?: CompressionStats | null,
832
+ upstream: "google" | "ollama" = "google",
833
+ ): Promise<CompatCompletion> {
834
+ const nodeStream = Readable.fromWeb(
835
+ body as import("node:stream/web").ReadableStream,
836
+ );
837
+ let text = "";
838
+ let thinkingText = "";
839
+ let inputTokens = 0;
840
+ let outputTokens = 0;
841
+ const streamStartMs = Date.now();
842
+ let firstByteMs: number | undefined;
843
+ const toolCalls: OpenAIToolCall[] = [];
844
+ let toolCallIndex = 0;
845
+ let nextOutputIndex = 0;
846
+ let messageOutputIndex = -1;
847
+ let messageItemId = "";
848
+ let reasoningOutputIndex = -1;
849
+ let reasoningItemId = "";
850
+ let reasoningDone = false;
851
+ let reqClosed = false;
852
+ let streamError: string | undefined;
853
+ const closeUpstreamForClient = (): void => {
854
+ reqClosed = true;
855
+ if (!nodeStream.destroyed) nodeStream.destroy();
856
+ };
857
+ const responseEvents = res as {
858
+ once?: (event: "close", listener: () => void) => unknown;
859
+ off?: (event: "close", listener: () => void) => unknown;
860
+ };
861
+ req.once("close", closeUpstreamForClient);
862
+ responseEvents.once?.("close", closeUpstreamForClient);
863
+
864
+ const rotatorHeaders = buildRotatorResponseHeaders({
865
+ accountLabel: context?.label,
866
+ model: request.model,
867
+ ttfbMs: Date.now() - (context?.requestStartMs ?? streamStartMs),
868
+ healthScore: context?.account?.healthScore,
869
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
870
+ retries: context?.retries,
871
+ compression: getCompressionHeaderOpts(compressionStats),
872
+ });
873
+
874
+ res.writeHead(200, {
875
+ "Content-Type": "text/event-stream",
876
+ "Cache-Control": "no-cache",
877
+ Connection: "keep-alive",
878
+ "X-Accel-Buffering": "no",
879
+ ...rotatorHeaders,
880
+ });
881
+ const emptyCompletion: CompatCompletion = {
882
+ text: "",
883
+ thinkingText: undefined,
884
+ inputTokens: 0,
885
+ outputTokens: 0,
886
+ toolCalls: [],
887
+ };
888
+ writeResponsesEvent(res, {
889
+ type: "response.created",
890
+ response: buildResponsesResponse(
891
+ request,
892
+ responseId,
893
+ createdAt,
894
+ emptyCompletion,
895
+ "in_progress",
896
+ previousResponseId,
897
+ ),
898
+ });
899
+ writeResponsesEvent(res, {
900
+ type: "response.in_progress",
901
+ response: buildResponsesResponse(
902
+ request,
903
+ responseId,
904
+ createdAt,
905
+ emptyCompletion,
906
+ "in_progress",
907
+ previousResponseId,
908
+ ),
909
+ });
910
+
911
+ let tailBuffer = "";
912
+ const emitOllamaLine = (line: string): void => {
913
+ try {
914
+ const parsed = JSON.parse(line) as Record<string, unknown>;
915
+ if (parsed.done === true) {
916
+ if (typeof parsed.prompt_eval_count === "number")
917
+ inputTokens = parsed.prompt_eval_count;
918
+ if (typeof parsed.eval_count === "number")
919
+ outputTokens = parsed.eval_count;
920
+ }
921
+ const message = isRecord(parsed.message) ? parsed.message : null;
922
+ if (!message) return;
923
+ const deltaText =
924
+ typeof message.content === "string" ? message.content : "";
925
+ const closeReasoningIfOpen = (): void => {
926
+ if (reasoningOutputIndex !== -1 && !reasoningDone) {
927
+ reasoningDone = true;
928
+ writeResponsesEvent(res, {
929
+ type: "response.reasoning_summary_text.done",
930
+ item_id: reasoningItemId,
931
+ output_index: reasoningOutputIndex,
932
+ summary_index: 0,
933
+ text: thinkingText,
934
+ });
935
+ writeResponsesEvent(res, {
936
+ type: "response.output_item.done",
937
+ output_index: reasoningOutputIndex,
938
+ item: {
939
+ id: reasoningItemId,
940
+ type: "reasoning",
941
+ status: "completed",
942
+ summary: [{ type: "summary_text", text: thinkingText }],
943
+ },
944
+ });
945
+ }
946
+ };
947
+ if (deltaText) {
948
+ closeReasoningIfOpen();
949
+ if (messageOutputIndex === -1) {
950
+ messageOutputIndex = nextOutputIndex++;
951
+ messageItemId = makeCompatId("msg");
952
+ writeResponsesEvent(res, {
953
+ type: "response.output_item.added",
954
+ output_index: messageOutputIndex,
955
+ item: {
956
+ id: messageItemId,
957
+ type: "message",
958
+ status: "completed",
959
+ role: "assistant",
960
+ content: [
961
+ { type: "output_text", text: "", annotations: [] },
962
+ ],
963
+ },
964
+ });
965
+ }
966
+ text += deltaText;
967
+ writeResponsesEvent(res, {
968
+ type: "response.output_text.delta",
969
+ item_id: messageItemId,
970
+ output_index: messageOutputIndex,
971
+ content_index: 0,
972
+ delta: deltaText,
973
+ });
974
+ }
975
+ if (Array.isArray(message.tool_calls)) {
976
+ for (const tc of message.tool_calls) {
977
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
978
+ const name =
979
+ typeof tc.function.name === "string" ? tc.function.name : "unknown";
980
+ const args =
981
+ typeof tc.function.arguments === "string"
982
+ ? tc.function.arguments
983
+ : JSON.stringify(tc.function.arguments ?? {});
984
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
985
+ closeReasoningIfOpen();
986
+ toolCalls.push({
987
+ id: callId,
988
+ type: "function",
989
+ function: { name, arguments: args },
990
+ });
991
+ const item = {
992
+ id: makeCompatId("fc"),
993
+ type: "function_call",
994
+ call_id: callId,
995
+ name,
996
+ arguments: args,
997
+ status: "completed",
998
+ };
999
+ const outputIndex = nextOutputIndex++;
1000
+ writeResponsesEvent(res, {
1001
+ type: "response.output_item.added",
1002
+ output_index: outputIndex,
1003
+ item,
1004
+ });
1005
+ writeResponsesEvent(res, {
1006
+ type: "response.function_call_arguments.delta",
1007
+ item_id: item.id,
1008
+ output_index: outputIndex,
1009
+ delta: args,
1010
+ });
1011
+ writeResponsesEvent(res, {
1012
+ type: "response.function_call_arguments.done",
1013
+ item_id: item.id,
1014
+ output_index: outputIndex,
1015
+ arguments: args,
1016
+ });
1017
+ writeResponsesEvent(res, {
1018
+ type: "response.output_item.done",
1019
+ output_index: outputIndex,
1020
+ item,
1021
+ });
1022
+ }
1023
+ }
1024
+ } catch {
1025
+ // Ignore malformed NDJSON lines
1026
+ }
1027
+ };
1028
+ try {
1029
+ for await (const chunk of nodeStream) {
1030
+ if (reqClosed) {
1031
+ break;
1032
+ }
1033
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
1034
+ tailBuffer += chunk.toString();
1035
+ let newlineIdx;
1036
+ while ((newlineIdx = tailBuffer.indexOf("\n")) >= 0) {
1037
+ const line = tailBuffer.slice(0, newlineIdx).trim();
1038
+ tailBuffer = tailBuffer.slice(newlineIdx + 1);
1039
+ if (upstream === "ollama") {
1040
+ if (line) emitOllamaLine(line);
1041
+ continue;
1042
+ }
1043
+ if (!line.startsWith("data:")) continue;
1044
+ const payload = line.slice(5).trim();
1045
+ if (!payload || payload === "[DONE]") continue;
1046
+ try {
1047
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
1048
+ const response = isRecord(parsed.response) ? parsed.response : parsed;
1049
+ const candidates = Array.isArray(response.candidates)
1050
+ ? response.candidates
1051
+ : [];
1052
+ for (const candidate of candidates) {
1053
+ if (
1054
+ !isRecord(candidate) ||
1055
+ !isRecord(candidate.content) ||
1056
+ !Array.isArray(candidate.content.parts)
1057
+ )
1058
+ continue;
1059
+ for (const part of candidate.content.parts) {
1060
+ if (!isRecord(part)) continue;
1061
+ if (typeof part.text === "string" && part.text) {
1062
+ if (part.thought === true) {
1063
+ // Stream reasoning content via Responses API reasoning events.
1064
+ // First thought chunk: open the reasoning output item.
1065
+ if (reasoningOutputIndex === -1) {
1066
+ reasoningOutputIndex = nextOutputIndex++;
1067
+ reasoningItemId = makeCompatId("rs");
1068
+ writeResponsesEvent(res, {
1069
+ type: "response.output_item.added",
1070
+ output_index: reasoningOutputIndex,
1071
+ item: {
1072
+ id: reasoningItemId,
1073
+ type: "reasoning",
1074
+ status: "in_progress",
1075
+ summary: [],
1076
+ },
1077
+ });
1078
+ }
1079
+ writeResponsesEvent(res, {
1080
+ type: "response.reasoning_summary_text.delta",
1081
+ item_id: reasoningItemId,
1082
+ output_index: reasoningOutputIndex,
1083
+ summary_index: 0,
1084
+ delta: part.text,
1085
+ });
1086
+ thinkingText += part.text;
1087
+ continue;
1088
+ }
1089
+ // Non-thought text arriving: close reasoning item immediately so Codex
1090
+ // sees a completed reasoning block before any content/tool items.
1091
+ if (reasoningOutputIndex !== -1 && !reasoningDone) {
1092
+ reasoningDone = true;
1093
+ writeResponsesEvent(res, {
1094
+ type: "response.reasoning_summary_text.done",
1095
+ item_id: reasoningItemId,
1096
+ output_index: reasoningOutputIndex,
1097
+ summary_index: 0,
1098
+ text: thinkingText,
1099
+ });
1100
+ writeResponsesEvent(res, {
1101
+ type: "response.output_item.done",
1102
+ output_index: reasoningOutputIndex,
1103
+ item: {
1104
+ id: reasoningItemId,
1105
+ type: "reasoning",
1106
+ status: "completed",
1107
+ summary: [{ type: "summary_text", text: thinkingText }],
1108
+ },
1109
+ });
1110
+ }
1111
+ if (messageOutputIndex === -1) {
1112
+ messageOutputIndex = nextOutputIndex++;
1113
+ messageItemId = makeCompatId("msg");
1114
+ writeResponsesEvent(res, {
1115
+ type: "response.output_item.added",
1116
+ output_index: messageOutputIndex,
1117
+ item: {
1118
+ id: messageItemId,
1119
+ type: "message",
1120
+ status: "completed",
1121
+ role: "assistant",
1122
+ content: [
1123
+ { type: "output_text", text: "", annotations: [] },
1124
+ ],
1125
+ },
1126
+ });
1127
+ }
1128
+ text += part.text;
1129
+ writeResponsesEvent(res, {
1130
+ type: "response.output_text.delta",
1131
+ item_id: messageItemId,
1132
+ output_index: messageOutputIndex,
1133
+ content_index: 0,
1134
+ delta: part.text,
1135
+ });
1136
+ } else if (isRecord(part.functionCall)) {
1137
+ // functionCall arriving: close reasoning item immediately if still open
1138
+ if (reasoningOutputIndex !== -1 && !reasoningDone) {
1139
+ reasoningDone = true;
1140
+ writeResponsesEvent(res, {
1141
+ type: "response.reasoning_summary_text.done",
1142
+ item_id: reasoningItemId,
1143
+ output_index: reasoningOutputIndex,
1144
+ summary_index: 0,
1145
+ text: thinkingText,
1146
+ });
1147
+ writeResponsesEvent(res, {
1148
+ type: "response.output_item.done",
1149
+ output_index: reasoningOutputIndex,
1150
+ item: {
1151
+ id: reasoningItemId,
1152
+ type: "reasoning",
1153
+ status: "completed",
1154
+ summary: [{ type: "summary_text", text: thinkingText }],
1155
+ },
1156
+ });
1157
+ }
1158
+ const fc = part.functionCall;
1159
+ const name = typeof fc.name === "string" ? fc.name : "unknown";
1160
+ const args =
1161
+ fc.args !== undefined ? JSON.stringify(fc.args) : "{}";
1162
+ const callId = `call_${Date.now().toString(36)}_${toolCallIndex++}`;
1163
+ if (
1164
+ typeof part.thoughtSignature === "string" &&
1165
+ part.thoughtSignature
1166
+ ) {
1167
+ cacheThoughtSignature(callId, part.thoughtSignature);
1168
+ }
1169
+ toolCalls.push({
1170
+ id: callId,
1171
+ type: "function",
1172
+ function: { name, arguments: args },
1173
+ });
1174
+ const item = {
1175
+ id: makeCompatId("fc"),
1176
+ type: "function_call",
1177
+ call_id: callId,
1178
+ name,
1179
+ arguments: args,
1180
+ status: "completed",
1181
+ };
1182
+ const outputIndex = nextOutputIndex++;
1183
+ writeResponsesEvent(res, {
1184
+ type: "response.output_item.added",
1185
+ output_index: outputIndex,
1186
+ item,
1187
+ });
1188
+ writeResponsesEvent(res, {
1189
+ type: "response.function_call_arguments.delta",
1190
+ item_id: item.id,
1191
+ output_index: outputIndex,
1192
+ delta: args,
1193
+ });
1194
+ writeResponsesEvent(res, {
1195
+ type: "response.function_call_arguments.done",
1196
+ item_id: item.id,
1197
+ output_index: outputIndex,
1198
+ arguments: args,
1199
+ });
1200
+ writeResponsesEvent(res, {
1201
+ type: "response.output_item.done",
1202
+ output_index: outputIndex,
1203
+ item,
1204
+ });
1205
+ }
1206
+ }
1207
+ }
1208
+ const usage = isRecord(response.usageMetadata)
1209
+ ? response.usageMetadata
1210
+ : isRecord(response.usage)
1211
+ ? response.usage
1212
+ : null;
1213
+ if (usage) {
1214
+ if (typeof usage.promptTokenCount === "number")
1215
+ inputTokens = usage.promptTokenCount;
1216
+ if (typeof usage.candidatesTokenCount === "number")
1217
+ outputTokens = usage.candidatesTokenCount;
1218
+ if (typeof usage.input_tokens === "number")
1219
+ inputTokens = usage.input_tokens;
1220
+ if (typeof usage.output_tokens === "number")
1221
+ outputTokens = usage.output_tokens;
1222
+ }
1223
+ } catch {
1224
+ // Ignore malformed JSON chunks
1225
+ }
1226
+ }
1227
+ }
1228
+ } catch (err) {
1229
+ if (!reqClosed) {
1230
+ streamError = redactSensitive(String(err)).slice(0, 200);
1231
+ compatLogger.warn(
1232
+ `Responses stream read error: ${streamError}`,
1233
+ );
1234
+ }
1235
+ } finally {
1236
+ req.off("close", closeUpstreamForClient);
1237
+ responseEvents.off?.("close", closeUpstreamForClient);
1238
+ }
1239
+
1240
+ const completion: CompatCompletion = {
1241
+ text,
1242
+ thinkingText: thinkingText || undefined,
1243
+ inputTokens,
1244
+ outputTokens,
1245
+ firstByteMs,
1246
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
1247
+ streamError,
1248
+ rawResponse: {
1249
+ id: responseId,
1250
+ object: "response",
1251
+ created: createdAt,
1252
+ output_text: text,
1253
+ usage: {
1254
+ prompt_tokens: inputTokens,
1255
+ completion_tokens: outputTokens,
1256
+ total_tokens: inputTokens + outputTokens,
1257
+ },
1258
+ },
1259
+ };
1260
+ if (!reqClosed && !res.writableEnded && streamError) {
1261
+ writeResponsesEvent(res, {
1262
+ type: "error",
1263
+ error: { code: "stream_error", message: streamError },
1264
+ });
1265
+ res.end();
1266
+ } else if (!reqClosed && !res.writableEnded) {
1267
+ // Close reasoning item if it was never closed mid-stream
1268
+ if (reasoningOutputIndex !== -1 && !reasoningDone) {
1269
+ writeResponsesEvent(res, {
1270
+ type: "response.reasoning_summary_text.done",
1271
+ item_id: reasoningItemId,
1272
+ output_index: reasoningOutputIndex,
1273
+ summary_index: 0,
1274
+ text: thinkingText,
1275
+ });
1276
+ writeResponsesEvent(res, {
1277
+ type: "response.output_item.done",
1278
+ output_index: reasoningOutputIndex,
1279
+ item: {
1280
+ id: reasoningItemId,
1281
+ type: "reasoning",
1282
+ status: "completed",
1283
+ summary: [{ type: "summary_text", text: thinkingText }],
1284
+ },
1285
+ });
1286
+ }
1287
+ if (messageOutputIndex !== -1) {
1288
+ writeResponsesEvent(res, {
1289
+ type: "response.output_text.done",
1290
+ item_id: messageItemId,
1291
+ output_index: messageOutputIndex,
1292
+ content_index: 0,
1293
+ text,
1294
+ });
1295
+ writeResponsesEvent(res, {
1296
+ type: "response.output_item.done",
1297
+ output_index: messageOutputIndex,
1298
+ item: {
1299
+ id: messageItemId,
1300
+ type: "message",
1301
+ status: "completed",
1302
+ role: "assistant",
1303
+ content: [{ type: "output_text", text, annotations: [] }],
1304
+ },
1305
+ });
1306
+ }
1307
+ writeResponsesEvent(res, {
1308
+ type: "response.completed",
1309
+ response: buildResponsesResponse(
1310
+ request,
1311
+ responseId,
1312
+ createdAt,
1313
+ completion,
1314
+ "completed",
1315
+ previousResponseId,
1316
+ ),
1317
+ });
1318
+ res.end();
1319
+ }
1320
+ return completion;
1321
+ }
1322
+
1323
+ async function completeResponsesViaRotator(
1324
+ req: IncomingMessage,
1325
+ res: ServerResponse,
1326
+ rotator: AccountRotator,
1327
+ request: OpenAIResponsesRequest,
1328
+ body: RequestBody,
1329
+ responseId: string,
1330
+ previousResponseId: string | null,
1331
+ options?: {
1332
+ callType?: string;
1333
+ apiKeyHash?: string | null;
1334
+ requesterIp?: string | null;
1335
+ rawRequest?: unknown;
1336
+ rawResponse?: unknown;
1337
+ compressionStats?: CompressionStats | null;
1338
+ },
1339
+ ): Promise<{
1340
+ completion: CompatCompletion;
1341
+ status: number;
1342
+ errorText?: string;
1343
+ streamed: boolean;
1344
+ context?: RotationAttemptContext;
1345
+ compressionStats?: CompressionStats | null;
1346
+ }> {
1347
+ const createdAt = Math.floor(Date.now() / 1000);
1348
+ const outcome = await withRotation(
1349
+ rotator,
1350
+ body.model,
1351
+ flattenHeaders(req.headers),
1352
+ body,
1353
+ async (response, context) => {
1354
+ const completion = await streamResponsesSse(
1355
+ response.body,
1356
+ req,
1357
+ res,
1358
+ request,
1359
+ responseId,
1360
+ previousResponseId,
1361
+ createdAt,
1362
+ context,
1363
+ rotator,
1364
+ options?.compressionStats,
1365
+ (rotator?.getOllamaModels?.() ?? []).includes(body.model)
1366
+ ? "ollama"
1367
+ : "google",
1368
+ );
1369
+ if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1370
+ rotator.recordTokenUsage(
1371
+ body.displayModel || body.model,
1372
+ completion.inputTokens,
1373
+ completion.outputTokens,
1374
+ );
1375
+ }
1376
+ recordCompatOutcome(
1377
+ rotator,
1378
+ body,
1379
+ context,
1380
+ completion.streamError ? 502 : response.status,
1381
+ completion,
1382
+ undefined,
1383
+ options,
1384
+ );
1385
+ return completion;
1386
+ },
1387
+ );
1388
+ if (!outcome.ok) {
1389
+ recordCompatFailure(rotator, body, outcome, options);
1390
+ return {
1391
+ completion: { text: "", inputTokens: 0, outputTokens: 0 },
1392
+ status: outcome.status,
1393
+ errorText: outcome.retryAfterMs
1394
+ ? `${outcome.errorText}; retryAfterMs=${outcome.retryAfterMs}`
1395
+ : outcome.errorText,
1396
+ streamed: false,
1397
+ context: outcome.context,
1398
+ };
1399
+ }
1400
+ return {
1401
+ completion: outcome.result,
1402
+ status: 200,
1403
+ streamed: true,
1404
+ context: outcome.context,
1405
+ compressionStats: options?.compressionStats,
1406
+ };
1407
+ }
1408
+
1409
+ class NonOkOutcomeError extends Error {
1410
+ constructor(public outcome: RotationOutcome<CompatCompletion>) {
1411
+ super("Non-ok rotation outcome");
1412
+ }
1413
+ }
1414
+
1415
+ async function completeViaRotator(
1416
+ req: IncomingMessage,
1417
+ res: ServerResponse,
1418
+ rotator: AccountRotator,
1419
+ body: RequestBody,
1420
+ streamMode: "none" | "openai" | "anthropic",
1421
+ options?: {
1422
+ callType?: string;
1423
+ apiKeyHash?: string | null;
1424
+ requesterIp?: string | null;
1425
+ rawRequest?: unknown;
1426
+ rawResponse?: unknown;
1427
+ compressionStats?: CompressionStats | null;
1428
+ },
1429
+ ): Promise<{
1430
+ completion: CompatCompletion;
1431
+ status: number;
1432
+ errorText?: string;
1433
+ streamed: boolean;
1434
+ context?: RotationAttemptContext;
1435
+ isDeduplicated?: boolean;
1436
+ compressionStats?: CompressionStats | null;
1437
+ }> {
1438
+ const ollamaModels = rotator?.getOllamaModels?.() ?? [];
1439
+ const isOllamaUpstream = (model: string): boolean => ollamaModels.includes(model);
1440
+ const cfg = typeof rotator?.getConfig === "function" ? rotator.getConfig() : undefined;
1441
+ const enabled = cfg?.idempotencyEnabled === true;
1442
+ const windowMs = cfg?.idempotencyWindowMs ?? 2000;
1443
+ const shouldDedup = enabled && streamMode === "none" && !idempotencyManager.isOptedOut(req);
1444
+
1445
+ const runWithRotation = () =>
1446
+ withRotation(
1447
+ rotator,
1448
+ body.model,
1449
+ flattenHeaders(req.headers),
1450
+ body,
1451
+ async (response, context) => {
1452
+ if (streamMode === "none") {
1453
+ const raw = await response.text();
1454
+ const completion = isOllamaUpstream(body.model)
1455
+ ? parseOllamaNdjson(raw)
1456
+ : parseAntigravitySse(raw);
1457
+ if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1458
+ rotator.recordTokenUsage(
1459
+ body.displayModel || body.model,
1460
+ completion.inputTokens,
1461
+ completion.outputTokens,
1462
+ );
1463
+ }
1464
+ recordCompatOutcome(
1465
+ rotator,
1466
+ body,
1467
+ context,
1468
+ completion.streamError ? 502 : response.status,
1469
+ completion,
1470
+ undefined,
1471
+ options,
1472
+ );
1473
+ return completion;
1474
+ } else {
1475
+ const completion = await streamCompatSse(
1476
+ response.body,
1477
+ req,
1478
+ res,
1479
+ body.displayModel || body.model,
1480
+ streamMode,
1481
+ context,
1482
+ rotator,
1483
+ options?.compressionStats,
1484
+ isOllamaUpstream(body.model) ? "ollama" : "google",
1485
+ );
1486
+ if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1487
+ rotator.recordTokenUsage(
1488
+ body.displayModel || body.model,
1489
+ completion.inputTokens,
1490
+ completion.outputTokens,
1491
+ );
1492
+ }
1493
+ recordCompatOutcome(
1494
+ rotator,
1495
+ body,
1496
+ context,
1497
+ completion.streamError ? 502 : response.status,
1498
+ completion,
1499
+ undefined,
1500
+ options,
1501
+ );
1502
+ return completion;
1503
+ }
1504
+ },
1505
+ );
1506
+
1507
+ let outcome: RotationOutcome<CompatCompletion>;
1508
+ let isDeduplicated = false;
1509
+
1510
+ if (shouldDedup) {
1511
+ const clientKey = idempotencyManager.extractClientKey(req);
1512
+ const key = idempotencyManager.computeKey(
1513
+ body.model,
1514
+ options?.rawRequest || body,
1515
+ clientKey,
1516
+ );
1517
+ const dedupRes = await idempotencyManager
1518
+ .execute(key, windowMs, async () => {
1519
+ const res = await runWithRotation();
1520
+ if (!res.ok) {
1521
+ throw new NonOkOutcomeError(res);
1522
+ }
1523
+ return res;
1524
+ })
1525
+ .catch((err) => {
1526
+ if (err instanceof NonOkOutcomeError) {
1527
+ return { result: err.outcome, isDeduplicated: false };
1528
+ }
1529
+ throw err;
1530
+ });
1531
+ outcome = dedupRes.result;
1532
+ isDeduplicated = dedupRes.isDeduplicated;
1533
+ } else {
1534
+ outcome = await runWithRotation();
1535
+ }
1536
+
1537
+ if (!outcome.ok) {
1538
+ recordCompatFailure(rotator, body, outcome, options);
1539
+ if (outcome.status === 404) {
1540
+ compatLogger.warn(
1541
+ `Compat upstream 404 endpoint=${outcome.endpoint || "unknown"} ${summarizeCompatRequest(body)} error=${(outcome.errorText || "").slice(0, 300)}`,
1542
+ );
1543
+ }
1544
+ return {
1545
+ completion: { text: "", inputTokens: 0, outputTokens: 0 },
1546
+ status: outcome.status,
1547
+ errorText: outcome.retryAfterMs
1548
+ ? `${outcome.errorText}; retryAfterMs=${outcome.retryAfterMs}`
1549
+ : outcome.errorText,
1550
+ streamed: false,
1551
+ context: outcome.context,
1552
+ isDeduplicated,
1553
+ compressionStats: options?.compressionStats,
1554
+ };
1555
+ }
1556
+ return {
1557
+ completion: outcome.result,
1558
+ status: 200,
1559
+ streamed: streamMode !== "none",
1560
+ context: outcome.context,
1561
+ isDeduplicated,
1562
+ compressionStats: options?.compressionStats,
1563
+ };
1564
+ }
1565
+
1566
+ const MODEL_CATALOG = [
1567
+ {
1568
+ id: "gemini-3.5-flash-medium",
1569
+ family: "gemini-3.5-flash",
1570
+ ctx: 1048576,
1571
+ quotaPool: "gemini",
1572
+ multimodal: true,
1573
+ tools: true,
1574
+ },
1575
+ {
1576
+ id: "gemini-3.5-flash-high",
1577
+ family: "gemini-3.5-flash",
1578
+ ctx: 1048576,
1579
+ quotaPool: "gemini",
1580
+ multimodal: true,
1581
+ tools: true,
1582
+ },
1583
+ {
1584
+ id: "gemini-3-flash",
1585
+ family: "gemini-3.5-flash",
1586
+ ctx: 1048576,
1587
+ quotaPool: "gemini",
1588
+ multimodal: true,
1589
+ tools: true,
1590
+ },
1591
+ {
1592
+ id: "gemini-3.6-flash-high",
1593
+ family: "gemini-3.6-flash",
1594
+ ctx: 1048576,
1595
+ quotaPool: "gemini",
1596
+ multimodal: true,
1597
+ tools: true,
1598
+ },
1599
+ {
1600
+ id: "gemini-3.6-flash-medium",
1601
+ family: "gemini-3.6-flash",
1602
+ ctx: 1048576,
1603
+ quotaPool: "gemini",
1604
+ multimodal: true,
1605
+ tools: true,
1606
+ },
1607
+ {
1608
+ id: "gemini-3.6-flash-low",
1609
+ family: "gemini-3.6-flash",
1610
+ ctx: 1048576,
1611
+ quotaPool: "gemini",
1612
+ multimodal: true,
1613
+ tools: true,
1614
+ },
1615
+ {
1616
+ id: "gemini-3.6-flash-tiered",
1617
+ family: "gemini-3.6-flash",
1618
+ ctx: 1048576,
1619
+ quotaPool: "gemini",
1620
+ multimodal: true,
1621
+ tools: true,
1622
+ },
1623
+ {
1624
+ id: "gemini-3.1-pro-low",
1625
+ family: "gemini-3.1-pro",
1626
+ ctx: 1048576,
1627
+ quotaPool: "gemini",
1628
+ multimodal: true,
1629
+ tools: true,
1630
+ },
1631
+ {
1632
+ id: "gemini-3.1-pro-high",
1633
+ family: "gemini-3.1-pro",
1634
+ ctx: 1048576,
1635
+ quotaPool: "gemini",
1636
+ multimodal: true,
1637
+ tools: true,
1638
+ },
1639
+ {
1640
+ id: "claude-sonnet-4-6",
1641
+ family: "claude",
1642
+ ctx: 500000,
1643
+ quotaPool: "claude",
1644
+ multimodal: true,
1645
+ tools: true,
1646
+ },
1647
+ {
1648
+ id: "claude-opus-4-6-thinking",
1649
+ family: "claude",
1650
+ ctx: 500000,
1651
+ quotaPool: "claude",
1652
+ multimodal: true,
1653
+ tools: true,
1654
+ },
1655
+ {
1656
+ id: "gpt-oss-120b-medium",
1657
+ family: "gpt-oss",
1658
+ ctx: 131072,
1659
+ quotaPool: "claude",
1660
+ multimodal: false,
1661
+ tools: true,
1662
+ },
1663
+ ] as const;
1664
+
1665
+ export function serveOpenAIModels(
1666
+ res: ServerResponse,
1667
+ rotator?: AccountRotator,
1668
+ ): void {
1669
+ const catalog: Array<Record<string, unknown>> = MODEL_CATALOG.map(
1670
+ ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
1671
+ id,
1672
+ object: "model",
1673
+ created: 0,
1674
+ owned_by: "tuxevil-rotator",
1675
+ context_window: ctx,
1676
+ max_model_len: ctx,
1677
+ meta: {
1678
+ context_length: ctx,
1679
+ family,
1680
+ quota_pool: quotaPool,
1681
+ multimodal,
1682
+ tool_calling: tools,
1683
+ },
1684
+ }),
1685
+ );
1686
+ const ollamaModels = rotator?.getOllamaModels?.() ?? [];
1687
+ for (const id of ollamaModels) {
1688
+ catalog.push({
1689
+ id,
1690
+ object: "model",
1691
+ created: 0,
1692
+ owned_by: "ollama",
1693
+ context_window: 128000,
1694
+ max_model_len: 128000,
1695
+ meta: {
1696
+ context_length: 128000,
1697
+ family: "ollama-cloud",
1698
+ quota_pool: "ollama-cloud",
1699
+ multimodal: false,
1700
+ tool_calling: true,
1701
+ },
1702
+ });
1703
+ }
1704
+ writeJson(res, 200, { object: "list", data: catalog });
1705
+ }
1706
+
1707
+ export function serveGeminiModels(res: ServerResponse): void {
1708
+ writeJson(res, 200, {
1709
+ models: MODEL_CATALOG.map(
1710
+ ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
1711
+ name: `models/${id}`,
1712
+ baseModelId: family,
1713
+ version: "v2.0",
1714
+ displayName: id,
1715
+ description: `Tuxevil Rotator Gemini-compatible model entry for ${id}`,
1716
+ inputTokenLimit: ctx,
1717
+ outputTokenLimit: ctx,
1718
+ supportedGenerationMethods: [
1719
+ "generateContent",
1720
+ "streamGenerateContent",
1721
+ ],
1722
+ capabilities: {
1723
+ tools,
1724
+ multimodal,
1725
+ quotaPool,
1726
+ },
1727
+ }),
1728
+ ),
1729
+ });
1730
+ }
1731
+
1732
+ export async function handleGeminiGenerateContent(
1733
+ req: IncomingMessage,
1734
+ res: ServerResponse,
1735
+ rotator: AccountRotator,
1736
+ ): Promise<void> {
1737
+ let parsed: unknown;
1738
+ try {
1739
+ parsed = await readJsonBody(req);
1740
+ } catch (err) {
1741
+ if (err instanceof PayloadTooLargeError)
1742
+ return writeJson(res, 413, {
1743
+ error: { message: "Payload too large", status: "INVALID_ARGUMENT" },
1744
+ });
1745
+ return writeJson(res, 400, {
1746
+ error: { message: "Invalid JSON body", status: "INVALID_ARGUMENT" },
1747
+ });
1748
+ }
1749
+ if (!isRecord(parsed))
1750
+ return writeJson(res, 400, {
1751
+ error: { message: "Body must be an object", status: "INVALID_ARGUMENT" },
1752
+ });
1753
+
1754
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
1755
+ const modelToken = pathname.match(
1756
+ /\/v1beta\/models\/(.+):(generateContent|streamGenerateContent)$/,
1757
+ )?.[1];
1758
+ const model = modelToken
1759
+ ? decodeURIComponent(modelToken).replace(/^models\//, "")
1760
+ : null;
1761
+ if (!model)
1762
+ return writeJson(res, 400, {
1763
+ error: { message: "Model path is required", status: "INVALID_ARGUMENT" },
1764
+ });
1765
+
1766
+ const auth = await authenticateVirtualKey(req, model);
1767
+ if (!auth.authenticated) {
1768
+ sendAuthErrorResponse(res, auth);
1769
+ return;
1770
+ }
1771
+ const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1772
+
1773
+ const body: RequestBody = {
1774
+ model,
1775
+ project: "",
1776
+ request: {
1777
+ contents: Array.isArray(parsed.contents) ? parsed.contents : [],
1778
+ systemInstruction: parsed.systemInstruction,
1779
+ generationConfig: parsed.generationConfig,
1780
+ tools: parsed.tools,
1781
+ },
1782
+ };
1783
+ const started = Date.now();
1784
+ const result = await completeViaRotator(req, res, rotator, body, "none", {
1785
+ callType: "gemini",
1786
+ apiKeyHash,
1787
+ requesterIp: req.socket?.remoteAddress || null,
1788
+ rawRequest: parsed,
1789
+ });
1790
+ if (result.status !== 200) {
1791
+ return writeJson(res, result.status, {
1792
+ error: {
1793
+ message: result.errorText || "Upstream error",
1794
+ status: "UPSTREAM_ERROR",
1795
+ },
1796
+ });
1797
+ }
1798
+ if (result.streamed) return;
1799
+ const totalMs = Date.now() - started;
1800
+ const ttfbMs = result.completion.firstByteMs ?? totalMs;
1801
+ const rotatorHeaders = buildRotatorResponseHeaders({
1802
+ accountLabel: result.context?.label,
1803
+ model: model,
1804
+ latencyMs: totalMs,
1805
+ ttfbMs,
1806
+ inputTokens: result.completion.inputTokens,
1807
+ outputTokens: result.completion.outputTokens,
1808
+ healthScore: result.context?.account?.healthScore,
1809
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
1810
+ idempotencyHit: result.isDeduplicated,
1811
+ retries: result.context?.retries,
1812
+ compression: getCompressionHeaderOpts(result.compressionStats),
1813
+ });
1814
+ writeJson(res, 200, {
1815
+ candidates: [
1816
+ {
1817
+ content: {
1818
+ role: "model",
1819
+ parts: [{ text: result.completion.text }],
1820
+ },
1821
+ finishReason: "STOP",
1822
+ },
1823
+ ],
1824
+ usageMetadata: {
1825
+ promptTokenCount: result.completion.inputTokens,
1826
+ candidatesTokenCount: result.completion.outputTokens,
1827
+ totalTokenCount:
1828
+ result.completion.inputTokens + result.completion.outputTokens,
1829
+ },
1830
+ }, rotatorHeaders);
1831
+ }
1832
+
1833
+ export async function handleOpenAIChatCompletions(
1834
+ req: IncomingMessage,
1835
+ res: ServerResponse,
1836
+ rotator: AccountRotator,
1837
+ ): Promise<void> {
1838
+ let parsed: unknown;
1839
+ try {
1840
+ parsed = await readJsonBody(req);
1841
+ } catch (err) {
1842
+ if (err instanceof PayloadTooLargeError)
1843
+ return writeJson(res, 413, {
1844
+ error: { message: "Payload too large", type: "invalid_request_error" },
1845
+ });
1846
+ return writeJson(res, 400, {
1847
+ error: { message: "Invalid JSON body", type: "invalid_request_error" },
1848
+ });
1849
+ }
1850
+ const validation = validateOpenAIChatCompletionRequest(
1851
+ normalizeOpenAIChatCompletionRequest(parsed),
1852
+ );
1853
+ if (!validation.ok)
1854
+ return writeJson(res, 400, {
1855
+ error: {
1856
+ message: validation.errors.join("; "),
1857
+ type: "invalid_request_error",
1858
+ },
1859
+ });
1860
+
1861
+ const auth = await authenticateVirtualKey(req, validation.value.model);
1862
+ if (!auth.authenticated) {
1863
+ sendAuthErrorResponse(res, auth);
1864
+ return;
1865
+ }
1866
+ const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1867
+
1868
+ const compMode = parseCompressionMode(
1869
+ req.headers["x-rotator-compression"],
1870
+ rotator?.getConfig?.()?.compressionMode,
1871
+ );
1872
+ const compRes = applyPromptCompression(
1873
+ validation.value.messages,
1874
+ compMode,
1875
+ { model: validation.value.model },
1876
+ );
1877
+ const chatReq = compRes.stats
1878
+ ? { ...validation.value, messages: compRes.messages }
1879
+ : validation.value;
1880
+
1881
+ const started = Date.now();
1882
+ const streamMode = validation.value.stream ? "openai" : "none";
1883
+ const result = await completeViaRotator(
1884
+ req,
1885
+ res,
1886
+ rotator,
1887
+ (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq)),
1888
+ streamMode,
1889
+ {
1890
+ callType: "chat_completion",
1891
+ apiKeyHash,
1892
+ requesterIp: req.socket?.remoteAddress || null,
1893
+ rawRequest: validation.value,
1894
+ compressionStats: compRes.stats,
1895
+ },
1896
+ );
1897
+ if (result.status !== 200) {
1898
+ compatLogger.warn(
1899
+ `OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
1900
+ );
1901
+ if (!res.headersSent) {
1902
+ return writeJson(res, result.status, {
1903
+ error: {
1904
+ message: result.errorText || "Upstream error",
1905
+ type: "upstream_error",
1906
+ },
1907
+ });
1908
+ }
1909
+ return;
1910
+ }
1911
+ if (result.streamed) {
1912
+ return;
1913
+ }
1914
+ const hasToolCalls =
1915
+ result.completion.toolCalls && result.completion.toolCalls.length > 0;
1916
+ const totalMs = Date.now() - started;
1917
+ const ttfbMs = result.completion.firstByteMs ?? totalMs;
1918
+ const rotatorHeaders = buildRotatorResponseHeaders({
1919
+ accountLabel: result.context?.label,
1920
+ model: validation.value.model,
1921
+ latencyMs: totalMs,
1922
+ ttfbMs,
1923
+ inputTokens: result.completion.inputTokens,
1924
+ outputTokens: result.completion.outputTokens,
1925
+ healthScore: result.context?.account?.healthScore,
1926
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
1927
+ idempotencyHit: result.isDeduplicated,
1928
+ retries: result.context?.retries,
1929
+ });
1930
+ writeJson(res, 200, {
1931
+ id: `chatcmpl-${started.toString(36)}`,
1932
+ object: "chat.completion",
1933
+ created: Math.floor(started / 1000),
1934
+ model: validation.value.model,
1935
+ choices: [
1936
+ {
1937
+ index: 0,
1938
+ message: {
1939
+ role: "assistant",
1940
+ ...(hasToolCalls
1941
+ ? { content: null, tool_calls: result.completion.toolCalls }
1942
+ : { content: result.completion.text }),
1943
+ ...(result.completion.thinkingText
1944
+ ? { reasoning_content: result.completion.thinkingText }
1945
+ : {}),
1946
+ },
1947
+ finish_reason: hasToolCalls ? "tool_calls" : "stop",
1948
+ },
1949
+ ],
1950
+ usage: {
1951
+ prompt_tokens: result.completion.inputTokens,
1952
+ completion_tokens: result.completion.outputTokens,
1953
+ total_tokens:
1954
+ result.completion.inputTokens + result.completion.outputTokens,
1955
+ },
1956
+ }, rotatorHeaders);
1957
+ }
1958
+
1959
+ export async function handleOpenAIResponsesCreate(
1960
+ req: IncomingMessage,
1961
+ res: ServerResponse,
1962
+ rotator: AccountRotator,
1963
+ ): Promise<void> {
1964
+ let parsed: unknown;
1965
+ try {
1966
+ parsed = await readJsonBody(req);
1967
+ } catch (err) {
1968
+ if (err instanceof PayloadTooLargeError)
1969
+ return writeJson(res, 413, {
1970
+ error: { message: "Payload too large", type: "invalid_request_error" },
1971
+ });
1972
+ return writeJson(res, 400, {
1973
+ error: { message: "Invalid JSON body", type: "invalid_request_error" },
1974
+ });
1975
+ }
1976
+
1977
+ const normalized = normalizeOpenAIResponsesRequest(parsed);
1978
+ const validation = validateOpenAIResponsesRequest(normalized);
1979
+ if (!validation.ok)
1980
+ return writeJson(res, 400, {
1981
+ error: {
1982
+ message: validation.errors.join("; "),
1983
+ type: "invalid_request_error",
1984
+ },
1985
+ });
1986
+
1987
+ const auth = await authenticateVirtualKey(req, validation.value.model);
1988
+ if (!auth.authenticated) {
1989
+ sendAuthErrorResponse(res, auth);
1990
+ return;
1991
+ }
1992
+ const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1993
+
1994
+ let converted: ResponsesConversionResult;
1995
+ try {
1996
+ converted = convertResponsesToChatRequest(validation.value);
1997
+ } catch {
1998
+ return writeJson(res, 400, {
1999
+ error: {
2000
+ message: "Invalid responses request",
2001
+ type: "invalid_request_error",
2002
+ },
2003
+ });
2004
+ }
2005
+
2006
+ const responseId = makeCompatId("resp");
2007
+ const createdAt = Math.floor(Date.now() / 1000);
2008
+ const compMode = parseCompressionMode(
2009
+ req.headers["x-rotator-compression"],
2010
+ rotator?.getConfig?.()?.compressionMode,
2011
+ );
2012
+ const compRes = applyPromptCompression(
2013
+ converted.chatRequest.messages,
2014
+ compMode,
2015
+ { model: converted.chatRequest.model },
2016
+ );
2017
+ const chatRequest = compRes.stats
2018
+ ? { ...converted.chatRequest, messages: compRes.messages }
2019
+ : converted.chatRequest;
2020
+
2021
+ const requestBody = (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
2022
+ requestBody.requestId = responseId;
2023
+
2024
+ if (validation.value.store !== false) {
2025
+ const expiresAt = Date.now() + 6 * 60 * 60 * 1000;
2026
+ setStoredResponse(responseId, {
2027
+ response: buildResponsesResponse(
2028
+ validation.value,
2029
+ responseId,
2030
+ createdAt,
2031
+ { text: "", inputTokens: 0, outputTokens: 0, toolCalls: [] },
2032
+ "in_progress",
2033
+ converted.previousResponseId,
2034
+ ),
2035
+ inputItems: converted.inputItems,
2036
+ conversationMessages: converted.conversationMessages as unknown as Array<
2037
+ Record<string, unknown>
2038
+ >,
2039
+ callIdToName: {},
2040
+ expiresAt,
2041
+ });
2042
+ }
2043
+
2044
+ if (validation.value.stream) {
2045
+ const result = await completeResponsesViaRotator(
2046
+ req,
2047
+ res,
2048
+ rotator,
2049
+ validation.value,
2050
+ requestBody,
2051
+ responseId,
2052
+ converted.previousResponseId,
2053
+ {
2054
+ callType: "responses",
2055
+ apiKeyHash,
2056
+ requesterIp: req.socket?.remoteAddress || null,
2057
+ compressionStats: compRes.stats,
2058
+ },
2059
+ );
2060
+ if (result.status !== 200) {
2061
+ responsesStore.delete(responseId);
2062
+ if (!res.headersSent)
2063
+ return writeJson(res, result.status, {
2064
+ error: {
2065
+ message: result.errorText || "Upstream error",
2066
+ type: "upstream_error",
2067
+ },
2068
+ });
2069
+ return;
2070
+ }
2071
+ if (validation.value.store !== false) {
2072
+ const responseObject = buildResponsesResponse(
2073
+ validation.value,
2074
+ responseId,
2075
+ createdAt,
2076
+ result.completion,
2077
+ "completed",
2078
+ converted.previousResponseId,
2079
+ );
2080
+ saveResponsesEntry(
2081
+ responseObject,
2082
+ converted.inputItems,
2083
+ converted.conversationMessages,
2084
+ result.completion,
2085
+ );
2086
+ }
2087
+ return;
2088
+ }
2089
+
2090
+ const result = await completeViaRotator(
2091
+ req,
2092
+ res,
2093
+ rotator,
2094
+ requestBody,
2095
+ "none",
2096
+ {
2097
+ callType: "responses",
2098
+ apiKeyHash,
2099
+ requesterIp: req.socket?.remoteAddress || null,
2100
+ rawRequest: validation.value,
2101
+ compressionStats: compRes.stats,
2102
+ },
2103
+ );
2104
+ if (result.status !== 200) {
2105
+ responsesStore.delete(responseId);
2106
+ return writeJson(res, result.status, {
2107
+ error: {
2108
+ message: result.errorText || "Upstream error",
2109
+ type: "upstream_error",
2110
+ },
2111
+ });
2112
+ }
2113
+
2114
+ const responseObject = buildResponsesResponse(
2115
+ validation.value,
2116
+ responseId,
2117
+ createdAt,
2118
+ result.completion,
2119
+ "completed",
2120
+ converted.previousResponseId,
2121
+ );
2122
+ if (validation.value.store !== false) {
2123
+ saveResponsesEntry(
2124
+ responseObject,
2125
+ converted.inputItems,
2126
+ converted.conversationMessages,
2127
+ result.completion,
2128
+ );
2129
+ } else {
2130
+ responsesStore.delete(responseId);
2131
+ }
2132
+ const totalMs = Date.now() - (createdAt * 1000);
2133
+ const ttfbMs = result.completion.firstByteMs ?? totalMs;
2134
+ const rotatorHeaders = buildRotatorResponseHeaders({
2135
+ accountLabel: result.context?.label,
2136
+ model: validation.value.model,
2137
+ latencyMs: totalMs,
2138
+ ttfbMs,
2139
+ inputTokens: result.completion.inputTokens,
2140
+ outputTokens: result.completion.outputTokens,
2141
+ healthScore: result.context?.account?.healthScore,
2142
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
2143
+ idempotencyHit: result.isDeduplicated,
2144
+ retries: result.context?.retries,
2145
+ });
2146
+ writeJson(res, 200, responseObject, rotatorHeaders);
2147
+ }
2148
+
2149
+ export function handleOpenAIResponsesRetrieve(
2150
+ _req: IncomingMessage,
2151
+ res: ServerResponse,
2152
+ responseId: string,
2153
+ ): void {
2154
+ const entry = getStoredResponse(responseId);
2155
+ if (!entry)
2156
+ return writeJson(res, 404, {
2157
+ error: {
2158
+ message: `Response not found: ${responseId}`,
2159
+ type: "invalid_request_error",
2160
+ },
2161
+ });
2162
+ writeJson(res, 200, entry.response);
2163
+ }
2164
+
2165
+ export function handleOpenAIResponsesDelete(
2166
+ _req: IncomingMessage,
2167
+ res: ServerResponse,
2168
+ responseId: string,
2169
+ ): void {
2170
+ writeJson(res, 200, {
2171
+ id: responseId,
2172
+ object: "response.deleted",
2173
+ deleted: responsesStore.delete(responseId),
2174
+ });
2175
+ }
2176
+
2177
+ export function handleOpenAIResponsesCancel(
2178
+ _req: IncomingMessage,
2179
+ res: ServerResponse,
2180
+ responseId: string,
2181
+ ): void {
2182
+ const entry = getStoredResponse(responseId);
2183
+ if (!entry)
2184
+ return writeJson(res, 404, {
2185
+ error: {
2186
+ message: `Response not found: ${responseId}`,
2187
+ type: "invalid_request_error",
2188
+ },
2189
+ });
2190
+ if (entry.response.status === "in_progress")
2191
+ entry.response.status = "cancelled";
2192
+ writeJson(res, 200, entry.response);
2193
+ }
2194
+
2195
+ export function handleOpenAIResponsesInputItems(
2196
+ _req: IncomingMessage,
2197
+ res: ServerResponse,
2198
+ responseId: string,
2199
+ ): void {
2200
+ const entry = getStoredResponse(responseId);
2201
+ if (!entry)
2202
+ return writeJson(res, 404, {
2203
+ error: {
2204
+ message: `Response not found: ${responseId}`,
2205
+ type: "invalid_request_error",
2206
+ },
2207
+ });
2208
+ writeJson(res, 200, {
2209
+ object: "list",
2210
+ data: entry.inputItems,
2211
+ has_more: false,
2212
+ first_id: entry.inputItems[0]?.id ?? null,
2213
+ last_id: entry.inputItems.at(-1)?.id ?? null,
2214
+ });
2215
+ }
2216
+
2217
+ export async function handleAnthropicMessages(
2218
+ req: IncomingMessage,
2219
+ res: ServerResponse,
2220
+ rotator: AccountRotator,
2221
+ ): Promise<void> {
2222
+ let parsed: unknown;
2223
+ try {
2224
+ parsed = await readJsonBody(req);
2225
+ } catch (err) {
2226
+ if (err instanceof PayloadTooLargeError)
2227
+ return writeJson(res, 413, {
2228
+ type: "error",
2229
+ error: { type: "invalid_request_error", message: "Payload too large" },
2230
+ });
2231
+ return writeJson(res, 400, {
2232
+ type: "error",
2233
+ error: { type: "invalid_request_error", message: "Invalid JSON body" },
2234
+ });
2235
+ }
2236
+ const validation = validateAnthropicMessagesRequest(
2237
+ normalizeAnthropicMessagesRequest(parsed),
2238
+ );
2239
+ if (!validation.ok)
2240
+ return writeJson(res, 400, {
2241
+ type: "error",
2242
+ error: {
2243
+ type: "invalid_request_error",
2244
+ message: validation.errors.join("; "),
2245
+ },
2246
+ });
2247
+
2248
+ const auth = await authenticateVirtualKey(req, validation.value.model);
2249
+ if (!auth.authenticated) {
2250
+ sendAuthErrorResponse(res, auth);
2251
+ return;
2252
+ }
2253
+ const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
2254
+
2255
+ const compMode = parseCompressionMode(
2256
+ req.headers["x-rotator-compression"],
2257
+ rotator?.getConfig?.()?.compressionMode,
2258
+ );
2259
+ const compRes = applyPromptCompression(
2260
+ validation.value.messages as ChatMessage[],
2261
+ compMode,
2262
+ { model: validation.value.model },
2263
+ );
2264
+ const anthropicReq = compRes.stats
2265
+ ? {
2266
+ ...validation.value,
2267
+ messages: compRes.messages as typeof validation.value.messages,
2268
+ }
2269
+ : validation.value;
2270
+
2271
+ const started = Date.now();
2272
+ const streamMode = validation.value.stream ? "anthropic" : "none";
2273
+ const result = await completeViaRotator(
2274
+ req,
2275
+ res,
2276
+ rotator,
2277
+ (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq)),
2278
+ streamMode,
2279
+ {
2280
+ callType: "anthropic",
2281
+ apiKeyHash,
2282
+ requesterIp: req.socket?.remoteAddress || null,
2283
+ rawRequest: validation.value,
2284
+ compressionStats: compRes.stats,
2285
+ },
2286
+ );
2287
+ if (result.status !== 200) {
2288
+ compatLogger.warn(
2289
+ `Anthropic compat upstream failed status=${result.status} model=${validation.value.model}`,
2290
+ );
2291
+ if (!res.headersSent) {
2292
+ return writeJson(res, result.status, {
2293
+ type: "error",
2294
+ error: {
2295
+ type: "upstream_error",
2296
+ message: result.errorText || "Upstream error",
2297
+ },
2298
+ });
2299
+ }
2300
+ return;
2301
+ }
2302
+ if (result.streamed) {
2303
+ return;
2304
+ }
2305
+ const contentBlocks: Array<Record<string, unknown>> = [];
2306
+ if (result.completion.thinkingText) {
2307
+ contentBlocks.push({
2308
+ type: "thinking",
2309
+ thinking: result.completion.thinkingText,
2310
+ });
2311
+ }
2312
+ if (result.completion.text) {
2313
+ contentBlocks.push({ type: "text", text: result.completion.text });
2314
+ }
2315
+ if (result.completion.toolCalls && result.completion.toolCalls.length > 0) {
2316
+ for (const tc of result.completion.toolCalls) {
2317
+ const parsedInput = toolArgumentsToObject(tc.function.arguments);
2318
+ contentBlocks.push({
2319
+ type: "tool_use",
2320
+ id: tc.id,
2321
+ name: tc.function.name,
2322
+ input: parsedInput,
2323
+ });
2324
+ }
2325
+ }
2326
+ const stopReason =
2327
+ result.completion.toolCalls && result.completion.toolCalls.length > 0
2328
+ ? "tool_use"
2329
+ : "end_turn";
2330
+ const totalMs = Date.now() - started;
2331
+ const ttfbMs = result.completion.firstByteMs ?? totalMs;
2332
+ const rotatorHeaders = buildRotatorResponseHeaders({
2333
+ accountLabel: result.context?.label,
2334
+ model: validation.value.model,
2335
+ latencyMs: totalMs,
2336
+ ttfbMs,
2337
+ inputTokens: result.completion.inputTokens,
2338
+ outputTokens: result.completion.outputTokens,
2339
+ healthScore: result.context?.account?.healthScore,
2340
+ routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
2341
+ idempotencyHit: result.isDeduplicated,
2342
+ retries: result.context?.retries,
2343
+ });
2344
+ writeJson(res, 200, {
2345
+ id: `msg_${started.toString(36)}`,
2346
+ type: "message",
2347
+ role: "assistant",
2348
+ model: validation.value.model,
2349
+ content: contentBlocks,
2350
+ stop_reason: stopReason,
2351
+ stop_sequence: null,
2352
+ usage: {
2353
+ input_tokens: result.completion.inputTokens,
2354
+ output_tokens: result.completion.outputTokens,
2355
+ },
2356
+ }, rotatorHeaders);
2357
+ }