claude-codex-proxy 1.0.3 → 1.0.4
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/package.json +1 -1
- package/public/index.html +4 -3
- package/public/js/app.js +14 -6
- package/src/account-manager.js +83 -29
- package/src/account-rotation/rate-limits.js +49 -0
- package/src/account-rotation/strategies/sticky-strategy.js +9 -22
- package/src/direct-api.js +15 -2
- package/src/routes/messages-route.js +4 -11
- package/src/routes/models-route.js +1 -1
- package/src/server-settings.js +0 -2
- package/src/server.js +5 -3
package/package.json
CHANGED
package/public/index.html
CHANGED
|
@@ -326,7 +326,7 @@
|
|
|
326
326
|
<tbody>
|
|
327
327
|
<template x-if="filteredAccounts.length === 0 && accounts.length === 0">
|
|
328
328
|
<tr>
|
|
329
|
-
<td colspan="6" class="py-16 text-center">
|
|
329
|
+
<td colspan="6" class="py-16 text-center flex justify-center">
|
|
330
330
|
<div class="flex flex-col items-center gap-4 max-w-lg mx-auto">
|
|
331
331
|
<svg class="w-20 h-20 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
332
332
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
|
|
@@ -383,8 +383,9 @@
|
|
|
383
383
|
:class="acc.tokenExpired ? 'text-red-400' : 'text-neon-green'"
|
|
384
384
|
x-text="acc.tokenExpired ? 'Expired' : 'Valid'"></span>
|
|
385
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)"
|
|
387
|
-
|
|
386
|
+
@click="refreshToken(acc.email)"
|
|
387
|
+
:disabled="refreshingTokenEmails.includes(acc.email)" title="Refresh token">
|
|
388
|
+
<svg class="w-4 h-4" :class="{'animate-spin': refreshingTokenEmails.includes(acc.email)}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
388
389
|
<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
390
|
</svg>
|
|
390
391
|
</button>
|
package/public/js/app.js
CHANGED
|
@@ -5,6 +5,7 @@ document.addEventListener('alpine:init', () => {
|
|
|
5
5
|
activeTab: 'dashboard',
|
|
6
6
|
sidebarOpen: window.innerWidth >= 1024,
|
|
7
7
|
loading: false,
|
|
8
|
+
refreshingTokenEmails: [],
|
|
8
9
|
toast: null,
|
|
9
10
|
currentTime: '',
|
|
10
11
|
|
|
@@ -346,12 +347,19 @@ document.addEventListener('alpine:init', () => {
|
|
|
346
347
|
},
|
|
347
348
|
|
|
348
349
|
async refreshToken(email) {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
350
|
+
if (this.refreshingTokenEmails.includes(email)) return;
|
|
351
|
+
|
|
352
|
+
this.refreshingTokenEmails.push(email);
|
|
353
|
+
try {
|
|
354
|
+
const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' });
|
|
355
|
+
if (ok && data.success) {
|
|
356
|
+
this.showToast(data.message, 'success');
|
|
357
|
+
await this.refreshAccounts();
|
|
358
|
+
} else {
|
|
359
|
+
this.showToast(data?.message || 'Refresh failed', 'error');
|
|
360
|
+
}
|
|
361
|
+
} finally {
|
|
362
|
+
this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email);
|
|
355
363
|
}
|
|
356
364
|
},
|
|
357
365
|
|
package/src/account-manager.js
CHANGED
|
@@ -14,6 +14,7 @@ const ACCOUNTS_FILE = join(CONFIG_DIR, 'accounts.json');
|
|
|
14
14
|
const ACCOUNTS_DIR = join(CONFIG_DIR, 'accounts');
|
|
15
15
|
|
|
16
16
|
const TOKEN_REFRESH_INTERVAL_MS = 5 * 60 * 60 * 1000;
|
|
17
|
+
const QUOTA_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
|
|
17
18
|
const TOKEN_CACHE_TTL_MS = 55 * 60 * 1000;
|
|
18
19
|
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
|
|
19
20
|
|
|
@@ -24,7 +25,9 @@ const DEFAULT_ACCOUNTS = {
|
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
let autoRefreshIntervalId = null;
|
|
28
|
+
let quotaRefreshIntervalId = null;
|
|
27
29
|
const tokenCache = new Map();
|
|
30
|
+
const tokenRefreshPromises = new Map();
|
|
28
31
|
let accountsData = null;
|
|
29
32
|
|
|
30
33
|
function ensureConfigDir() {
|
|
@@ -54,8 +57,6 @@ function loadAccounts() {
|
|
|
54
57
|
return accountsData;
|
|
55
58
|
}
|
|
56
59
|
|
|
57
|
-
ensureConfigDir();
|
|
58
|
-
|
|
59
60
|
if (!existsSync(ACCOUNTS_FILE)) {
|
|
60
61
|
accountsData = { ...DEFAULT_ACCOUNTS };
|
|
61
62
|
return accountsData;
|
|
@@ -236,45 +237,56 @@ function isTokenExpiredOrExpiringSoon(account) {
|
|
|
236
237
|
}
|
|
237
238
|
|
|
238
239
|
async function refreshAccountToken(email) {
|
|
240
|
+
if (tokenRefreshPromises.has(email)) {
|
|
241
|
+
return tokenRefreshPromises.get(email);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const refreshPromise = refreshAccountTokenOnce(email).finally(() => {
|
|
245
|
+
tokenRefreshPromises.delete(email);
|
|
246
|
+
});
|
|
247
|
+
tokenRefreshPromises.set(email, refreshPromise);
|
|
248
|
+
return refreshPromise;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function refreshAccountTokenOnce(email) {
|
|
239
252
|
const data = loadAccounts();
|
|
240
253
|
const account = data.accounts.find(a => a.email === email);
|
|
241
|
-
|
|
254
|
+
|
|
242
255
|
if (!account) {
|
|
243
256
|
return { success: false, message: `Account not found: ${email}` };
|
|
244
257
|
}
|
|
245
|
-
|
|
258
|
+
|
|
246
259
|
if (!account.refreshToken) {
|
|
247
260
|
return { success: false, message: 'No refresh token available' };
|
|
248
261
|
}
|
|
249
|
-
|
|
262
|
+
|
|
250
263
|
try {
|
|
251
264
|
const tokens = await refreshAccessToken(account.refreshToken);
|
|
252
265
|
const accountInfo = extractAccountInfo(tokens.accessToken);
|
|
253
|
-
|
|
254
|
-
const index =
|
|
266
|
+
const latestData = loadAccounts();
|
|
267
|
+
const index = latestData.accounts.findIndex(a => a.email === email);
|
|
255
268
|
if (index >= 0) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
269
|
+
latestData.accounts[index].accessToken = tokens.accessToken;
|
|
270
|
+
latestData.accounts[index].refreshToken = tokens.refreshToken || latestData.accounts[index].refreshToken;
|
|
271
|
+
latestData.accounts[index].idToken = tokens.idToken || latestData.accounts[index].idToken;
|
|
272
|
+
latestData.accounts[index].expiresAt = accountInfo?.expiresAt || (Date.now() + tokens.expiresIn * 1000);
|
|
260
273
|
if (accountInfo?.planType) {
|
|
261
|
-
|
|
274
|
+
latestData.accounts[index].planType = accountInfo.planType;
|
|
262
275
|
}
|
|
263
|
-
saveAccounts(
|
|
264
|
-
|
|
276
|
+
saveAccounts(latestData);
|
|
277
|
+
|
|
265
278
|
tokenCache.set(email, {
|
|
266
279
|
token: tokens.accessToken,
|
|
267
280
|
extractedAt: Date.now()
|
|
268
281
|
});
|
|
269
|
-
|
|
270
|
-
if (
|
|
271
|
-
updateAccountAuth(
|
|
282
|
+
|
|
283
|
+
if (latestData.activeAccount === email) {
|
|
284
|
+
updateAccountAuth(latestData.accounts[index]);
|
|
272
285
|
}
|
|
273
286
|
}
|
|
274
|
-
|
|
287
|
+
|
|
275
288
|
console.log(`[AccountManager] Token refreshed for: ${email}`);
|
|
276
|
-
|
|
277
|
-
// Auto-fetch quota after refresh
|
|
289
|
+
|
|
278
290
|
try {
|
|
279
291
|
const quotaData = await fetchQuota(tokens.accessToken, accountInfo.accountId);
|
|
280
292
|
updateAccountQuota(email, quotaData);
|
|
@@ -293,14 +305,41 @@ async function refreshAccountToken(email) {
|
|
|
293
305
|
async function refreshAllAccounts() {
|
|
294
306
|
const data = loadAccounts();
|
|
295
307
|
const results = [];
|
|
296
|
-
|
|
308
|
+
|
|
297
309
|
for (const account of data.accounts) {
|
|
298
310
|
if (account.refreshToken) {
|
|
299
311
|
const result = await refreshAccountToken(account.email);
|
|
300
312
|
results.push({ email: account.email, ...result });
|
|
301
313
|
}
|
|
302
314
|
}
|
|
303
|
-
|
|
315
|
+
|
|
316
|
+
return results;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function refreshAllAccountQuotas() {
|
|
320
|
+
const data = loadAccounts();
|
|
321
|
+
const results = [];
|
|
322
|
+
|
|
323
|
+
for (const account of data.accounts) {
|
|
324
|
+
if (!account.accessToken || !account.accountId) continue;
|
|
325
|
+
|
|
326
|
+
try {
|
|
327
|
+
if (isTokenExpiredOrExpiringSoon(account) && account.refreshToken) {
|
|
328
|
+
const result = await refreshAccountToken(account.email);
|
|
329
|
+
results.push({ email: account.email, ...result });
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const quotaData = await fetchQuota(account.accessToken, account.accountId);
|
|
334
|
+
updateAccountQuota(account.email, quotaData);
|
|
335
|
+
console.log(`[AccountManager] Quota refreshed for: ${account.email}`);
|
|
336
|
+
results.push({ email: account.email, success: true });
|
|
337
|
+
} catch (error) {
|
|
338
|
+
console.warn(`[AccountManager] Failed to refresh quota for ${account.email}: ${error.message}`);
|
|
339
|
+
results.push({ email: account.email, success: false, message: error.message });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
304
343
|
return results;
|
|
305
344
|
}
|
|
306
345
|
|
|
@@ -308,7 +347,10 @@ function startAutoRefresh() {
|
|
|
308
347
|
if (autoRefreshIntervalId) {
|
|
309
348
|
clearInterval(autoRefreshIntervalId);
|
|
310
349
|
}
|
|
311
|
-
|
|
350
|
+
if (quotaRefreshIntervalId) {
|
|
351
|
+
clearInterval(quotaRefreshIntervalId);
|
|
352
|
+
}
|
|
353
|
+
|
|
312
354
|
setTimeout(async () => {
|
|
313
355
|
console.log('[AccountManager] Startup: refreshing all account tokens...');
|
|
314
356
|
const data = loadAccounts();
|
|
@@ -319,27 +361,36 @@ function startAutoRefresh() {
|
|
|
319
361
|
}
|
|
320
362
|
}
|
|
321
363
|
}, 2000);
|
|
322
|
-
|
|
364
|
+
|
|
323
365
|
autoRefreshIntervalId = setInterval(async () => {
|
|
324
366
|
const data = loadAccounts();
|
|
325
|
-
|
|
367
|
+
|
|
326
368
|
for (const account of data.accounts) {
|
|
327
369
|
if (account.refreshToken) {
|
|
328
|
-
console.log(`[AccountManager] Periodic refresh for ${account.email}`);
|
|
370
|
+
console.log(`[AccountManager] Periodic token refresh for ${account.email}`);
|
|
329
371
|
await refreshAccountToken(account.email);
|
|
330
372
|
}
|
|
331
373
|
}
|
|
332
374
|
}, TOKEN_REFRESH_INTERVAL_MS);
|
|
333
|
-
|
|
334
|
-
|
|
375
|
+
|
|
376
|
+
quotaRefreshIntervalId = setInterval(async () => {
|
|
377
|
+
console.log('[AccountManager] Periodic quota refresh for all accounts');
|
|
378
|
+
await refreshAllAccountQuotas();
|
|
379
|
+
}, QUOTA_REFRESH_INTERVAL_MS);
|
|
380
|
+
|
|
381
|
+
console.log('[AccountManager] Auto-refresh started (tokens every 5 hours, quotas every 1 hour)');
|
|
335
382
|
}
|
|
336
383
|
|
|
337
384
|
function stopAutoRefresh() {
|
|
338
385
|
if (autoRefreshIntervalId) {
|
|
339
386
|
clearInterval(autoRefreshIntervalId);
|
|
340
387
|
autoRefreshIntervalId = null;
|
|
341
|
-
console.log('[AccountManager] Auto-refresh stopped');
|
|
342
388
|
}
|
|
389
|
+
if (quotaRefreshIntervalId) {
|
|
390
|
+
clearInterval(quotaRefreshIntervalId);
|
|
391
|
+
quotaRefreshIntervalId = null;
|
|
392
|
+
}
|
|
393
|
+
console.log('[AccountManager] Auto-refresh stopped');
|
|
343
394
|
}
|
|
344
395
|
|
|
345
396
|
function getCachedToken(email) {
|
|
@@ -490,6 +541,7 @@ export {
|
|
|
490
541
|
refreshActiveAccount,
|
|
491
542
|
refreshAccountToken,
|
|
492
543
|
refreshAllAccounts,
|
|
544
|
+
refreshAllAccountQuotas,
|
|
493
545
|
importFromCodex,
|
|
494
546
|
getStatus,
|
|
495
547
|
updateAccountAuth,
|
|
@@ -502,6 +554,7 @@ export {
|
|
|
502
554
|
getCachedToken,
|
|
503
555
|
setCachedToken,
|
|
504
556
|
TOKEN_REFRESH_INTERVAL_MS,
|
|
557
|
+
QUOTA_REFRESH_INTERVAL_MS,
|
|
505
558
|
TOKEN_CACHE_TTL_MS,
|
|
506
559
|
ACCOUNTS_FILE,
|
|
507
560
|
CONFIG_DIR
|
|
@@ -515,6 +568,7 @@ export default {
|
|
|
515
568
|
refreshActiveAccount,
|
|
516
569
|
refreshAccountToken,
|
|
517
570
|
refreshAllAccounts,
|
|
571
|
+
refreshAllAccountQuotas,
|
|
518
572
|
importFromCodex,
|
|
519
573
|
getStatus,
|
|
520
574
|
ensureAccountsPersist,
|
|
@@ -8,6 +8,7 @@ export const CooldownReason = {
|
|
|
8
8
|
};
|
|
9
9
|
|
|
10
10
|
const DEFAULT_COOLDOWN_MS = 60000;
|
|
11
|
+
const DEFAULT_QUOTA_WAIT_MS = DEFAULT_COOLDOWN_MS;
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Check if all accounts are rate-limited for a specific model
|
|
@@ -44,6 +45,49 @@ export function isQuotaLimitReached(account) {
|
|
|
44
45
|
return usage?.allowed === false || usage?.limitReached === true;
|
|
45
46
|
}
|
|
46
47
|
|
|
48
|
+
function getPrimaryWindowFromQuotaUsage(usage) {
|
|
49
|
+
return usage?.rate_limit?.primary_window
|
|
50
|
+
|| usage?.error?.rate_limit?.primary_window
|
|
51
|
+
|| usage?.raw?.rate_limit?.primary_window
|
|
52
|
+
|| usage?.raw?.error?.rate_limit?.primary_window
|
|
53
|
+
|| usage?.primary_window
|
|
54
|
+
|| null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function getWaitFromPrimaryWindow(primaryWindow, now) {
|
|
58
|
+
const resetAfterSeconds = Number(primaryWindow?.reset_after_seconds);
|
|
59
|
+
if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds > 0) {
|
|
60
|
+
return resetAfterSeconds * 1000;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const resetAt = Number(primaryWindow?.reset_at);
|
|
64
|
+
if (Number.isFinite(resetAt) && resetAt > 0) {
|
|
65
|
+
const wait = resetAt * 1000 - now;
|
|
66
|
+
if (wait > 0) return wait;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function getQuotaWaitTimeMs(account, now) {
|
|
73
|
+
if (!isQuotaLimitReached(account)) return 0;
|
|
74
|
+
|
|
75
|
+
const usage = account?.quota?.usage;
|
|
76
|
+
const resetAfterSeconds = Number(usage?.resetAfterSeconds);
|
|
77
|
+
if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds > 0) {
|
|
78
|
+
return resetAfterSeconds * 1000;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const resetAt = Date.parse(usage?.resetAt);
|
|
82
|
+
if (Number.isFinite(resetAt)) {
|
|
83
|
+
const wait = resetAt - now;
|
|
84
|
+
if (wait > 0) return wait;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const primaryWindowWait = getWaitFromPrimaryWindow(getPrimaryWindowFromQuotaUsage(usage), now);
|
|
88
|
+
return primaryWindowWait > 0 ? primaryWindowWait : DEFAULT_QUOTA_WAIT_MS;
|
|
89
|
+
}
|
|
90
|
+
|
|
47
91
|
/**
|
|
48
92
|
* Clear all expired rate limits across all accounts
|
|
49
93
|
* @param {Array} accounts - Array of account objects
|
|
@@ -181,6 +225,11 @@ export function getMinWaitTimeMs(accounts, modelId) {
|
|
|
181
225
|
minWait = waitTime;
|
|
182
226
|
}
|
|
183
227
|
}
|
|
228
|
+
|
|
229
|
+
const quotaWait = getQuotaWaitTimeMs(account, now);
|
|
230
|
+
if (quotaWait > 0 && quotaWait < minWait) {
|
|
231
|
+
minWait = quotaWait;
|
|
232
|
+
}
|
|
184
233
|
}
|
|
185
234
|
|
|
186
235
|
return minWait === Infinity ? 0 : minWait;
|
|
@@ -9,7 +9,7 @@ export class StickyStrategy extends BaseStrategy {
|
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
selectAccount(accounts, modelId, options = {}) {
|
|
12
|
-
const { currentIndex = 0, onSave } = options;
|
|
12
|
+
const { currentIndex = 0, onSave, random = Math.random } = options;
|
|
13
13
|
|
|
14
14
|
if (!accounts || accounts.length === 0) {
|
|
15
15
|
return { account: null, index: currentIndex, waitMs: 0 };
|
|
@@ -29,10 +29,7 @@ export class StickyStrategy extends BaseStrategy {
|
|
|
29
29
|
const usableAccounts = this.getUsableAccounts(accounts, modelId);
|
|
30
30
|
|
|
31
31
|
if (usableAccounts.length > 0) {
|
|
32
|
-
|
|
33
|
-
if (nextResult) {
|
|
34
|
-
return nextResult;
|
|
35
|
-
}
|
|
32
|
+
return this.#pickRandom(usableAccounts, onSave, random);
|
|
36
33
|
}
|
|
37
34
|
|
|
38
35
|
// Check if we should wait for the current account
|
|
@@ -73,23 +70,13 @@ export class StickyStrategy extends BaseStrategy {
|
|
|
73
70
|
return { shouldWait: false, waitMs: 0 };
|
|
74
71
|
}
|
|
75
72
|
|
|
76
|
-
#
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
for (let i = 0; i < accounts.length; i++) {
|
|
80
|
-
const checkIndex = (startIndex + i) % accounts.length;
|
|
81
|
-
const account = accounts[checkIndex];
|
|
82
|
-
|
|
83
|
-
if (checkIndex === currentIndex) continue;
|
|
84
|
-
|
|
85
|
-
if (this.isAccountUsable(account, modelId)) {
|
|
86
|
-
account.lastUsed = Date.now();
|
|
87
|
-
if (onSave) onSave();
|
|
88
|
-
logger.debug(`StickyStrategy: Switched to account at index ${checkIndex}`);
|
|
89
|
-
return { account, index: checkIndex, waitMs: 0 };
|
|
90
|
-
}
|
|
91
|
-
}
|
|
73
|
+
#pickRandom(usableAccounts, onSave, random) {
|
|
74
|
+
const randomIndex = Math.floor(random() * usableAccounts.length);
|
|
75
|
+
const { account, index } = usableAccounts[randomIndex];
|
|
92
76
|
|
|
93
|
-
|
|
77
|
+
account.lastUsed = Date.now();
|
|
78
|
+
if (onSave) onSave();
|
|
79
|
+
logger.debug(`StickyStrategy: Switched to random account at index ${index}`);
|
|
80
|
+
return { account, index, waitMs: 0 };
|
|
94
81
|
}
|
|
95
82
|
}
|
package/src/direct-api.js
CHANGED
|
@@ -4,13 +4,16 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import os from 'os';
|
|
7
|
+
import { createRequire } from 'module';
|
|
7
8
|
import { convertAnthropicToResponsesAPI, convertOutputToAnthropic, generateMessageId } from './format-converter.js';
|
|
8
9
|
import { streamResponsesAPI, parseResponsesAPIResponse, createResponsesAPIError } from './response-streamer.js';
|
|
9
10
|
import { getServerSettings } from './server-settings.js';
|
|
10
11
|
import { logger } from './utils/logger.js';
|
|
11
12
|
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
const packageJson = require('../package.json');
|
|
12
15
|
const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
|
13
|
-
const APP_VERSION =
|
|
16
|
+
const APP_VERSION = packageJson.version;
|
|
14
17
|
|
|
15
18
|
function shouldLogRawProxyPayloads() {
|
|
16
19
|
return getServerSettings().logRawProxyPayloads === true;
|
|
@@ -168,7 +171,7 @@ export async function createMessageStream(anthropicRequest, accessToken, account
|
|
|
168
171
|
/**
|
|
169
172
|
* Send a non-streaming request to ChatGPT API
|
|
170
173
|
*/
|
|
171
|
-
export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}) {
|
|
174
|
+
export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}, accountRotator = null, currentEmail = null) {
|
|
172
175
|
const request = convertAnthropicToResponsesAPI({
|
|
173
176
|
...anthropicRequest,
|
|
174
177
|
stream: false
|
|
@@ -193,6 +196,16 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
193
196
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
|
194
197
|
}
|
|
195
198
|
|
|
199
|
+
if (response.status === 429) {
|
|
200
|
+
const resetMs = parseResetTime(response, errorText);
|
|
201
|
+
if (accountRotator && currentEmail) {
|
|
202
|
+
accountRotator.markRateLimited(currentEmail, resetMs, anthropicRequest.model);
|
|
203
|
+
}
|
|
204
|
+
const error = createHTTPError(`RATE_LIMITED:${resetMs}:${errorText}`, 429, 'rate_limit_error', response.status);
|
|
205
|
+
error.resetMs = resetMs;
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
|
|
196
209
|
throw createUpstreamHTTPError(response, errorText);
|
|
197
210
|
}
|
|
198
211
|
|
|
@@ -67,16 +67,9 @@ export async function handleMessages(req, res) {
|
|
|
67
67
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
68
68
|
if (rotator.isAllRateLimited(upstreamModel)) {
|
|
69
69
|
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
logger.info(`[Messages] All accounts rate-limited, waiting ${Math.round(minWait/1000)}s...`);
|
|
76
|
-
await sleep(minWait + 500);
|
|
77
|
-
rotator.clearExpiredLimits();
|
|
78
|
-
attempt--;
|
|
79
|
-
continue;
|
|
70
|
+
const waitSeconds = minWait > 0 ? Math.round(minWait / 1000) : 'unknown';
|
|
71
|
+
logger.info(`[Messages] All accounts rate-limited, not retrying. Next possible reset: ${waitSeconds}s`);
|
|
72
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
80
73
|
}
|
|
81
74
|
|
|
82
75
|
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
@@ -149,7 +142,7 @@ async function _streamDirectWithRotation(res, anthropicRequest, creds, responseM
|
|
|
149
142
|
}
|
|
150
143
|
|
|
151
144
|
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
152
|
-
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext);
|
|
145
|
+
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
153
146
|
const duration = Date.now() - startTime;
|
|
154
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
155
148
|
res.json({ ...response, model: responseModel });
|
|
@@ -11,7 +11,7 @@ import { getActiveAccount, loadAccounts } from '../account-manager.js';
|
|
|
11
11
|
import { logger } from '../utils/logger.js';
|
|
12
12
|
import { getCredentialsOrError } from '../middleware/credentials.js';
|
|
13
13
|
|
|
14
|
-
const FALLBACK_MODELS = [
|
|
14
|
+
export const FALLBACK_MODELS = [
|
|
15
15
|
// OpenAI upstream models
|
|
16
16
|
{ id: 'gpt-5.3-codex', object: 'model', owned_by: 'openai' },
|
|
17
17
|
{ id: 'gpt-5.2-codex', object: 'model', owned_by: 'openai' },
|
package/src/server-settings.js
CHANGED
package/src/server.js
CHANGED
|
@@ -9,9 +9,11 @@ import cors from 'cors';
|
|
|
9
9
|
import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
|
|
10
10
|
import { registerApiRoutes } from './routes/api-routes.js';
|
|
11
11
|
|
|
12
|
-
export function createServer({ port }) {
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export function createServer({ port, testMode = false }) {
|
|
13
|
+
if (!testMode) {
|
|
14
|
+
ensureAccountsPersist();
|
|
15
|
+
startAutoRefresh();
|
|
16
|
+
}
|
|
15
17
|
|
|
16
18
|
const app = express();
|
|
17
19
|
app.disable('x-powered-by');
|