tuxevil-rotator 3.0.0 → 3.2.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 (42) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +20 -6
  3. package/package.json +1 -1
  4. package/src/account-store.ts +37 -5
  5. package/src/cli.ts +24 -3
  6. package/src/compat/model-specs.ts +1 -0
  7. package/src/compat.ts +540 -24
  8. package/src/config-normalize.ts +73 -30
  9. package/src/dashboard.ts +43 -42
  10. package/src/index.ts +1 -0
  11. package/src/onboarding.ts +349 -21
  12. package/src/providers/adapter.ts +18 -0
  13. package/src/providers/credential-helpers.ts +64 -0
  14. package/src/providers/google-antigravity/index.ts +9 -0
  15. package/src/providers/google-antigravity/quota.ts +2 -1
  16. package/src/providers/google-antigravity/translators.ts +83 -24
  17. package/src/providers/ollama/index.ts +8 -0
  18. package/src/providers/ollama/quota.ts +2 -1
  19. package/src/providers/openai-codex/catalog.ts +117 -0
  20. package/src/providers/openai-codex/compat.ts +556 -0
  21. package/src/providers/openai-codex/credentials.ts +82 -0
  22. package/src/providers/openai-codex/forward.ts +240 -0
  23. package/src/providers/openai-codex/index.ts +153 -0
  24. package/src/providers/openai-codex/login.ts +172 -0
  25. package/src/providers/openai-codex/oauth.ts +359 -0
  26. package/src/providers/openai-codex/quota.ts +231 -0
  27. package/src/providers/opencode-zen/catalog.ts +37 -0
  28. package/src/providers/opencode-zen/credentials.ts +31 -0
  29. package/src/providers/opencode-zen/forward.ts +214 -0
  30. package/src/providers/opencode-zen/index.ts +73 -0
  31. package/src/providers/opencode-zen/login.ts +81 -0
  32. package/src/providers/opencode-zen/quota.ts +67 -0
  33. package/src/providers/registry.ts +24 -5
  34. package/src/proxy.ts +75 -27
  35. package/src/rate-limit-parser.ts +2 -1
  36. package/src/rotator.ts +259 -48
  37. package/src/spend-logger.ts +2 -0
  38. package/src/static/dashboard-keys.js +152 -2
  39. package/src/static/dashboard.js +161 -37
  40. package/src/types.ts +83 -1
  41. package/src/validators.ts +11 -2
  42. package/tools/telemetry-receiver/receiver.js +14 -0
package/src/compat.ts CHANGED
@@ -54,19 +54,24 @@ import {
54
54
  convertResponsesToChatRequest,
55
55
  openAIToAntigravityBody,
56
56
  anthropicToAntigravityBody,
57
+ convertAnthropicToolsToOpenAI,
58
+ convertAnthropicToolChoice,
59
+ convertAnthropicMessagesToOpenAI,
60
+ extractText,
57
61
  validateOpenAIChatCompletionRequest,
58
62
  validateOpenAIResponsesRequest,
59
63
  validateAnthropicMessagesRequest,
60
64
  buildResponsesResponse,
61
65
  saveResponsesEntry,
62
66
  toolArgumentsToObject,
63
- toolArgumentsToString,
64
67
  } from "./providers/google-antigravity/translators.js";
65
68
  import {
66
69
  openAIToOllamaBody,
67
70
  anthropicToOllamaBody,
68
71
  parseOllamaNdjson,
69
72
  } from "./providers/ollama/translators.js";
