claude-codex-proxy 1.0.5-beta.2 → 1.0.5-beta.20

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.
Files changed (42) hide show
  1. package/README.md +0 -272
  2. package/bin/cli.js +37 -2
  3. package/package.json +1 -1
  4. package/public/css/style.css +210 -9
  5. package/public/index.html +32 -926
  6. package/public/js/app.js +168 -737
  7. package/public/login.html +32 -0
  8. package/public/views/accounts-modals.html +218 -0
  9. package/public/views/accounts.html +202 -0
  10. package/public/views/client-api-keys-modals.html +55 -0
  11. package/public/views/client-api-keys.html +69 -0
  12. package/public/views/dashboard.html +90 -0
  13. package/public/views/empty.html +0 -0
  14. package/public/views/logs.html +99 -0
  15. package/public/views/settings.html +123 -0
  16. package/src/account-manager.js +34 -3
  17. package/src/account-rotation/rate-limits.js +4 -26
  18. package/src/account-rotation/strategies/base-strategy.js +4 -0
  19. package/src/account-rotation/strategies/sticky-strategy.js +7 -0
  20. package/src/admin-path.js +33 -0
  21. package/src/claude-config.js +0 -18
  22. package/src/client-key-usage.js +125 -0
  23. package/src/deployment.js +49 -49
  24. package/src/direct-api.js +16 -13
  25. package/src/format-converter.js +77 -48
  26. package/src/index.js +13 -4
  27. package/src/middleware/auth.js +46 -11
  28. package/src/middleware/credentials.js +13 -3
  29. package/src/model-api.js +60 -0
  30. package/src/model-pricing.js +127 -0
  31. package/src/response-streamer.js +17 -7
  32. package/src/routes/accounts-route.js +106 -2
  33. package/src/routes/api-routes.js +61 -35
  34. package/src/routes/chat-route.js +25 -4
  35. package/src/routes/claude-config-route.js +22 -15
  36. package/src/routes/client-quota-route.js +25 -0
  37. package/src/routes/logs-route.js +21 -2
  38. package/src/routes/messages-route.js +45 -14
  39. package/src/routes/settings-route.js +36 -5
  40. package/src/server-settings.js +18 -2
  41. package/src/utils/logger.js +18 -0
  42. package/src/utils/proxy-logging.js +5 -0
