tuxevil-rotator 3.2.1 → 3.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/compat/model-specs.ts +31 -28
- package/src/compat.ts +2 -2
- package/src/providers/google-antigravity/catalog.ts +99 -0
- package/src/providers/google-antigravity/index.ts +5 -0
- package/src/providers/ollama/context-window.ts +117 -0
- package/src/providers/ollama/index.ts +1 -0
- package/src/providers/openai-codex/catalog.ts +8 -2
- package/src/providers/opencode-zen/catalog.ts +13 -1
- package/src/proxy.ts +42 -37
- package/src/rotator.ts +340 -55
- package/src/spend-logger.ts +75 -38
- package/src/virtual-keys.ts +28 -4
package/src/rotator.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
3
2
|
import {
|
|
4
3
|
type AccountConfig,
|
|
5
4
|
type AccountRuntime,
|
|
@@ -10,6 +9,7 @@ import {
|
|
|
10
9
|
type ModelQuota,
|
|
11
10
|
type ModelRotationState,
|
|
12
11
|
type PersistedState,
|
|
12
|
+
type ProviderCredential,
|
|
13
13
|
type RoutingAccountDiagnostic,
|
|
14
14
|
type RoutingModelDiagnostics,
|
|
15
15
|
type RoutingRejectionReason,
|
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
saveAccountsConfig,
|
|
43
43
|
removeAccountFromConfig,
|
|
44
44
|
mergeCredentials,
|
|
45
|
+
normalizeAccountConfig,
|
|
45
46
|
} from "./account-store.js";
|
|
46
47
|
import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
|
|
47
48
|
import type { RequestBody } from "./proxy.js";
|
|
@@ -82,6 +83,125 @@ import {
|
|
|
82
83
|
setCachedTokenUsage,
|
|
83
84
|
} from "./db-store.js";
|
|
84
85
|
|
|
86
|
+
function credentialFingerprint(secret?: string): string {
|
|
87
|
+
if (!secret) return "";
|
|
88
|
+
return createHash("sha256").update(secret).digest("hex").slice(0, 12);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function getProviderCredentialDetails(
|
|
92
|
+
norm: AccountConfig,
|
|
93
|
+
cred?: ProviderCredential,
|
|
94
|
+
): {
|
|
95
|
+
provider: string;
|
|
96
|
+
projectId: string;
|
|
97
|
+
providerAccountId: string;
|
|
98
|
+
secret: string;
|
|
99
|
+
fingerprint: string;
|
|
100
|
+
} {
|
|
101
|
+
const provider = cred?.provider ?? DEFAULT_PROVIDER;
|
|
102
|
+
let projectId = cred?.projectId || "";
|
|
103
|
+
let providerAccountId = cred?.providerAccountId || "";
|
|
104
|
+
let secret = cred?.refreshToken || cred?.apiKey || "";
|
|
105
|
+
|
|
106
|
+
if (provider === "google-antigravity") {
|
|
107
|
+
projectId ||= norm.projectId || "";
|
|
108
|
+
secret ||= norm.refreshToken || norm.apiKey || "";
|
|
109
|
+
} else if (provider === "openai-codex") {
|
|
110
|
+
providerAccountId ||= norm.codexAccountId || "";
|
|
111
|
+
secret ||= norm.codexRefreshToken || "";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const fingerprint = !projectId && !providerAccountId && secret ? credentialFingerprint(secret) : "";
|
|
115
|
+
return { provider, projectId, providerAccountId, secret, fingerprint };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function getAccountIdentity(account: AccountConfig | AccountRuntime): string {
|
|
119
|
+
const config = "config" in account ? account.config : account;
|
|
120
|
+
const norm = normalizeAccountConfig(config);
|
|
121
|
+
const email = norm.email.toLowerCase().trim();
|
|
122
|
+
const creds = (norm.credentials ?? [])
|
|
123
|
+
.slice()
|
|
124
|
+
.sort((a, b) => a.provider.localeCompare(b.provider))
|
|
125
|
+
.map((c) => {
|
|
126
|
+
const details = getProviderCredentialDetails(norm, c);
|
|
127
|
+
return `${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
|
|
128
|
+
})
|
|
129
|
+
.join("|");
|
|
130
|
+
if (!creds) {
|
|
131
|
+
const details = getProviderCredentialDetails(norm, { provider: DEFAULT_PROVIDER });
|
|
132
|
+
return `${email}#${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
|
|
133
|
+
}
|
|
134
|
+
return `${email}#${creds}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function areAccountIdentitiesCompatible(
|
|
138
|
+
incomingConfig: AccountConfig,
|
|
139
|
+
existingConfig: AccountConfig,
|
|
140
|
+
): boolean {
|
|
141
|
+
const normInc = normalizeAccountConfig(incomingConfig);
|
|
142
|
+
const normExt = normalizeAccountConfig(existingConfig);
|
|
143
|
+
if (normInc.email.toLowerCase().trim() !== normExt.email.toLowerCase().trim()) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const incCreds = normInc.credentials ?? [];
|
|
148
|
+
const extCreds = normExt.credentials ?? [];
|
|
149
|
+
|
|
150
|
+
let hadOverlap = false;
|
|
151
|
+
for (const inc of incCreds) {
|
|
152
|
+
const ext = extCreds.find((c) => c.provider === inc.provider);
|
|
153
|
+
if (ext) {
|
|
154
|
+
hadOverlap = true;
|
|
155
|
+
const incDetails = getProviderCredentialDetails(normInc, inc);
|
|
156
|
+
const extDetails = getProviderCredentialDetails(normExt, ext);
|
|
157
|
+
|
|
158
|
+
if (incDetails.projectId && extDetails.projectId && incDetails.projectId !== extDetails.projectId) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
if (incDetails.providerAccountId && extDetails.providerAccountId && incDetails.providerAccountId !== extDetails.providerAccountId) {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
if (!incDetails.projectId && !extDetails.projectId && !incDetails.providerAccountId && !extDetails.providerAccountId) {
|
|
165
|
+
if (incDetails.secret && extDetails.secret && incDetails.secret !== extDetails.secret) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (hadOverlap) {
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const incDef = getProviderCredentialDetails(normInc, { provider: DEFAULT_PROVIDER });
|
|
177
|
+
const extDef = getProviderCredentialDetails(normExt, { provider: DEFAULT_PROVIDER });
|
|
178
|
+
if (incDef.projectId && extDef.projectId && incDef.projectId !== extDef.projectId) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
if (incDef.providerAccountId && extDef.providerAccountId && incDef.providerAccountId !== extDef.providerAccountId) {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
if (!incDef.projectId && !extDef.projectId && !incDef.providerAccountId && !extDef.providerAccountId) {
|
|
185
|
+
if (incDef.secret && extDef.secret && incDef.secret !== extDef.secret) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function getCredentialGeneration(
|
|
194
|
+
account: AccountRuntime | AccountConfig,
|
|
195
|
+
providerId: string,
|
|
196
|
+
): string {
|
|
197
|
+
const config = "config" in account ? account.config : account;
|
|
198
|
+
const norm = normalizeAccountConfig(config);
|
|
199
|
+
const cred = norm.credentials?.find((c) => c.provider === providerId);
|
|
200
|
+
const details = getProviderCredentialDetails(norm, cred ?? { provider: providerId });
|
|
201
|
+
if (!cred && !details.secret) return "none";
|
|
202
|
+
return `${providerId}:${details.projectId}:${details.providerAccountId}:${details.secret}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
85
205
|
const rotatorLogger = logger.child("rotator");
|
|
86
206
|
|
|
87
207
|
function currentUtcDay(now = Date.now()): string {
|
|
@@ -115,6 +235,8 @@ export class AccountRotator {
|
|
|
115
235
|
private defaultIndex = 0;
|
|
116
236
|
private startTime = Date.now();
|
|
117
237
|
private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
|
|
238
|
+
private quotaInitialPollTimer: ReturnType<typeof setTimeout> | null = null;
|
|
239
|
+
private inFlightRefreshes = new WeakMap<AccountRuntime, Map<string, Promise<void>>>();
|
|
118
240
|
private protectivePauseUntil = 0;
|
|
119
241
|
private protectivePauseReason: string | null = null;
|
|
120
242
|
private allowFreshWindowStarts = true;
|
|
@@ -613,12 +735,16 @@ export class AccountRotator {
|
|
|
613
735
|
this.log(`Quota polling every ${Math.round(intervalMs / 1000)}s`);
|
|
614
736
|
|
|
615
737
|
// Initial poll (delayed 2s to allow token refresh first)
|
|
616
|
-
setTimeout(() => this.pollAllQuotas(), 2000);
|
|
738
|
+
this.quotaInitialPollTimer = setTimeout(() => this.pollAllQuotas(), 2000);
|
|
617
739
|
|
|
618
740
|
this.quotaPollTimer = setInterval(() => this.pollAllQuotas(), intervalMs);
|
|
619
741
|
}
|
|
620
742
|
|
|
621
743
|
stopQuotaPolling(): void {
|
|
744
|
+
if (this.quotaInitialPollTimer) {
|
|
745
|
+
clearTimeout(this.quotaInitialPollTimer);
|
|
746
|
+
this.quotaInitialPollTimer = null;
|
|
747
|
+
}
|
|
622
748
|
if (this.quotaPollTimer) {
|
|
623
749
|
clearInterval(this.quotaPollTimer);
|
|
624
750
|
this.quotaPollTimer = null;
|
|
@@ -1000,7 +1126,7 @@ export class AccountRotator {
|
|
|
1000
1126
|
return best;
|
|
1001
1127
|
}
|
|
1002
1128
|
|
|
1003
|
-
|
|
1129
|
+
countModelAssignment(modelKey: string): void {
|
|
1004
1130
|
const state = this.modelState.get(modelKey);
|
|
1005
1131
|
if (state) {
|
|
1006
1132
|
state.requestsOnActiveAccount++;
|
|
@@ -1025,11 +1151,7 @@ export class AccountRotator {
|
|
|
1025
1151
|
now: number = Date.now(),
|
|
1026
1152
|
excludeIdx?: number,
|
|
1027
1153
|
): Promise<AccountRuntime | null> {
|
|
1028
|
-
|
|
1029
|
-
if (account) {
|
|
1030
|
-
this.countModelAssignment(modelKey);
|
|
1031
|
-
}
|
|
1032
|
-
return account;
|
|
1154
|
+
return this.rotateModel(modelKey, now, excludeIdx, true);
|
|
1033
1155
|
}
|
|
1034
1156
|
|
|
1035
1157
|
private rollDailySafetyIfNeeded(now: number): void {
|
|
@@ -1655,11 +1777,18 @@ export class AccountRotator {
|
|
|
1655
1777
|
}
|
|
1656
1778
|
}
|
|
1657
1779
|
this.startRequest(current, modelKey ?? undefined);
|
|
1780
|
+
if (modelKey && state) {
|
|
1781
|
+
state.requestsOnActiveAccount++;
|
|
1782
|
+
this.scheduleStateSave();
|
|
1783
|
+
}
|
|
1658
1784
|
try {
|
|
1659
1785
|
await this.ensureValidTokenForModel(current, modelKey);
|
|
1660
|
-
if (modelKey) this.countModelAssignment(modelKey);
|
|
1661
1786
|
return current;
|
|
1662
1787
|
} catch (err) {
|
|
1788
|
+
if (modelKey && state) {
|
|
1789
|
+
state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
|
|
1790
|
+
this.scheduleStateSave();
|
|
1791
|
+
}
|
|
1663
1792
|
this.refundTokenBucket(current, Date.now());
|
|
1664
1793
|
this.finishRequest(current, modelKey ?? undefined);
|
|
1665
1794
|
if (modelKey && this.isCodexPoolKey(modelKey)) {
|
|
@@ -1673,7 +1802,8 @@ export class AccountRotator {
|
|
|
1673
1802
|
if (modelKey) {
|
|
1674
1803
|
return this.rotateModelForRequest(modelKey, now, state ? idx : -1);
|
|
1675
1804
|
}
|
|
1676
|
-
|
|
1805
|
+
const defaultAcc = await this.rotateDefault(now, true);
|
|
1806
|
+
return defaultAcc;
|
|
1677
1807
|
}
|
|
1678
1808
|
|
|
1679
1809
|
private async restorePreferredModelAccount(
|
|
@@ -1710,8 +1840,8 @@ export class AccountRotator {
|
|
|
1710
1840
|
modelKey,
|
|
1711
1841
|
preferred,
|
|
1712
1842
|
preferredIndex,
|
|
1843
|
+
true,
|
|
1713
1844
|
);
|
|
1714
|
-
this.countModelAssignment(modelKey);
|
|
1715
1845
|
return restored;
|
|
1716
1846
|
}
|
|
1717
1847
|
|
|
@@ -1721,6 +1851,7 @@ export class AccountRotator {
|
|
|
1721
1851
|
now: number = Date.now(),
|
|
1722
1852
|
excludeIdx: number = this.modelState.get(modelKey)?.activeAccountIndex ??
|
|
1723
1853
|
-1,
|
|
1854
|
+
forRequest = false,
|
|
1724
1855
|
): Promise<AccountRuntime | null> {
|
|
1725
1856
|
const best = this.pickBestModelAccount(modelKey, now, excludeIdx);
|
|
1726
1857
|
|
|
@@ -1751,13 +1882,23 @@ export class AccountRotator {
|
|
|
1751
1882
|
`[${modelKey}] Rotated to ${best.config.label || best.config.email} [${timerType}] (quota: ${quota >= 0 ? quota + "%" : "unknown"})`,
|
|
1752
1883
|
);
|
|
1753
1884
|
try {
|
|
1754
|
-
return await this.activateModelAccount(
|
|
1885
|
+
return await this.activateModelAccount(
|
|
1886
|
+
modelKey,
|
|
1887
|
+
best,
|
|
1888
|
+
stickyAccountIndex,
|
|
1889
|
+
forRequest,
|
|
1890
|
+
);
|
|
1755
1891
|
} catch (error) {
|
|
1756
1892
|
if (!this.isCodexPoolKey(modelKey)) throw error;
|
|
1757
1893
|
// A bad Codex refresh token is provider-scoped. The failed account is
|
|
1758
1894
|
// marked invalid by ensureValidTokenForProvider, so retry selection
|
|
1759
1895
|
// with the next Codex account without touching Google/Ollama pools.
|
|
1760
|
-
return this.rotateModel(
|
|
1896
|
+
return this.rotateModel(
|
|
1897
|
+
modelKey,
|
|
1898
|
+
now,
|
|
1899
|
+
this.accounts.indexOf(best),
|
|
1900
|
+
forRequest,
|
|
1901
|
+
);
|
|
1761
1902
|
}
|
|
1762
1903
|
}
|
|
1763
1904
|
|
|
@@ -1809,25 +1950,34 @@ export class AccountRotator {
|
|
|
1809
1950
|
modelKey: string,
|
|
1810
1951
|
account: AccountRuntime,
|
|
1811
1952
|
stickyAccountIndex?: number,
|
|
1953
|
+
forRequest = false,
|
|
1812
1954
|
): Promise<AccountRuntime> {
|
|
1955
|
+
if (forRequest) {
|
|
1956
|
+
this.startRequest(account, modelKey);
|
|
1957
|
+
}
|
|
1813
1958
|
const newIdx = this.accounts.indexOf(account);
|
|
1814
1959
|
const quota = this.getModelQuota(account, modelKey);
|
|
1815
|
-
|
|
1960
|
+
const state: ModelRotationState = {
|
|
1816
1961
|
activeAccountIndex: newIdx,
|
|
1817
1962
|
stickyAccountIndex: this.isQuotaAwarePolicy()
|
|
1818
1963
|
? stickyAccountIndex ?? newIdx
|
|
1819
1964
|
: undefined,
|
|
1820
1965
|
quotaAtRotationStart: quota,
|
|
1821
|
-
requestsOnActiveAccount: 0,
|
|
1822
|
-
}
|
|
1823
|
-
|
|
1824
|
-
this.startRequest(account, modelKey);
|
|
1966
|
+
requestsOnActiveAccount: forRequest ? 1 : 0,
|
|
1967
|
+
};
|
|
1968
|
+
this.modelState.set(modelKey, state);
|
|
1825
1969
|
try {
|
|
1970
|
+
await this.saveState();
|
|
1826
1971
|
await this.ensureValidTokenForModel(account, modelKey);
|
|
1827
1972
|
return account;
|
|
1828
1973
|
} catch (err) {
|
|
1829
|
-
|
|
1830
|
-
|
|
1974
|
+
if (forRequest) {
|
|
1975
|
+
if (this.modelState.get(modelKey) === state) {
|
|
1976
|
+
state.requestsOnActiveAccount = Math.max(0, state.requestsOnActiveAccount - 1);
|
|
1977
|
+
}
|
|
1978
|
+
this.refundTokenBucket(account, Date.now());
|
|
1979
|
+
this.finishRequest(account, modelKey);
|
|
1980
|
+
}
|
|
1831
1981
|
throw err;
|
|
1832
1982
|
}
|
|
1833
1983
|
}
|
|
@@ -1835,11 +1985,13 @@ export class AccountRotator {
|
|
|
1835
1985
|
// Fallback rotation when model can't be resolved
|
|
1836
1986
|
private async rotateDefault(
|
|
1837
1987
|
now: number = Date.now(),
|
|
1988
|
+
forRequest = false,
|
|
1989
|
+
excludeIdx = this.defaultIndex,
|
|
1838
1990
|
): Promise<AccountRuntime | null> {
|
|
1839
1991
|
let best: AccountRuntime | null = null;
|
|
1840
1992
|
|
|
1841
1993
|
for (let i = 0; i < this.accounts.length; i++) {
|
|
1842
|
-
if (i ===
|
|
1994
|
+
if (i === excludeIdx) continue;
|
|
1843
1995
|
const account = this.accounts[i];
|
|
1844
1996
|
if (this.isAvailable(account, now)) {
|
|
1845
1997
|
best = account;
|
|
@@ -1848,18 +2000,22 @@ export class AccountRotator {
|
|
|
1848
2000
|
}
|
|
1849
2001
|
|
|
1850
2002
|
if (best) {
|
|
2003
|
+
if (forRequest) {
|
|
2004
|
+
this.startRequest(best);
|
|
2005
|
+
}
|
|
1851
2006
|
this.defaultIndex = this.accounts.indexOf(best);
|
|
1852
2007
|
this.log(
|
|
1853
2008
|
`[default] Rotated to ${best.config.label || best.config.email}`,
|
|
1854
2009
|
);
|
|
1855
|
-
await this.saveState();
|
|
1856
|
-
this.startRequest(best);
|
|
1857
2010
|
try {
|
|
2011
|
+
await this.saveState();
|
|
1858
2012
|
await this.ensureValidToken(best);
|
|
1859
2013
|
return best;
|
|
1860
2014
|
} catch (err) {
|
|
1861
|
-
|
|
1862
|
-
|
|
2015
|
+
if (forRequest) {
|
|
2016
|
+
this.refundTokenBucket(best, Date.now());
|
|
2017
|
+
this.finishRequest(best);
|
|
2018
|
+
}
|
|
1863
2019
|
throw err;
|
|
1864
2020
|
}
|
|
1865
2021
|
}
|
|
@@ -1888,10 +2044,31 @@ export class AccountRotator {
|
|
|
1888
2044
|
}
|
|
1889
2045
|
|
|
1890
2046
|
// Force rotation for a model (called from proxy on 429 etc.)
|
|
1891
|
-
async rotateToNext(
|
|
2047
|
+
async rotateToNext(
|
|
2048
|
+
model?: string,
|
|
2049
|
+
failedAccount?: AccountRuntime | number | string,
|
|
2050
|
+
): Promise<AccountRuntime | null> {
|
|
1892
2051
|
if (this.isProtectivePauseActive(Date.now())) return null;
|
|
1893
2052
|
const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
|
|
1894
|
-
|
|
2053
|
+
let excludeIdx: number;
|
|
2054
|
+
if (typeof failedAccount === "number") {
|
|
2055
|
+
excludeIdx = failedAccount;
|
|
2056
|
+
} else if (typeof failedAccount === "string") {
|
|
2057
|
+
excludeIdx = this.accounts.findIndex(
|
|
2058
|
+
(a) =>
|
|
2059
|
+
getAccountIdentity(a.config) === failedAccount ||
|
|
2060
|
+
a.config.email.toLowerCase() === failedAccount.toLowerCase(),
|
|
2061
|
+
);
|
|
2062
|
+
} else if (failedAccount && typeof failedAccount === "object") {
|
|
2063
|
+
excludeIdx = this.accounts.indexOf(failedAccount);
|
|
2064
|
+
} else {
|
|
2065
|
+
excludeIdx = modelKey
|
|
2066
|
+
? this.modelState.get(modelKey)?.activeAccountIndex ?? -1
|
|
2067
|
+
: this.defaultIndex;
|
|
2068
|
+
}
|
|
2069
|
+
return modelKey
|
|
2070
|
+
? this.rotateModel(modelKey, Date.now(), excludeIdx)
|
|
2071
|
+
: this.rotateDefault(Date.now(), false, excludeIdx);
|
|
1895
2072
|
}
|
|
1896
2073
|
|
|
1897
2074
|
// Record a successful request. Returns true if rotation is needed.
|
|
@@ -2732,10 +2909,10 @@ export class AccountRotator {
|
|
|
2732
2909
|
}
|
|
2733
2910
|
const adapter = getProviderForAccount(account.config);
|
|
2734
2911
|
try {
|
|
2735
|
-
await
|
|
2912
|
+
await this.ensureValidTokenForProvider(account, adapter.id);
|
|
2736
2913
|
} catch (err) {
|
|
2737
2914
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2738
|
-
if (msg.startsWith("Token refresh failed")) {
|
|
2915
|
+
if (msg.startsWith("Token refresh failed") || msg.startsWith("Token refresh error:")) {
|
|
2739
2916
|
this.markError(account, msg);
|
|
2740
2917
|
throw err;
|
|
2741
2918
|
}
|
|
@@ -2749,22 +2926,111 @@ export class AccountRotator {
|
|
|
2749
2926
|
account: AccountRuntime,
|
|
2750
2927
|
providerId: string,
|
|
2751
2928
|
): Promise<void> {
|
|
2752
|
-
const
|
|
2929
|
+
const startGen = getCredentialGeneration(account, providerId);
|
|
2930
|
+
const flightKey = `${providerId}:${startGen}`;
|
|
2931
|
+
|
|
2932
|
+
let providerMap = this.inFlightRefreshes.get(account);
|
|
2933
|
+
if (!providerMap) {
|
|
2934
|
+
providerMap = new Map();
|
|
2935
|
+
this.inFlightRefreshes.set(account, providerMap);
|
|
2936
|
+
}
|
|
2937
|
+
const existing = providerMap.get(flightKey);
|
|
2938
|
+
if (existing) {
|
|
2939
|
+
await existing;
|
|
2940
|
+
const currentGen = getCredentialGeneration(account, providerId);
|
|
2941
|
+
if (currentGen === startGen) {
|
|
2942
|
+
return;
|
|
2943
|
+
}
|
|
2944
|
+
return this.ensureValidTokenForProvider(account, providerId);
|
|
2945
|
+
}
|
|
2946
|
+
|
|
2947
|
+
const refreshPromise = (async () => {
|
|
2948
|
+
const adapter = getProviderAdapter(providerId);
|
|
2949
|
+
const snapshotAccount: AccountRuntime = {
|
|
2950
|
+
...account,
|
|
2951
|
+
config: {
|
|
2952
|
+
...account.config,
|
|
2953
|
+
credentials: (account.config.credentials ?? []).map((c) => ({ ...c })),
|
|
2954
|
+
},
|
|
2955
|
+
providerTokens: account.providerTokens
|
|
2956
|
+
? { ...account.providerTokens }
|
|
2957
|
+
: {},
|
|
2958
|
+
};
|
|
2959
|
+
|
|
2960
|
+
try {
|
|
2961
|
+
await adapter.ensureValidToken(snapshotAccount);
|
|
2962
|
+
} catch (error) {
|
|
2963
|
+
const currentGen = getCredentialGeneration(account, providerId);
|
|
2964
|
+
if (currentGen !== startGen) {
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2967
|
+
if (
|
|
2968
|
+
providerId === "openai-codex" &&
|
|
2969
|
+
(error instanceof CodexOAuthError ||
|
|
2970
|
+
(typeof error === "object" &&
|
|
2971
|
+
error !== null &&
|
|
2972
|
+
(error as { reloginRequired?: unknown }).reloginRequired === true))
|
|
2973
|
+
) {
|
|
2974
|
+
const reason =
|
|
2975
|
+
error instanceof Error
|
|
2976
|
+
? error.message
|
|
2977
|
+
: "Codex credential requires re-authentication";
|
|
2978
|
+
this.markProviderInvalid(account, providerId, reason);
|
|
2979
|
+
}
|
|
2980
|
+
throw error;
|
|
2981
|
+
}
|
|
2982
|
+
|
|
2983
|
+
const currentGen = getCredentialGeneration(account, providerId);
|
|
2984
|
+
if (currentGen !== startGen) {
|
|
2985
|
+
return;
|
|
2986
|
+
}
|
|
2987
|
+
|
|
2988
|
+
// Publish ONLY the state owned by providerId
|
|
2989
|
+
if (providerId === "google-antigravity" || providerId === DEFAULT_PROVIDER) {
|
|
2990
|
+
account.accessToken = snapshotAccount.accessToken;
|
|
2991
|
+
account.tokenExpires = snapshotAccount.tokenExpires;
|
|
2992
|
+
if (snapshotAccount.config.refreshToken !== undefined) {
|
|
2993
|
+
account.config.refreshToken = snapshotAccount.config.refreshToken;
|
|
2994
|
+
}
|
|
2995
|
+
} else {
|
|
2996
|
+
if (snapshotAccount.providerTokens?.[providerId]) {
|
|
2997
|
+
account.providerTokens ??= {};
|
|
2998
|
+
account.providerTokens[providerId] = snapshotAccount.providerTokens[providerId];
|
|
2999
|
+
}
|
|
3000
|
+
if (providerId === "openai-codex" && snapshotAccount.config.codexRefreshToken !== undefined) {
|
|
3001
|
+
account.config.codexRefreshToken = snapshotAccount.config.codexRefreshToken;
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
// Update ONLY providerId's credential in account.config.credentials
|
|
3006
|
+
const snapshotCred = snapshotAccount.config.credentials?.find((c) => c.provider === providerId);
|
|
3007
|
+
if (snapshotCred) {
|
|
3008
|
+
if (!account.config.credentials) {
|
|
3009
|
+
account.config.credentials = [{ ...snapshotCred }];
|
|
3010
|
+
} else {
|
|
3011
|
+
const idx = account.config.credentials.findIndex((c) => c.provider === providerId);
|
|
3012
|
+
if (idx >= 0) {
|
|
3013
|
+
account.config.credentials[idx] = { ...account.config.credentials[idx], ...snapshotCred };
|
|
3014
|
+
} else {
|
|
3015
|
+
account.config.credentials.push({ ...snapshotCred });
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
account.consecutiveErrors = 0;
|
|
3020
|
+
})();
|
|
3021
|
+
|
|
3022
|
+
providerMap.set(flightKey, refreshPromise);
|
|
2753
3023
|
try {
|
|
2754
|
-
await
|
|
2755
|
-
|
|
2756
|
-
if (
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
) {
|
|
2762
|
-
|
|
2763
|
-
? error.message
|
|
2764
|
-
: "Codex credential requires re-authentication";
|
|
2765
|
-
this.markProviderInvalid(account, providerId, reason);
|
|
3024
|
+
await refreshPromise;
|
|
3025
|
+
const currentGen = getCredentialGeneration(account, providerId);
|
|
3026
|
+
if (currentGen !== startGen) {
|
|
3027
|
+
return this.ensureValidTokenForProvider(account, providerId);
|
|
3028
|
+
}
|
|
3029
|
+
} finally {
|
|
3030
|
+
providerMap.delete(flightKey);
|
|
3031
|
+
if (providerMap.size === 0) {
|
|
3032
|
+
this.inFlightRefreshes.delete(account);
|
|
2766
3033
|
}
|
|
2767
|
-
throw error;
|
|
2768
3034
|
}
|
|
2769
3035
|
}
|
|
2770
3036
|
|
|
@@ -3164,22 +3430,39 @@ export class AccountRotator {
|
|
|
3164
3430
|
|
|
3165
3431
|
async replaceConfig(nextConfig: Config): Promise<void> {
|
|
3166
3432
|
const normalized = applyConfigDefaults(nextConfig);
|
|
3167
|
-
const
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3433
|
+
const unmatchedExisting = [...this.accounts];
|
|
3434
|
+
const matchAndReuseAccount = (config: AccountConfig): AccountRuntime => {
|
|
3435
|
+
const targetId = getAccountIdentity(config);
|
|
3436
|
+
const exactIdx = unmatchedExisting.findIndex(
|
|
3437
|
+
(a) => getAccountIdentity(a.config) === targetId,
|
|
3438
|
+
);
|
|
3439
|
+
if (exactIdx !== -1) {
|
|
3440
|
+
const [existing] = unmatchedExisting.splice(exactIdx, 1);
|
|
3441
|
+
existing.config = {
|
|
3174
3442
|
...existing.config,
|
|
3175
3443
|
...config,
|
|
3176
3444
|
credentials: mergeCredentials(existing.config.credentials, config.credentials),
|
|
3177
3445
|
};
|
|
3178
|
-
return
|
|
3179
|
-
|
|
3180
|
-
|
|
3446
|
+
return existing;
|
|
3447
|
+
}
|
|
3448
|
+
|
|
3449
|
+
const matchingIndices: number[] = [];
|
|
3450
|
+
for (let i = 0; i < unmatchedExisting.length; i++) {
|
|
3451
|
+
if (areAccountIdentitiesCompatible(config, unmatchedExisting[i].config)) {
|
|
3452
|
+
matchingIndices.push(i);
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
|
|
3456
|
+
if (matchingIndices.length === 1) {
|
|
3457
|
+
const [existing] = unmatchedExisting.splice(matchingIndices[0], 1);
|
|
3458
|
+
existing.config = {
|
|
3459
|
+
...existing.config,
|
|
3460
|
+
...config,
|
|
3461
|
+
credentials: mergeCredentials(existing.config.credentials, config.credentials),
|
|
3181
3462
|
};
|
|
3463
|
+
return existing;
|
|
3182
3464
|
}
|
|
3465
|
+
|
|
3183
3466
|
return {
|
|
3184
3467
|
config,
|
|
3185
3468
|
accessToken: null,
|
|
@@ -3212,7 +3495,9 @@ export class AccountRotator {
|
|
|
3212
3495
|
lastRefillAt: Date.now(),
|
|
3213
3496
|
},
|
|
3214
3497
|
};
|
|
3215
|
-
}
|
|
3498
|
+
};
|
|
3499
|
+
|
|
3500
|
+
const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
|
|
3216
3501
|
this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
|
|
3217
3502
|
this.accounts = mergedAccounts;
|
|
3218
3503
|
await saveAccountsConfig(this.config);
|