73
+ import { OPENCODE_ZEN_CATALOG, isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
74
+ import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
70
75
  import type {
71
76
  ChatMessage,
72
77
  OpenAITool,
@@ -78,6 +83,22 @@ import type {
78
83
  CompatCompletion,
79
84
  ResponsesConversionResult,
80
85
  } from "./providers/google-antigravity/translators.js";
86
+ import {
87
+ isCodexRequestModel,
88
+ isCodexProviderModelId,
89
+ getCodexModels,
90
+ } from "./providers/openai-codex/catalog.js";
91
+ import { serveCodexChat, serveCodexResponses } from "./providers/openai-codex/compat.js";
92
+
93
+ function isCodexModelForRotator(rotator: AccountRotator, model: string): boolean {
94
+ if (isCodexRequestModel(model)) return true;
95
+ if (!isCodexProviderModelId(model)) return false;
96
+ try {
97
+ return rotator.getCodexModels?.().includes(model) ?? false;
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
81
102
 
82
103
  export {
83
104
  isRecord,
@@ -100,6 +121,7 @@ export {
100
121
  validateOpenAIChatCompletionRequest,
101
122
  validateOpenAIResponsesRequest,
102
123
  validateAnthropicMessagesRequest,
124
+ isCodexModelForRotator,
103
125
  };
104
126
  export type {
105
127
  ModelSpec,
@@ -134,6 +156,162 @@ export function logValidationFailure(scope: string, payload: unknown): void {
134
156
 
135
157
  // Helper and translation functions have been moved to src/providers/google-antigravity/translators.ts
136
158
 
159
+ export function anthropicToOpenAIChatRequest(
160
+ input: AnthropicMessagesRequest,
161
+ ): OpenAIChatCompletionRequest {
162
+ const systemText =
163
+ typeof input.system === "string"
164
+ ? input.system
165
+ : Array.isArray(input.system)
166
+ ? extractText(input.system as ChatMessage["content"])
167
+ : "";
168
+ const tools = convertAnthropicToolsToOpenAI(input.tools);
169
+ const toolChoice = convertAnthropicToolChoice(input.tool_choice);
170
+ const convertedMessages = convertAnthropicMessagesToOpenAI(input.messages);
171
+ return {
172
+ model: input.model,
173
+ stream: input.stream,
174
+ temperature: input.temperature,
175
+ max_tokens: input.max_tokens,
176
+ tools: tools as OpenAIChatCompletionRequest["tools"],
177
+ tool_choice: toolChoice as OpenAIChatCompletionRequest["tool_choice"],
178
+ messages: [
179
+ ...(systemText ? [{ role: "system" as const, content: systemText }] : []),
180
+ ...convertedMessages,
181
+ ],
182
+ };
183
+ }
184
+
185
+ export function extractRetryAfterSeconds(errorText?: string): number | null {
186
+ if (!errorText) return null;
187
+ const match = errorText.match(/retryAfterMs=(\d+)/i);
188
+ if (match) {
189
+ const ms = parseInt(match[1], 10);
190
+ return Math.max(1, Math.ceil(ms / 1000));
191
+ }
192
+ const secMatch = errorText.match(/(?:wait|retry in|after)\s+(\d+)\s*s/i);
193
+ if (secMatch) {
194
+ return Math.max(1, parseInt(secMatch[1], 10));
195
+ }
196
+ return null;
197
+ }
198
+
199
+ export function parseOpenAiJson(raw: string): CompatCompletion {
200
+ let text = "";
201
+ let thinkingText = "";
202
+ let inputTokens = 0;
203
+ let outputTokens = 0;
204
+ let responseId: string | undefined;
205
+ const toolCallsMap = new Map<string, OpenAIToolCall>();
206
+ let toolCallIndex = 0;
207
+
208
+ const trimmed = raw.trim();
209
+ if (trimmed.startsWith("data:") || trimmed.includes("\ndata:")) {
210
+ const lines = trimmed.split("\n");
211
+ for (const line of lines) {
212
+ const lineTrimmed = line.trim();
213
+ if (!lineTrimmed.startsWith("data:")) continue;
214
+ const payload = lineTrimmed.slice(5).trim();
215
+ if (!payload || payload === "[DONE]") continue;
216
+ try {
217
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
218
+ if (isRecord(parsed.usage)) {
219
+ if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
220
+ if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
221
+ }
222
+ if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
223
+ const choice = parsed.choices[0];
224
+ if (isRecord(choice)) {
225
+ const delta = isRecord(choice.delta) ? choice.delta : isRecord(choice.message) ? choice.message : {};
226
+ if (typeof delta.reasoning_content === "string") {
227
+ thinkingText += delta.reasoning_content;
228
+ }
229
+ if (typeof delta.content === "string") {
230
+ text += delta.content;
231
+ }
232
+ if (Array.isArray(delta.tool_calls)) {
233
+ for (const tc of delta.tool_calls) {
234
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
235
+ const tcIndex = typeof tc.index === "number" ? tc.index : 0;
236
+ const key = String(tcIndex);
237
+ let existing = toolCallsMap.get(key);
238
+ if (!existing) {
239
+ const callId = typeof tc.id === "string" && tc.id ? tc.id : `call_${Date.now().toString(36)}_${toolCallIndex++}`;
240
+ const name = typeof tc.function.name === "string" && tc.function.name ? tc.function.name : "unknown";
241
+ existing = {
242
+ id: callId,
243
+ type: "function",
244
+ function: { name, arguments: "" },
245
+ };
246
+ toolCallsMap.set(key, existing);
247
+ } else {
248
+ if (typeof tc.id === "string" && tc.id) existing.id = tc.id;
249
+ if (typeof tc.function.name === "string" && tc.function.name && existing.function.name === "unknown") {
250
+ existing.function.name = tc.function.name;
251
+ }
252
+ }
253
+ const argsDelta = typeof tc.function.arguments === "string" ? tc.function.arguments : "";
254
+ if (argsDelta) {
255
+ existing.function.arguments += argsDelta;
256
+ }
257
+ }
258
+ }
259
+ }
260
+ }
261
+ } catch {
262
+ // Ignore bad SSE line
263
+ }
264
+ }
265
+ } else {
266
+ try {
267
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
268
+ if (typeof parsed.id === "string") responseId = parsed.id;
269
+ if (isRecord(parsed.usage)) {
270
+ if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
271
+ if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
272
+ }
273
+ if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
274
+ const choice = parsed.choices[0];
275
+ if (isRecord(choice) && isRecord(choice.message)) {
276
+ const msg = choice.message;
277
+ if (typeof msg.content === "string") {
278
+ text = msg.content;
279
+ }
280
+ if (typeof msg.reasoning_content === "string") {
281
+ thinkingText = msg.reasoning_content;
282
+ }
283
+ if (Array.isArray(msg.tool_calls)) {
284
+ for (const tc of msg.tool_calls) {
285
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
286
+ const name = typeof tc.function.name === "string" ? tc.function.name : "unknown";
287
+ const args = typeof tc.function.arguments === "string"
288
+ ? tc.function.arguments
289
+ : JSON.stringify(tc.function.arguments ?? {});
290
+ const callId = typeof tc.id === "string" ? tc.id : `call_${Date.now().toString(36)}_${toolCallIndex++}`;
291
+ toolCallsMap.set(name + callId, {
292
+ id: callId,
293
+ type: "function",
294
+ function: { name, arguments: args },
295
+ });
296
+ }
297
+ }
298
+ }
299
+ }
300
+ } catch {
301
+ // Ignore invalid JSON
302
+ }
303
+ }
304
+
305
+ return {
306
+ text,
307
+ thinkingText,
308
+ inputTokens,
309
+ outputTokens,
310
+ responseId,
311
+ toolCalls: Array.from(toolCallsMap.values()),
312
+ };
313
+ }
314
+
137
315
  export function parseAntigravitySse(raw: string): CompatCompletion {
138
316
  let text = "";
139
317
  let thinkingText = "";
@@ -402,7 +580,7 @@ async function streamCompatSse(
402
580
  context?: RotationAttemptContext,
403
581
  rotator?: AccountRotator,
404
582
  compressionStats?: CompressionStats | null,
405
- upstream: "google" | "ollama" = "google",
583
+ upstream: "google" | "ollama" | "opencode-zen" = "google",
406
584
  ): Promise<CompatCompletion> {
407
585
  const nodeStream = Readable.fromWeb(
408
586
  body as import("node:stream/web").ReadableStream,
@@ -458,6 +636,15 @@ async function streamCompatSse(
458
636
  let tailBuffer = "";
459
637
  let reqClosed = false;
460
638
  let streamError: string | undefined;
639
+ interface OpenAiStreamingToolState {
640
+ id: string;
641
+ name: string;
642
+ arguments: string;
643
+ anthropicBlockIndex?: number;
644
+ anthropicStarted?: boolean;
645
+ openaiToolCallIndex: number;
646
+ }
647
+ const openAiStreamingTools = new Map<number, OpenAiStreamingToolState>();
461
648
  const emitOllamaLine = (line: string): void => {
462
649
  try {
463
650
  const parsed = JSON.parse(line) as Record<string, unknown>;
@@ -534,6 +721,191 @@ async function streamCompatSse(
534
721
  // Ignore malformed NDJSON lines
535
722
  }
536
723
  };
724
+ const emitOpenAiSseLine = (line: string): void => {
725
+ if (!line.startsWith("data:")) return;
726
+ const payload = line.slice(5).trim();
727
+ if (!payload || payload === "[DONE]") return;
728
+ try {
729
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
730
+ if (!isRecord(parsed)) return;
731
+
732
+ if (isRecord(parsed.usage)) {
733
+ if (typeof parsed.usage.prompt_tokens === "number") inputTokens = parsed.usage.prompt_tokens;
734
+ if (typeof parsed.usage.completion_tokens === "number") outputTokens = parsed.usage.completion_tokens;
735
+ }
736
+
737
+ if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
738
+ const choice = parsed.choices[0];
739
+ if (!isRecord(choice)) return;
740
+
741
+ const delta = isRecord(choice.delta) ? choice.delta : {};
742
+ const reasoningText = typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
743
+ const deltaText = typeof delta.content === "string" ? delta.content : "";
744
+
745
+ if (reasoningText) {
746
+ if (format === "openai") {
747
+ res.write(
748
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { reasoning_content: reasoningText }, finish_reason: null }] })}\n\n`,
749
+ );
750
+ } else {
751
+ if (anthropicActiveBlockType !== "thinking") {
752
+ if (anthropicActiveBlockType === "text") {
753
+ res.write(
754
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
755
+ );
756
+ }
757
+ anthropicActiveBlockIndex = 0;
758
+ anthropicActiveBlockType = "thinking";
759
+ res.write(
760
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "thinking", thinking: "" } })}\n\n`,
761
+ );
762
+ }
763
+ res.write(
764
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "thinking_delta", thinking: reasoningText } })}\n\n`,
765
+ );
766
+ }
767
+ }
768
+
769
+ if (deltaText) {
770
+ text += deltaText;
771
+ if (format === "openai") {
772
+ res.write(
773
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { content: deltaText }, finish_reason: null }] })}\n\n`,
774
+ );
775
+ } else {
776
+ if (anthropicActiveBlockType !== "text") {
777
+ if (anthropicActiveBlockType === "thinking") {
778
+ res.write(
779
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
780
+ );
781
+ anthropicActiveBlockIndex = 1;
782
+ } else {
783
+ anthropicActiveBlockIndex = 0;
784
+ }
785
+ anthropicActiveBlockType = "text";
786
+ res.write(
787
+ `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: anthropicActiveBlockIndex, content_block: { type: "text", text: "" } })}\n\n`,
788
+ );
789
+ }
790
+ res.write(
791
+ `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: anthropicActiveBlockIndex, delta: { type: "text_delta", text: deltaText } })}\n\n`,
792
+ );
793
+ }
794
+ }
795
+
796
+ if (Array.isArray(delta.tool_calls)) {
797
+ for (const tc of delta.tool_calls) {
798
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
799
+ const tcIndex = typeof tc.index === "number" ? tc.index : 0;
800
+ let state = openAiStreamingTools.get(tcIndex);
801
+ if (!state) {
802
+ const callId = typeof tc.id === "string" && tc.id ? tc.id : `call_${Date.now().toString(36)}_${toolCallIndex++}`;
803
+ const name = typeof tc.function.name === "string" && tc.function.name ? tc.function.name : "unknown";
804
+ state = {
805
+ id: callId,
806
+ name,
807
+ arguments: "",
808
+ openaiToolCallIndex: toolCallIndex - 1,
809
+ };
810
+ openAiStreamingTools.set(tcIndex, state);
811
+ } else {
812
+ if (typeof tc.id === "string" && tc.id) state.id = tc.id;
813
+ if (typeof tc.function.name === "string" && tc.function.name && state.name === "unknown") {
814
+ state.name = tc.function.name;
815
+ }
816
+ }
817
+
818
+ const argsDelta = typeof tc.function.arguments === "string" ? tc.function.arguments : "";
819
+ if (argsDelta) {
820
+ state.arguments += argsDelta;
821
+ }
822
+
823
+ if (format === "openai") {
824
+ const existingRecord = openaiToolCalls.find((c) => c.id === state!.id);
825
+ if (existingRecord) {
826
+ existingRecord.function.name = state.name;
827
+ existingRecord.function.arguments = state.arguments;
828
+ } else {
829
+ openaiToolCalls.push({
830
+ id: state.id,
831
+ type: "function",
832
+ function: { name: state.name, arguments: state.arguments },
833
+ });
834
+ }
835
+
836
+ res.write(
837
+ `data: ${JSON.stringify({
838
+ id,
839
+ object: "chat.completion.chunk",
840
+ created,
841
+ model,
842
+ choices: [{
843
+ index: 0,
844
+ delta: {
845
+ tool_calls: [{
846
+ index: tcIndex,
847
+ ...(tc.id ? { id: state.id } : {}),
848
+ ...(tc.type ? { type: "function" } : {}),
849
+ function: {
850
+ ...(tc.function.name ? { name: state.name } : {}),
851
+ arguments: argsDelta,
852
+ },
853
+ }],
854
+ },
855
+ finish_reason: null,
856
+ }],
857
+ })}\n\n`,
858
+ );
859
+ } else {
860
+ if (!state.anthropicStarted) {
861
+ if (anthropicActiveBlockType !== null) {
862
+ res.write(
863
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
864
+ );
865
+ anthropicActiveBlockType = null;
866
+ }
867
+ anthropicActiveBlockIndex++;
868
+ state.anthropicBlockIndex = anthropicActiveBlockIndex;
869
+ state.anthropicStarted = true;
870
+ anthropicHasToolUse = true;
871
+
872
+ anthropicToolCalls.push({
873
+ id: state.id,
874
+ type: "function",
875
+ function: { name: state.name, arguments: state.arguments },
876
+ });
877
+
878
+ res.write(
879
+ `event: content_block_start\ndata: ${JSON.stringify({
880
+ type: "content_block_start",
881
+ index: state.anthropicBlockIndex,
882
+ content_block: { type: "tool_use", id: state.id, name: state.name, input: {} },
883
+ })}\n\n`,
884
+ );
885
+ } else {
886
+ const rec = anthropicToolCalls.find((c) => c.id === state!.id);
887
+ if (rec) {
888
+ rec.function.name = state.name;
889
+ rec.function.arguments = state.arguments;
890
+ }
891
+ }
892
+
893
+ if (argsDelta) {
894
+ res.write(
895
+ `event: content_block_delta\ndata: ${JSON.stringify({
896
+ type: "content_block_delta",
897
+ index: state.anthropicBlockIndex,
898
+ delta: { type: "input_json_delta", partial_json: argsDelta },
899
+ })}\n\n`,
900
+ );
901
+ }
902
+ }
903
+ }
904
+ }
905
+ } catch {
906
+ // Ignore malformed SSE lines
907
+ }
908
+ };
537
909
  const closeUpstreamForClient = (): void => {
538
910
  reqClosed = true;
539
911
  if (!nodeStream.destroyed) nodeStream.destroy();
@@ -562,6 +934,10 @@ async function streamCompatSse(
562
934
  if (line) emitOllamaLine(line);
563
935
  continue;
564
936
  }
937
+ if (upstream === "opencode-zen") {
938
+ if (line) emitOpenAiSseLine(line);
939
+ continue;
940
+ }
565
941
  if (!line.startsWith("data:")) continue;
566
942
  const payload = line.slice(5).trim();
567
943
  if (!payload || payload === "[DONE]") continue;
@@ -743,6 +1119,13 @@ async function streamCompatSse(
743
1119
  `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
744
1120
  );
745
1121
  }
1122
+ for (const toolState of openAiStreamingTools.values()) {
1123
+ if (toolState.anthropicStarted) {
1124
+ res.write(
1125
+ `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: toolState.anthropicBlockIndex })}\n\n`,
1126
+ );
1127
+ }
1128
+ }
746
1129
  const anthropicStopReason = anthropicHasToolUse ? "tool_use" : "end_turn";
747
1130
  // message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
748
1131
  res.write(
@@ -1451,9 +1834,11 @@ async function completeViaRotator(
1451
1834
  async (response, context) => {
1452
1835
  if (streamMode === "none") {
1453
1836
  const raw = await response.text();
1454
- const completion = isOllamaUpstream(body.model)
1455
- ? parseOllamaNdjson(raw)
1456
- : parseAntigravitySse(raw);
1837
+ const completion = isOpenCodeZenModel(body.model)
1838
+ ? parseOpenAiJson(raw)
1839
+ : isOllamaUpstream(body.model)
1840
+ ? parseOllamaNdjson(raw)
1841
+ : parseAntigravitySse(raw);
1457
1842
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1458
1843
  rotator.recordTokenUsage(
1459
1844
  body.displayModel || body.model,
@@ -1481,7 +1866,11 @@ async function completeViaRotator(
1481
1866
  context,
1482
1867
  rotator,
1483
1868
  options?.compressionStats,
1484
- isOllamaUpstream(body.model) ? "ollama" : "google",
1869
+ isOpenCodeZenModel(body.model)
1870
+ ? "opencode-zen"
1871
+ : isOllamaUpstream(body.model)
1872
+ ? "ollama"
1873
+ : "google",
1485
1874
  );
1486
1875
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1487
1876
  rotator.recordTokenUsage(
@@ -1620,6 +2009,14 @@ const MODEL_CATALOG = [
1620
2009
  multimodal: true,
1621
2010
  tools: true,
1622
2011
  },
2012
+ {
2013
+ id: "gemini-3.7-flash-tiered",
2014
+ family: "gemini-3.7-flash",
2015
+ ctx: 1048576,
2016
+ quotaPool: "gemini",
2017
+ multimodal: true,
2018
+ tools: true,
2019
+ },
1623
2020
  {
1624
2021
  id: "gemini-3.1-pro-low",
1625
2022
  family: "gemini-3.1-pro",
@@ -1662,11 +2059,33 @@ const MODEL_CATALOG = [
1662
2059
  },
1663
2060
  ] as const;
1664
2061
 
1665
- export function serveOpenAIModels(
1666
- res: ServerResponse,
2062
+ export interface OpenAIModelCatalogEntry {
2063
+ id: string;
2064
+ object: "model";
2065
+ created: number;
2066
+ owned_by: string;
2067
+ context_window: number;
2068
+ max_model_len: number;
2069
+ meta: Record<string, unknown>;
2070
+ }
2071
+
2072
+ /**
2073
+ * Build the full OpenAI-compatible model catalog (static Antigravity catalog
2074
+ * + active-provider models for Ollama, OpenAI Codex and OpenCode Zen).
2075
+ *
2076
+ * This is the single source of truth for "what models can the rotator route
2077
+ * today" and is consumed by:
2078
+ * - the public /v1/models endpoint (OpenAI compat)
2079
+ * - the admin /api/models endpoint (dashboard virtual key editor)
2080
+ *
2081
+ * Pass the live AccountRotator so dynamic provider catalogs (Ollama tags
2082
+ * fetched at startup, Codex base + discovered models) are included. Without
2083
+ * a rotator, only the static MODEL_CATALOG is returned.
2084
+ */
2085
+ export function buildOpenAIModelCatalog(
1667
2086
  rotator?: AccountRotator,
1668
- ): void {
1669
- const catalog: Array<Record<string, unknown>> = MODEL_CATALOG.map(
2087
+ ): OpenAIModelCatalogEntry[] {
2088
+ const catalog: OpenAIModelCatalogEntry[] = MODEL_CATALOG.map(
1670
2089
  ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
1671
2090
  id,
1672
2091
  object: "model",
@@ -1683,7 +2102,31 @@ export function serveOpenAIModels(
1683
2102
  },
1684
2103
  }),
1685
2104
  );
1686
- const ollamaModels = rotator?.getOllamaModels?.() ?? [];
2105
+ const hasActiveProvider = (providerId: string): boolean =>
2106
+ rotator?.hasActiveProvider(providerId) ?? false;
2107
+ const ollamaModels = hasActiveProvider("ollama")
2108
+ ? rotator?.getOllamaModels?.() ?? []
2109
+ : [];
2110
+ if (hasActiveProvider("openai-codex")) {
2111
+ for (const model of getCodexModels()) {
2112
+ catalog.push({
2113
+ id: model.id,
2114
+ object: "model",
2115
+ created: 0,
2116
+ owned_by: "openai-codex",
2117
+ context_window: model.contextWindow,
2118
+ max_model_len: model.contextWindow,
2119
+ meta: {
2120
+ context_length: model.contextWindow,
2121
+ family: "openai-codex",
2122
+ provider: "openai-codex",
2123
+ reasoning: model.reasoning,
2124
+ multimodal: model.multimodal,
2125
+ tool_calling: model.tools,
2126
+ },
2127
+ });
2128
+ }
2129
+ }
1687
2130
  for (const id of ollamaModels) {
1688
2131
  catalog.push({
1689
2132
  id,
@@ -1701,7 +2144,33 @@ export function serveOpenAIModels(
1701
2144
  },
1702
2145
  });
1703
2146
  }
1704
- writeJson(res, 200, { object: "list", data: catalog });
2147
+ if (hasActiveProvider(OPENCODE_ZEN_PROVIDER_ID)) {
2148
+ for (const spec of OPENCODE_ZEN_CATALOG) {
2149
+ catalog.push({
2150
+ id: spec.id,
2151
+ object: "model",
2152
+ created: 0,
2153
+ owned_by: OPENCODE_ZEN_PROVIDER_ID,
2154
+ context_window: spec.contextWindow,
2155
+ max_model_len: spec.contextWindow,
2156
+ meta: {
2157
+ context_length: spec.contextWindow,
2158
+ family: "opencode-zen",
2159
+ provider: OPENCODE_ZEN_PROVIDER_ID,
2160
+ multimodal: false,
2161
+ tool_calling: true,
2162
+ },
2163
+ });
2164
+ }
2165
+ }
2166
+ return catalog;
2167
+ }
2168
+
2169
+ export function serveOpenAIModels(
2170
+ res: ServerResponse,
2171
+ rotator?: AccountRotator,
2172
+ ): void {
2173
+ writeJson(res, 200, { object: "list", data: buildOpenAIModelCatalog(rotator) });
1705
2174
  }
1706
2175
 
1707
2176
  export function serveGeminiModels(res: ServerResponse): void {
@@ -1788,12 +2257,18 @@ export async function handleGeminiGenerateContent(
1788
2257
  rawRequest: parsed,
1789
2258
  });
1790
2259
  if (result.status !== 200) {
2260
+ const retrySec = extractRetryAfterSeconds(result.errorText);
2261
+ const headers: Record<string, string> = retrySec ? { "Retry-After": String(retrySec) } : {};
2262
+ const message = retrySec
2263
+ ? `Rate limit exceeded. All accounts cooling down. Please wait ${retrySec} seconds before retrying.`
2264
+ : (result.errorText || "Upstream error");
1791
2265
  return writeJson(res, result.status, {
1792
2266
  error: {
1793
- message: result.errorText || "Upstream error",
1794
- status: "UPSTREAM_ERROR",
2267
+ message,
2268
+ status: result.status === 429 ? "RESOURCE_EXHAUSTED" : "UPSTREAM_ERROR",
2269
+ ...(retrySec ? { retry_after_seconds: retrySec } : {}),
1795
2270
  },
1796
- });
2271
+ }, headers);
1797
2272
  }
1798
2273
  if (result.streamed) return;
1799
2274
  const totalMs = Date.now() - started;
@@ -1865,6 +2340,16 @@ export async function handleOpenAIChatCompletions(
1865
2340
  }
1866
2341
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1867
2342
 
2343
+ if (isCodexModelForRotator(rotator, validation.value.model)) {
2344
+ await serveCodexChat(req, res, rotator, validation.value, {
2345
+ callType: "chat_completion",
2346
+ apiKeyHash,
2347
+ requesterIp: req.socket?.remoteAddress || null,
2348
+ rawRequest: validation.value,
2349
+ });
2350
+ return;
2351
+ }
2352
+
1868
2353
  const compMode = parseCompressionMode(
1869
2354
  req.headers["x-rotator-compression"],
1870
2355
  rotator?.getConfig?.()?.compressionMode,
@@ -1880,11 +2365,14 @@ export async function handleOpenAIChatCompletions(
1880
2365
 
1881
2366
  const started = Date.now();
1882
2367
  const streamMode = validation.value.stream ? "openai" : "none";
2368
+ const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model)
2369
+ ? { project: "", model: chatReq.model, request: chatReq }
2370
+ : (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq));
1883
2371
  const result = await completeViaRotator(
1884
2372
  req,
1885
2373
  res,
1886
2374
  rotator,
1887
- (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq)),
2375
+ bodyToForward,
1888
2376
  streamMode,
1889
2377
  {
1890
2378
  callType: "chat_completion",
@@ -1899,12 +2387,20 @@ export async function handleOpenAIChatCompletions(
1899
2387
  `OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
