claude-codex-proxy 1.0.2 → 1.0.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/docs/ACCOUNTS.md +1 -1
- package/package.json +1 -1
- package/public/css/style.css +3 -0
- package/public/index.html +9 -9
- package/src/account-manager.js +9 -5
- package/src/account-rotation/index.js +31 -3
- package/src/account-rotation/rate-limits.js +8 -4
- package/src/account-rotation/strategies/base-strategy.js +3 -2
- package/src/account-rotation/strategies/sticky-strategy.js +0 -2
- package/src/direct-api.js +21 -4
- package/src/oauth.js +11 -2
- package/src/routes/accounts-route.js +26 -10
- package/src/routes/messages-route.js +22 -2
package/docs/ACCOUNTS.md
CHANGED
|
@@ -136,7 +136,7 @@ curl -X POST http://localhost:8081/accounts/refresh/all
|
|
|
136
136
|
|
|
137
137
|
### Auto-Refresh
|
|
138
138
|
|
|
139
|
-
- Background refresh every **
|
|
139
|
+
- Background refresh every **5 hours**
|
|
140
140
|
- Startup refresh 2 seconds after server start
|
|
141
141
|
- Proactive refresh 5 minutes before expiry
|
|
142
142
|
|
package/package.json
CHANGED
package/public/css/style.css
CHANGED
|
@@ -57,6 +57,9 @@ body::before {
|
|
|
57
57
|
.bg-neon-purple { background-color: var(--color-neon-purple); }
|
|
58
58
|
.bg-neon-cyan { background-color: var(--color-neon-cyan); }
|
|
59
59
|
.bg-neon-green { background-color: var(--color-neon-green); }
|
|
60
|
+
.bg-yellow-500 { background-color: #eab308; }
|
|
61
|
+
.bg-red-500 { background-color: #ef4444; }
|
|
62
|
+
.bg-gray-500 { background-color: #6b7280; }
|
|
60
63
|
|
|
61
64
|
.border-neon-purple { border-color: var(--color-neon-purple); }
|
|
62
65
|
.border-neon-cyan { border-color: var(--color-neon-cyan); }
|
package/public/index.html
CHANGED
|
@@ -316,7 +316,7 @@
|
|
|
316
316
|
<thead x-show="filteredAccounts.length > 0">
|
|
317
317
|
<tr class="bg-space-900/50 border-b border-space-border/50">
|
|
318
318
|
<th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Status</th>
|
|
319
|
-
<th class="py-3 text-
|
|
319
|
+
<th class="py-3 text-center text-[10px] font-bold text-gray-500 uppercase tracking-wider flex-1 min-w-[200px]">Account (Email)</th>
|
|
320
320
|
<th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Plan</th>
|
|
321
321
|
<th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-32">Token</th>
|
|
322
322
|
<th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-24">Quota</th>
|
|
@@ -364,7 +364,7 @@
|
|
|
364
364
|
</span>
|
|
365
365
|
</div>
|
|
366
366
|
</td>
|
|
367
|
-
<td class="py-4">
|
|
367
|
+
<td class="py-4 text-center">
|
|
368
368
|
<span class="font-mono text-sm text-gray-300 truncate max-w-[320px] inline-block group-hover:text-white transition-colors"
|
|
369
369
|
x-text="acc.email"></span>
|
|
370
370
|
</td>
|
|
@@ -382,6 +382,12 @@
|
|
|
382
382
|
<span class="text-xs font-mono"
|
|
383
383
|
:class="acc.tokenExpired ? 'text-red-400' : 'text-neon-green'"
|
|
384
384
|
x-text="acc.tokenExpired ? 'Expired' : 'Valid'"></span>
|
|
385
|
+
<button class="btn btn-xs btn-ghost p-2 rounded hover:bg-white/10 text-gray-500 hover:text-white transition-colors"
|
|
386
|
+
@click="refreshToken(acc.email)" title="Refresh token">
|
|
387
|
+
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
388
|
+
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
|
389
|
+
</svg>
|
|
390
|
+
</button>
|
|
385
391
|
</div>
|
|
386
392
|
</td>
|
|
387
393
|
<td class="py-4 cursor-pointer" @click="showQuotaModal(acc)">
|
|
@@ -415,16 +421,10 @@
|
|
|
415
421
|
<td class="py-4 pr-6">
|
|
416
422
|
<div class="flex justify-end gap-2">
|
|
417
423
|
<button x-show="!acc.isActive"
|
|
418
|
-
class="px-3 py-1 text-[10px] font-bold font-mono uppercase tracking-wider rounded bg-neon-purple/10 text-neon-purple hover:bg-neon-purple/20 border border-neon-purple/30 hover:border-neon-purple/50 transition-all"
|
|
424
|
+
class="cursor-pointer px-3 py-1 text-[10px] font-bold font-mono uppercase tracking-wider rounded bg-neon-purple/10 text-neon-purple hover:bg-neon-purple/20 border border-neon-purple/30 hover:border-neon-purple/50 transition-all"
|
|
419
425
|
@click="switchAccount(acc.email)">
|
|
420
426
|
SWITCH
|
|
421
427
|
</button>
|
|
422
|
-
<button class="btn btn-xs btn-ghost p-2 rounded hover:bg-white/10 text-gray-500 hover:text-white transition-colors"
|
|
423
|
-
@click="refreshToken(acc.email)" title="Refresh token">
|
|
424
|
-
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
425
|
-
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
|
426
|
-
</svg>
|
|
427
|
-
</button>
|
|
428
428
|
<button class="btn btn-xs btn-ghost p-2 rounded hover:bg-red-500/10 text-gray-500 hover:text-red-400 transition-colors"
|
|
429
429
|
@click="confirmDelete(acc.email)" title="Delete account">
|
|
430
430
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
package/src/account-manager.js
CHANGED
|
@@ -13,7 +13,8 @@ const CONFIG_DIR = join(homedir(), '.claude-codex-proxy');
|
|
|
13
13
|
const ACCOUNTS_FILE = join(CONFIG_DIR, 'accounts.json');
|
|
14
14
|
const ACCOUNTS_DIR = join(CONFIG_DIR, 'accounts');
|
|
15
15
|
|
|
16
|
-
const TOKEN_REFRESH_INTERVAL_MS =
|
|
16
|
+
const TOKEN_REFRESH_INTERVAL_MS = 5 * 60 * 60 * 1000;
|
|
17
|
+
const TOKEN_CACHE_TTL_MS = 55 * 60 * 1000;
|
|
17
18
|
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
|
|
18
19
|
|
|
19
20
|
const DEFAULT_ACCOUNTS = {
|
|
@@ -228,8 +229,10 @@ function getAccountQuota(email) {
|
|
|
228
229
|
}
|
|
229
230
|
|
|
230
231
|
function isTokenExpiredOrExpiringSoon(account) {
|
|
231
|
-
|
|
232
|
-
|
|
232
|
+
const info = account?.accessToken ? extractAccountInfo(account.accessToken) : null;
|
|
233
|
+
const expiresAt = info?.expiresAt || account?.expiresAt;
|
|
234
|
+
if (!expiresAt) return true;
|
|
235
|
+
return Date.now() >= (expiresAt - TOKEN_EXPIRY_BUFFER_MS);
|
|
233
236
|
}
|
|
234
237
|
|
|
235
238
|
async function refreshAccountToken(email) {
|
|
@@ -328,7 +331,7 @@ function startAutoRefresh() {
|
|
|
328
331
|
}
|
|
329
332
|
}, TOKEN_REFRESH_INTERVAL_MS);
|
|
330
333
|
|
|
331
|
-
console.log('[AccountManager] Auto-refresh started (every
|
|
334
|
+
console.log('[AccountManager] Auto-refresh started (every 5 hours)');
|
|
332
335
|
}
|
|
333
336
|
|
|
334
337
|
function stopAutoRefresh() {
|
|
@@ -341,7 +344,7 @@ function stopAutoRefresh() {
|
|
|
341
344
|
|
|
342
345
|
function getCachedToken(email) {
|
|
343
346
|
const cached = tokenCache.get(email);
|
|
344
|
-
if (cached && (Date.now() - cached.extractedAt) <
|
|
347
|
+
if (cached && (Date.now() - cached.extractedAt) < TOKEN_CACHE_TTL_MS) {
|
|
345
348
|
return cached.token;
|
|
346
349
|
}
|
|
347
350
|
return null;
|
|
@@ -499,6 +502,7 @@ export {
|
|
|
499
502
|
getCachedToken,
|
|
500
503
|
setCachedToken,
|
|
501
504
|
TOKEN_REFRESH_INTERVAL_MS,
|
|
505
|
+
TOKEN_CACHE_TTL_MS,
|
|
502
506
|
ACCOUNTS_FILE,
|
|
503
507
|
CONFIG_DIR
|
|
504
508
|
};
|
|
@@ -4,7 +4,8 @@ import {
|
|
|
4
4
|
clearInvalid,
|
|
5
5
|
isAllRateLimited,
|
|
6
6
|
getMinWaitTimeMs,
|
|
7
|
-
clearExpiredLimits
|
|
7
|
+
clearExpiredLimits,
|
|
8
|
+
isQuotaLimitReached
|
|
8
9
|
} from './rate-limits.js';
|
|
9
10
|
|
|
10
11
|
import { createStrategy, STRATEGIES } from './strategies/index.js';
|
|
@@ -13,11 +14,37 @@ export class AccountRotator {
|
|
|
13
14
|
constructor(accountManager, strategyName = 'sticky') {
|
|
14
15
|
this.accountManager = accountManager;
|
|
15
16
|
this.strategy = createStrategy(strategyName);
|
|
17
|
+
this.currentIndex = null;
|
|
18
|
+
this.lastActiveEmail = null;
|
|
16
19
|
}
|
|
17
20
|
|
|
18
21
|
selectAccount(modelId, options = {}) {
|
|
19
22
|
const { accounts } = this.accountManager.listAccounts();
|
|
20
|
-
|
|
23
|
+
const strategyOptions = { ...options };
|
|
24
|
+
|
|
25
|
+
if (this.strategy.name === STRATEGIES.STICKY) {
|
|
26
|
+
const activeAccount = this.accountManager.getActiveAccount?.();
|
|
27
|
+
const activeEmail = activeAccount?.email || null;
|
|
28
|
+
const activeIndex = activeEmail
|
|
29
|
+
? accounts.findIndex(account => account.email === activeEmail)
|
|
30
|
+
: -1;
|
|
31
|
+
|
|
32
|
+
if (this.currentIndex === null || activeEmail !== this.lastActiveEmail) {
|
|
33
|
+
this.currentIndex = activeIndex >= 0 ? activeIndex : 0;
|
|
34
|
+
this.lastActiveEmail = activeEmail;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
strategyOptions.currentIndex = this.currentIndex;
|
|
38
|
+
strategyOptions.onSave = this.accountManager.save;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const result = this.strategy.selectAccount(accounts, modelId, strategyOptions);
|
|
42
|
+
|
|
43
|
+
if (this.strategy.name === STRATEGIES.STICKY && Number.isInteger(result.index)) {
|
|
44
|
+
this.currentIndex = result.index;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return result;
|
|
21
48
|
}
|
|
22
49
|
|
|
23
50
|
markRateLimited(email, resetMs, modelId) {
|
|
@@ -89,5 +116,6 @@ export {
|
|
|
89
116
|
clearInvalid,
|
|
90
117
|
isAllRateLimited,
|
|
91
118
|
getMinWaitTimeMs,
|
|
92
|
-
clearExpiredLimits
|
|
119
|
+
clearExpiredLimits,
|
|
120
|
+
isQuotaLimitReached
|
|
93
121
|
};
|
|
@@ -17,10 +17,7 @@ const DEFAULT_COOLDOWN_MS = 60000;
|
|
|
17
17
|
*/
|
|
18
18
|
export function isAllRateLimited(accounts, modelId) {
|
|
19
19
|
if (!accounts || accounts.length === 0) return true;
|
|
20
|
-
return accounts.
|
|
21
|
-
const rateLimit = account.modelRateLimits?.[modelId];
|
|
22
|
-
return rateLimit?.isRateLimited && rateLimit.resetTime > Date.now();
|
|
23
|
-
});
|
|
20
|
+
return getAvailableAccounts(accounts, modelId).length === 0;
|
|
24
21
|
}
|
|
25
22
|
|
|
26
23
|
/**
|
|
@@ -34,12 +31,19 @@ export function getAvailableAccounts(accounts, modelId) {
|
|
|
34
31
|
const now = Date.now();
|
|
35
32
|
return accounts.filter(account => {
|
|
36
33
|
if (account.isInvalid) return false;
|
|
34
|
+
if (account.enabled === false) return false;
|
|
37
35
|
if (isAccountCoolingDown(account)) return false;
|
|
36
|
+
if (isQuotaLimitReached(account)) return false;
|
|
38
37
|
const rateLimit = account.modelRateLimits?.[modelId];
|
|
39
38
|
return !rateLimit?.isRateLimited || rateLimit.resetTime <= now;
|
|
40
39
|
});
|
|
41
40
|
}
|
|
42
41
|
|
|
42
|
+
export function isQuotaLimitReached(account) {
|
|
43
|
+
const usage = account?.quota?.usage;
|
|
44
|
+
return usage?.allowed === false || usage?.limitReached === true;
|
|
45
|
+
}
|
|
46
|
+
|
|
43
47
|
/**
|
|
44
48
|
* Clear all expired rate limits across all accounts
|
|
45
49
|
* @param {Array} accounts - Array of account objects
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isAccountCoolingDown } from '../rate-limits.js';
|
|
1
|
+
import { isAccountCoolingDown, isQuotaLimitReached } from '../rate-limits.js';
|
|
2
2
|
|
|
3
3
|
export class BaseStrategy {
|
|
4
4
|
constructor(config, name = 'base') {
|
|
@@ -24,7 +24,8 @@ export class BaseStrategy {
|
|
|
24
24
|
if (account.isInvalid) return false;
|
|
25
25
|
if (account.enabled === false) return false;
|
|
26
26
|
if (isAccountCoolingDown(account)) return false;
|
|
27
|
-
|
|
27
|
+
if (isQuotaLimitReached(account)) return false;
|
|
28
|
+
|
|
28
29
|
// Check model-specific rate limit
|
|
29
30
|
if (modelId && account.modelRateLimits && account.modelRateLimits[modelId]) {
|
|
30
31
|
const limit = account.modelRateLimits[modelId];
|
|
@@ -6,7 +6,6 @@ const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
|
6
6
|
export class StickyStrategy extends BaseStrategy {
|
|
7
7
|
constructor(config) {
|
|
8
8
|
super(config, 'sticky');
|
|
9
|
-
this.currentIndex = 0;
|
|
10
9
|
}
|
|
11
10
|
|
|
12
11
|
selectAccount(accounts, modelId, options = {}) {
|
|
@@ -32,7 +31,6 @@ export class StickyStrategy extends BaseStrategy {
|
|
|
32
31
|
if (usableAccounts.length > 0) {
|
|
33
32
|
const nextResult = this.#pickNext(accounts, clampedIndex, modelId, onSave);
|
|
34
33
|
if (nextResult) {
|
|
35
|
-
this.currentIndex = nextResult.index;
|
|
36
34
|
return nextResult;
|
|
37
35
|
}
|
|
38
36
|
}
|
package/src/direct-api.js
CHANGED
|
@@ -39,27 +39,44 @@ function parseResetTime(response, errorText) {
|
|
|
39
39
|
const seconds = parseInt(retryAfter, 10);
|
|
40
40
|
if (!isNaN(seconds)) return seconds * 1000;
|
|
41
41
|
}
|
|
42
|
-
|
|
42
|
+
|
|
43
43
|
const ratelimitReset = response.headers?.get?.('x-ratelimit-reset');
|
|
44
44
|
if (ratelimitReset) {
|
|
45
45
|
const timestamp = parseInt(ratelimitReset, 10) * 1000;
|
|
46
46
|
const wait = timestamp - Date.now();
|
|
47
47
|
if (wait > 0) return wait;
|
|
48
48
|
}
|
|
49
|
-
|
|
49
|
+
|
|
50
50
|
if (errorText) {
|
|
51
|
+
try {
|
|
52
|
+
const errorData = JSON.parse(errorText);
|
|
53
|
+
const primaryWindow = errorData?.rate_limit?.primary_window || errorData?.error?.rate_limit?.primary_window;
|
|
54
|
+
const resetAfterSeconds = Number(primaryWindow?.reset_after_seconds);
|
|
55
|
+
if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds > 0) {
|
|
56
|
+
return resetAfterSeconds * 1000;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const resetAt = Number(primaryWindow?.reset_at);
|
|
60
|
+
if (Number.isFinite(resetAt) && resetAt > 0) {
|
|
61
|
+
const wait = resetAt * 1000 - Date.now();
|
|
62
|
+
if (wait > 0) return wait;
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// Fall back to regex parsing for plain-text upstream errors.
|
|
66
|
+
}
|
|
67
|
+
|
|
51
68
|
const delayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
|
|
52
69
|
if (delayMatch) {
|
|
53
70
|
const value = parseFloat(delayMatch[1]);
|
|
54
71
|
return delayMatch[2] === 's' ? value * 1000 : value;
|
|
55
72
|
}
|
|
56
|
-
|
|
73
|
+
|
|
57
74
|
const secMatch = errorText.match(/retry\s+(?:after\s+)?(\d+)\s*(?:sec|s\b)/i);
|
|
58
75
|
if (secMatch) {
|
|
59
76
|
return parseInt(secMatch[1], 10) * 1000;
|
|
60
77
|
}
|
|
61
78
|
}
|
|
62
|
-
|
|
79
|
+
|
|
63
80
|
return 60000;
|
|
64
81
|
}
|
|
65
82
|
|
package/src/oauth.js
CHANGED
|
@@ -287,10 +287,19 @@ function startCallbackServer(expectedState, timeoutMs = 120000) {
|
|
|
287
287
|
}
|
|
288
288
|
|
|
289
289
|
if (code) {
|
|
290
|
+
if (state !== expectedState) {
|
|
291
|
+
console.error('[OAuth] State mismatch in callback');
|
|
292
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
293
|
+
res.end(getErrorHtml('Invalid OAuth state'));
|
|
294
|
+
server.close();
|
|
295
|
+
reject(new Error('Invalid OAuth state'));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
|
|
290
299
|
console.log('[OAuth] Got authorization code');
|
|
291
300
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
292
301
|
res.end(getSuccessHtml('Authentication Successful! You can close this window.'));
|
|
293
|
-
|
|
302
|
+
|
|
294
303
|
setTimeout(() => {
|
|
295
304
|
server.close();
|
|
296
305
|
clearTimeout(timeoutId);
|
|
@@ -496,7 +505,7 @@ async function performOAuthFlow(customPort) {
|
|
|
496
505
|
const authUrl = getAuthorizationUrl(verifier, state, port);
|
|
497
506
|
|
|
498
507
|
// Start callback server
|
|
499
|
-
const { promise: callbackPromise
|
|
508
|
+
const { promise: callbackPromise } = startCallbackServer(state);
|
|
500
509
|
|
|
501
510
|
console.log(`\n[OAuth] Starting authentication flow...`);
|
|
502
511
|
console.log(`[OAuth] Callback URL: http://localhost:${port}${OAUTH_CONFIG.callbackPath}`);
|
|
@@ -100,16 +100,16 @@ export async function handleAddAccount(req, res) {
|
|
|
100
100
|
activeCallbackServers.set(callbackPort, serverResult);
|
|
101
101
|
|
|
102
102
|
serverResult.promise
|
|
103
|
-
.then(
|
|
103
|
+
.then(code => {
|
|
104
104
|
activeCallbackServers.delete(callbackPort);
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
});
|
|
112
|
-
|
|
105
|
+
if (!code) return null;
|
|
106
|
+
|
|
107
|
+
return exchangeCodeForTokens(code, verifier, callbackPort)
|
|
108
|
+
.then(async tokens => {
|
|
109
|
+
const accountInfo = createAccountInfoFromTokens(tokens);
|
|
110
|
+
await _upsertAccount(accountInfo);
|
|
111
|
+
logger.info(`Added account: ${accountInfo.email}`);
|
|
112
|
+
});
|
|
113
113
|
})
|
|
114
114
|
.catch(err => {
|
|
115
115
|
activeCallbackServers.delete(callbackPort);
|
|
@@ -135,7 +135,7 @@ export async function handleAddAccountManual(req, res) {
|
|
|
135
135
|
try {
|
|
136
136
|
const { code: extractedCode } = extractCodeFromInput(code);
|
|
137
137
|
const tokens = await exchangeCodeForTokens(extractedCode, verifier);
|
|
138
|
-
const accountInfo =
|
|
138
|
+
const accountInfo = createAccountInfoFromTokens(tokens);
|
|
139
139
|
|
|
140
140
|
await _upsertAccount(accountInfo);
|
|
141
141
|
logger.info(`Added account via manual OAuth: ${accountInfo.email}`);
|
|
@@ -250,6 +250,22 @@ export async function handleGetAllQuotas(req, res) {
|
|
|
250
250
|
|
|
251
251
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
252
252
|
|
|
253
|
+
export function createAccountInfoFromTokens(tokens) {
|
|
254
|
+
const tokenInfo = extractAccountInfo(tokens.accessToken) || {};
|
|
255
|
+
|
|
256
|
+
return {
|
|
257
|
+
email: tokenInfo.email || 'unknown',
|
|
258
|
+
accountId: tokenInfo.accountId,
|
|
259
|
+
planType: tokenInfo.planType || 'free',
|
|
260
|
+
accessToken: tokens.accessToken,
|
|
261
|
+
refreshToken: tokens.refreshToken,
|
|
262
|
+
idToken: tokens.idToken,
|
|
263
|
+
expiresAt: tokenInfo.expiresAt || (Date.now() + tokens.expiresIn * 1000),
|
|
264
|
+
addedAt: new Date().toISOString(),
|
|
265
|
+
lastUsed: new Date().toISOString()
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
253
269
|
/**
|
|
254
270
|
* Inserts or updates an account in the persisted accounts store,
|
|
255
271
|
* and sets it as the active account.
|
|
@@ -4,7 +4,7 @@ import { sendAuthError, getCredentialsForAccount } from '../middleware/credentia
|
|
|
4
4
|
import { initSSEResponse, pipeSSEStream, handleStreamError } from '../middleware/sse.js';
|
|
5
5
|
import { logger } from '../utils/logger.js';
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
|
-
import { listAccounts, getActiveAccount, save } from '../account-manager.js';
|
|
7
|
+
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
9
|
|
|
10
10
|
const MAX_RETRIES = 5;
|
|
@@ -29,7 +29,14 @@ function getAccountRotator() {
|
|
|
29
29
|
|
|
30
30
|
if (!accountRotator || currentStrategy !== strategy) {
|
|
31
31
|
accountRotator = new AccountRotator({
|
|
32
|
-
listAccounts
|
|
32
|
+
listAccounts: () => {
|
|
33
|
+
const data = loadAccounts();
|
|
34
|
+
return {
|
|
35
|
+
accounts: data.accounts,
|
|
36
|
+
activeAccount: data.activeAccount,
|
|
37
|
+
total: data.accounts.length
|
|
38
|
+
};
|
|
39
|
+
},
|
|
33
40
|
save,
|
|
34
41
|
getActiveAccount
|
|
35
42
|
}, strategy);
|
|
@@ -83,6 +90,9 @@ export async function handleMessages(req, res) {
|
|
|
83
90
|
return sendAuthError(res, 'No available accounts');
|
|
84
91
|
}
|
|
85
92
|
|
|
93
|
+
syncActiveAccount(account.email);
|
|
94
|
+
logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
|
|
95
|
+
|
|
86
96
|
const creds = await getCredentialsForAccount(account.email);
|
|
87
97
|
if (!creds) {
|
|
88
98
|
rotator.markInvalid(account.email, 'Failed to get credentials');
|
|
@@ -145,6 +155,16 @@ async function _sendDirectWithRotation(res, anthropicRequest, creds, responseMod
|
|
|
145
155
|
res.json({ ...response, model: responseModel });
|
|
146
156
|
}
|
|
147
157
|
|
|
158
|
+
function syncActiveAccount(email) {
|
|
159
|
+
const active = getActiveAccount();
|
|
160
|
+
if (active?.email === email) return;
|
|
161
|
+
|
|
162
|
+
const result = setActiveAccount(email);
|
|
163
|
+
if (result.success) {
|
|
164
|
+
logger.info(`[Messages] Synced active account to actual account: ${email}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
148
168
|
function getTokenDetails(usage = {}) {
|
|
149
169
|
const inputTokens = usage?.input_tokens || 0;
|
|
150
170
|
const outputTokens = usage?.output_tokens || 0;
|