tuxevil-rotator 3.1.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.
package/src/compat.ts CHANGED
@@ -54,20 +54,23 @@ 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";
70
- import { OPENCODE_ZEN_CATALOG } from "./providers/opencode-zen/catalog.js";
73
+ import { OPENCODE_ZEN_CATALOG, isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
71
74
  import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
72
75
  import type {
73
76
  ChatMessage,
@@ -153,6 +156,162 @@ export function logValidationFailure(scope: string, payload: unknown): void {
153
156
 
154
157
  // Helper and translation functions have been moved to src/providers/google-antigravity/translators.ts
155
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
+
156
315
  export function parseAntigravitySse(raw: string): CompatCompletion {
157
316
  let text = "";
158
317
  let thinkingText = "";
@@ -421,7 +580,7 @@ async function streamCompatSse(
421
580
  context?: RotationAttemptContext,
422
581
  rotator?: AccountRotator,
423
582
  compressionStats?: CompressionStats | null,
424
- upstream: "google" | "ollama" = "google",
583
+ upstream: "google" | "ollama" | "opencode-zen" = "google",
425
584
  ): Promise<CompatCompletion> {
426
585
  const nodeStream = Readable.fromWeb(
427
586
  body as import("node:stream/web").ReadableStream,
@@ -477,6 +636,15 @@ async function streamCompatSse(
477
636
  let tailBuffer = "";
478
637
  let reqClosed = false;
479
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>();
480
648
  const emitOllamaLine = (line: string): void => {
481
649
  try {
482
650
  const parsed = JSON.parse(line) as Record<string, unknown>;
@@ -553,6 +721,191 @@ async function streamCompatSse(
553
721
  // Ignore malformed NDJSON lines
554
722
  }
555
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
+ };
556
909
  const closeUpstreamForClient = (): void => {
557
910
  reqClosed = true;
558
911
  if (!nodeStream.destroyed) nodeStream.destroy();
@@ -581,6 +934,10 @@ async function streamCompatSse(
581
934
  if (line) emitOllamaLine(line);
582
935
  continue;
583
936
  }
937
+ if (upstream === "opencode-zen") {
938
+ if (line) emitOpenAiSseLine(line);
939
+ continue;
940
+ }
584
941
  if (!line.startsWith("data:")) continue;
585
942
  const payload = line.slice(5).trim();
586
943
  if (!payload || payload === "[DONE]") continue;
@@ -762,6 +1119,13 @@ async function streamCompatSse(
762
1119
  `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: anthropicActiveBlockIndex })}\n\n`,
763
1120
  );
764
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
+ }
765
1129
  const anthropicStopReason = anthropicHasToolUse ? "tool_use" : "end_turn";
766
1130
  // message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
767
1131
  res.write(
@@ -1470,9 +1834,11 @@ async function completeViaRotator(
1470
1834
  async (response, context) => {
1471
1835
  if (streamMode === "none") {
1472
1836
  const raw = await response.text();
1473
- const completion = isOllamaUpstream(body.model)
1474
- ? parseOllamaNdjson(raw)
1475
- : parseAntigravitySse(raw);
1837
+ const completion = isOpenCodeZenModel(body.model)
1838
+ ? parseOpenAiJson(raw)
1839
+ : isOllamaUpstream(body.model)
1840
+ ? parseOllamaNdjson(raw)
1841
+ : parseAntigravitySse(raw);
1476
1842
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1477
1843
  rotator.recordTokenUsage(
1478
1844
  body.displayModel || body.model,
@@ -1500,7 +1866,11 @@ async function completeViaRotator(
1500
1866
  context,
1501
1867
  rotator,
1502
1868
  options?.compressionStats,
1503
- isOllamaUpstream(body.model) ? "ollama" : "google",
1869
+ isOpenCodeZenModel(body.model)
1870
+ ? "opencode-zen"
1871
+ : isOllamaUpstream(body.model)
1872
+ ? "ollama"
1873
+ : "google",
1504
1874
  );
1505
1875
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1506
1876
  rotator.recordTokenUsage(
@@ -1639,6 +2009,14 @@ const MODEL_CATALOG = [
1639
2009
  multimodal: true,
1640
2010
  tools: true,
1641
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
+ },
1642
2020
  {
1643
2021
  id: "gemini-3.1-pro-low",
1644
2022
  family: "gemini-3.1-pro",
@@ -1681,11 +2059,33 @@ const MODEL_CATALOG = [
1681
2059
  },
1682
2060
  ] as const;
1683
2061
 
1684
- export function serveOpenAIModels(
1685
- 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(
1686
2086
  rotator?: AccountRotator,
1687
- ): void {
1688
- const catalog: Array<Record<string, unknown>> = MODEL_CATALOG.map(
2087
+ ): OpenAIModelCatalogEntry[] {
2088
+ const catalog: OpenAIModelCatalogEntry[] = MODEL_CATALOG.map(
1689
2089
  ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
1690
2090
  id,
1691
2091
  object: "model",
@@ -1763,7 +2163,14 @@ export function serveOpenAIModels(
1763
2163
  });
1764
2164
  }
1765
2165
  }
1766
- writeJson(res, 200, { object: "list", data: catalog });
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) });
1767
2174
  }
1768
2175
 
1769
2176
  export function serveGeminiModels(res: ServerResponse): void {
@@ -1850,12 +2257,18 @@ export async function handleGeminiGenerateContent(
1850
2257
  rawRequest: parsed,
1851
2258
  });
1852
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");
1853
2265
  return writeJson(res, result.status, {
1854
2266
  error: {
1855
- message: result.errorText || "Upstream error",
1856
- status: "UPSTREAM_ERROR",
2267
+ message,
2268
+ status: result.status === 429 ? "RESOURCE_EXHAUSTED" : "UPSTREAM_ERROR",
2269
+ ...(retrySec ? { retry_after_seconds: retrySec } : {}),
1857
2270
  },
1858
- });
2271
+ }, headers);
1859
2272
  }
1860
2273
  if (result.streamed) return;
1861
2274
  const totalMs = Date.now() - started;
@@ -1952,11 +2365,14 @@ export async function handleOpenAIChatCompletions(
1952
2365
 
1953
2366
  const started = Date.now();
1954
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));
1955
2371
  const result = await completeViaRotator(
1956
2372
  req,
1957
2373
  res,
1958
2374
  rotator,
1959
- (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq)),
2375
+ bodyToForward,
1960
2376
  streamMode,
1961
2377
  {
1962
2378
  callType: "chat_completion",
@@ -1971,12 +2387,20 @@ export async function handleOpenAIChatCompletions(
1971
2387
  `OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
1972
2388
  );
1973
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");
1974
2395
  return writeJson(res, result.status, {
1975
2396
  error: {
1976
- message: result.errorText || "Upstream error",
1977
- 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 } : {}),
1978
2402
  },
1979
- });
2403
+ }, headers);
1980
2404
  }
1981
2405
  return;
1982
2406
  }
@@ -2100,7 +2524,9 @@ export async function handleOpenAIResponsesCreate(
2100
2524
  ? { ...converted.chatRequest, messages: compRes.messages }
2101
2525
  : converted.chatRequest;
2102
2526
 
2103
- 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));
2104
2530
  requestBody.requestId = responseId;
2105
2531
 
2106
2532
  if (validation.value.store !== false) {
@@ -2352,11 +2778,14 @@ export async function handleAnthropicMessages(
2352
2778
 
2353
2779
  const started = Date.now();
2354
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));
2355
2784
  const result = await completeViaRotator(
2356
2785
  req,
2357
2786
  res,
2358
2787
  rotator,
2359
- (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq)),
2788
+ bodyToForward,
2360
2789
  streamMode,
2361
2790
  {
2362
2791
  callType: "anthropic",
@@ -2371,13 +2800,18 @@ export async function handleAnthropicMessages(
2371
2800
  `Anthropic compat upstream failed status=${result.status} model=${validation.value.model}`,
2372
2801
  );
2373
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");
2374
2808
  return writeJson(res, result.status, {
2375
2809
  type: "error",
2376
2810
  error: {
2377
- type: "upstream_error",
2378
- message: result.errorText || "Upstream error",
2811
+ type: result.status === 429 ? "rate_limit_error" : "upstream_error",
2812
+ message,
2379
2813
  },
2380
- });
2814
+ }, headers);
2381
2815
  }
2382
2816
  return;
2383
2817
  }
@@ -3,7 +3,7 @@
3
3
  // account-store (write path) can use it without import cycles.
4
4
 
5
5
  import type { AccountConfig } from "./types.js";
6
- import { DEFAULT_PROVIDER } from "./providers/credential-helpers.js";
6
+ import { DEFAULT_PROVIDER, sortAccountCredentials } from "./providers/credential-helpers.js";
7
7
 
8
8
  /**
9
9
  * Migrate a flat legacy account shape (provider/apiKey/refreshToken at the
@@ -28,15 +28,16 @@ export function normalizeAccountConfig(account: AccountConfig): AccountConfig {
28
28
  };
29
29
 
30
30
  if (
31
- !providers.has("ollama") &&
32
31
  typeof account.apiKey === "string" &&
33
32
  account.apiKey.trim() !== ""
34
33
  ) {
35
- addCredential({
36
- provider: "ollama",
37
- apiKey: account.apiKey,
38
- proxyUrl: account.proxyUrl,
39
- });
34
+ if (!providers.has(provider)) {
35
+ addCredential({
36
+ provider,
37
+ apiKey: account.apiKey,
38
+ proxyUrl: account.proxyUrl,
39
+ });
40
+ }
40
41
  }
41
42
 
42
43
  if (
@@ -72,10 +73,15 @@ export function normalizeAccountConfig(account: AccountConfig): AccountConfig {
72
73
  }
73
74
 
74
75
  if (credentials.length > 0) {
75
- if (Array.isArray(account.credentials) && credentials.length === account.credentials.length) {
76
+ const sorted = sortAccountCredentials(credentials);
77
+ if (
78
+ Array.isArray(account.credentials) &&
79
+ credentials.length === account.credentials.length &&
80
+ JSON.stringify(sorted) === JSON.stringify(account.credentials)
81
+ ) {
76
82
  return account;
77
83
  }
78
- return { ...account, credentials };
84
+ return { ...account, credentials: sorted };
79
85
  }
80
86
 
81
87
  // Mirror the flat legacy fields onto the parent-account credentials and