1900
2388
  );
1901
2389
  if (!res.headersSent) {
2390
+ const retrySec = extractRetryAfterSeconds(result.errorText);
2391
+ const headers: Record<string, string> = retrySec ? { "Retry-After": String(retrySec) } : {};
2392
+ const message = retrySec
2393
+ ? `Rate limit exceeded. All accounts cooling down. Please wait ${retrySec} seconds before retrying.`
2394
+ : (result.errorText || "Upstream error");
1902
2395
  return writeJson(res, result.status, {
1903
2396
  error: {
1904
- message: result.errorText || "Upstream error",
1905
- type: "upstream_error",
2397
+ message,
2398
+ type: result.status === 429 ? "rate_limit_error" : "upstream_error",
2399
+ param: null,
2400
+ code: result.status === 429 ? "rate_limit_exceeded" : "upstream_error",
2401
+ ...(retrySec ? { retry_after_seconds: retrySec } : {}),
1906
2402
  },
1907
- });
2403
+ }, headers);
1908
2404
  }
1909
2405
  return;
1910
2406
  }
@@ -1991,6 +2487,16 @@ export async function handleOpenAIResponsesCreate(
1991
2487
  }
1992
2488
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1993
2489
 
2490
+ if (isCodexModelForRotator(rotator, validation.value.model)) {
2491
+ await serveCodexResponses(req, res, rotator, validation.value, {
2492
+ callType: "responses",
2493
+ apiKeyHash,
2494
+ requesterIp: req.socket?.remoteAddress || null,
2495
+ rawRequest: validation.value,
2496
+ });
2497
+ return;
2498
+ }
2499
+
1994
2500
  let converted: ResponsesConversionResult;
