claude-codex-proxy 1.0.5-beta.30 → 1.0.5-beta.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/public/js/app.js +8 -7
- package/public/views/accounts-modals.html +29 -27
- package/src/daily-anchor-ping.js +149 -0
- package/src/model-api.js +26 -13
- package/src/server.js +4 -0
package/package.json
CHANGED
package/public/js/app.js
CHANGED
|
@@ -92,13 +92,14 @@ document.addEventListener('alpine:init', () => {
|
|
|
92
92
|
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'; } },
|
|
93
93
|
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; },
|
|
94
94
|
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; },
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
95
|
+
getQuotaWindow(account, windowName = 'primary') { const usage = account?.quota?.usage; if (!usage) return null; const normalized = usage[`${windowName}Window`]; if (normalized) return normalized; return usage?.raw?.rate_limit?.[`${windowName}_window`] || null; },
|
|
96
|
+
getRemainingPercentage(account, windowName = 'primary') { const usage = account?.quota?.usage, window = this.getQuotaWindow(account, windowName); if (!window) return null; const values = [Number(window.remainingPercent), Number.isFinite(Number(window.usedPercent)) ? 100 - Number(window.usedPercent) : NaN, Number.isFinite(Number(window.used_percent)) ? 100 - Number(window.used_percent) : NaN, Number.isFinite(Number(window.remaining)) ? Number(window.remaining) : NaN, windowName === 'primary' && Number.isFinite(Number(usage.remaining)) ? Number(usage.remaining) : NaN]; const remaining = values.find(Number.isFinite); if (!Number.isFinite(remaining)) return windowName === 'primary' && (usage.limitReached === true || usage.allowed === false) ? 0 : null; return Math.max(0, Math.round(Math.min(100, remaining))); },
|
|
97
|
+
isQuotaExhausted(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining !== null && (remaining <= 0 || (windowName === 'primary' && (account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false))); },
|
|
98
|
+
quotaBarClass(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
|
|
99
|
+
quotaTextClass(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? '-' : `${remaining}%`; },
|
|
100
|
+
getQuotaResetAt(account, windowName = 'primary') { const window = this.getQuotaWindow(account, windowName); if (!window) return null; if (window.resetAt) return window.resetAt; const epoch = Number(window.reset_at); if (Number.isFinite(epoch) && epoch > 0) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(window.resetAfterSeconds ?? window.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
|
|
101
|
+
quotaResetAtLabel(account, windowName = 'primary') { const resetAt = this.getQuotaResetAt(account, windowName); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
|
|
102
|
+
quotaResetSummary(account, windowName = 'primary') { const resetAt = this.getQuotaResetAt(account, windowName); 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 days = Math.floor(seconds / 86400), hours = Math.floor((seconds % 86400) / 3600), minutes = Math.floor((seconds % 3600) / 60); return days ? `Resets in ${days}d ${hours}h` : hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
|
|
102
103
|
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'); },
|
|
103
104
|
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'); },
|
|
104
105
|
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'); },
|
|
@@ -138,37 +138,39 @@
|
|
|
138
138
|
</h3>
|
|
139
139
|
<p class="text-sm text-gray-500 font-mono mb-4" x-text="selectedAccount?.email"></p>
|
|
140
140
|
|
|
141
|
-
<div class="space-y-3 max-h-[60vh] overflow-y-auto" x-show="
|
|
142
|
-
<
|
|
143
|
-
<div class="
|
|
144
|
-
<
|
|
145
|
-
|
|
146
|
-
<
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
<
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
<div class="
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
<div class="mt-3 pt-3 border-t border-space-border/30 space-y-1">
|
|
160
|
-
<div class="flex items-center justify-between text-xs">
|
|
161
|
-
<span class="text-gray-500">Reset window</span>
|
|
162
|
-
<span class="font-mono text-gray-300" x-text="quotaResetSummary(selectedAccount) || '-'"></span>
|
|
141
|
+
<div class="space-y-3 max-h-[60vh] overflow-y-auto" x-show="getQuotaWindow(selectedAccount, 'primary') || getQuotaWindow(selectedAccount, 'secondary')">
|
|
142
|
+
<template x-for="window in [{ name: 'primary', label: '5-hour usage' }, { name: 'secondary', label: 'Weekly usage' }]" :key="window.name">
|
|
143
|
+
<div x-show="getQuotaWindow(selectedAccount, window.name)" class="p-3 bg-space-800/50 border border-space-border/30 rounded-lg">
|
|
144
|
+
<div class="flex justify-between items-center mb-2">
|
|
145
|
+
<span class="text-sm font-semibold text-gray-200" x-text="window.label"></span>
|
|
146
|
+
<template x-if="!isQuotaExhausted(selectedAccount, window.name)">
|
|
147
|
+
<span class="text-xs font-mono"
|
|
148
|
+
:class="quotaTextClass(selectedAccount, window.name)"
|
|
149
|
+
x-text="quotaLabel(selectedAccount, window.name) + ' remaining'"></span>
|
|
150
|
+
</template>
|
|
151
|
+
<template x-if="isQuotaExhausted(selectedAccount, window.name)">
|
|
152
|
+
<span class="text-[10px] font-bold uppercase text-red-400 bg-red-500/10 px-2 py-0.5 rounded border border-red-500/30">QUOTA EXHAUSTED</span>
|
|
153
|
+
</template>
|
|
154
|
+
</div>
|
|
155
|
+
<div class="w-full bg-gray-700 rounded-full h-3 overflow-hidden">
|
|
156
|
+
<div class="h-full rounded-full transition-all"
|
|
157
|
+
:class="quotaBarClass(selectedAccount, window.name)"
|
|
158
|
+
:style="`width: ${getRemainingPercentage(selectedAccount, window.name)}%`"></div>
|
|
163
159
|
</div>
|
|
164
|
-
<
|
|
160
|
+
<div class="mt-3 pt-3 border-t border-space-border/30 space-y-1">
|
|
165
161
|
<div class="flex items-center justify-between text-xs">
|
|
166
|
-
<span class="text-gray-500">
|
|
167
|
-
<span class="font-mono text-gray-300" x-text="
|
|
162
|
+
<span class="text-gray-500">Reset window</span>
|
|
163
|
+
<span class="font-mono text-gray-300" x-text="quotaResetSummary(selectedAccount, window.name) || '-'"></span>
|
|
168
164
|
</div>
|
|
169
|
-
|
|
165
|
+
<template x-if="quotaResetAtLabel(selectedAccount, window.name)">
|
|
166
|
+
<div class="flex items-center justify-between text-xs">
|
|
167
|
+
<span class="text-gray-500">Resets at</span>
|
|
168
|
+
<span class="font-mono text-gray-300" x-text="quotaResetAtLabel(selectedAccount, window.name)"></span>
|
|
169
|
+
</div>
|
|
170
|
+
</template>
|
|
171
|
+
</div>
|
|
170
172
|
</div>
|
|
171
|
-
</
|
|
173
|
+
</template>
|
|
172
174
|
</div>
|
|
173
175
|
|
|
174
176
|
<div class="mt-4 p-3 bg-space-800/50 border border-space-border/30 rounded-lg">
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daily Anchor Ping
|
|
3
|
+
* Every day at a fixed local hour (default 09:00) this module sends a minimal
|
|
4
|
+
* "你好" message to every configured account so the upstream Codex five-hour
|
|
5
|
+
* usage window is re-anchored to that moment. Because the upstream window
|
|
6
|
+
* advances from the first usage of the window, an anchor ping at 09:00 local
|
|
7
|
+
* time makes the upstream reset time settle at 14:00 local time (09:00 + 5h).
|
|
8
|
+
*
|
|
9
|
+
* The scheduler uses a self-rescheduling setTimeout that targets the exact
|
|
10
|
+
* next anchor instant, so the ping lands at 09:00:00.000 even across long
|
|
11
|
+
* uptimes; on the first run after a restart it only fires if 09:00 has not
|
|
12
|
+
* passed yet today, so it never disturbs an already-active window.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { loadAccounts } from './account-manager.js';
|
|
16
|
+
import { getCredentialsForAccount } from './middleware/credentials.js';
|
|
17
|
+
import { sendMessage } from './direct-api.js';
|
|
18
|
+
import { resolveModelRouting } from './model-mapper.js';
|
|
19
|
+
import { logger } from './utils/logger.js';
|
|
20
|
+
|
|
21
|
+
/** Local hour at which the anchor ping runs every day. */
|
|
22
|
+
export const ANCHOR_HOUR = 9;
|
|
23
|
+
|
|
24
|
+
/** Payload text sent upstream to advance the five-hour window start. */
|
|
25
|
+
export const PING_TEXT = '你好';
|
|
26
|
+
|
|
27
|
+
/** Maximum completion tokens for the anchor ping; only a single reply is needed. */
|
|
28
|
+
const PING_MAX_TOKENS = 16;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Hard cap for one anchor ping round. `sendMessage` has no built-in request
|
|
32
|
+
* timeout, so a hung upstream response could otherwise stall `pingAllAccounts`
|
|
33
|
+
* forever and break the self-rescheduling chain.
|
|
34
|
+
*/
|
|
35
|
+
const PING_TIMEOUT_MS = 5 * 60 * 1000;
|
|
36
|
+
|
|
37
|
+
/** Sample Claude model used to resolve the active upstream Codex model. */
|
|
38
|
+
const SAMPLE_MODEL = 'claude-sonnet-4-5';
|
|
39
|
+
|
|
40
|
+
let anchorTimer = null;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Computes the next Date at the given local hour (minutes/seconds zeroed)
|
|
44
|
+
* that is strictly after `now`.
|
|
45
|
+
*
|
|
46
|
+
* @param {Date} now - current time
|
|
47
|
+
* @param {number} [anchorHour] - local hour of the anchor
|
|
48
|
+
* @returns {Date} the next anchor instant
|
|
49
|
+
*/
|
|
50
|
+
export function getNextAnchorTime(now, anchorHour = ANCHOR_HOUR) {
|
|
51
|
+
const next = new Date(now);
|
|
52
|
+
next.setHours(anchorHour, 0, 0, 0);
|
|
53
|
+
if (next.getTime() <= now.getTime()) {
|
|
54
|
+
next.setDate(next.getDate() + 1);
|
|
55
|
+
}
|
|
56
|
+
return next;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Builds the minimal Anthropic-style request used for the anchor ping.
|
|
61
|
+
*/
|
|
62
|
+
function buildAnchorRequest() {
|
|
63
|
+
const { upstreamModel } = resolveModelRouting(SAMPLE_MODEL);
|
|
64
|
+
return {
|
|
65
|
+
model: upstreamModel,
|
|
66
|
+
max_tokens: PING_MAX_TOKENS,
|
|
67
|
+
messages: [{ role: 'user', content: PING_TEXT }]
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Sends the anchor message to every configured account. Each account is
|
|
73
|
+
* handled independently so a single failure never aborts the rest.
|
|
74
|
+
*/
|
|
75
|
+
async function pingAllAccounts() {
|
|
76
|
+
const data = loadAccounts();
|
|
77
|
+
const accounts = data.accounts || [];
|
|
78
|
+
if (accounts.length === 0) {
|
|
79
|
+
logger.info('[AnchorPing] No accounts configured; skipping daily ping');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const request = buildAnchorRequest();
|
|
84
|
+
logger.info(`[AnchorPing] Sending "${PING_TEXT}" to ${accounts.length} account(s) to anchor the five-hour window`);
|
|
85
|
+
|
|
86
|
+
for (const account of accounts) {
|
|
87
|
+
try {
|
|
88
|
+
const creds = await getCredentialsForAccount(account.email);
|
|
89
|
+
if (!creds) {
|
|
90
|
+
logger.warn(`[AnchorPing] Skip ${account.email}: no valid credentials`);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
await sendMessage(request, creds.accessToken, creds.accountId, {}, null, creds.email);
|
|
94
|
+
logger.info(`[AnchorPing] Sent "${PING_TEXT}" via ${account.email}`);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
logger.warn(`[AnchorPing] Failed for ${account.email}: ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Starts the daily anchor ping scheduler. Safe to call multiple times.
|
|
103
|
+
*/
|
|
104
|
+
export function startDailyAnchorPing() {
|
|
105
|
+
if (anchorTimer) return;
|
|
106
|
+
|
|
107
|
+
const scheduleNext = () => {
|
|
108
|
+
const next = getNextAnchorTime(new Date());
|
|
109
|
+
const delay = next.getTime() - Date.now();
|
|
110
|
+
logger.info(`[AnchorPing] Next ping scheduled at ${next.toLocaleString()}`);
|
|
111
|
+
anchorTimer = setTimeout(async () => {
|
|
112
|
+
// Race the whole ping round against a hard cap: even if one `sendMessage`
|
|
113
|
+
// hangs upstream, `scheduleNext()` in the `finally` block still runs and
|
|
114
|
+
// tomorrow's ping is never lost. A stray hung request may linger in the
|
|
115
|
+
// background, but it can no longer break the daily chain.
|
|
116
|
+
const guard = new Promise(resolve => setTimeout(resolve, PING_TIMEOUT_MS));
|
|
117
|
+
try {
|
|
118
|
+
await Promise.race([pingAllAccounts(), guard]);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// Guard against any unforeseen error so the loop always reschedules.
|
|
121
|
+
logger.warn(`[AnchorPing] Unexpected ping error: ${error.message}`);
|
|
122
|
+
} finally {
|
|
123
|
+
scheduleNext();
|
|
124
|
+
}
|
|
125
|
+
}, delay);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
scheduleNext();
|
|
129
|
+
logger.info(`[AnchorPing] Daily anchor ping enabled at local hour ${ANCHOR_HOUR}:00`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Stops the daily anchor ping scheduler and clears any pending timer.
|
|
134
|
+
*/
|
|
135
|
+
export function stopDailyAnchorPing() {
|
|
136
|
+
if (anchorTimer) {
|
|
137
|
+
clearTimeout(anchorTimer);
|
|
138
|
+
anchorTimer = null;
|
|
139
|
+
}
|
|
140
|
+
logger.info('[AnchorPing] Daily anchor ping stopped');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default {
|
|
144
|
+
startDailyAnchorPing,
|
|
145
|
+
stopDailyAnchorPing,
|
|
146
|
+
getNextAnchorTime,
|
|
147
|
+
ANCHOR_HOUR,
|
|
148
|
+
PING_TEXT
|
|
149
|
+
};
|
package/src/model-api.js
CHANGED
|
@@ -72,27 +72,40 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
72
72
|
|
|
73
73
|
const data = await response.json();
|
|
74
74
|
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
const usedPercent = Number.isFinite(usedPercentRaw) ? usedPercentRaw : 0;
|
|
75
|
+
const normalizeWindow = (window) => {
|
|
76
|
+
if (!window) return null;
|
|
78
77
|
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
const usedPercentRaw = Number(window.used_percent);
|
|
79
|
+
const usedPercent = Number.isFinite(usedPercentRaw) ? usedPercentRaw : 0;
|
|
80
|
+
const limitWindowSecondsRaw = Number(window.limit_window_seconds);
|
|
81
|
+
const resetAfterSecondsRaw = Number(window.reset_after_seconds);
|
|
82
|
+
const resetAtEpoch = Number(window.reset_at);
|
|
81
83
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
+
return {
|
|
85
|
+
usedPercent,
|
|
86
|
+
remainingPercent: Math.max(0, 100 - usedPercent),
|
|
87
|
+
limitWindowSeconds: Number.isFinite(limitWindowSecondsRaw) ? limitWindowSecondsRaw : null,
|
|
88
|
+
resetAfterSeconds: Number.isFinite(resetAfterSecondsRaw) ? resetAfterSecondsRaw : null,
|
|
89
|
+
resetAt: Number.isFinite(resetAtEpoch) && resetAtEpoch > 0
|
|
90
|
+
? new Date(resetAtEpoch * 1000).toISOString()
|
|
91
|
+
: null
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const primaryWindow = normalizeWindow(data.rate_limit?.primary_window);
|
|
96
|
+
const secondaryWindow = normalizeWindow(data.rate_limit?.secondary_window);
|
|
97
|
+
const usedPercent = primaryWindow?.usedPercent ?? 0;
|
|
84
98
|
|
|
85
|
-
const resetAtEpoch = Number(primaryWindow?.reset_at);
|
|
86
|
-
const resetAt = Number.isFinite(resetAtEpoch) ? new Date(resetAtEpoch * 1000).toISOString() : null;
|
|
87
|
-
|
|
88
99
|
return {
|
|
89
100
|
totalTokenUsage: usedPercent,
|
|
90
101
|
limit: 100,
|
|
91
102
|
remaining: 100 - usedPercent,
|
|
92
103
|
percentage: usedPercent,
|
|
93
|
-
resetAt: resetAt,
|
|
94
|
-
resetAfterSeconds: resetAfterSeconds,
|
|
95
|
-
limitWindowSeconds: limitWindowSeconds,
|
|
104
|
+
resetAt: primaryWindow?.resetAt ?? null,
|
|
105
|
+
resetAfterSeconds: primaryWindow?.resetAfterSeconds ?? null,
|
|
106
|
+
limitWindowSeconds: primaryWindow?.limitWindowSeconds ?? null,
|
|
107
|
+
primaryWindow,
|
|
108
|
+
secondaryWindow,
|
|
96
109
|
planType: data.plan_type || null,
|
|
97
110
|
limitReached: data.rate_limit?.limit_reached || false,
|
|
98
111
|
allowed: data.rate_limit?.allowed ?? true,
|
package/src/server.js
CHANGED
|
@@ -9,6 +9,7 @@ import cors from 'cors';
|
|
|
9
9
|
import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
|
|
10
10
|
import { getServerHost } from './deployment.js';
|
|
11
11
|
import { registerApiRoutes } from './routes/api-routes.js';
|
|
12
|
+
import { startDailyAnchorPing } from './daily-anchor-ping.js';
|
|
12
13
|
|
|
13
14
|
export function createServer({ port, testMode = false, startBackgroundJobs = true, persistAccounts = true }) {
|
|
14
15
|
if (!testMode && persistAccounts) {
|
|
@@ -16,6 +17,9 @@ export function createServer({ port, testMode = false, startBackgroundJobs = tru
|
|
|
16
17
|
}
|
|
17
18
|
if (!testMode && startBackgroundJobs) {
|
|
18
19
|
startAutoRefresh();
|
|
20
|
+
// Every day at 09:00 local time, re-anchor each account's upstream
|
|
21
|
+
// five-hour usage window so its reset time settles at 14:00.
|
|
22
|
+
startDailyAnchorPing();
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
const app = express();
|