claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.31
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/index.html +60 -60
- package/public/js/app.js +195 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +90 -29
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +15 -1
- package/public/views/client-api-keys.html +68 -31
- package/public/views/logs.html +10 -3
- package/src/account-manager.js +34 -3
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +11 -11
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +54 -16
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +69 -29
- package/src/model-api.js +86 -13
- package/src/model-pricing.js +127 -0
- package/src/response-streamer.js +23 -7
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +25 -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 +100 -51
- package/src/routes/settings-route.js +66 -5
- package/src/server-settings.js +25 -2
- package/src/utils/logger.js +30 -0
- package/src/utils/proxy-logging.js +5 -0
|
@@ -6,10 +6,9 @@ import { logger } from '../utils/logger.js';
|
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
7
|
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const SHORT_RATE_LIMIT_THRESHOLD_MS = 5000;
|
|
9
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
13
12
|
|
|
14
13
|
let accountRotator = null;
|
|
15
14
|
let currentStrategy = null;
|
|
@@ -49,11 +48,10 @@ function getAccountRotator() {
|
|
|
49
48
|
export async function handleMessages(req, res) {
|
|
50
49
|
const startTime = Date.now();
|
|
51
50
|
const body = req.body;
|
|
52
|
-
|
|
53
|
-
if (settings.logRawProxyPayloads === true) {
|
|
51
|
+
if (shouldLogRawProxyPayloads()) {
|
|
54
52
|
logger.info('[Claude Request]', body);
|
|
55
53
|
}
|
|
56
|
-
const requestedModel = body.model
|
|
54
|
+
const requestedModel = body.model;
|
|
57
55
|
const isStreaming = body.stream !== false;
|
|
58
56
|
|
|
59
57
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -62,71 +60,85 @@ export async function handleMessages(req, res) {
|
|
|
62
60
|
|
|
63
61
|
rotator.clearExpiredLimits();
|
|
64
62
|
|
|
65
|
-
const maxAttempts =
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
63
|
+
const maxAttempts = listAccounts().total;
|
|
64
|
+
let { account } = rotator.selectAccount(upstreamModel);
|
|
65
|
+
|
|
66
|
+
if (!account && rotator.isAllRateLimited(upstreamModel)) {
|
|
67
|
+
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
68
|
+
if (minWait > 0) {
|
|
69
|
+
const waitSeconds = Math.round(minWait / 1000);
|
|
70
|
+
logger.info(`[Messages] All accounts temporarily unavailable. Next possible reset: ${waitSeconds}s`);
|
|
72
71
|
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
73
72
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
return sendAuthError(res, 'No available accounts');
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
syncActiveAccount(account.email);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (!account) {
|
|
76
|
+
return sendAuthError(res, 'No available accounts');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
syncActiveAccount(account.email);
|
|
80
|
+
|
|
81
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
87
82
|
logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
|
|
88
83
|
|
|
89
84
|
const creds = await getCredentialsForAccount(account.email);
|
|
90
85
|
if (!creds) {
|
|
91
86
|
rotator.markInvalid(account.email, 'Failed to get credentials');
|
|
87
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
|
|
88
|
+
if (!replacement) {
|
|
89
|
+
return sendAuthError(res, 'No other available account');
|
|
90
|
+
}
|
|
91
|
+
account = replacement;
|
|
92
92
|
continue;
|
|
93
93
|
}
|
|
94
|
-
|
|
94
|
+
|
|
95
95
|
const anthropicRequest = { ...body, model: upstreamModel };
|
|
96
96
|
const requestContext = getRequestContext(req);
|
|
97
97
|
|
|
98
98
|
try {
|
|
99
99
|
if (isStreaming) {
|
|
100
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
100
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
101
101
|
} else {
|
|
102
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
102
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
103
103
|
}
|
|
104
104
|
rotator.notifySuccess(account, upstreamModel);
|
|
105
105
|
return;
|
|
106
106
|
} catch (error) {
|
|
107
|
+
if (res.headersSent) {
|
|
108
|
+
return handleStreamError(res, error, upstreamModel, startTime);
|
|
109
|
+
}
|
|
110
|
+
|
|
107
111
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
108
|
-
const parts = error.message.split(':');
|
|
109
|
-
const resetMs = parseInt(parts[1], 10);
|
|
110
|
-
const errorText = parts.slice(2).join(':');
|
|
111
|
-
|
|
112
112
|
rotator.notifyRateLimit(account, upstreamModel);
|
|
113
|
-
|
|
114
|
-
if (
|
|
115
|
-
logger.info(`[Messages]
|
|
116
|
-
|
|
117
|
-
attempt--;
|
|
118
|
-
continue;
|
|
113
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
|
|
114
|
+
if (!replacement) {
|
|
115
|
+
logger.info(`[Messages] Rate limit on ${account.email}; no other account available, stopping retry`);
|
|
116
|
+
return handleStreamError(res, error, upstreamModel, startTime);
|
|
119
117
|
}
|
|
120
|
-
|
|
121
|
-
logger.info(`[Messages] Rate limit on ${account.email}
|
|
118
|
+
|
|
119
|
+
logger.info(`[Messages] Rate limit on ${account.email}; switched to ${replacement.email}`);
|
|
120
|
+
account = replacement;
|
|
122
121
|
continue;
|
|
123
122
|
}
|
|
124
|
-
|
|
123
|
+
|
|
125
124
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
126
125
|
rotator.markInvalid(account.email, 'Auth expired');
|
|
126
|
+
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
|
|
127
|
+
if (!replacement) {
|
|
128
|
+
logger.info(`[Messages] Auth expired on ${account.email}; no other account available, stopping retry`);
|
|
129
|
+
return handleStreamError(res, error, upstreamModel, startTime);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
logger.info(`[Messages] Auth expired on ${account.email}; switched to ${replacement.email}`);
|
|
133
|
+
account = replacement;
|
|
127
134
|
continue;
|
|
128
135
|
}
|
|
129
|
-
|
|
136
|
+
|
|
137
|
+
if (error.status === 400 || error.anthropicErrorType === 'invalid_request_error') {
|
|
138
|
+
logger.info(`[Messages] Invalid request on ${account.email}; stopping account rotation`);
|
|
139
|
+
return handleStreamError(res, error, upstreamModel, startTime);
|
|
140
|
+
}
|
|
141
|
+
|
|
130
142
|
return handleStreamError(res, error, upstreamModel, startTime);
|
|
131
143
|
}
|
|
132
144
|
}
|
|
@@ -134,28 +146,69 @@ export async function handleMessages(req, res) {
|
|
|
134
146
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
135
147
|
}
|
|
136
148
|
|
|
137
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
149
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
138
150
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
139
151
|
initSSEResponse(res);
|
|
140
152
|
const usage = await pipeSSEStream(res, stream);
|
|
153
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
141
154
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
142
155
|
}
|
|
143
156
|
|
|
144
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
157
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
145
158
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
159
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
146
160
|
const duration = Date.now() - startTime;
|
|
147
161
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
148
162
|
res.json({ ...response, model: responseModel });
|
|
149
163
|
}
|
|
150
164
|
|
|
165
|
+
function recordRequestUsage(clientKeyId, model, usage) {
|
|
166
|
+
if (!clientKeyId) return;
|
|
167
|
+
|
|
168
|
+
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
169
|
+
...usage,
|
|
170
|
+
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
171
|
+
input_tokens_details: {
|
|
172
|
+
...(usage?.input_tokens_details || {}),
|
|
173
|
+
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
if (costMicrousd === null) {
|
|
177
|
+
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Selects and activates a different usable account before allowing a retry.
|
|
186
|
+
* @returns {object|null} The activated replacement account, or null when switching failed.
|
|
187
|
+
*/
|
|
188
|
+
export function switchToReplacementAccount(rotator, failedEmail, modelId, activateAccount = setActiveAccount) {
|
|
189
|
+
const { account } = rotator.selectAccount(modelId);
|
|
190
|
+
if (!account || account.email === failedEmail) {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const result = activateAccount(account.email);
|
|
195
|
+
if (!result?.success) {
|
|
196
|
+
logger.warn(`[Messages] Failed to switch account from ${failedEmail} to ${account.email}`);
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return account;
|
|
201
|
+
}
|
|
202
|
+
|
|
151
203
|
function syncActiveAccount(email) {
|
|
152
204
|
const active = getActiveAccount();
|
|
153
|
-
if (active?.email === email) return;
|
|
205
|
+
if (active?.email === email) return true;
|
|
154
206
|
|
|
155
207
|
const result = setActiveAccount(email);
|
|
156
208
|
if (result.success) {
|
|
157
209
|
logger.info(`[Messages] Synced active account to actual account: ${email}`);
|
|
158
210
|
}
|
|
211
|
+
return result.success;
|
|
159
212
|
}
|
|
160
213
|
|
|
161
214
|
function getTokenDetails(usage = {}) {
|
|
@@ -170,8 +223,4 @@ function getTokenDetails(usage = {}) {
|
|
|
170
223
|
};
|
|
171
224
|
}
|
|
172
225
|
|
|
173
|
-
function sleep(ms) {
|
|
174
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
175
|
-
}
|
|
176
|
-
|
|
177
226
|
export default { handleMessages };
|
|
@@ -10,13 +10,34 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import crypto from 'crypto';
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
getServerSettings,
|
|
15
|
+
setServerSettings,
|
|
16
|
+
DEFAULT_MODEL_MAP,
|
|
17
|
+
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
18
|
+
DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
19
|
+
} from '../server-settings.js';
|
|
20
|
+
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
14
21
|
|
|
15
22
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
16
23
|
|
|
17
24
|
function getSafeClientApiKey(clientApiKey) {
|
|
18
25
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
19
|
-
return
|
|
26
|
+
return {
|
|
27
|
+
...safeClientApiKey,
|
|
28
|
+
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd, {
|
|
29
|
+
enabled: clientApiKey.fiveHourLimitEnabled,
|
|
30
|
+
usd: clientApiKey.fiveHourLimitUsd
|
|
31
|
+
})
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function validateLimitUsd(value, fieldName) {
|
|
36
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
37
|
+
return `${fieldName} must be a non-negative number`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return null;
|
|
20
41
|
}
|
|
21
42
|
|
|
22
43
|
function createClientApiKeyValue() {
|
|
@@ -168,17 +189,38 @@ export function handleListClientApiKeys(req, res) {
|
|
|
168
189
|
* Creates a Claude Code client API key.
|
|
169
190
|
*/
|
|
170
191
|
export function handleCreateClientApiKey(req, res) {
|
|
171
|
-
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 || {};
|
|
172
199
|
|
|
173
200
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
174
201
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
175
202
|
}
|
|
203
|
+
if (typeof fiveHourLimitEnabled !== 'boolean') {
|
|
204
|
+
return res.status(400).json({ success: false, error: 'fiveHourLimitEnabled must be a boolean' });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
|
|
208
|
+
if (weeklyLimitError) {
|
|
209
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
210
|
+
}
|
|
211
|
+
const fiveHourLimitError = validateLimitUsd(fiveHourLimitUsd, 'fiveHourLimitUsd');
|
|
212
|
+
if (fiveHourLimitError) {
|
|
213
|
+
return res.status(400).json({ success: false, error: fiveHourLimitError });
|
|
214
|
+
}
|
|
176
215
|
|
|
177
216
|
const clientApiKey = {
|
|
178
217
|
id: crypto.randomUUID(),
|
|
179
218
|
key: createClientApiKeyValue(),
|
|
180
219
|
name: name.trim(),
|
|
181
220
|
remark: remark.trim(),
|
|
221
|
+
weeklyLimitUsd,
|
|
222
|
+
fiveHourLimitEnabled,
|
|
223
|
+
fiveHourLimitUsd,
|
|
182
224
|
createdAt: new Date().toISOString()
|
|
183
225
|
};
|
|
184
226
|
const settings = getServerSettings();
|
|
@@ -193,7 +235,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
193
235
|
*/
|
|
194
236
|
export function handleUpdateClientApiKey(req, res) {
|
|
195
237
|
const { id } = req.params;
|
|
196
|
-
const { name, remark } = req.body || {};
|
|
238
|
+
const { name, remark, weeklyLimitUsd, fiveHourLimitEnabled, fiveHourLimitUsd } = req.body || {};
|
|
197
239
|
|
|
198
240
|
if (name !== undefined && typeof name !== 'string') {
|
|
199
241
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -201,6 +243,21 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
201
243
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
202
244
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
203
245
|
}
|
|
246
|
+
if (weeklyLimitUsd !== undefined) {
|
|
247
|
+
const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
|
|
248
|
+
if (weeklyLimitError) {
|
|
249
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
250
|
+
}
|
|
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
|
+
}
|
|
204
261
|
|
|
205
262
|
const settings = getServerSettings();
|
|
206
263
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -212,7 +269,10 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
212
269
|
const clientApiKey = {
|
|
213
270
|
...current,
|
|
214
271
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
215
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
272
|
+
...(remark === undefined ? {} : { remark: remark.trim() }),
|
|
273
|
+
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd }),
|
|
274
|
+
...(fiveHourLimitEnabled === undefined ? {} : { fiveHourLimitEnabled }),
|
|
275
|
+
...(fiveHourLimitUsd === undefined ? {} : { fiveHourLimitUsd })
|
|
216
276
|
};
|
|
217
277
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
218
278
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -235,6 +295,7 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
235
295
|
}
|
|
236
296
|
|
|
237
297
|
setServerSettings({ clientApiKeys });
|
|
298
|
+
deleteClientKeyUsage(id);
|
|
238
299
|
res.json({ success: true });
|
|
239
300
|
}
|
|
240
301
|
|
package/src/server-settings.js
CHANGED
|
@@ -10,6 +10,9 @@ export const DEFAULT_MODEL_MAP = {
|
|
|
10
10
|
haiku: 'gpt-5.4-mini'
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
+
export const DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD = 50;
|
|
14
|
+
export const DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD = 0;
|
|
15
|
+
|
|
13
16
|
export const DEFAULT_SETTINGS = {
|
|
14
17
|
accountStrategy: 'sticky',
|
|
15
18
|
defaultCodexModel: 'gpt-5.5',
|
|
@@ -24,6 +27,21 @@ function ensureConfigDir() {
|
|
|
24
27
|
}
|
|
25
28
|
}
|
|
26
29
|
|
|
30
|
+
function normalizeClientApiKey(clientApiKey) {
|
|
31
|
+
const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
|
|
32
|
+
const fiveHourLimitUsd = Number(clientApiKey?.fiveHourLimitUsd);
|
|
33
|
+
return {
|
|
34
|
+
...clientApiKey,
|
|
35
|
+
weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
|
|
36
|
+
? weeklyLimitUsd
|
|
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
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
27
45
|
function mergeSettings(data = {}) {
|
|
28
46
|
return {
|
|
29
47
|
...DEFAULT_SETTINGS,
|
|
@@ -31,7 +49,10 @@ function mergeSettings(data = {}) {
|
|
|
31
49
|
modelMap: {
|
|
32
50
|
...DEFAULT_MODEL_MAP,
|
|
33
51
|
...(data.modelMap || {})
|
|
34
|
-
}
|
|
52
|
+
},
|
|
53
|
+
clientApiKeys: Array.isArray(data.clientApiKeys)
|
|
54
|
+
? data.clientApiKeys.map(normalizeClientApiKey)
|
|
55
|
+
: []
|
|
35
56
|
};
|
|
36
57
|
}
|
|
37
58
|
|
|
@@ -65,5 +86,7 @@ export default {
|
|
|
65
86
|
setServerSettings,
|
|
66
87
|
SETTINGS_FILE,
|
|
67
88
|
DEFAULT_SETTINGS,
|
|
68
|
-
DEFAULT_MODEL_MAP
|
|
89
|
+
DEFAULT_MODEL_MAP,
|
|
90
|
+
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
91
|
+
DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
|
|
69
92
|
};
|
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
|
}
|
|
@@ -156,6 +174,18 @@ class Logger extends EventEmitter {
|
|
|
156
174
|
if (details.inputTokens !== undefined) parts.push(`input_tokens=${details.inputTokens}`);
|
|
157
175
|
if (details.outputTokens !== undefined) parts.push(`output_tokens=${details.outputTokens}`);
|
|
158
176
|
if (details.cacheReadInputTokens !== undefined) parts.push(`cache_read_input_tokens=${details.cacheReadInputTokens}`);
|
|
177
|
+
if (details.transport) parts.push(`transport=${details.transport}`);
|
|
178
|
+
if (details.clientHttpStatus !== undefined) parts.push(`client_http_status=${details.clientHttpStatus}`);
|
|
179
|
+
if (details.errorType) parts.push(`error_type=${details.errorType}`);
|
|
180
|
+
if (details.retrySignal !== undefined) parts.push(`retry_signal=${details.retrySignal}`);
|
|
181
|
+
if (details.errorName) parts.push(`error_name=${details.errorName}`);
|
|
182
|
+
if (details.errorCode) parts.push(`error_code=${details.errorCode}`);
|
|
183
|
+
if (details.upstreamStatus !== undefined) parts.push(`upstream_status=${details.upstreamStatus}`);
|
|
184
|
+
if (details.isUpstreamError !== undefined) parts.push(`is_upstream_error=${details.isUpstreamError}`);
|
|
185
|
+
if (details.sseWriteAttempted !== undefined) parts.push(`sse_write_attempted=${details.sseWriteAttempted}`);
|
|
186
|
+
if (details.sseWriteBackpressure !== undefined) parts.push(`sse_write_backpressure=${details.sseWriteBackpressure}`);
|
|
187
|
+
if (details.socketDestroyed !== undefined) parts.push(`socket_destroyed=${details.socketDestroyed}`);
|
|
188
|
+
if (details.writableEnded !== undefined) parts.push(`writable_ended=${details.writableEnded}`);
|
|
159
189
|
if (details.duration) parts.push(`${details.duration}ms`);
|
|
160
190
|
if (details.error) parts.push(`error=${details.error}`);
|
|
161
191
|
|