1995
2501
  try {
1996
2502
  converted = convertResponsesToChatRequest(validation.value);
@@ -2018,7 +2524,9 @@ export async function handleOpenAIResponsesCreate(
2018
2524
  ? { ...converted.chatRequest, messages: compRes.messages }
2019
2525
  : converted.chatRequest;
2020
2526
 
2021
- const requestBody = (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
2527
+ const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model)
2528
+ ? { project: "", model: chatRequest.model, request: chatRequest }
2529
+ : (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
2022
2530
  requestBody.requestId = responseId;
2023
2531
 
2024
2532
  if (validation.value.store !== false) {
@@ -2270,11 +2778,14 @@ export async function handleAnthropicMessages(
2270
2778
 
2271
2779
  const started = Date.now();
2272
2780
  const streamMode = validation.value.stream ? "anthropic" : "none";
2781
+ const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model)
2782
+ ? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq) }
2783
+ : (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq));
2273
2784
  const result = await completeViaRotator(
2274
2785
  req,
2275
2786
  res,
2276
2787
  rotator,
2277
- (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq)),
2788
+ bodyToForward,
2278
2789
  streamMode,
2279
2790
  {
2280
2791
  callType: "anthropic",
@@ -2289,13 +2800,18 @@ export async function handleAnthropicMessages(
2289
2800
  `Anthropic compat upstream failed status=${result.status} model=${validation.value.model}`,
2290
2801
  );
2291
2802
  if (!res.headersSent) {
2803
+ const retrySec = extractRetryAfterSeconds(result.errorText);
2804
+ const headers: Record<string, string> = retrySec ? { "Retry-After": String(retrySec) } : {};
2805
+ const message = retrySec
2806
+ ? `Rate limit exceeded. All accounts cooling down. Please wait ${retrySec} seconds before retrying.`
2807
+ : (result.errorText || "Upstream error");
2292
2808
  return writeJson(res, result.status, {
2293
2809
  type: "error",
2294
2810
  error: {
2295
- type: "upstream_error",
2296
- message: result.errorText || "Upstream error",
2811
+ type: result.status === 429 ? "rate_limit_error" : "upstream_error",
2812
+ message,
2297
2813
  },
2298
- });
2814
+ }, headers);
2299
2815
  }
2300
2816
  return;
2301
2817
  }