claude-codex-proxy 1.0.2 → 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/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 **55 minutes**
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -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-left text-[10px] font-bold text-gray-500 uppercase tracking-wider flex-1 min-w-[200px]">Account (Email)</th>
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>
@@ -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" />
@@ -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,13 @@
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)"
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">
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" />
390
+ </svg>
391
+ </button>
385
392
  </div>
386
393
  </td>
387
394
  <td class="py-4 cursor-pointer" @click="showQuotaModal(acc)">
@@ -415,16 +422,10 @@
415
422
  <td class="py-4 pr-6">
416
423
  <div class="flex justify-end gap-2">
417
424
  <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"
425
+ 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
426
  @click="switchAccount(acc.email)">
420
427
  SWITCH
421
428
  </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
429
  <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
430
  @click="confirmDelete(acc.email)" title="Delete account">
430
431
  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
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
- const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' });
350
- if (ok && data.success) {
351
- this.showToast(data.message, 'success');
352
- this.refreshAccounts();
353
- } else {
354
- this.showToast(data?.message || 'Refresh failed', 'error');
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
 
@@ -13,7 +13,9 @@ 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 = 55 * 60 * 1000;
16
+ const TOKEN_REFRESH_INTERVAL_MS = 5 * 60 * 60 * 1000;
17
+ const QUOTA_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
18
+ const TOKEN_CACHE_TTL_MS = 55 * 60 * 1000;
17
19
  const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
18
20
 
19
21
  const DEFAULT_ACCOUNTS = {
@@ -23,7 +25,9 @@ const DEFAULT_ACCOUNTS = {
23
25
  };
24
26
 
25
27
  let autoRefreshIntervalId = null;
28
+ let quotaRefreshIntervalId = null;
26
29
  const tokenCache = new Map();
30
+ const tokenRefreshPromises = new Map();
27
31
  let accountsData = null;
28
32
 
29
33
  function ensureConfigDir() {
@@ -53,8 +57,6 @@ function loadAccounts() {
53
57
  return accountsData;
54
58
  }
55
59
 
56
- ensureConfigDir();
57
-
58
60
  if (!existsSync(ACCOUNTS_FILE)) {
59
61
  accountsData = { ...DEFAULT_ACCOUNTS };
60
62
  return accountsData;
@@ -228,50 +230,63 @@ function getAccountQuota(email) {
228
230
  }
229
231
 
230
232
  function isTokenExpiredOrExpiringSoon(account) {
231
- if (!account.expiresAt) return true;
232
- return Date.now() >= (account.expiresAt - TOKEN_EXPIRY_BUFFER_MS);
233
+ const info = account?.accessToken ? extractAccountInfo(account.accessToken) : null;
234
+ const expiresAt = info?.expiresAt || account?.expiresAt;
235
+ if (!expiresAt) return true;
236
+ return Date.now() >= (expiresAt - TOKEN_EXPIRY_BUFFER_MS);
233
237
  }
234
238
 
235
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) {
236
252
  const data = loadAccounts();
237
253
  const account = data.accounts.find(a => a.email === email);
238
-
254
+
239
255
  if (!account) {
240
256
  return { success: false, message: `Account not found: ${email}` };
241
257
  }
242
-
258
+
243
259
  if (!account.refreshToken) {
244
260
  return { success: false, message: 'No refresh token available' };
245
261
  }
246
-
262
+
247
263
  try {
248
264
  const tokens = await refreshAccessToken(account.refreshToken);
249
265
  const accountInfo = extractAccountInfo(tokens.accessToken);
250
-
251
- const index = data.accounts.findIndex(a => a.email === email);
266
+ const latestData = loadAccounts();
267
+ const index = latestData.accounts.findIndex(a => a.email === email);
252
268
  if (index >= 0) {
253
- data.accounts[index].accessToken = tokens.accessToken;
254
- data.accounts[index].refreshToken = tokens.refreshToken || data.accounts[index].refreshToken;
255
- data.accounts[index].idToken = tokens.idToken || data.accounts[index].idToken;
256
- data.accounts[index].expiresAt = accountInfo?.expiresAt || (Date.now() + tokens.expiresIn * 1000);
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);
257
273
  if (accountInfo?.planType) {
258
- data.accounts[index].planType = accountInfo.planType;
274
+ latestData.accounts[index].planType = accountInfo.planType;
259
275
  }
260
- saveAccounts(data);
261
-
276
+ saveAccounts(latestData);
277
+
262
278
  tokenCache.set(email, {
263
279
  token: tokens.accessToken,
264
280
  extractedAt: Date.now()
265
281
  });
266
-
267
- if (data.activeAccount === email) {
268
- updateAccountAuth(data.accounts[index]);
282
+
283
+ if (latestData.activeAccount === email) {
284
+ updateAccountAuth(latestData.accounts[index]);
269
285
  }
270
286
  }
271
-
287
+
272
288
  console.log(`[AccountManager] Token refreshed for: ${email}`);
273
-
274
- // Auto-fetch quota after refresh
289
+
275
290
  try {
276
291
  const quotaData = await fetchQuota(tokens.accessToken, accountInfo.accountId);
277
292
  updateAccountQuota(email, quotaData);
@@ -290,14 +305,41 @@ async function refreshAccountToken(email) {
290
305
  async function refreshAllAccounts() {
291
306
  const data = loadAccounts();
292
307
  const results = [];
293
-
308
+
294
309
  for (const account of data.accounts) {
295
310
  if (account.refreshToken) {
296
311
  const result = await refreshAccountToken(account.email);
297
312
  results.push({ email: account.email, ...result });
298
313
  }
299
314
  }
300
-
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
+
301
343
  return results;
302
344
  }
303
345
 
@@ -305,7 +347,10 @@ function startAutoRefresh() {
305
347
  if (autoRefreshIntervalId) {
306
348
  clearInterval(autoRefreshIntervalId);
307
349
  }
308
-
350
+ if (quotaRefreshIntervalId) {
351
+ clearInterval(quotaRefreshIntervalId);
352
+ }
353
+
309
354
  setTimeout(async () => {
310
355
  console.log('[AccountManager] Startup: refreshing all account tokens...');
311
356
  const data = loadAccounts();
@@ -316,32 +361,41 @@ function startAutoRefresh() {
316
361
  }
317
362
  }
318
363
  }, 2000);
319
-
364
+
320
365
  autoRefreshIntervalId = setInterval(async () => {
321
366
  const data = loadAccounts();
322
-
367
+
323
368
  for (const account of data.accounts) {
324
369
  if (account.refreshToken) {
325
- console.log(`[AccountManager] Periodic refresh for ${account.email}`);
370
+ console.log(`[AccountManager] Periodic token refresh for ${account.email}`);
326
371
  await refreshAccountToken(account.email);
327
372
  }
328
373
  }
329
374
  }, TOKEN_REFRESH_INTERVAL_MS);
330
-
331
- console.log('[AccountManager] Auto-refresh started (every 55 minutes)');
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)');
332
382
  }
333
383
 
334
384
  function stopAutoRefresh() {
335
385
  if (autoRefreshIntervalId) {
336
386
  clearInterval(autoRefreshIntervalId);
337
387
  autoRefreshIntervalId = null;
338
- console.log('[AccountManager] Auto-refresh stopped');
339
388
  }
389
+ if (quotaRefreshIntervalId) {
390
+ clearInterval(quotaRefreshIntervalId);
391
+ quotaRefreshIntervalId = null;
392
+ }
393
+ console.log('[AccountManager] Auto-refresh stopped');
340
394
  }
341
395
 
342
396
  function getCachedToken(email) {
343
397
  const cached = tokenCache.get(email);
344
- if (cached && (Date.now() - cached.extractedAt) < TOKEN_REFRESH_INTERVAL_MS) {
398
+ if (cached && (Date.now() - cached.extractedAt) < TOKEN_CACHE_TTL_MS) {
345
399
  return cached.token;
346
400
  }
347
401
  return null;
@@ -487,6 +541,7 @@ export {
487
541
  refreshActiveAccount,
488
542
  refreshAccountToken,
489
543
  refreshAllAccounts,
544
+ refreshAllAccountQuotas,
490
545
  importFromCodex,
491
546
  getStatus,
492
547
  updateAccountAuth,
@@ -499,6 +554,8 @@ export {
499
554
  getCachedToken,
500
555
  setCachedToken,
501
556
  TOKEN_REFRESH_INTERVAL_MS,
557
+ QUOTA_REFRESH_INTERVAL_MS,
558
+ TOKEN_CACHE_TTL_MS,
502
559
  ACCOUNTS_FILE,
503
560
  CONFIG_DIR
504
561
  };
@@ -511,6 +568,7 @@ export default {
511
568
  refreshActiveAccount,
512
569
  refreshAccountToken,
513
570
  refreshAllAccounts,
571
+ refreshAllAccountQuotas,
514
572
  importFromCodex,
515
573
  getStatus,
516
574
  ensureAccountsPersist,
@@ -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
- return this.strategy.selectAccount(accounts, modelId, options);
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
  };
@@ -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
@@ -17,10 +18,7 @@ const DEFAULT_COOLDOWN_MS = 60000;
17
18
  */
18
19
  export function isAllRateLimited(accounts, modelId) {
19
20
  if (!accounts || accounts.length === 0) return true;
20
- return accounts.every(account => {
21
- const rateLimit = account.modelRateLimits?.[modelId];
22
- return rateLimit?.isRateLimited && rateLimit.resetTime > Date.now();
23
- });
21
+ return getAvailableAccounts(accounts, modelId).length === 0;
24
22
  }
25
23
 
26
24
  /**
@@ -34,12 +32,62 @@ export function getAvailableAccounts(accounts, modelId) {
34
32
  const now = Date.now();
35
33
  return accounts.filter(account => {
36
34
  if (account.isInvalid) return false;
35
+ if (account.enabled === false) return false;
37
36
  if (isAccountCoolingDown(account)) return false;
37
+ if (isQuotaLimitReached(account)) return false;
38
38
  const rateLimit = account.modelRateLimits?.[modelId];
39
39
  return !rateLimit?.isRateLimited || rateLimit.resetTime <= now;
40
40
  });
41
41
  }
42
42
 
43
+ export function isQuotaLimitReached(account) {
44
+ const usage = account?.quota?.usage;
45
+ return usage?.allowed === false || usage?.limitReached === true;
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
+
43
91
  /**
44
92
  * Clear all expired rate limits across all accounts
45
93
  * @param {Array} accounts - Array of account objects
@@ -177,6 +225,11 @@ export function getMinWaitTimeMs(accounts, modelId) {
177
225
  minWait = waitTime;
178
226
  }
179
227
  }
228
+
229
+ const quotaWait = getQuotaWaitTimeMs(account, now);
230
+ if (quotaWait > 0 && quotaWait < minWait) {
231
+ minWait = quotaWait;
232
+ }
180
233
  }
181
234
 
182
235
  return minWait === Infinity ? 0 : minWait;
@@ -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,11 +6,10 @@ 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 = {}) {
13
- const { currentIndex = 0, onSave } = options;
12
+ const { currentIndex = 0, onSave, random = Math.random } = options;
14
13
 
15
14
  if (!accounts || accounts.length === 0) {
16
15
  return { account: null, index: currentIndex, waitMs: 0 };
@@ -30,11 +29,7 @@ export class StickyStrategy extends BaseStrategy {
30
29
  const usableAccounts = this.getUsableAccounts(accounts, modelId);
31
30
 
32
31
  if (usableAccounts.length > 0) {
33
- const nextResult = this.#pickNext(accounts, clampedIndex, modelId, onSave);
34
- if (nextResult) {
35
- this.currentIndex = nextResult.index;
36
- return nextResult;
37
- }
32
+ return this.#pickRandom(usableAccounts, onSave, random);
38
33
  }
39
34
 
40
35
  // Check if we should wait for the current account
@@ -75,23 +70,13 @@ export class StickyStrategy extends BaseStrategy {
75
70
  return { shouldWait: false, waitMs: 0 };
76
71
  }
77
72
 
78
- #pickNext(accounts, currentIndex, modelId, onSave) {
79
- const startIndex = (currentIndex + 1) % accounts.length;
80
-
81
- for (let i = 0; i < accounts.length; i++) {
82
- const checkIndex = (startIndex + i) % accounts.length;
83
- const account = accounts[checkIndex];
84
-
85
- if (checkIndex === currentIndex) continue;
86
-
87
- if (this.isAccountUsable(account, modelId)) {
88
- account.lastUsed = Date.now();
89
- if (onSave) onSave();
90
- logger.debug(`StickyStrategy: Switched to account at index ${checkIndex}`);
91
- return { account, index: checkIndex, waitMs: 0 };
92
- }
93
- }
73
+ #pickRandom(usableAccounts, onSave, random) {
74
+ const randomIndex = Math.floor(random() * usableAccounts.length);
75
+ const { account, index } = usableAccounts[randomIndex];
94
76
 
95
- return null;
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 };
96
81
  }
97
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 = '1.0.5';
16
+ const APP_VERSION = packageJson.version;
14
17
 
15
18
  function shouldLogRawProxyPayloads() {
16
19
  return getServerSettings().logRawProxyPayloads === true;
@@ -39,27 +42,44 @@ function parseResetTime(response, errorText) {
39
42
  const seconds = parseInt(retryAfter, 10);
40
43
  if (!isNaN(seconds)) return seconds * 1000;
41
44
  }
42
-
45
+
43
46
  const ratelimitReset = response.headers?.get?.('x-ratelimit-reset');
44
47
  if (ratelimitReset) {
45
48
  const timestamp = parseInt(ratelimitReset, 10) * 1000;
46
49
  const wait = timestamp - Date.now();
47
50
  if (wait > 0) return wait;
48
51
  }
49
-
52
+
50
53
  if (errorText) {
54
+ try {
55
+ const errorData = JSON.parse(errorText);
56
+ const primaryWindow = errorData?.rate_limit?.primary_window || errorData?.error?.rate_limit?.primary_window;
57
+ const resetAfterSeconds = Number(primaryWindow?.reset_after_seconds);
58
+ if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds > 0) {
59
+ return resetAfterSeconds * 1000;
60
+ }
61
+
62
+ const resetAt = Number(primaryWindow?.reset_at);
63
+ if (Number.isFinite(resetAt) && resetAt > 0) {
64
+ const wait = resetAt * 1000 - Date.now();
65
+ if (wait > 0) return wait;
66
+ }
67
+ } catch {
68
+ // Fall back to regex parsing for plain-text upstream errors.
69
+ }
70
+
51
71
  const delayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
52
72
  if (delayMatch) {
53
73
  const value = parseFloat(delayMatch[1]);
54
74
  return delayMatch[2] === 's' ? value * 1000 : value;
55
75
  }
56
-
76
+
57
77
  const secMatch = errorText.match(/retry\s+(?:after\s+)?(\d+)\s*(?:sec|s\b)/i);
58
78
  if (secMatch) {
59
79
  return parseInt(secMatch[1], 10) * 1000;
60
80
  }
61
81
  }
62
-
82
+
63
83
  return 60000;
64
84
  }
65
85
 
@@ -151,7 +171,7 @@ export async function createMessageStream(anthropicRequest, accessToken, account
151
171
  /**
152
172
  * Send a non-streaming request to ChatGPT API
153
173
  */
154
- export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}) {
174
+ export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}, accountRotator = null, currentEmail = null) {
155
175
  const request = convertAnthropicToResponsesAPI({
156
176
  ...anthropicRequest,
157
177
  stream: false
@@ -176,6 +196,16 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
176
196
  throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
177
197
  }
178
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
+
179
209
  throw createUpstreamHTTPError(response, errorText);
180
210
  }
181
211
 
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, server } = startCallbackServer(port, state);
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(result => {
103
+ .then(code => {
104
104
  activeCallbackServers.delete(callbackPort);
105
- if (result?.code) {
106
- return exchangeCodeForTokens(result.code, verifier, callbackPort)
107
- .then(async tokens => {
108
- const accountInfo = extractAccountInfo(tokens);
109
- await _upsertAccount(accountInfo);
110
- logger.info(`Added account: ${accountInfo.email}`);
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 = extractAccountInfo(tokens);
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);
@@ -60,16 +67,9 @@ export async function handleMessages(req, res) {
60
67
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
61
68
  if (rotator.isAllRateLimited(upstreamModel)) {
62
69
  const minWait = rotator.getMinWaitTimeMs(upstreamModel);
63
-
64
- if (minWait > MAX_WAIT_BEFORE_ERROR_MS) {
65
- return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${Math.round(minWait/1000)}s`), upstreamModel, startTime);
66
- }
67
-
68
- logger.info(`[Messages] All accounts rate-limited, waiting ${Math.round(minWait/1000)}s...`);
69
- await sleep(minWait + 500);
70
- rotator.clearExpiredLimits();
71
- attempt--;
72
- 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);
73
73
  }
74
74
 
75
75
  const { account, waitMs } = rotator.selectAccount(upstreamModel);
@@ -83,6 +83,9 @@ export async function handleMessages(req, res) {
83
83
  return sendAuthError(res, 'No available accounts');
84
84
  }
85
85
 
86
+ syncActiveAccount(account.email);
87
+ logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
88
+
86
89
  const creds = await getCredentialsForAccount(account.email);
87
90
  if (!creds) {
88
91
  rotator.markInvalid(account.email, 'Failed to get credentials');
@@ -139,12 +142,22 @@ async function _streamDirectWithRotation(res, anthropicRequest, creds, responseM
139
142
  }
140
143
 
141
144
  async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
142
- const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext);
145
+ const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
143
146
  const duration = Date.now() - startTime;
144
147
  logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
145
148
  res.json({ ...response, model: responseModel });
146
149
  }
147
150
 
151
+ function syncActiveAccount(email) {
152
+ const active = getActiveAccount();
153
+ if (active?.email === email) return;
154
+
155
+ const result = setActiveAccount(email);
156
+ if (result.success) {
157
+ logger.info(`[Messages] Synced active account to actual account: ${email}`);
158
+ }
159
+ }
160
+
148
161
  function getTokenDetails(usage = {}) {
149
162
  const inputTokens = usage?.input_tokens || 0;
150
163
  const outputTokens = usage?.output_tokens || 0;
@@ -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' },
@@ -35,8 +35,6 @@ function mergeSettings(data = {}) {
35
35
  }
36
36
 
37
37
  export function getServerSettings() {
38
- ensureConfigDir();
39
-
40
38
  if (!existsSync(SETTINGS_FILE)) {
41
39
  return mergeSettings();
42
40
  }
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
- ensureAccountsPersist();
14
- startAutoRefresh();
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');