claude-codex-proxy 1.0.5-beta.4 → 1.0.5-beta.41
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 +0 -272
- package/bin/cli.js +37 -2
- package/package.json +1 -1
- package/public/css/style.css +132 -0
- package/public/js/app.js +105 -26
- package/public/views/accounts-modals.html +90 -29
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +10 -1
- package/public/views/client-api-keys.html +68 -39
- package/public/views/logs.html +10 -3
- package/public/views/settings.html +11 -1
- package/src/account-manager.js +34 -3
- package/src/account-rotation/index.js +6 -0
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/round-robin-strategy.js +78 -3
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -125
- package/src/daily-anchor-ping.js +149 -0
- package/src/direct-api.js +6 -5
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +23 -20
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +72 -30
- package/src/model-api.js +86 -13
- package/src/model-mapper.js +3 -4
- package/src/model-pricing.js +187 -96
- package/src/response-streamer.js +18 -2
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +5 -4
- package/src/routes/claude-config-route.js +19 -10
- package/src/routes/client-quota-route.js +31 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +135 -55
- package/src/routes/models-route.js +5 -0
- package/src/routes/settings-route.js +40 -10
- package/src/server-settings.js +10 -3
- package/src/server.js +4 -0
- package/src/utils/logger.js +34 -2
- package/src/utils/proxy-logging.js +5 -5
package/src/routes/chat-route.js
CHANGED
|
@@ -39,14 +39,15 @@ export async function handleChatCompletion(req, res) {
|
|
|
39
39
|
|
|
40
40
|
const creds = await getCredentialsOrError();
|
|
41
41
|
if (!creds) {
|
|
42
|
-
logger.response(401, { error: 'No active account' });
|
|
42
|
+
logger.response(401, { model: upstreamModel, requestedModel, error: 'No active account' });
|
|
43
43
|
return sendAuthError(res, 'No active account. Add an account via /accounts/add');
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
const anthropicRequest = _buildAnthropicRequest(body, upstreamModel);
|
|
47
47
|
|
|
48
|
-
logger.request(
|
|
48
|
+
logger.request({
|
|
49
49
|
model: upstreamModel,
|
|
50
|
+
requestedModel,
|
|
50
51
|
account: creds.email,
|
|
51
52
|
messages: body.messages?.length || 0,
|
|
52
53
|
tools: body.tools?.length || 0
|
|
@@ -57,11 +58,11 @@ export async function handleChatCompletion(req, res) {
|
|
|
57
58
|
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
58
59
|
|
|
59
60
|
const duration = Date.now() - startTime;
|
|
60
|
-
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
61
|
+
logger.response(200, { model: upstreamModel, requestedModel, ...getTokenDetails(response.usage), duration });
|
|
61
62
|
|
|
62
63
|
res.json(_buildOpenAIResponse(response, requestedModel));
|
|
63
64
|
} catch (error) {
|
|
64
|
-
handleStreamError(res, error, upstreamModel, startTime);
|
|
65
|
+
handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -58,17 +58,26 @@ export async function handleSetProxyMode(req, res, { port }) {
|
|
|
58
58
|
try {
|
|
59
59
|
const proxyUrl = getProxyConfigBaseUrl(req, port);
|
|
60
60
|
const apiKeyPlaceholder = '<client-api-key>';
|
|
61
|
+
const clearEnvironmentVariables = [
|
|
62
|
+
'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
63
|
+
'ANTHROPIC_DEFAULT_OPUS_MODEL',
|
|
64
|
+
'ANTHROPIC_DEFAULT_SONNET_MODEL',
|
|
65
|
+
'ANTHROPIC_MODEL'
|
|
66
|
+
];
|
|
67
|
+
const configureCommands = [
|
|
68
|
+
`cc config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
69
|
+
`cc config set env.ANTHROPIC_AUTH_TOKEN ${apiKeyPlaceholder}`,
|
|
70
|
+
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
71
|
+
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
72
|
+
];
|
|
73
|
+
const clearCommands = clearEnvironmentVariables.map(variable => `cc config unset env.${variable}`);
|
|
61
74
|
const commands = {
|
|
62
|
-
bash:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
`cc config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
69
|
-
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
70
|
-
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
71
|
-
]
|
|
75
|
+
bash: configureCommands,
|
|
76
|
+
powershell: configureCommands,
|
|
77
|
+
clear: {
|
|
78
|
+
bash: clearCommands,
|
|
79
|
+
powershell: clearCommands
|
|
80
|
+
}
|
|
72
81
|
};
|
|
73
82
|
|
|
74
83
|
res.json({
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
2
|
+
|
|
3
|
+
function getUtilization(consumedUsd, limitUsd) {
|
|
4
|
+
return limitUsd > 0
|
|
5
|
+
? Math.min(100, Math.max(0, (consumedUsd / limitUsd) * 100))
|
|
6
|
+
: null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Returns the authenticated client key's five-hour and weekly quota using
|
|
11
|
+
* Claude Code's utilization response shape, so the terminal can consume it directly.
|
|
12
|
+
*/
|
|
13
|
+
export function handleGetClientQuota(req, res) {
|
|
14
|
+
const quota = req.clientApiKeyQuota;
|
|
15
|
+
const weeklyLimitUsd = quota?.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD;
|
|
16
|
+
|
|
17
|
+
return res.json({
|
|
18
|
+
five_hour: quota?.fiveHourLimitEnabled ? {
|
|
19
|
+
utilization: getUtilization(quota.fiveHourConsumedUsd, quota.fiveHourLimitUsd),
|
|
20
|
+
resets_at: quota.nextFiveHourPeriodStart
|
|
21
|
+
} : null,
|
|
22
|
+
seven_day: quota ? {
|
|
23
|
+
utilization: getUtilization(quota.consumedUsd, weeklyLimitUsd),
|
|
24
|
+
resets_at: quota.nextPeriodStart
|
|
25
|
+
} : null,
|
|
26
|
+
seven_day_oauth_apps: null,
|
|
27
|
+
seven_day_opus: null,
|
|
28
|
+
seven_day_sonnet: null,
|
|
29
|
+
extra_usage: null
|
|
30
|
+
});
|
|
31
|
+
}
|
package/src/routes/logs-route.js
CHANGED
|
@@ -7,12 +7,31 @@
|
|
|
7
7
|
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
+
const LOGS_PER_PAGE = 30;
|
|
11
|
+
const MAX_PAGE_SIZE = 100;
|
|
12
|
+
|
|
13
|
+
function parsePositiveInteger(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
|
|
14
|
+
const parsed = Number.parseInt(value, 10);
|
|
15
|
+
return Number.isInteger(parsed) && parsed > 0 ? Math.min(parsed, maximum) : fallback;
|
|
16
|
+
}
|
|
17
|
+
|
|
10
18
|
/**
|
|
11
19
|
* GET /api/logs
|
|
12
|
-
* Returns
|
|
20
|
+
* Returns a newest-first page of in-memory log history.
|
|
13
21
|
*/
|
|
14
22
|
export function handleGetLogs(req, res) {
|
|
15
|
-
|
|
23
|
+
const page = parsePositiveInteger(req.query.page, 1);
|
|
24
|
+
const pageSize = parsePositiveInteger(req.query.pageSize, LOGS_PER_PAGE, MAX_PAGE_SIZE);
|
|
25
|
+
const { logs, total } = logger.getHistoryPage(page, pageSize);
|
|
26
|
+
|
|
27
|
+
res.json({
|
|
28
|
+
status: 'ok',
|
|
29
|
+
logs,
|
|
30
|
+
page,
|
|
31
|
+
pageSize,
|
|
32
|
+
total,
|
|
33
|
+
totalPages: Math.ceil(total / pageSize)
|
|
34
|
+
});
|
|
16
35
|
}
|
|
17
36
|
|
|
18
37
|
/**
|
|
@@ -10,20 +10,35 @@ import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
|
10
10
|
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
11
|
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
12
12
|
|
|
13
|
-
const MAX_RETRIES = 5;
|
|
14
|
-
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
15
|
-
const SHORT_RATE_LIMIT_THRESHOLD_MS = 5000;
|
|
16
|
-
|
|
17
13
|
let accountRotator = null;
|
|
18
14
|
let currentStrategy = null;
|
|
19
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Resolves the session affinity identifier used by the upstream Codex request.
|
|
18
|
+
* Metadata is preferred for Claude Code compatibility, followed by Pi's
|
|
19
|
+
* supported session affinity headers.
|
|
20
|
+
*/
|
|
20
21
|
function getRequestContext(req) {
|
|
22
|
+
let metadataSessionId;
|
|
23
|
+
|
|
21
24
|
try {
|
|
22
25
|
const metadata = JSON.parse(req.body?.metadata?.user_id || '{}');
|
|
23
|
-
|
|
26
|
+
metadataSessionId = metadata.session_id;
|
|
24
27
|
} catch (_) {
|
|
25
|
-
|
|
28
|
+
// Ignore malformed optional metadata and continue with HTTP headers.
|
|
26
29
|
}
|
|
30
|
+
|
|
31
|
+
const getHeader = (name) => {
|
|
32
|
+
if (typeof req.get === 'function') return req.get(name);
|
|
33
|
+
return req.headers?.[name];
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
sessionId: metadataSessionId
|
|
38
|
+
|| getHeader('session-id')
|
|
39
|
+
|| getHeader('x-session-id')
|
|
40
|
+
|| getHeader('x-session-affinity')
|
|
41
|
+
};
|
|
27
42
|
}
|
|
28
43
|
|
|
29
44
|
function getAccountRotator() {
|
|
@@ -52,7 +67,6 @@ function getAccountRotator() {
|
|
|
52
67
|
export async function handleMessages(req, res) {
|
|
53
68
|
const startTime = Date.now();
|
|
54
69
|
const body = req.body;
|
|
55
|
-
const settings = getServerSettings();
|
|
56
70
|
if (shouldLogRawProxyPayloads()) {
|
|
57
71
|
logger.info('[Claude Request]', body);
|
|
58
72
|
}
|
|
@@ -61,42 +75,59 @@ export async function handleMessages(req, res) {
|
|
|
61
75
|
|
|
62
76
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
63
77
|
|
|
78
|
+
logger.request({
|
|
79
|
+
model: upstreamModel,
|
|
80
|
+
requestedModel,
|
|
81
|
+
stream: isStreaming,
|
|
82
|
+
messages: body.messages?.length || 0,
|
|
83
|
+
tools: body.tools?.length || 0
|
|
84
|
+
});
|
|
85
|
+
|
|
64
86
|
const rotator = getAccountRotator();
|
|
65
|
-
|
|
87
|
+
const requestContext = getRequestContext(req);
|
|
88
|
+
|
|
66
89
|
rotator.clearExpiredLimits();
|
|
67
|
-
|
|
68
|
-
const maxAttempts =
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (!account) {
|
|
81
|
-
if (waitMs > 0) {
|
|
82
|
-
await sleep(waitMs);
|
|
83
|
-
attempt--;
|
|
84
|
-
continue;
|
|
85
|
-
}
|
|
86
|
-
return sendAuthError(res, 'No available accounts');
|
|
90
|
+
|
|
91
|
+
const maxAttempts = listAccounts().total;
|
|
92
|
+
let { account } = rotator.selectAccount(upstreamModel, {
|
|
93
|
+
sessionId: requestContext.sessionId
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
if (!account && rotator.isAllRateLimited(upstreamModel)) {
|
|
97
|
+
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
98
|
+
if (minWait > 0) {
|
|
99
|
+
const waitSeconds = Math.round(minWait / 1000);
|
|
100
|
+
logger.info(`[Messages] All accounts temporarily unavailable. Next possible reset: ${waitSeconds}s`);
|
|
101
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime, requestedModel);
|
|
87
102
|
}
|
|
88
|
-
|
|
89
|
-
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (!account) {
|
|
106
|
+
return sendAuthError(res, 'No available accounts');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
syncActiveAccount(account.email);
|
|
110
|
+
const attemptedEmails = new Set();
|
|
111
|
+
|
|
112
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
90
113
|
logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
|
|
91
114
|
|
|
92
115
|
const creds = await getCredentialsForAccount(account.email);
|
|
93
116
|
if (!creds) {
|
|
117
|
+
attemptedEmails.add(account.email);
|
|
94
118
|
rotator.markInvalid(account.email, 'Failed to get credentials');
|
|
119
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
|
|
120
|
+
sessionId: requestContext.sessionId,
|
|
121
|
+
excludeEmails: attemptedEmails
|
|
122
|
+
});
|
|
123
|
+
if (!replacement) {
|
|
124
|
+
return sendAuthError(res, 'No other available account');
|
|
125
|
+
}
|
|
126
|
+
account = replacement;
|
|
95
127
|
continue;
|
|
96
128
|
}
|
|
97
|
-
|
|
129
|
+
|
|
98
130
|
const anthropicRequest = { ...body, model: upstreamModel };
|
|
99
|
-
const requestContext = getRequestContext(req);
|
|
100
131
|
|
|
101
132
|
try {
|
|
102
133
|
if (isStreaming) {
|
|
@@ -107,34 +138,54 @@ export async function handleMessages(req, res) {
|
|
|
107
138
|
rotator.notifySuccess(account, upstreamModel);
|
|
108
139
|
return;
|
|
109
140
|
} catch (error) {
|
|
141
|
+
if (res.headersSent) {
|
|
142
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
143
|
+
}
|
|
144
|
+
|
|
110
145
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
111
|
-
|
|
112
|
-
const resetMs = parseInt(parts[1], 10);
|
|
113
|
-
const errorText = parts.slice(2).join(':');
|
|
114
|
-
|
|
146
|
+
attemptedEmails.add(account.email);
|
|
115
147
|
rotator.notifyRateLimit(account, upstreamModel);
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
148
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
|
|
149
|
+
sessionId: requestContext.sessionId,
|
|
150
|
+
excludeEmails: attemptedEmails
|
|
151
|
+
});
|
|
152
|
+
if (!replacement) {
|
|
153
|
+
logger.info(`[Messages] Rate limit on ${account.email}; no other account available, stopping retry`);
|
|
154
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
122
155
|
}
|
|
123
|
-
|
|
124
|
-
logger.info(`[Messages] Rate limit on ${account.email}
|
|
156
|
+
|
|
157
|
+
logger.info(`[Messages] Rate limit on ${account.email}; switched to ${replacement.email}`);
|
|
158
|
+
account = replacement;
|
|
125
159
|
continue;
|
|
126
160
|
}
|
|
127
|
-
|
|
161
|
+
|
|
128
162
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
163
|
+
attemptedEmails.add(account.email);
|
|
129
164
|
rotator.markInvalid(account.email, 'Auth expired');
|
|
165
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
|
|
166
|
+
sessionId: requestContext.sessionId,
|
|
167
|
+
excludeEmails: attemptedEmails
|
|
168
|
+
});
|
|
169
|
+
if (!replacement) {
|
|
170
|
+
logger.info(`[Messages] Auth expired on ${account.email}; no other account available, stopping retry`);
|
|
171
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
logger.info(`[Messages] Auth expired on ${account.email}; switched to ${replacement.email}`);
|
|
175
|
+
account = replacement;
|
|
130
176
|
continue;
|
|
131
177
|
}
|
|
132
|
-
|
|
133
|
-
|
|
178
|
+
|
|
179
|
+
if (error.status === 400 || error.anthropicErrorType === 'invalid_request_error') {
|
|
180
|
+
logger.info(`[Messages] Invalid request on ${account.email}; stopping account rotation`);
|
|
181
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
134
185
|
}
|
|
135
186
|
}
|
|
136
187
|
|
|
137
|
-
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
188
|
+
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime, requestedModel);
|
|
138
189
|
}
|
|
139
190
|
|
|
140
191
|
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
@@ -142,14 +193,14 @@ async function _streamDirectWithRotation(res, anthropicRequest, creds, responseM
|
|
|
142
193
|
initSSEResponse(res);
|
|
143
194
|
const usage = await pipeSSEStream(res, stream);
|
|
144
195
|
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
145
|
-
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
196
|
+
logger.response(200, { model: anthropicRequest.model, requestedModel: responseModel, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
146
197
|
}
|
|
147
198
|
|
|
148
199
|
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
149
200
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
201
|
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
151
202
|
const duration = Date.now() - startTime;
|
|
152
|
-
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
203
|
+
logger.response(200, { model: anthropicRequest.model, requestedModel: responseModel, ...getTokenDetails(response.usage), duration });
|
|
153
204
|
res.json({ ...response, model: responseModel });
|
|
154
205
|
}
|
|
155
206
|
|
|
@@ -172,14 +223,47 @@ function recordRequestUsage(clientKeyId, model, usage) {
|
|
|
172
223
|
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
173
224
|
}
|
|
174
225
|
|
|
226
|
+
/**
|
|
227
|
+
* Selects and activates a different usable account before allowing a retry.
|
|
228
|
+
* @returns {object|null} The activated replacement account, or null when switching failed.
|
|
229
|
+
*/
|
|
230
|
+
export function switchToReplacementAccount(
|
|
231
|
+
rotator,
|
|
232
|
+
failedEmail,
|
|
233
|
+
modelId,
|
|
234
|
+
selectionOptions = {},
|
|
235
|
+
activateAccount = setActiveAccount
|
|
236
|
+
) {
|
|
237
|
+
const excludeEmails = new Set(selectionOptions.excludeEmails || []);
|
|
238
|
+
excludeEmails.add(failedEmail);
|
|
239
|
+
const { account } = rotator.selectAccount(modelId, {
|
|
240
|
+
...selectionOptions,
|
|
241
|
+
excludeEmails,
|
|
242
|
+
deferSessionBinding: true
|
|
243
|
+
});
|
|
244
|
+
if (!account || account.email === failedEmail) {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const result = activateAccount(account.email);
|
|
249
|
+
if (!result?.success) {
|
|
250
|
+
logger.warn(`[Messages] Failed to switch account from ${failedEmail} to ${account.email}`);
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
rotator.commitSessionBinding?.(selectionOptions.sessionId, account.email);
|
|
255
|
+
return account;
|
|
256
|
+
}
|
|
257
|
+
|
|
175
258
|
function syncActiveAccount(email) {
|
|
176
259
|
const active = getActiveAccount();
|
|
177
|
-
if (active?.email === email) return;
|
|
260
|
+
if (active?.email === email) return true;
|
|
178
261
|
|
|
179
262
|
const result = setActiveAccount(email);
|
|
180
263
|
if (result.success) {
|
|
181
264
|
logger.info(`[Messages] Synced active account to actual account: ${email}`);
|
|
182
265
|
}
|
|
266
|
+
return result.success;
|
|
183
267
|
}
|
|
184
268
|
|
|
185
269
|
function getTokenDetails(usage = {}) {
|
|
@@ -194,8 +278,4 @@ function getTokenDetails(usage = {}) {
|
|
|
194
278
|
};
|
|
195
279
|
}
|
|
196
280
|
|
|
197
|
-
function sleep(ms) {
|
|
198
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
199
|
-
}
|
|
200
|
-
|
|
201
281
|
export default { handleMessages };
|
|
@@ -13,6 +13,11 @@ import { getCredentialsOrError } from '../middleware/credentials.js';
|
|
|
13
13
|
|
|
14
14
|
export const FALLBACK_MODELS = [
|
|
15
15
|
// OpenAI upstream models
|
|
16
|
+
{ id: 'gpt-6.1-sol', object: 'model', owned_by: 'openai' },
|
|
17
|
+
{ id: 'gpt-6-astra', object: 'model', owned_by: 'openai' },
|
|
18
|
+
{ id: 'gpt-6-sol', object: 'model', owned_by: 'openai' },
|
|
19
|
+
{ id: 'gpt-6-luna', object: 'model', owned_by: 'openai' },
|
|
20
|
+
{ id: 'gpt-5.6-luna', object: 'model', owned_by: 'openai' },
|
|
16
21
|
{ id: 'gpt-5.3-codex', object: 'model', owned_by: 'openai' },
|
|
17
22
|
{ id: 'gpt-5.2-codex', object: 'model', owned_by: 'openai' },
|
|
18
23
|
{ id: 'gpt-5.1-codex', object: 'model', owned_by: 'openai' },
|
|
@@ -14,7 +14,8 @@ import {
|
|
|
14
14
|
getServerSettings,
|
|
15
15
|
setServerSettings,
|
|
16
16
|
DEFAULT_MODEL_MAP,
|
|
17
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
17
|
+
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
18
|
+
DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
18
19
|
} from '../server-settings.js';
|
|
19
20
|
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
20
21
|
|
|
@@ -24,13 +25,16 @@ function getSafeClientApiKey(clientApiKey) {
|
|
|
24
25
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
25
26
|
return {
|
|
26
27
|
...safeClientApiKey,
|
|
27
|
-
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd
|
|
28
|
+
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd, {
|
|
29
|
+
enabled: clientApiKey.fiveHourLimitEnabled,
|
|
30
|
+
usd: clientApiKey.fiveHourLimitUsd
|
|
31
|
+
})
|
|
28
32
|
};
|
|
29
33
|
}
|
|
30
34
|
|
|
31
|
-
function
|
|
32
|
-
if (typeof
|
|
33
|
-
return
|
|
35
|
+
function validateLimitUsd(value, fieldName) {
|
|
36
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
37
|
+
return `${fieldName} must be a non-negative number`;
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
return null;
|
|
@@ -185,16 +189,29 @@ export function handleListClientApiKeys(req, res) {
|
|
|
185
189
|
* Creates a Claude Code client API key.
|
|
186
190
|
*/
|
|
187
191
|
export function handleCreateClientApiKey(req, res) {
|
|
188
|
-
const {
|
|
192
|
+
const {
|
|
193
|
+
name = '',
|
|
194
|
+
remark = '',
|
|
195
|
+
weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
196
|
+
fiveHourLimitEnabled = false,
|
|
197
|
+
fiveHourLimitUsd = DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
198
|
+
} = req.body || {};
|
|
189
199
|
|
|
190
200
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
191
201
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
192
202
|
}
|
|
203
|
+
if (typeof fiveHourLimitEnabled !== 'boolean') {
|
|
204
|
+
return res.status(400).json({ success: false, error: 'fiveHourLimitEnabled must be a boolean' });
|
|
205
|
+
}
|
|
193
206
|
|
|
194
|
-
const weeklyLimitError =
|
|
207
|
+
const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
|
|
195
208
|
if (weeklyLimitError) {
|
|
196
209
|
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
210
|
}
|
|
211
|
+
const fiveHourLimitError = validateLimitUsd(fiveHourLimitUsd, 'fiveHourLimitUsd');
|
|
212
|
+
if (fiveHourLimitError) {
|
|
213
|
+
return res.status(400).json({ success: false, error: fiveHourLimitError });
|
|
214
|
+
}
|
|
198
215
|
|
|
199
216
|
const clientApiKey = {
|
|
200
217
|
id: crypto.randomUUID(),
|
|
@@ -202,6 +219,8 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
202
219
|
name: name.trim(),
|
|
203
220
|
remark: remark.trim(),
|
|
204
221
|
weeklyLimitUsd,
|
|
222
|
+
fiveHourLimitEnabled,
|
|
223
|
+
fiveHourLimitUsd,
|
|
205
224
|
createdAt: new Date().toISOString()
|
|
206
225
|
};
|
|
207
226
|
const settings = getServerSettings();
|
|
@@ -216,7 +235,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
216
235
|
*/
|
|
217
236
|
export function handleUpdateClientApiKey(req, res) {
|
|
218
237
|
const { id } = req.params;
|
|
219
|
-
const { name, remark, weeklyLimitUsd } = req.body || {};
|
|
238
|
+
const { name, remark, weeklyLimitUsd, fiveHourLimitEnabled, fiveHourLimitUsd } = req.body || {};
|
|
220
239
|
|
|
221
240
|
if (name !== undefined && typeof name !== 'string') {
|
|
222
241
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -225,11 +244,20 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
225
244
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
226
245
|
}
|
|
227
246
|
if (weeklyLimitUsd !== undefined) {
|
|
228
|
-
const weeklyLimitError =
|
|
247
|
+
const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
|
|
229
248
|
if (weeklyLimitError) {
|
|
230
249
|
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
250
|
}
|
|
232
251
|
}
|
|
252
|
+
if (fiveHourLimitEnabled !== undefined && typeof fiveHourLimitEnabled !== 'boolean') {
|
|
253
|
+
return res.status(400).json({ success: false, error: 'fiveHourLimitEnabled must be a boolean' });
|
|
254
|
+
}
|
|
255
|
+
if (fiveHourLimitUsd !== undefined) {
|
|
256
|
+
const fiveHourLimitError = validateLimitUsd(fiveHourLimitUsd, 'fiveHourLimitUsd');
|
|
257
|
+
if (fiveHourLimitError) {
|
|
258
|
+
return res.status(400).json({ success: false, error: fiveHourLimitError });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
233
261
|
|
|
234
262
|
const settings = getServerSettings();
|
|
235
263
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -242,7 +270,9 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
242
270
|
...current,
|
|
243
271
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
244
272
|
...(remark === undefined ? {} : { remark: remark.trim() }),
|
|
245
|
-
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
273
|
+
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd }),
|
|
274
|
+
...(fiveHourLimitEnabled === undefined ? {} : { fiveHourLimitEnabled }),
|
|
275
|
+
...(fiveHourLimitUsd === undefined ? {} : { fiveHourLimitUsd })
|
|
246
276
|
};
|
|
247
277
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
248
278
|
clientApiKeys[index] = clientApiKey;
|
package/src/server-settings.js
CHANGED
|
@@ -11,10 +11,11 @@ export const DEFAULT_MODEL_MAP = {
|
|
|
11
11
|
};
|
|
12
12
|
|
|
13
13
|
export const DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD = 50;
|
|
14
|
+
export const DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD = 0;
|
|
14
15
|
|
|
15
16
|
export const DEFAULT_SETTINGS = {
|
|
16
17
|
accountStrategy: 'sticky',
|
|
17
|
-
defaultCodexModel: 'gpt-
|
|
18
|
+
defaultCodexModel: 'gpt-6.1-sol',
|
|
18
19
|
logRawProxyPayloads: false,
|
|
19
20
|
modelMap: DEFAULT_MODEL_MAP,
|
|
20
21
|
clientApiKeys: []
|
|
@@ -28,11 +29,16 @@ function ensureConfigDir() {
|
|
|
28
29
|
|
|
29
30
|
function normalizeClientApiKey(clientApiKey) {
|
|
30
31
|
const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
|
|
32
|
+
const fiveHourLimitUsd = Number(clientApiKey?.fiveHourLimitUsd);
|
|
31
33
|
return {
|
|
32
34
|
...clientApiKey,
|
|
33
35
|
weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
|
|
34
36
|
? weeklyLimitUsd
|
|
35
|
-
: DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
37
|
+
: DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
38
|
+
fiveHourLimitEnabled: clientApiKey?.fiveHourLimitEnabled === true,
|
|
39
|
+
fiveHourLimitUsd: Number.isFinite(fiveHourLimitUsd) && fiveHourLimitUsd >= 0
|
|
40
|
+
? fiveHourLimitUsd
|
|
41
|
+
: DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
36
42
|
};
|
|
37
43
|
}
|
|
38
44
|
|
|
@@ -81,5 +87,6 @@ export default {
|
|
|
81
87
|
SETTINGS_FILE,
|
|
82
88
|
DEFAULT_SETTINGS,
|
|
83
89
|
DEFAULT_MODEL_MAP,
|
|
84
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
90
|
+
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
91
|
+
DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
85
92
|
};
|
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();
|
package/src/utils/logger.js
CHANGED
|
@@ -40,6 +40,24 @@ class Logger extends EventEmitter {
|
|
|
40
40
|
return [...this.history];
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Returns a newest-first page of in-memory log entries.
|
|
45
|
+
*
|
|
46
|
+
* @param {number} page - One-based page number.
|
|
47
|
+
* @param {number} pageSize - Maximum number of entries per page.
|
|
48
|
+
* @returns {{ logs: object[], total: number }} Requested page and total entry count.
|
|
49
|
+
*/
|
|
50
|
+
getHistoryPage(page, pageSize) {
|
|
51
|
+
const total = this.history.length;
|
|
52
|
+
const end = Math.max(0, total - (page - 1) * pageSize);
|
|
53
|
+
const start = Math.max(0, end - pageSize);
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
logs: this.history.slice(start, end).reverse(),
|
|
57
|
+
total
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
43
61
|
clear() {
|
|
44
62
|
this.history = [];
|
|
45
63
|
}
|
|
@@ -139,9 +157,10 @@ class Logger extends EventEmitter {
|
|
|
139
157
|
this._log('DEBUG', ...args);
|
|
140
158
|
}
|
|
141
159
|
|
|
142
|
-
request(
|
|
143
|
-
const parts = [
|
|
160
|
+
request(details = {}) {
|
|
161
|
+
const parts = [];
|
|
144
162
|
if (details.model) parts.push(`model=${details.model}`);
|
|
163
|
+
if (details.requestedModel) parts.push(`requested_model=${details.requestedModel}`);
|
|
145
164
|
if (details.account) parts.push(`account=${details.account}`);
|
|
146
165
|
if (details.stream !== undefined) parts.push(`stream=${details.stream}`);
|
|
147
166
|
if (details.messages) parts.push(`messages=${details.messages}`);
|
|
@@ -152,10 +171,23 @@ class Logger extends EventEmitter {
|
|
|
152
171
|
response(status, details = {}) {
|
|
153
172
|
const parts = [`status=${status}`];
|
|
154
173
|
if (details.model) parts.push(`model=${details.model}`);
|
|
174
|
+
if (details.requestedModel) parts.push(`requested_model=${details.requestedModel}`);
|
|
155
175
|
if (details.tokens !== undefined) parts.push(`tokens=${details.tokens}`);
|
|
156
176
|
if (details.inputTokens !== undefined) parts.push(`input_tokens=${details.inputTokens}`);
|
|
157
177
|
if (details.outputTokens !== undefined) parts.push(`output_tokens=${details.outputTokens}`);
|
|
158
178
|
if (details.cacheReadInputTokens !== undefined) parts.push(`cache_read_input_tokens=${details.cacheReadInputTokens}`);
|
|
179
|
+
if (details.transport) parts.push(`transport=${details.transport}`);
|
|
180
|
+
if (details.clientHttpStatus !== undefined) parts.push(`client_http_status=${details.clientHttpStatus}`);
|
|
181
|
+
if (details.errorType) parts.push(`error_type=${details.errorType}`);
|
|
182
|
+
if (details.retrySignal !== undefined) parts.push(`retry_signal=${details.retrySignal}`);
|
|
183
|
+
if (details.errorName) parts.push(`error_name=${details.errorName}`);
|
|
184
|
+
if (details.errorCode) parts.push(`error_code=${details.errorCode}`);
|
|
185
|
+
if (details.upstreamStatus !== undefined) parts.push(`upstream_status=${details.upstreamStatus}`);
|
|
186
|
+
if (details.isUpstreamError !== undefined) parts.push(`is_upstream_error=${details.isUpstreamError}`);
|
|
187
|
+
if (details.sseWriteAttempted !== undefined) parts.push(`sse_write_attempted=${details.sseWriteAttempted}`);
|
|
188
|
+
if (details.sseWriteBackpressure !== undefined) parts.push(`sse_write_backpressure=${details.sseWriteBackpressure}`);
|
|
189
|
+
if (details.socketDestroyed !== undefined) parts.push(`socket_destroyed=${details.socketDestroyed}`);
|
|
190
|
+
if (details.writableEnded !== undefined) parts.push(`writable_ended=${details.writableEnded}`);
|
|
159
191
|
if (details.duration) parts.push(`${details.duration}ms`);
|
|
160
192
|
if (details.error) parts.push(`error=${details.error}`);
|
|
161
193
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getServerSettings } from '../server-settings.js';
|
|
2
|
-
|
|
3
|
-
export function shouldLogRawProxyPayloads() {
|
|
4
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
5
|
-
}
|
|
1
|
+
import { getServerSettings } from '../server-settings.js';
|
|
2
|
+
|
|
3
|
+
export function shouldLogRawProxyPayloads() {
|
|
4
|
+
return getServerSettings().logRawProxyPayloads === true;
|
|
5
|
+
}
|