tuxevil-rotator 3.0.0 → 3.1.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.
@@ -0,0 +1,199 @@
1
+ // OpenCode Zen request forwarding and SSE stream accumulation.
2
+
3
+ import type { AccountRuntime } from "../../types.js";
4
+ import type { ForwardedResponse, RequestBody } from "../../proxy.js";
5
+ import type { StreamAccumulator, TokenUsage } from "../adapter.js";
6
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
+ import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
8
+ import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
+ import { OPENCODE_ZEN_CHAT_URL } from "./catalog.js";
10
+ import { isRecord } from "../../compat/schema-sanitizer.js";
11
+
12
+ const HOP_BY_HOP = new Set([
13
+ "connection",
14
+ "keep-alive",
15
+ "proxy-authenticate",
16
+ "proxy-authorization",
17
+ "te",
18
+ "trailers",
19
+ "transfer-encoding",
20
+ "upgrade",
21
+ "host",
22
+ "content-length",
23
+ "x-forwarded-for",
24
+ "x-forwarded-host",
25
+ "x-forwarded-proto",
26
+ "x-forwarded-port",
27
+ "x-real-ip",
28
+ "forwarded",
29
+ "via",
30
+ ]);
31
+
32
+ export function buildOpenCodeZenPayload(body: RequestBody): Record<string, unknown> {
33
+ const request = isRecord(body.request) ? body.request : {};
34
+ return {
35
+ ...request,
36
+ model: body.model,
37
+ };
38
+ }
39
+
40
+ export async function forwardRequest(
41
+ account: AccountRuntime,
42
+ body: RequestBody,
43
+ originalHeaders: Record<string, string>,
44
+ signal?: AbortSignal,
45
+ ): Promise<ForwardedResponse> {
46
+ const payload = buildOpenCodeZenPayload(body);
47
+ const apiKey = getOpenCodeZenApiKey(account.config) ?? "";
48
+
49
+ const forwardHeaders: Record<string, string> = {};
50
+ for (const [key, value] of Object.entries(originalHeaders)) {
51
+ const lower = key.toLowerCase();
52
+ if (!HOP_BY_HOP.has(lower) && lower !== "authorization") {
53
+ forwardHeaders[key] = value;
54
+ }
55
+ }
56
+
57
+ forwardHeaders["Authorization"] = `Bearer ${apiKey}`;
58
+ forwardHeaders["Content-Type"] = "application/json";
59
+ if (!forwardHeaders["Accept"] && !forwardHeaders["accept"]) {
60
+ forwardHeaders["Accept"] = payload.stream === false ? "application/json" : "text/event-stream";
61
+ }
62
+
63
+ const endpoint = OPENCODE_ZEN_CHAT_URL;
64
+ const response = await fetch(endpoint, {
65
+ method: "POST",
66
+ headers: forwardHeaders,
67
+ body: JSON.stringify(payload),
68
+ signal,
69
+ dispatcher: getAccountProxyDispatcher(account, OPENCODE_ZEN_PROVIDER_ID),
70
+ } as RequestInitWithDispatcher);
71
+
72
+ return { response, endpoint };
73
+ }
74
+
75
+ function extractUsageFromRecord(record: Record<string, unknown>): TokenUsage | null {
76
+ const usage = isRecord(record.usage) ? record.usage : record;
77
+ const inputTokens =
78
+ typeof usage.prompt_tokens === "number"
79
+ ? usage.prompt_tokens
80
+ : typeof usage.input_tokens === "number"
81
+ ? usage.input_tokens
82
+ : 0;
83
+ const outputTokens =
84
+ typeof usage.completion_tokens === "number"
85
+ ? usage.completion_tokens
86
+ : typeof usage.output_tokens === "number"
87
+ ? usage.output_tokens
88
+ : 0;
89
+
90
+ return inputTokens > 0 || outputTokens > 0
91
+ ? { inputTokens, outputTokens }
92
+ : null;
93
+ }
94
+
95
+ export class OpenCodeZenSseAccumulator implements StreamAccumulator {
96
+ private buffer = "";
97
+ private accumulatedText = "";
98
+ private usage: TokenUsage | null = null;
99
+
100
+ append(chunkText: string): TokenUsage | null {
101
+ this.buffer += chunkText;
102
+ let newlyFound: TokenUsage | null = null;
103
+ let newlineIdx = this.buffer.indexOf("\n");
104
+
105
+ while (newlineIdx >= 0) {
106
+ const line = this.buffer.slice(0, newlineIdx).trim();
107
+ this.buffer = this.buffer.slice(newlineIdx + 1);
108
+
109
+ if (line.startsWith("data:")) {
110
+ const payload = line.slice(5).trim();
111
+ if (payload && payload !== "[DONE]") {
112
+ try {
113
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
114
+
115
+ // Extract delta text if present
116
+ if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
117
+ const choice = parsed.choices[0];
118
+ if (isRecord(choice) && isRecord(choice.delta)) {
119
+ const content = choice.delta.content;
120
+ if (typeof content === "string" && this.accumulatedText.length < 100000) {
121
+ this.accumulatedText += content;
122
+ }
123
+ }
124
+ }
125
+
126
+ const extractedUsage = extractUsageFromRecord(parsed);
127
+ if (extractedUsage) {
128
+ this.usage = extractedUsage;
129
+ newlyFound = extractedUsage;
130
+ }
131
+ } catch {
132
+ // Ignore malformed SSE lines
133
+ }
134
+ }
135
+ }
136
+
137
+ newlineIdx = this.buffer.indexOf("\n");
138
+ }
139
+
140
+ return newlyFound;
141
+ }
142
+
143
+ getText(): string {
144
+ return this.accumulatedText;
145
+ }
146
+
147
+ final(): TokenUsage | null {
148
+ if (this.buffer.trim()) {
149
+ this.append(`${this.buffer}\n`);
150
+ }
151
+ return this.usage;
152
+ }
153
+ }
154
+
155
+ const BENCHMARK_MODEL = "deepseek-v4-flash-free";
156
+
157
+ export function getBenchmarkSpec(): {
158
+ body: RequestBody;
159
+ parseUsage(raw: string): { outputTokens: number } | null;
160
+ parseText(raw: string): string;
161
+ } {
162
+ return {
163
+ body: {
164
+ project: "",
165
+ model: BENCHMARK_MODEL,
166
+ request: {
167
+ model: BENCHMARK_MODEL,
168
+ messages: [{ role: "user", content: "Reply with: OK" }],
169
+ stream: false,
170
+ max_tokens: 16,
171
+ },
172
+ },
173
+ parseUsage(raw: string) {
174
+ try {
175
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
176
+ const usage = extractUsageFromRecord(parsed);
177
+ return usage ? { outputTokens: usage.outputTokens } : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ },
182
+ parseText(raw: string) {
183
+ try {
184
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
185
+ if (Array.isArray(parsed.choices) && parsed.choices.length > 0) {
186
+ const choice = parsed.choices[0];
187
+ if (isRecord(choice) && isRecord(choice.message)) {
188
+ return typeof choice.message.content === "string"
189
+ ? choice.message.content
190
+ : "";
191
+ }
192
+ }
193
+ return raw.slice(0, 1000);
194
+ } catch {
195
+ return raw.slice(0, 1000);
196
+ }
197
+ },
198
+ };
199
+ }
@@ -0,0 +1,64 @@
1
+ // OpenCode Zen provider adapter.
2
+
3
+ import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
4
+ import { runLogin } from "./login.js";
5
+ import { getOpenCodeZenApiKey, validateCredentials, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
6
+ import { forwardRequest, OpenCodeZenSseAccumulator, getBenchmarkSpec } from "./forward.js";
7
+ import { fetchOpenCodeZenQuota } from "./quota.js";
8
+ import type { AccountRuntime } from "../../types.js";
9
+
10
+ const OPENCODE_ZEN_TIER_RANKING = {
11
+ free: 0,
12
+ unknown: 1,
13
+ };
14
+
15
+ export const opencodeZenAdapter: ProviderAdapter = {
16
+ id: OPENCODE_ZEN_PROVIDER_ID,
17
+ displayName: "OpenCode Zen",
18
+ credentialKind: "api-key",
19
+ tierRanking: OPENCODE_ZEN_TIER_RANKING,
20
+
21
+ features: {
22
+ circuitBreakers: true,
23
+ concurrencyLimits: true,
24
+ proactiveRotation: false,
25
+ } satisfies ProviderFeatures,
26
+
27
+ runLogin,
28
+
29
+ validateCredentials,
30
+
31
+ hasValidCredentials(account: AccountRuntime): boolean {
32
+ const key = getOpenCodeZenApiKey(account.config);
33
+ return typeof key === "string" && key.trim().length > 0;
34
+ },
35
+
36
+ async ensureValidToken(): Promise<void> {},
37
+
38
+ getAuthHeader(account: AccountRuntime): string {
39
+ const key = getOpenCodeZenApiKey(account.config) ?? "";
40
+ return `Bearer ${key}`;
41
+ },
42
+
43
+ shouldRetryOnQuotaExhaustion(): boolean {
44
+ return true;
45
+ },
46
+
47
+ async fetchQuota(account: AccountRuntime, ctx): Promise<void> {
48
+ await fetchOpenCodeZenQuota(account, ctx);
49
+ },
50
+
51
+ forwardRequest,
52
+
53
+ createStreamAccumulator: () => new OpenCodeZenSseAccumulator(),
54
+
55
+ getKickstartModelForPool(): string | undefined {
56
+ return undefined;
57
+ },
58
+
59
+ getBenchmark() {
60
+ return getBenchmarkSpec();
61
+ },
62
+ };
63
+
64
+ export { OPENCODE_ZEN_PROVIDER_ID };
@@ -0,0 +1,81 @@
1
+ // OpenCode Zen interactive login flow.
2
+
3
+ import { createInterface } from "node:readline";
4
+ import type { AccountConfig } from "../../types.js";
5
+ import { OPENCODE_ZEN_MODELS_URL } from "./catalog.ts";
6
+ import { defaultAccountEmail, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
7
+
8
+ function askQuestion(prompt: string): Promise<string> {
9
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10
+ return new Promise((resolve) => {
11
+ rl.question(prompt, (answer) => {
12
+ rl.close();
13
+ resolve(answer.trim());
14
+ });
15
+ });
16
+ }
17
+
18
+ export async function validateApiKey(
19
+ apiKey: string,
20
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
21
+ try {
22
+ const res = await fetch(OPENCODE_ZEN_MODELS_URL, {
23
+ method: "GET",
24
+ headers: {
25
+ Authorization: `Bearer ${apiKey}`,
26
+ Accept: "application/json",
27
+ },
28
+ });
29
+
30
+ if (!res.ok) {
31
+ const text = await res.text().catch(() => "");
32
+ return {
33
+ ok: false,
34
+ status: res.status,
35
+ error: `HTTP ${res.status}: ${text.slice(0, 200) || res.statusText}`,
36
+ };
37
+ }
38
+
39
+ return { ok: true };
40
+ } catch (err) {
41
+ return {
42
+ ok: false,
43
+ status: 0,
44
+ error: err instanceof Error ? err.message : String(err),
45
+ };
46
+ }
47
+ }
48
+
49
+ export async function runLogin(): Promise<AccountConfig> {
50
+ console.log("=== Tuxevil Rotator - Add OpenCode Zen Account ===");
51
+ console.log();
52
+
53
+ const apiKey = await askQuestion("Paste your OpenCode Zen API key: ");
54
+
55
+ if (!apiKey) {
56
+ console.error("No API key provided.");
57
+ process.exit(1);
58
+ }
59
+
60
+ console.log("Validating API key against opencode.ai/zen...");
61
+ const result = await validateApiKey(apiKey);
62
+ if (!result.ok) {
63
+ console.error(`API key validation failed: ${result.error}`);
64
+ process.exit(1);
65
+ }
66
+
67
+ const email = defaultAccountEmail(apiKey);
68
+ const defaultLabel = email.split("@")[0];
69
+ const label = await askQuestion(`Account label (default: ${defaultLabel}): `);
70
+
71
+ return {
72
+ email,
73
+ credentials: [
74
+ {
75
+ provider: OPENCODE_ZEN_PROVIDER_ID,
76
+ apiKey,
77
+ },
78
+ ],
79
+ label: label || defaultLabel,
80
+ };
81
+ }
@@ -0,0 +1,66 @@
1
+ // OpenCode Zen quota polling.
2
+
3
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
4
+ import type { AccountRuntime, ModelQuota } from "../../types.js";
5
+ import type { QuotaFetchContext } from "../adapter.js";
6
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
+ import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
8
+ import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
+
10
+ export async function fetchOpenCodeZenQuota(
11
+ account: AccountRuntime,
12
+ ctx: QuotaFetchContext,
13
+ ): Promise<void> {
14
+ const apiKey = getOpenCodeZenApiKey(account.config);
15
+ if (!apiKey) return;
16
+
17
+ try {
18
+ const response = await fetchWithRetry(OPENCODE_ZEN_MODELS_URL, {
19
+ method: "GET",
20
+ headers: {
21
+ Authorization: `Bearer ${apiKey}`,
22
+ Accept: "application/json",
23
+ },
24
+ timeoutMs: 8000,
25
+ dispatcher: getAccountProxyDispatcher(account, OPENCODE_ZEN_PROVIDER_ID),
26
+ });
27
+
28
+ if (!response.ok) {
29
+ if (response.status === 401 || response.status === 403) {
30
+ const errorText = await response.text().catch(() => "");
31
+ ctx.log(`${account.config.email}: OpenCode Zen API returned ${response.status}, flagging account`);
32
+ ctx.reportQuotaPollFlag(account, response.status, errorText);
33
+ ctx.markFlagged(
34
+ account,
35
+ `OpenCode Zen API ${response.status}: ${errorText}`,
36
+ { triggerProtectivePause: false },
37
+ );
38
+ }
39
+ return;
40
+ }
41
+
42
+ const oldQuota = account.quota || [];
43
+ const otherProviders = oldQuota.filter(
44
+ (q) => (q as { providerId?: string }).providerId &&
45
+ (q as { providerId?: string }).providerId !== OPENCODE_ZEN_PROVIDER_ID,
46
+ );
47
+
48
+ const freshQuota: ModelQuota = {
49
+ modelKey: OPENCODE_ZEN_PROVIDER_ID,
50
+ displayName: "OpenCode Zen Free Pool",
51
+ providerId: OPENCODE_ZEN_PROVIDER_ID,
52
+ percentRemaining: 100,
53
+ resetTime: null,
54
+ timerType: "fresh",
55
+ };
56
+
57
+ account.quota = [...otherProviders, freshQuota];
58
+ account.lastQuotaPoll = Date.now();
59
+
60
+ account.lastPollByProvider ??= {};
61
+ account.lastPollByProvider[OPENCODE_ZEN_PROVIDER_ID] =
62
+ `[${freshQuota.modelKey}: ${freshQuota.timerType} ${freshQuota.percentRemaining}%]`;
63
+ } catch {
64
+ // Swallow network errors; retain prior quota state
65
+ }
66
+ }
@@ -9,6 +9,7 @@
9
9
  import type { ProviderAdapter } from "./adapter.js";
10
10
  import { googleAntigravityAdapter } from "./google-antigravity/index.js";
11
11
  import { ollamaAdapter } from "./ollama/index.js";
12
+ import { openaiCodexAdapter } from "./openai-codex/index.js";
12
13
  import { logger } from "../logger.js";
13
14
  import {
14
15
  DEFAULT_PROVIDER,
@@ -31,6 +32,7 @@ export {
31
32
  const PROVIDERS: Record<string, ProviderAdapter> = {
32
33
  "google-antigravity": googleAntigravityAdapter,
33
34
  ollama: ollamaAdapter,
35
+ "openai-codex": openaiCodexAdapter,
34
36
  };
35
37
 
36
38
  export function getProviderAdapter(providerId: string): ProviderAdapter {
@@ -67,4 +69,3 @@ export function getProviderForAccount(
67
69
  return getProviderAdapter(DEFAULT_PROVIDER);
68
70
  }
69
71
  }
70
-
package/src/proxy.ts CHANGED
@@ -15,6 +15,12 @@ import {
15
15
  resolveQuotaModelKey,
16
16
  resolveDisplayModelKey,
17
17
  } from "./types.js";
18
+ import {
19
+ isCodexRequestModel,
20
+ isCodexProviderModelId,
21
+ } from "./providers/openai-codex/catalog.js";
22
+ import { isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
23
+ import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
18
24
  import type { AccountRuntime } from "./types.js";
19
25
  import type { AccountRotator } from "./rotator.js";
20
26
  import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount } from "./providers/registry.js";
@@ -96,15 +102,34 @@ import type { FlagEventData } from "./telemetry.js";
96
102
  * The rotator is required only when it exposes `getOllamaModels()`; test
97
103
  * stubs that omit it fall back to the credentials-only dispatch.
98
104
  */
99
- function providerAdapterForModel(
105
+ export function providerAdapterForModel(
100
106
  account: AccountRuntime,
101
107
  model: string | undefined,
102
- rotator?: { getOllamaModels?: () => string[] },
108
+ rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
103
109
  ): ProviderAdapter {
104
110
  const creds = account.config.credentials ?? [];
111
+ if (model && isOpenCodeZenModel(model)) {
112
+ return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
113
+ }
114
+ let isCodex = Boolean(model && isCodexRequestModel(model));
115
+ try {
116
+ if (
117
+ model &&
118
+ isCodexProviderModelId(model) &&
119
+ rotator?.getCodexModels?.().includes(model)
120
+ ) isCodex = true;
121
+ } catch {
122
+ // Ignore catalog read failures and retain the safe static allowlist.
123
+ }
124
+ if (isCodex) {
125
+ // Codex models are provider-owned and never fall back to Google/Ollama.
126
+ return getProviderAdapter("openai-codex");
127
+ }
105
128
  if (creds.length > 0) {
129
+ const onlyZen = creds.every((c) => c.provider === OPENCODE_ZEN_PROVIDER_ID);
106
130
  const onlyOllama = creds.every((c) => c.provider === "ollama");
107
- const onlyGoogle = creds.every((c) => c.provider !== "ollama");
131
+ const onlyGoogle = creds.every((c) => c.provider === DEFAULT_PROVIDER);
132
+ if (onlyZen) return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
108
133
  if (onlyOllama) return getProviderAdapter("ollama");
109
134
  if (onlyGoogle) return getProviderAdapter(DEFAULT_PROVIDER);
110
135
  }
@@ -120,7 +145,20 @@ function providerAdapterForModel(
120
145
  if (isOllamaModel) {
121
146
  return getProviderAdapter("ollama");
122
147
  }
123
- return getProviderForAccount(account.config);
148
+ if (creds.some((credential) => credential.provider === DEFAULT_PROVIDER)) {
149
+ return getProviderAdapter(DEFAULT_PROVIDER);
150
+ }
151
+ const fallback = getProviderForAccount(account.config);
152
+ return fallback.id === "openai-codex"
153
+ ? getProviderAdapter(DEFAULT_PROVIDER)
154
+ : fallback;
155
+ }
156
+
157
+ function routingModelKey(rotator: AccountRotator, model: string): string {
158
+ const resolver = (rotator as unknown as {
159
+ resolveQuotaModelKeyForDisplay?: (value: string) => string | null;
160
+ }).resolveQuotaModelKeyForDisplay;
161
+ return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
124
162
  }
125
163
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
126
164
  import { startNotificationPoller } from "./notification-poller.js";
@@ -453,6 +491,23 @@ async function handleUpstreamAccountAction(
453
491
  recordFailureAttempt,
454
492
  } = options;
455
493
 
494
+ if (
495
+ provider.id === "openai-codex" &&
496
+ (action.kind === "flagged-401" ||
497
+ action.kind === "flagged-403" ||
498
+ action.kind === "forbidden")
499
+ ) {
500
+ const status = action.kind === "flagged-401" ? 401 : 403;
501
+ const message = `Codex credential rejected (${status}); re-authentication required`;
502
+ writeLog(`[${label}] ${message}`, "warn");
503
+ rotator.markProviderInvalid(account, "openai-codex", message);
504
+ logRequestEnd(status, `endpoint=${action.endpoint}`);
505
+ if (!options.canRetry) return buildFailureDecision(options, status, message);
506
+ const nextAccount = await rotateAndRelease();
507
+ if (nextAccount) return { kind: "retry" };
508
+ return buildNoReplacementDecision(options, `no replacement Codex account remained after ${label} was rejected`);
509
+ }
510
+
456
511
  if (action.kind === "rate-limited") {
457
512
  writeLog(
458
513
  `[${label}] 429 rate limited${action.providerResourceExhausted ? " (RESOURCE_EXHAUSTED)" : ""}, cooldown ${Math.ceil(action.cooldownMs / 1000)}s. Error text: ${action.errorText.slice(0, 300)}`,
@@ -476,8 +531,10 @@ async function handleUpstreamAccountAction(
476
531
  `cooldownMs=${action.cooldownMs}${action.providerResourceExhausted ? " resourceExhausted=true" : ""} endpoint=${action.endpoint}`,
477
532
  );
478
533
 
534
+ const shouldRetryProviderRateLimit =
535
+ provider.id === "openai-codex" || action.providerResourceExhausted;
479
536
  if (
480
- action.providerResourceExhausted &&
537
+ shouldRetryProviderRateLimit &&
481
538
  options.canRetry &&
482
539
  provider.shouldRetryOnQuotaExhaustion(account, model, action.errorText)
483
540
  ) {
@@ -1080,6 +1137,7 @@ export async function withRotation<T>(
1080
1137
  response: Response,
1081
1138
  context: RotationAttemptContext,
1082
1139
  ) => Promise<T>,
1140
+ signal?: AbortSignal,
1083
1141
  ): Promise<RotationOutcome<T>> {
1084
1142
  const sendNoAccountsAvailable = (
1085
1143
  reason: string,
@@ -1112,7 +1170,7 @@ export async function withRotation<T>(
1112
1170
  if (nextAccount) {
1113
1171
  rotator.finishRequest(
1114
1172
  nextAccount,
1115
- resolveQuotaModelKey(model) ?? undefined,
1173
+ routingModelKey(rotator, model),
1116
1174
  );
1117
1175
  }
1118
1176
  return nextAccount;
@@ -1128,7 +1186,7 @@ export async function withRotation<T>(
1128
1186
  }
1129
1187
 
1130
1188
  const label = account.config.label || account.config.email;
1131
- const modelKey = resolveQuotaModelKey(model) ?? model;
1189
+ const modelKey = routingModelKey(rotator, model);
1132
1190
  const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1133
1191
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1134
1192
  const requestStartMs = Date.now();
@@ -1173,10 +1231,14 @@ export async function withRotation<T>(
1173
1231
  model,
1174
1232
  rotator,
1175
1233
  );
1234
+ // A parent account may carry Google + Codex credentials; refresh the
1235
+ // selected provider, never merely the account's primary provider.
1236
+ await provider.ensureValidToken(account);
1176
1237
  const forwarded = await provider.forwardRequest(
1177
1238
  account,
1178
1239
  { ...body },
1179
1240
  originalHeaders,
1241
+ signal,
1180
1242
  );
1181
1243
  const { response, endpoint } = forwarded;
1182
1244
  const context: RotationAttemptContext = {
@@ -1281,7 +1343,7 @@ export async function withRotation<T>(
1281
1343
  }
1282
1344
  continue;
1283
1345
  } finally {
1284
- rotator.finishRequest(account, resolveQuotaModelKey(model) ?? undefined);
1346
+ rotator.finishRequest(account, routingModelKey(rotator, model));
1285
1347
  }
1286
1348
  }
1287
1349
 
@@ -1444,7 +1506,7 @@ async function handleProxyRequest(
1444
1506
  if (nextAccount) {
1445
1507
  rotator.finishRequest(
1446
1508
  nextAccount,
1447
- resolveQuotaModelKey(body.model) ?? undefined,
1509
+ routingModelKey(rotator, body.model),
1448
1510
  );
1449
1511
  }
1450
1512
  return nextAccount;
@@ -1579,6 +1641,7 @@ async function handleProxyRequest(
1579
1641
  body.model,
1580
1642
  rotator,
1581
1643
  );
1644
+ await provider.ensureValidToken(account);
1582
1645
  const forwarded = await provider.forwardRequest(
1583
1646
  account,
1584
1647
  { ...body },
@@ -1744,7 +1807,7 @@ async function handleProxyRequest(
1744
1807
  } finally {
1745
1808
  rotator.finishRequest(
1746
1809
  account,
1747
- resolveQuotaModelKey(body.model) ?? undefined,
1810
+ routingModelKey(rotator, body.model),
1748
1811
  );
1749
1812
  if (onComplete) onComplete();
1750
1813
  }