package/public/js/app.js CHANGED
@@ -1,762 +1,193 @@
1
+ const adminPath = window.__PROXY_ADMIN_PATH__ || '/admin';
2
+ const adminUrl = (path) => `${adminPath}${path}`;
3
+
1
4
  document.addEventListener('alpine:init', () => {
2
5
  Alpine.data('app', () => ({
3
- version: '',
4
- connectionStatus: 'connecting',
5
- activeTab: 'dashboard',
6
- sidebarOpen: window.innerWidth >= 1024,
7
- loading: false,
8
- refreshingTokenEmails: [],
9
- toast: null,
10
- currentTime: '',
11
- authRequired: false,
12
- authChecked: false,
13
- apiKey: localStorage.getItem('codexProxyApiKey') || '',
14
- loginApiKey: '',
15
-
16
- accounts: [],
17
- searchQuery: '',
18
- stats: { total: 0, active: 0, expired: 0, planType: '-' },
19
-
20
- accountStrategy: 'sticky',
21
- modelMappings: {
22
- sonnet: '',
23
- opus: '',
24
- haiku: ''
25
- },
26
- modelMapLoading: false,
27
- modelMapSaving: false,
28
- strategySaving: false,
29
- logRawProxyPayloads: false,
30
- rawProxyLogsSaving: false,
31
- clientApiKeys: [],
32
- clientApiKeyName: '',
33
- clientApiKeyRemark: '',
34
- clientApiKeysLoading: false,
35
- clientApiKeySaving: false,
36
- revealedClientApiKey: '',
37
- showCreateClientApiKeyModal: false,
38
-
39
- showAddModal: false,
40
- showDeleteModal: false,
41
- deleteTarget: '',
42
- showQuotaModalView: false,
43
- selectedAccount: null,
44
-
45
- oauthManualMode: false,
46
- oauthManualUrl: '',
47
- oauthManualVerifier: '',
48
- oauthManualCode: '',
49
-
50
- testPrompt: 'Say hello',
51
- testResponse: '',
52
- testing: false,
53
-
54
- configPath: '~/.claude-codex-proxy/accounts.json',
55
- serverUrl: window.location.origin,
56
-
57
- logs: [],
58
- logSearchQuery: '',
59
- logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false },
60
- logEventSource: null,
61
-
62
- get isAuthenticated() {
63
- return !this.authRequired || Boolean(this.apiKey);
64
- },
65
-
66
- get filteredLogs() {
67
- const query = this.logSearchQuery.trim().toLowerCase();
68
- return this.logs.filter(log => {
69
- if (!this.logFilters[log.level]) return false;
70
- if (query && !log.message.toLowerCase().includes(query)) return false;
71
- return true;
72
- });
73
- },
74
-
75
- get filteredAccounts() {
76
- if (!this.searchQuery) return this.accounts;
77
- const q = this.searchQuery.toLowerCase();
78
- return this.accounts.filter(a => a.email.toLowerCase().includes(q));
79
- },
6
+ version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
7
+ loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
8
+ authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
9
+ accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
10
+ accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
11
+ modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
12
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
13
+ clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
14
+ showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
15
+ showAccountExpirationModalView: false, expirationTarget: null, accountExpirationInput: '', accountExpirationSaving: false,
16
+ resetCreditsLoading: false, resetCreditsRedeeming: false, resetCreditsRefreshPending: false, resetCredits: [], resetCreditsAccountEmail: '', resetCreditRedeemRequestId: '',
17
+ oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
18
+ testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
19
+ serverUrl: window.location.origin, logs: [], logSearchQuery: '', logPage: 1, logPageSize: 30, logTotal: 0, logTotalPages: 0, logLoading: false,
20
+ logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
21
+
22
+ get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
23
+ get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
24
+ get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
80
25
 
81
26
  async init() {
82
- this.updateTime();
83
- setInterval(() => this.updateTime(), 1000);
84
27
  await this.checkHealth();
85
- if (this.isAuthenticated) {
86
- this.loadProtectedData();
28
+ this.authChecked = true;
29
+ if (this.isLoginPage()) {
30
+ if (this.isAuthenticated) window.location.replace(adminUrl('/dashboard'));
31
+ return;
87
32
  }
33
+ if (!this.isAuthenticated) { window.location.replace(adminUrl('/login')); return; }
34
+ await this.loadCurrentView();
35
+ this.updateTime();
36
+ setInterval(() => this.updateTime(), 1000);
88
37
  setInterval(() => this.checkHealth(), 30000);
89
-
90
- window.addEventListener('resize', () => {
91
- this.sidebarOpen = window.innerWidth >= 1024;
92
- });
93
-
94
- window.addEventListener('message', (event) => {
95
- if (event.data && event.data.type === 'oauth-success') {
96
- this.showToast(`Account ${event.data.email} added!`, 'success');
97
- this.showAddModal = false;
98
- this.refreshAccounts();
99
- }
100
- });
101
- },
102
-
103
- loadProtectedData() {
104
- this.refreshAccounts();
105
- this.startLogStream();
106
- this.loadAccountStrategySetting();
107
- this.loadModelMapSetting();
108
- this.loadRawProxyLogsSetting();
109
- this.loadClientApiKeys();
110
- },
111
-
112
- updateTime() {
113
- this.currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});
114
- },
115
-
116
- setActiveTab(tab) {
117
- this.activeTab = tab;
118
- if (window.innerWidth < 1024) {
119
- this.sidebarOpen = false;
120
- }
38
+ window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
39
+ window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
40
+ },
41
+
42
+ isLoginPage() { return window.location.pathname === adminUrl('/login') || window.location.pathname === adminUrl('/login.html'); },
43
+ async loadCurrentView() {
44
+ const route = window.location.pathname.slice(adminPath.length).replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
45
+ const tab = route === 'account-management' ? 'accounts' : route;
46
+ const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
47
+ this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
48
+ if (this.activeTab !== tab) { window.location.replace(adminUrl('/dashboard')); return; }
49
+ const [viewResponse, modalResponse] = await Promise.all([
50
+ fetch(adminUrl(`/views/${this.activeTab}.html`)),
51
+ fetch(adminUrl(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html'))
52
+ ]);
53
+ if (!viewResponse.ok) { window.location.replace(adminUrl('/dashboard')); return; }
54
+ document.querySelector('#view-content').innerHTML = await viewResponse.text();
55
+ document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
56
+ Alpine.initTree(document.querySelector('#view-content'));
57
+ Alpine.initTree(document.querySelector('#modal-content'));
58
+ this.loadViewData();
59
+ },
60
+ loadViewData() {
61
+ const loaders = {
62
+ dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
63
+ accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
64
+ 'client-api-keys': () => this.loadClientApiKeys(),
65
+ settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
66
+ };
67
+ return loaders[this.activeTab]?.();
121
68
  },
122
-
69
+ updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
123
70
  async api(endpoint, options = {}) {
124
71
  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
-
134
- const response = await fetch(endpoint, {
135
- ...options,
136
- headers
137
- });
72
+ const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
73
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
74
+ const url = endpoint.startsWith('/v1/') ? endpoint : adminUrl(endpoint);
75
+ const response = await fetch(url, { ...options, headers });
138
76
  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
-
77
+ if (response.status === 401 && endpoint !== '/health') this.logout(false);
145
78
  return { ok: response.ok, data };
146
- } catch (error) {
147
- return { ok: false, error: error.message };
148
- }
79
+ } catch (error) { return { ok: false, error: error.message }; }
149
80
  },
150
-
151
- login() {
81
+ async login() {
152
82
  const key = this.loginApiKey.trim();
153
- if (!key) {
154
- this.showToast('Access key is required', 'error');
155
- return;
156
- }
157
-
83
+ if (!key) { this.loginError = 'Access key is required'; return; }
158
84
  this.apiKey = key;
85
+ const { ok } = await this.api('/settings/account-strategy');
86
+ if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
159
87
  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
-
176
- async checkHealth() {
177
- const { ok, data } = await this.api('/health');
178
- this.connectionStatus = ok ? 'connected' : 'disconnected';
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;
88
+ window.location.replace(adminUrl('/dashboard'));
89
+ },
90
+ logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace(adminUrl('/login')); },
91
+ async checkHealth() { try { const response = await fetch('/health'); const data = await response.json(); this.connectionStatus = response.ok ? 'connected' : 'disconnected'; if (response.ok && data?.version) this.version = data.version; if (response.ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; } catch { this.connectionStatus = 'disconnected'; } },
92
+ async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
93
+ async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
94
+ getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
95
+ isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
96
+ quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
97
+ quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
98
+ getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
99
+ quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
100
+ quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
101
+ async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
102
+ async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
103
+ async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
104
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
105
+ async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
106
+ async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
107
+ accountExpirationLabel(account) { if (!account?.accountExpiresAt) return 'Never'; const date = new Date(account.accountExpiresAt); if (Number.isNaN(date.getTime())) return 'Never'; return date.toLocaleString([], { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); },
108
+ showAccountExpirationModal(account) { this.expirationTarget = account; const date = account?.accountExpiresAt ? new Date(account.accountExpiresAt) : null; if (date && !Number.isNaN(date.getTime())) { const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000); this.accountExpirationInput = local.toISOString().slice(0, 16); } else this.accountExpirationInput = ''; this.showAccountExpirationModalView = true; },
109
+ closeAccountExpirationModal() { if (this.accountExpirationSaving) return; this.showAccountExpirationModalView = false; this.expirationTarget = null; this.accountExpirationInput = ''; },
110
+ async updateAccountExpiration(accountExpiresAt) { if (!this.expirationTarget || this.accountExpirationSaving) return; this.accountExpirationSaving = true; const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.expirationTarget.email)}/expiration`, { method: 'PUT', body: JSON.stringify({ accountExpiresAt }) }); this.accountExpirationSaving = false; if (ok && data?.success) { this.closeAccountExpirationModal(); await this.refreshAccounts(); this.showToast(accountExpiresAt ? 'Account expiration updated' : 'Account expiration cleared', 'success'); } else this.showToast(data?.message || 'Failed to update account expiration', 'error'); },
111
+ saveAccountExpiration() { if (!this.accountExpirationInput) return; const expiresAt = new Date(this.accountExpirationInput); if (Number.isNaN(expiresAt.getTime())) { this.showToast('Enter a valid expiration time', 'error'); return; } return this.updateAccountExpiration(expiresAt.toISOString()); },
112
+ clearAccountExpiration() { return this.updateAccountExpiration(null); },
113
+ async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
114
+ async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
115
+ async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, async showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; await this.loadRateLimitResetCredits(acc.email); },
116
+ normalizeRateLimitResetCredits(payload) { if (Array.isArray(payload)) return payload; for (const key of ['credits', 'items', 'data']) { if (Array.isArray(payload?.[key])) return payload[key]; } return []; },
117
+ async loadRateLimitResetCredits(email) { this.resetCreditsLoading = true; this.resetCredits = []; this.resetCreditsAccountEmail = email; this.resetCreditRedeemRequestId = ''; const { ok, data } = await this.api(`/accounts/rate-limit-reset-credits?email=${encodeURIComponent(email)}`); this.resetCreditsLoading = false; if (this.resetCreditsAccountEmail !== email) return; if (ok) this.resetCredits = this.normalizeRateLimitResetCredits(data?.credits); else this.showToast(data?.error || 'Failed to load reset credits', 'error'); },
118
+ availableRateLimitResetCredits() { return this.resetCredits.filter(credit => credit?.status === 'available').sort((a, b) => new Date(b.expires_at || 0).getTime() - new Date(a.expires_at || 0).getTime()); },
119
+ resetCreditExpiryLabel(credit) { const date = credit?.expires_at && new Date(credit.expires_at); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : '-'; },
120
+ generateUUID() {
121
+ if (typeof globalThis.crypto?.randomUUID === 'function') {
122
+ return globalThis.crypto.randomUUID();
183
123
  }
184
- },
185
-
186
- async refreshAccounts() {
187
- this.loading = true;
188
- const { ok, data } = await this.api('/accounts');
189
-
190
- if (ok && data.accounts) {
191
- this.accounts = data.accounts;
192
- this.stats = {
193
- total: data.total || data.accounts.length,
194
- active: data.accounts.filter(a => a.isActive).length,
195
- expired: data.accounts.filter(a => a.tokenExpired).length,
196
- planType: data.accounts.find(a => a.isActive)?.planType || '-'
197
- };
198
-
199
- await this.refreshAllQuotaData();
200
- }
201
- this.loading = false;
202
- },
203
-
204
- async refreshAllQuotaData() {
205
- if (!this.accounts.length) return;
206
- const { ok, data } = await this.api('/accounts/quota/all');
207
- if (!ok || !data?.accounts) return;
208
-
209
- const quotaMap = new Map(
210
- data.accounts.map((entry) => [entry.email, entry.quota || null])
211
- );
212
-
213
- this.accounts = this.accounts.map((account) => ({
214
- ...account,
215
- quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota
216
- }));
217
-
218
- if (this.selectedAccount?.email) {
219
- const refreshed = this.accounts.find((account) => account.email === this.selectedAccount.email);
220
- if (refreshed) this.selectedAccount = refreshed;
221
- }
222
- },
223
-
224
- getRemainingPercentage(account) {
225
- const usage = account?.quota?.usage;
226
- if (!usage) return null;
227
-
228
- const percentage = Number(usage.percentage);
229
- const usedFromTotal = Number(usage.totalTokenUsage);
230
- const remainingFromApi = Number(usage.remaining);
231
-
232
- let used = null;
233
- if (Number.isFinite(percentage)) {
234
- used = percentage;
235
- } else if (Number.isFinite(usedFromTotal)) {
236
- used = usedFromTotal;
237
- } else if (Number.isFinite(remainingFromApi)) {
238
- used = 100 - remainingFromApi;
239
- } else if (usage.limitReached === true || usage.allowed === false) {
240
- used = 100;
241
- }
242
-
243
- if (!Number.isFinite(used)) return null;
244
- const clampedUsed = Math.max(0, Math.min(100, used));
245
- return Math.max(0, Math.round(100 - clampedUsed));
246
- },
247
-
248
- isQuotaExhausted(account) {
249
- const remaining = this.getRemainingPercentage(account);
250
- if (remaining === null) return false;
251
- const usage = account?.quota?.usage;
252
- return remaining <= 0 || usage?.limitReached === true || usage?.allowed === false;
253
- },
254
-
255
- quotaBarClass(account) {
256
- const remaining = this.getRemainingPercentage(account);
257
- if (remaining === null) return 'bg-gray-500';
258
- if (remaining > 50) return 'bg-neon-green';
259
- if (remaining > 20) return 'bg-yellow-500';
260
- return 'bg-red-500';
261
- },
262
-
263
- quotaTextClass(account) {
264
- const remaining = this.getRemainingPercentage(account);
265
- if (remaining === null) return 'text-gray-500';
266
- return remaining <= 20 ? 'text-red-400' : 'text-gray-400';
267
- },
268
-
269
- quotaLabel(account) {
270
- const remaining = this.getRemainingPercentage(account);
271
- if (remaining === null) return '-';
272
- return `${remaining}%`;
273
- },
274
-
275
- getQuotaResetAt(account) {
276
- const usage = account?.quota?.usage;
277
- if (!usage) return null;
278
-
279
- if (usage.resetAt) return usage.resetAt;
280
-
281
- const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at);
282
- if (Number.isFinite(epoch)) {
283
- return new Date(epoch * 1000).toISOString();
284
- }
285
-
286
- const resetAfter = Number(
287
- usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds
124
+
125
+ const bytes = new Uint8Array(16);
126
+ globalThis.crypto.getRandomValues(bytes);
127
+
128
+ // UUID v4
129
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
130
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
131
+
132
+ const hex = Array.from(
133
+ bytes,
134
+ byte => byte.toString(16).padStart(2, '0')
288
135
  );
289
- if (Number.isFinite(resetAfter) && resetAfter > 0) {
290
- return new Date(Date.now() + resetAfter * 1000).toISOString();
291
- }
292
-
293
- return null;
294
- },
295
-
296
- quotaResetAtLabel(account) {
297
- const resetAt = this.getQuotaResetAt(account);
298
- if (!resetAt) return null;
299
- const date = new Date(resetAt);
300
- if (Number.isNaN(date.getTime())) return null;
301
- return date.toLocaleString();
302
- },
303
-
304
- quotaResetSummary(account) {
305
- const resetAt = this.getQuotaResetAt(account);
306
- if (!resetAt) return null;
307
-
308
- const resetMs = new Date(resetAt).getTime();
309
- if (!Number.isFinite(resetMs)) return null;
310
-
311
- const deltaSec = Math.max(0, Math.floor((resetMs - Date.now()) / 1000));
312
- if (deltaSec === 0) return 'Reset due now';
313
-
314
- const days = Math.floor(deltaSec / 86400);
315
- const hours = Math.floor((deltaSec % 86400) / 3600);
316
- const minutes = Math.floor((deltaSec % 3600) / 60);
317
-
318
- if (days > 0) return `Resets in ${days}d ${hours}h`;
319
- if (hours > 0) return `Resets in ${hours}h ${minutes}m`;
320
- return `Resets in ${minutes}m`;
321
- },
322
-
323
- async startOAuth() {
324
- await this.api('/accounts/oauth/cleanup', { method: 'POST' });
325
- const { ok, data } = await this.api('/accounts/add', { method: 'POST' });
326
-
327
- if (ok && data.oauth_url) {
328
- const width = 500, height = 700;
329
- const left = (screen.width - width) / 2;
330
- const top = (screen.height - height) / 2;
331
- window.open(data.oauth_url, 'ChatGPT Login', `width=${width},height=${height},left=${left},top=${top}`);
332
-
333
- const checkAdded = setInterval(async () => {
334
- const { ok, data } = await this.api('/accounts');
335
- if (ok && data.accounts?.length > this.accounts.length) {
336
- clearInterval(checkAdded);
337
- this.showAddModal = false;
338
- this.refreshAccounts();
339
- }
340
- }, 2000);
341
-
342
- setTimeout(() => clearInterval(checkAdded), 120000);
343
- } else {
344
- this.showToast(data?.message || 'Failed to start OAuth', 'error');
345
- }
346
- },
347
-
348
- async startManualOAuth() {
349
- await this.api('/accounts/oauth/cleanup', { method: 'POST' });
350
- const { ok, data } = await this.api('/accounts/add', { method: 'POST' });
351
-
352
- if (ok && data.oauth_url) {
353
- this.oauthManualUrl = data.oauth_url;
354
- this.oauthManualVerifier = data.verifier;
355
- this.oauthManualCode = '';
356
- this.oauthManualMode = true;
357
- } else {
358
- this.showToast(data?.message || 'Failed to start OAuth', 'error');
359
- }
360
- },
361
-
362
- async submitManualOAuth() {
363
- if (!this.oauthManualCode) return;
364
-
365
- const { ok, data } = await this.api('/accounts/add/manual', {
366
- method: 'POST',
367
- body: JSON.stringify({
368
- code: this.oauthManualCode,
369
- verifier: this.oauthManualVerifier
370
- })
371
- });
372
-
373
- if (ok && data.success) {
374
- this.showToast(data.message, 'success');
375
- this.showAddModal = false;
376
- this.oauthManualMode = false;
377
- this.refreshAccounts();
378
- } else {
379
- this.showToast(data?.error || 'Failed to add account', 'error');
380
- }
381
- },
382
-
383
- async copyToClipboard(text) {
384
- try {
385
- await navigator.clipboard.writeText(text);
386
- this.showToast('Copied to clipboard', 'success');
387
- } catch (e) {
388
- this.showToast('Failed to copy', 'error');
389
- }
390
- },
391
-
392
- async importFromCodex() {
393
- const { ok, data } = await this.api('/accounts/import', { method: 'POST' });
394
- if (ok && data.success) {
395
- this.showToast(data.message, 'success');
396
- this.showAddModal = false;
397
- this.refreshAccounts();
398
- } else {
399
- this.showToast(data?.message || 'Import failed', 'error');
400
- }
401
- },
402
-
403
- async switchAccount(email) {
404
- const { ok, data } = await this.api('/accounts/switch', {
405
- method: 'POST',
406
- body: JSON.stringify({ email })
407
- });
408
- if (ok && data.success) {
409
- this.showToast(data.message, 'success');
410
- this.refreshAccounts();
411
- } else {
412
- this.showToast(data?.message || 'Failed to switch', 'error');
413
- }
414
- },
415
-
416
- async refreshToken(email) {
417
- if (this.refreshingTokenEmails.includes(email)) return;
418
-
419
- this.refreshingTokenEmails.push(email);
136
+
137
+ return [
138
+ hex.slice(0, 4).join(''),
139
+ hex.slice(4, 6).join(''),
140
+ hex.slice(6, 8).join(''),
141
+ hex.slice(8, 10).join(''),
142
+ hex.slice(10, 16).join('')
143
+ ].join('-');
144
+ },
145
+ async redeemRateLimitResetCredit(creditId = null) {
146
+ if (!this.selectedAccount || this.resetCreditsRedeeming) return;
147
+ const email = this.selectedAccount.email;
148
+ this.resetCreditsRedeeming = true;
149
+ this.resetCreditsRefreshPending = false;
420
150
  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');
151
+ if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = this.generateUUID();
152
+ const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', {
153
+ method: 'POST',
154
+ body: JSON.stringify({ email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId })
155
+ });
156
+ if (!ok || !data?.success) {
157
+ this.showToast(data?.error || 'Failed to redeem reset credit', 'error');
158
+ return;
427
159
  }
428
- } finally {
429
- this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email);
430
- }
431
- },
432
-
433
- async refreshAllTokens() {
434
- this.showToast('Refreshing all tokens...', 'info');
435
- const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' });
436
- if (ok) {
437
- this.showToast(data.message, 'success');
438
- this.refreshAccounts();
439
- } else {
440
- this.showToast(data?.message || 'Failed', 'error');
441
- }
442
- },
443
-
444
- confirmDelete(email) {
445
- this.deleteTarget = email;
446
- this.showDeleteModal = true;
447
- },
448
-
449
- async executeDelete() {
450
- const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' });
451
- this.showDeleteModal = false;
452
- if (ok && data.success) {
453
- this.showToast(data.message, 'success');
454
- this.refreshAccounts();
455
- } else {
456
- this.showToast(data?.message || 'Delete failed', 'error');
457
- }
458
- },
459
-
460
- showQuotaModal(acc) {
461
- this.selectedAccount = acc;
462
- this.showQuotaModalView = true;
463
- },
464
-
465
- async testChat() {
466
- if (!this.testPrompt.trim()) return;
467
-
468
- this.testing = true;
469
- this.testResponse = '';
470
-
471
- const testModel = this.modelMappings?.sonnet || 'gpt-5.5';
472
-
473
- const { ok, data } = await this.api('/v1/chat/completions', {
474
- method: 'POST',
475
- body: JSON.stringify({
476
- model: testModel,
477
- messages: [{ role: 'user', content: this.testPrompt }]
478
- })
479
- });
480
-
481
- this.testing = false;
482
-
483
- if (ok && data.choices) {
484
- const content = data.choices[0]?.message?.content;
485
-
486
- this.testResponse = content && content.trim()
487
- ? content
488
- : `[Empty response]\n\n${JSON.stringify(data, null, 2)}`;
489
- } else {
490
- this.testResponse = data?.error?.message || data?.error || 'Request failed';
491
- }
492
- },
493
-
494
- async loadAccountStrategySetting() {
495
- const { ok, data } = await this.api('/settings/account-strategy');
496
- if (ok && data?.accountStrategy) {
497
- this.accountStrategy = data.accountStrategy;
498
- }
499
- },
500
-
501
- async setAccountStrategy(strategy) {
502
- if (this.strategySaving || this.accountStrategy === strategy) return;
503
- this.strategySaving = true;
504
- const { ok, data } = await this.api('/settings/account-strategy', {
505
- method: 'POST',
506
- body: JSON.stringify({ accountStrategy: strategy })
507
- });
508
- this.strategySaving = false;
509
- if (ok && data?.accountStrategy) {
510
- this.accountStrategy = data.accountStrategy;
511
- this.showToast(`Account strategy set to ${data.accountStrategy === 'sticky' ? 'Sticky' : 'Round-Robin'}`, 'success');
512
- } else {
513
- this.showToast(data?.error || 'Failed to update strategy', 'error');
514
- }
515
- },
516
-
517
- async loadRawProxyLogsSetting() {
518
- const { ok, data } = await this.api('/settings/raw-proxy-logs');
519
- if (ok && typeof data?.logRawProxyPayloads === 'boolean') {
520
- this.logRawProxyPayloads = data.logRawProxyPayloads;
521
- }
522
- },
523
-
524
- async setRawProxyLogs(enabled) {
525
- if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return;
526
- this.rawProxyLogsSaving = true;
527
- const { ok, data } = await this.api('/settings/raw-proxy-logs', {
528
- method: 'POST',
529
- body: JSON.stringify({ enabled })
530
- });
531
- this.rawProxyLogsSaving = false;
532
-
533
- if (ok && typeof data?.logRawProxyPayloads === 'boolean') {
534
- this.logRawProxyPayloads = data.logRawProxyPayloads;
535
- this.showToast(data.logRawProxyPayloads ? 'Raw proxy payload logging enabled' : 'Raw proxy payload logging disabled', 'success');
536
- } else {
537
- this.showToast(data?.error || 'Failed to update raw proxy logging', 'error');
538
- }
539
- },
540
-
541
- async loadModelMapSetting() {
542
- this.modelMapLoading = true;
543
- const { ok, data } = await this.api('/settings/model-map');
544
- this.modelMapLoading = false;
545
-
546
- if (ok && data?.modelMap) {
547
- this.modelMappings = {
548
- sonnet: data.modelMap.sonnet || this.modelMappings.sonnet,
549
- opus: data.modelMap.opus || this.modelMappings.opus,
550
- haiku: data.modelMap.haiku || this.modelMappings.haiku
551
- };
552
- }
553
- },
554
-
555
- async saveModelMapSetting() {
556
- if (this.modelMapSaving) return;
557
-
558
- const modelMap = {
559
- sonnet: this.modelMappings.sonnet.trim(),
560
- opus: this.modelMappings.opus.trim(),
561
- haiku: this.modelMappings.haiku.trim()
562
- };
563
-
564
- if (!modelMap.sonnet || !modelMap.opus || !modelMap.haiku) {
565
- this.showToast('All Claude model mappings are required.', 'error');
566
- return;
567
- }
568
-
569
- this.modelMapSaving = true;
570
- const { ok, data } = await this.api('/settings/model-map', {
571
- method: 'POST',
572
- body: JSON.stringify({
573
- modelMap,
574
- reset: true
575
- })
576
- });
577
- this.modelMapSaving = false;
578
-
579
- if (ok && data?.modelMap) {
580
- this.modelMappings = {
581
- sonnet: data.modelMap.sonnet || modelMap.sonnet,
582
- opus: data.modelMap.opus || modelMap.opus,
583
- haiku: data.modelMap.haiku || modelMap.haiku
584
- };
585
- this.showToast('Model mapping updated', 'success');
586
- } else {
587
- this.showToast(data?.error || 'Failed to update model mapping', 'error');
588
- }
589
- },
590
-
591
- async resetModelMapSetting() {
592
- if (this.modelMapSaving) return;
593
- this.modelMapSaving = true;
594
- const { ok, data } = await this.api('/settings/model-map', {
595
- method: 'POST',
596
- body: JSON.stringify({ reset: true })
597
- });
598
- this.modelMapSaving = false;
599
-
600
- if (ok && data?.modelMap) {
601
- this.modelMappings = {
602
- sonnet: data.modelMap.sonnet || 'gpt-5.5',
603
- opus: data.modelMap.opus || 'gpt-5.5',
604
- haiku: data.modelMap.haiku || 'gpt-5.4-mini'
605
- };
606
- this.showToast('Model mapping reset', 'success');
607
- } else {
608
- this.showToast(data?.error || 'Failed to reset model mapping', 'error');
609
- }
610
- },
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
-
676
- async setClaudeCodeProxyTestConfig() {
677
- const { ok, data, error } = await this.api('/claude/config/set', {
678
- method: 'POST',
679
- body: JSON.stringify({
680
- apiUrl: this.serverUrl,
681
- apiKey: 'test'
682
- })
683
- });
684
-
685
- if (ok && data?.success) {
686
- this.showToast('Updated Claude Code settings.json (API URL + API key).', 'success');
687
- } else {
688
- this.showToast(data?.error || error || 'Failed to update Claude Code settings.json', 'error');
689
- }
690
- },
691
-
692
- showToast(message, type = 'success') {
693
- this.toast = { message, type };
694
- setTimeout(() => { this.toast = null; }, 3000);
695
- },
696
160
 
697
- startLogStream() {
698
- if (!this.isAuthenticated) return;
699
- if (this.logEventSource) this.logEventSource.close();
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()}`);
704
- this.logEventSource.onmessage = (event) => {
705
- try {
706
- const log = JSON.parse(event.data);
707
- this.logs.unshift(log);
708
-
709
- if (this.logs.length > 500) {
710
- this.logs = this.logs.slice(0, 500);
711
- }
712
- } catch (e) {}
713
- };
714
-
715
- this.logEventSource.onerror = () => {
716
- setTimeout(() => this.startLogStream(), 3000);
717
- };
718
- },
719
-
720
- clearLogs() {
721
- this.logs = [];
722
- },
723
-
724
- formatLogMessage(message) {
725
- if (!message) return '';
726
- const match = message.match(/^\[(\w+)\]\s*/);
727
- if (match) {
728
- return message.replace(match[0], '');
729
- }
730
- return message;
731
- },
161
+ this.resetCreditRedeemRequestId = '';
162
+ this.resetCreditsRefreshPending = true;
163
+ await this.loadRateLimitResetCredits(email);
164
+ await new Promise(resolve => setTimeout(resolve, 3000));
165
+ const { ok: quotaOk, data: quotaData } = await this.api(`/accounts/quota?email=${encodeURIComponent(email)}&refresh=true`);
166
+ if (!quotaOk || !quotaData?.quota) {
167
+ this.showToast(quotaData?.error || 'Quota reset succeeded, but quota refresh failed', 'error');
168
+ return;
169
+ }
732
170
 
733
- getLogDetails(message) {
734
- if (!message) return null;
735
- const details = {};
736
-
737
- const patterns = [
738
- ['model', /model=([^\s|,]+)/],
739
- ['account', /account=([^\s|,]+)/],
740
- ['stream', /stream=(true|false)/],
741
- ['messages', /messages=(\d+)/],
742
- ['tools', /tools=(\d+)/],
743
- ['tokens', /tokens=(\d+)/],
744
- ['cache_read_input_tokens', /cache_read_input_tokens=(\d+)/],
745
- ['input_tokens', /input_tokens=(\d+)/],
746
- ['output_tokens', /output_tokens=(\d+)/],
747
- ['duration', /(\d+)ms/],
748
- ['status', /status=(\d+)/],
749
- ['error', /error=([^\s|]+)/]
750
- ];
751
-
752
- for (const [key, pattern] of patterns) {
753
- const match = message.match(pattern);
754
- if (match) {
755
- details[key] = match[1];
171
+ this.accounts = this.accounts.map(account => account.email === email ? { ...account, quota: quotaData.quota } : account);
172
+ if (this.selectedAccount?.email === email) {
173
+ this.selectedAccount = { ...this.selectedAccount, quota: quotaData.quota };
756
174
  }
757
- }
758
-
759
- return Object.keys(details).length > 0 ? details : null;
760
- }
175
+ this.showToast('Quota reset and refreshed', 'success');
176
+ } finally {
177
+ this.resetCreditsRefreshPending = false;
178
+ this.resetCreditsRedeeming = false;
179
+ }
180
+ },
181
+ async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
182
+ async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
183
+ async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
184
+ async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
185
+ async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
186
+ async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
187
+ async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
188
+ async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
189
+ async loadClientProxyConfig() { try { const response = await fetch('/claude/config/proxy', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); if (response.ok && data?.success && data?.env) this.clientProxyConfig = data; } catch {} }, async copyClientText(text, successMessage) { if (!text) return; try { if (navigator.clipboard?.writeText && window.isSecureContext) await navigator.clipboard.writeText(text); else { const textarea = document.createElement('textarea'); textarea.value = text; textarea.setAttribute('readonly', ''); textarea.style.cssText = 'position:absolute;opacity:0;left:-999999px;top:-999999px'; document.body.appendChild(textarea); textarea.focus(); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('Clipboard copy was rejected'); } this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const configureCommands = this.clientProxyConfig?.commands?.powershell; const clearCommands = this.clientProxyConfig?.commands?.clear?.powershell; const commands = [...(Array.isArray(configureCommands) ? configureCommands : []), ...(Array.isArray(clearCommands) ? clearCommands : [])]; return commands.length ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
190
+ async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
191
+ showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, async loadLogs(page = 1) { if (this.logLoading) return; this.logLoading = true; const { ok, data } = await this.api(`/api/logs?page=${page}&pageSize=${this.logPageSize}`); this.logLoading = false; if (!ok || !Array.isArray(data?.logs)) { this.showToast(data?.error || 'Failed to load logs', 'error'); return; } this.logs = data.logs; this.logPage = data.page; this.logTotal = data.total; this.logTotalPages = data.totalPages; }, async changeLogPage(page) { if (page < 1 || page > this.logTotalPages || page === this.logPage) return; await this.loadLogs(page); }, startLogStream() { if (!this.isAuthenticated) return; this.loadLogs(); this.logEventSource?.close(); const params = new URLSearchParams(); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(adminUrl(`/api/logs/stream?${params}`)); this.logEventSource.onmessage = event => { try { this.logTotal += 1; this.logTotalPages = Math.ceil(this.logTotal / this.logPageSize); if (this.logPage === 1) this.logs = [JSON.parse(event.data), ...this.logs].slice(0, this.logPageSize); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; this.logTotal = 0; this.logTotalPages = 0; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
761
192
  }));
762
193
  });