claude-codex-proxy 1.0.3 → 1.0.5-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -6
- package/bin/cli.js +43 -0
- package/docs/API.md +22 -0
- package/package.json +3 -2
- package/public/index.html +130 -14
- package/public/js/app.js +162 -20
- 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 +30 -7
- package/src/index.js +7 -1
- package/src/middleware/auth.js +81 -0
- package/src/response-streamer.js +6 -1
- package/src/routes/api-routes.js +31 -7
- package/src/routes/chat-route.js +1 -1
- package/src/routes/claude-config-route.js +18 -1
- package/src/routes/messages-route.js +5 -12
- package/src/routes/models-route.js +1 -1
- package/src/routes/settings-route.js +99 -1
- package/src/server-settings.js +2 -3
- package/src/server.js +10 -5
package/public/js/app.js
CHANGED
|
@@ -5,9 +5,14 @@ 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
|
+
authRequired: false,
|
|
12
|
+
authChecked: false,
|
|
13
|
+
apiKey: localStorage.getItem('codexProxyApiKey') || '',
|
|
14
|
+
loginApiKey: '',
|
|
15
|
+
|
|
11
16
|
accounts: [],
|
|
12
17
|
searchQuery: '',
|
|
13
18
|
stats: { total: 0, active: 0, expired: 0, planType: '-' },
|
|
@@ -23,6 +28,13 @@ document.addEventListener('alpine:init', () => {
|
|
|
23
28
|
strategySaving: false,
|
|
24
29
|
logRawProxyPayloads: false,
|
|
25
30
|
rawProxyLogsSaving: false,
|
|
31
|
+
clientApiKeys: [],
|
|
32
|
+
clientApiKeyName: '',
|
|
33
|
+
clientApiKeyRemark: '',
|
|
34
|
+
clientApiKeysLoading: false,
|
|
35
|
+
clientApiKeySaving: false,
|
|
36
|
+
revealedClientApiKey: '',
|
|
37
|
+
showCreateClientApiKeyModal: false,
|
|
26
38
|
|
|
27
39
|
showAddModal: false,
|
|
28
40
|
showDeleteModal: false,
|
|
@@ -40,12 +52,17 @@ document.addEventListener('alpine:init', () => {
|
|
|
40
52
|
testing: false,
|
|
41
53
|
|
|
42
54
|
configPath: '~/.claude-codex-proxy/accounts.json',
|
|
43
|
-
|
|
55
|
+
serverUrl: window.location.origin,
|
|
56
|
+
|
|
44
57
|
logs: [],
|
|
45
58
|
logSearchQuery: '',
|
|
46
59
|
logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false },
|
|
47
60
|
logEventSource: null,
|
|
48
61
|
|
|
62
|
+
get isAuthenticated() {
|
|
63
|
+
return !this.authRequired || Boolean(this.apiKey);
|
|
64
|
+
},
|
|
65
|
+
|
|
49
66
|
get filteredLogs() {
|
|
50
67
|
const query = this.logSearchQuery.trim().toLowerCase();
|
|
51
68
|
return this.logs.filter(log => {
|
|
@@ -61,16 +78,14 @@ document.addEventListener('alpine:init', () => {
|
|
|
61
78
|
return this.accounts.filter(a => a.email.toLowerCase().includes(q));
|
|
62
79
|
},
|
|
63
80
|
|
|
64
|
-
init() {
|
|
81
|
+
async init() {
|
|
65
82
|
this.updateTime();
|
|
66
83
|
setInterval(() => this.updateTime(), 1000);
|
|
67
|
-
this.
|
|
68
|
-
this.
|
|
84
|
+
await this.checkHealth();
|
|
85
|
+
if (this.isAuthenticated) {
|
|
86
|
+
this.loadProtectedData();
|
|
87
|
+
}
|
|
69
88
|
setInterval(() => this.checkHealth(), 30000);
|
|
70
|
-
this.startLogStream();
|
|
71
|
-
this.loadAccountStrategySetting();
|
|
72
|
-
this.loadModelMapSetting();
|
|
73
|
-
this.loadRawProxyLogsSetting();
|
|
74
89
|
|
|
75
90
|
window.addEventListener('resize', () => {
|
|
76
91
|
this.sidebarOpen = window.innerWidth >= 1024;
|
|
@@ -85,6 +100,15 @@ document.addEventListener('alpine:init', () => {
|
|
|
85
100
|
});
|
|
86
101
|
},
|
|
87
102
|
|
|
103
|
+
loadProtectedData() {
|
|
104
|
+
this.refreshAccounts();
|
|
105
|
+
this.startLogStream();
|
|
106
|
+
this.loadAccountStrategySetting();
|
|
107
|
+
this.loadModelMapSetting();
|
|
108
|
+
this.loadRawProxyLogsSetting();
|
|
109
|
+
this.loadClientApiKeys();
|
|
110
|
+
},
|
|
111
|
+
|
|
88
112
|
updateTime() {
|
|
89
113
|
this.currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});
|
|
90
114
|
},
|
|
@@ -98,21 +122,65 @@ document.addEventListener('alpine:init', () => {
|
|
|
98
122
|
|
|
99
123
|
async api(endpoint, options = {}) {
|
|
100
124
|
try {
|
|
125
|
+
const headers = {
|
|
126
|
+
'Content-Type': 'application/json',
|
|
127
|
+
...(options.headers || {})
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
if (this.apiKey) {
|
|
131
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
101
134
|
const response = await fetch(endpoint, {
|
|
102
|
-
|
|
103
|
-
|
|
135
|
+
...options,
|
|
136
|
+
headers
|
|
104
137
|
});
|
|
105
138
|
const data = await response.json();
|
|
139
|
+
|
|
140
|
+
if (response.status === 401 && endpoint !== '/health') {
|
|
141
|
+
this.logout(false);
|
|
142
|
+
this.showToast('Access key is invalid or expired', 'error');
|
|
143
|
+
}
|
|
144
|
+
|
|
106
145
|
return { ok: response.ok, data };
|
|
107
146
|
} catch (error) {
|
|
108
147
|
return { ok: false, error: error.message };
|
|
109
148
|
}
|
|
110
149
|
},
|
|
111
150
|
|
|
151
|
+
login() {
|
|
152
|
+
const key = this.loginApiKey.trim();
|
|
153
|
+
if (!key) {
|
|
154
|
+
this.showToast('Access key is required', 'error');
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
this.apiKey = key;
|
|
159
|
+
localStorage.setItem('codexProxyApiKey', key);
|
|
160
|
+
this.loginApiKey = '';
|
|
161
|
+
this.showToast('Access key saved', 'success');
|
|
162
|
+
this.loadProtectedData();
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
logout(showMessage = true) {
|
|
166
|
+
this.apiKey = '';
|
|
167
|
+
this.loginApiKey = '';
|
|
168
|
+
localStorage.removeItem('codexProxyApiKey');
|
|
169
|
+
if (this.logEventSource) {
|
|
170
|
+
this.logEventSource.close();
|
|
171
|
+
this.logEventSource = null;
|
|
172
|
+
}
|
|
173
|
+
if (showMessage) this.showToast('Logged out', 'info');
|
|
174
|
+
},
|
|
175
|
+
|
|
112
176
|
async checkHealth() {
|
|
113
177
|
const { ok, data } = await this.api('/health');
|
|
114
178
|
this.connectionStatus = ok ? 'connected' : 'disconnected';
|
|
115
179
|
if (ok && data?.version) this.version = data.version;
|
|
180
|
+
if (ok && typeof data?.publicMode === 'boolean') {
|
|
181
|
+
this.authRequired = data.publicMode;
|
|
182
|
+
this.authChecked = true;
|
|
183
|
+
}
|
|
116
184
|
},
|
|
117
185
|
|
|
118
186
|
async refreshAccounts() {
|
|
@@ -346,12 +414,19 @@ document.addEventListener('alpine:init', () => {
|
|
|
346
414
|
},
|
|
347
415
|
|
|
348
416
|
async refreshToken(email) {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
417
|
+
if (this.refreshingTokenEmails.includes(email)) return;
|
|
418
|
+
|
|
419
|
+
this.refreshingTokenEmails.push(email);
|
|
420
|
+
try {
|
|
421
|
+
const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' });
|
|
422
|
+
if (ok && data.success) {
|
|
423
|
+
this.showToast(data.message, 'success');
|
|
424
|
+
await this.refreshAccounts();
|
|
425
|
+
} else {
|
|
426
|
+
this.showToast(data?.message || 'Refresh failed', 'error');
|
|
427
|
+
}
|
|
428
|
+
} finally {
|
|
429
|
+
this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email);
|
|
355
430
|
}
|
|
356
431
|
},
|
|
357
432
|
|
|
@@ -534,11 +609,75 @@ document.addEventListener('alpine:init', () => {
|
|
|
534
609
|
}
|
|
535
610
|
},
|
|
536
611
|
|
|
612
|
+
async loadClientApiKeys() {
|
|
613
|
+
this.clientApiKeysLoading = true;
|
|
614
|
+
const { ok, data } = await this.api('/settings/client-api-keys');
|
|
615
|
+
this.clientApiKeysLoading = false;
|
|
616
|
+
if (ok && Array.isArray(data?.clientApiKeys)) {
|
|
617
|
+
this.clientApiKeys = data.clientApiKeys;
|
|
618
|
+
} else {
|
|
619
|
+
this.showToast(data?.error || 'Failed to load client API keys', 'error');
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
|
|
623
|
+
async createClientApiKey() {
|
|
624
|
+
if (this.clientApiKeySaving) return;
|
|
625
|
+
this.clientApiKeySaving = true;
|
|
626
|
+
const { ok, data } = await this.api('/settings/client-api-keys', {
|
|
627
|
+
method: 'POST',
|
|
628
|
+
body: JSON.stringify({
|
|
629
|
+
name: this.clientApiKeyName,
|
|
630
|
+
remark: this.clientApiKeyRemark
|
|
631
|
+
})
|
|
632
|
+
});
|
|
633
|
+
this.clientApiKeySaving = false;
|
|
634
|
+
|
|
635
|
+
if (ok && data?.clientApiKey?.key) {
|
|
636
|
+
this.revealedClientApiKey = data.clientApiKey.key;
|
|
637
|
+
this.clientApiKeyName = '';
|
|
638
|
+
this.clientApiKeyRemark = '';
|
|
639
|
+
this.showCreateClientApiKeyModal = false;
|
|
640
|
+
await this.loadClientApiKeys();
|
|
641
|
+
this.showToast('Client API key created. Copy it now; it will not be shown again.', 'success');
|
|
642
|
+
} else {
|
|
643
|
+
this.showToast(data?.error || 'Failed to create client API key', 'error');
|
|
644
|
+
}
|
|
645
|
+
},
|
|
646
|
+
|
|
647
|
+
async updateClientApiKey(clientApiKey) {
|
|
648
|
+
if (this.clientApiKeySaving) return;
|
|
649
|
+
this.clientApiKeySaving = true;
|
|
650
|
+
const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, {
|
|
651
|
+
method: 'PUT',
|
|
652
|
+
body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark })
|
|
653
|
+
});
|
|
654
|
+
this.clientApiKeySaving = false;
|
|
655
|
+
if (ok) {
|
|
656
|
+
this.showToast('Client API key updated', 'success');
|
|
657
|
+
await this.loadClientApiKeys();
|
|
658
|
+
} else {
|
|
659
|
+
this.showToast(data?.error || 'Failed to update client API key', 'error');
|
|
660
|
+
}
|
|
661
|
+
},
|
|
662
|
+
|
|
663
|
+
async deleteClientApiKey(clientApiKey) {
|
|
664
|
+
if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return;
|
|
665
|
+
this.clientApiKeySaving = true;
|
|
666
|
+
const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' });
|
|
667
|
+
this.clientApiKeySaving = false;
|
|
668
|
+
if (ok) {
|
|
669
|
+
await this.loadClientApiKeys();
|
|
670
|
+
this.showToast('Client API key deleted', 'success');
|
|
671
|
+
} else {
|
|
672
|
+
this.showToast(data?.error || 'Failed to delete client API key', 'error');
|
|
673
|
+
}
|
|
674
|
+
},
|
|
675
|
+
|
|
537
676
|
async setClaudeCodeProxyTestConfig() {
|
|
538
677
|
const { ok, data, error } = await this.api('/claude/config/set', {
|
|
539
678
|
method: 'POST',
|
|
540
679
|
body: JSON.stringify({
|
|
541
|
-
apiUrl:
|
|
680
|
+
apiUrl: this.serverUrl,
|
|
542
681
|
apiKey: 'test'
|
|
543
682
|
})
|
|
544
683
|
});
|
|
@@ -556,9 +695,12 @@ document.addEventListener('alpine:init', () => {
|
|
|
556
695
|
},
|
|
557
696
|
|
|
558
697
|
startLogStream() {
|
|
698
|
+
if (!this.isAuthenticated) return;
|
|
559
699
|
if (this.logEventSource) this.logEventSource.close();
|
|
560
|
-
|
|
561
|
-
|
|
700
|
+
|
|
701
|
+
const params = new URLSearchParams({ history: 'true' });
|
|
702
|
+
if (this.apiKey) params.set('api_key', this.apiKey);
|
|
703
|
+
this.logEventSource = new EventSource(`/api/logs/stream?${params.toString()}`);
|
|
562
704
|
this.logEventSource.onmessage = (event) => {
|
|
563
705
|
try {
|
|
564
706
|
const log = JSON.parse(event.data);
|
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,18 +4,35 @@
|
|
|
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;
|
|
17
20
|
}
|
|
18
21
|
|
|
22
|
+
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
|
+
const usage = {
|
|
24
|
+
input_tokens: upstreamUsage.input_tokens || 0,
|
|
25
|
+
output_tokens: upstreamUsage.output_tokens || 0,
|
|
26
|
+
// Responses API cache metrics are already included in input_tokens.
|
|
27
|
+
cache_read_input_tokens: 0
|
|
28
|
+
};
|
|
29
|
+
Object.defineProperty(usage, 'upstreamCacheReadInputTokens', {
|
|
30
|
+
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
|
+
enumerable: false
|
|
32
|
+
});
|
|
33
|
+
return usage;
|
|
34
|
+
}
|
|
35
|
+
|
|
19
36
|
function buildOpencodeHeaders(accessToken, accountId, context = {}) {
|
|
20
37
|
const headers = {
|
|
21
38
|
'Authorization': `Bearer ${accessToken}`,
|
|
@@ -168,7 +185,7 @@ export async function createMessageStream(anthropicRequest, accessToken, account
|
|
|
168
185
|
/**
|
|
169
186
|
* Send a non-streaming request to ChatGPT API
|
|
170
187
|
*/
|
|
171
|
-
export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}) {
|
|
188
|
+
export async function sendMessage(anthropicRequest, accessToken, accountId, context = {}, accountRotator = null, currentEmail = null) {
|
|
172
189
|
const request = convertAnthropicToResponsesAPI({
|
|
173
190
|
...anthropicRequest,
|
|
174
191
|
stream: false
|
|
@@ -193,6 +210,16 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
193
210
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
|
194
211
|
}
|
|
195
212
|
|
|
213
|
+
if (response.status === 429) {
|
|
214
|
+
const resetMs = parseResetTime(response, errorText);
|
|
215
|
+
if (accountRotator && currentEmail) {
|
|
216
|
+
accountRotator.markRateLimited(currentEmail, resetMs, anthropicRequest.model);
|
|
217
|
+
}
|
|
218
|
+
const error = createHTTPError(`RATE_LIMITED:${resetMs}:${errorText}`, 429, 'rate_limit_error', response.status);
|
|
219
|
+
error.resetMs = resetMs;
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
|
|
196
223
|
throw createUpstreamHTTPError(response, errorText);
|
|
197
224
|
}
|
|
198
225
|
|
|
@@ -213,11 +240,7 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
213
240
|
model: anthropicRequest.model,
|
|
214
241
|
stop_reason: stopReason,
|
|
215
242
|
stop_sequence: null,
|
|
216
|
-
usage:
|
|
217
|
-
input_tokens: apiResponse.usage?.input_tokens || 0,
|
|
218
|
-
output_tokens: apiResponse.usage?.output_tokens || 0,
|
|
219
|
-
cache_read_input_tokens: apiResponse.usage?.cache_read_input_tokens || apiResponse.usage?.input_tokens_details?.cached_tokens || 0
|
|
220
|
-
}
|
|
243
|
+
usage: createAnthropicUsage(apiResponse.usage)
|
|
221
244
|
};
|
|
222
245
|
}
|
|
223
246
|
|