claude-codex-proxy 1.0.5-beta.13 → 1.0.5-beta.2
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 +272 -0
- package/bin/cli.js +2 -37
- package/package.json +1 -1
- package/public/css/style.css +9 -210
- package/public/index.html +926 -32
- package/public/js/app.js +744 -115
- package/src/account-manager.js +3 -34
- package/src/account-rotation/rate-limits.js +26 -4
- package/src/account-rotation/strategies/base-strategy.js +0 -4
- package/src/account-rotation/strategies/sticky-strategy.js +0 -7
- package/src/claude-config.js +18 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +13 -12
- package/src/index.js +4 -13
- package/src/middleware/auth.js +11 -46
- package/src/middleware/credentials.js +3 -13
- package/src/model-api.js +0 -60
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +2 -106
- package/src/routes/api-routes.js +35 -61
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +15 -22
- package/src/routes/logs-route.js +2 -21
- package/src/routes/messages-route.js +13 -39
- package/src/routes/settings-route.js +5 -36
- package/src/server-settings.js +2 -18
- package/src/utils/logger.js +0 -18
- package/public/login.html +0 -32
- package/public/views/accounts-modals.html +0 -215
- package/public/views/accounts.html +0 -202
- package/public/views/client-api-keys-modals.html +0 -55
- package/public/views/client-api-keys.html +0 -69
- package/public/views/dashboard.html +0 -90
- package/public/views/empty.html +0 -0
- package/public/views/logs.html +0 -99
- package/public/views/settings.html +0 -123
- package/src/admin-path.js +0 -33
- package/src/client-key-usage.js +0 -125
- package/src/model-pricing.js +0 -96
- package/src/routes/client-quota-route.js +0 -25
- package/src/utils/proxy-logging.js +0 -5
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
* GET /accounts/status
|
|
6
6
|
* GET /accounts/quota
|
|
7
7
|
* GET /accounts/quota/all
|
|
8
|
-
* GET /accounts/rate-limit-reset-credits
|
|
9
|
-
* POST /accounts/rate-limit-reset-credits/consume
|
|
10
8
|
* POST /accounts/add
|
|
11
9
|
* POST /accounts/add/manual
|
|
12
10
|
* POST /accounts/switch
|
|
@@ -14,7 +12,6 @@
|
|
|
14
12
|
* POST /accounts/refresh
|
|
15
13
|
* POST /accounts/refresh/all
|
|
16
14
|
* POST /accounts/:email/refresh
|
|
17
|
-
* PUT /accounts/:email/expiration
|
|
18
15
|
* POST /accounts/oauth/cleanup
|
|
19
16
|
* DELETE /accounts/:email
|
|
20
17
|
*/
|
|
@@ -33,8 +30,7 @@ import {
|
|
|
33
30
|
saveAccounts,
|
|
34
31
|
updateAccountAuth,
|
|
35
32
|
updateAccountQuota,
|
|
36
|
-
getAccountQuota
|
|
37
|
-
updateAccountExpiration
|
|
33
|
+
getAccountQuota
|
|
38
34
|
} from '../account-manager.js';
|
|
39
35
|
|
|
40
36
|
import {
|
|
@@ -49,13 +45,9 @@ import {
|
|
|
49
45
|
} from '../oauth.js';
|
|
50
46
|
|
|
51
47
|
import {
|
|
52
|
-
getAccountQuota as fetchAccountQuota
|
|
53
|
-
fetchRateLimitResetCredits,
|
|
54
|
-
consumeRateLimitResetCredit
|
|
48
|
+
getAccountQuota as fetchAccountQuota
|
|
55
49
|
} from '../model-api.js';
|
|
56
50
|
|
|
57
|
-
import { randomUUID } from 'crypto';
|
|
58
|
-
|
|
59
51
|
import { logger } from '../utils/logger.js';
|
|
60
52
|
|
|
61
53
|
// Tracks active OAuth callback servers keyed by port
|
|
@@ -180,30 +172,6 @@ export async function handleRefreshAllAccounts(req, res) {
|
|
|
180
172
|
res.json(result);
|
|
181
173
|
}
|
|
182
174
|
|
|
183
|
-
export function handleUpdateAccountExpiration(req, res) {
|
|
184
|
-
const email = decodeURIComponent(req.params.email);
|
|
185
|
-
const { accountExpiresAt } = req.body || {};
|
|
186
|
-
|
|
187
|
-
if (accountExpiresAt !== null && accountExpiresAt !== undefined) {
|
|
188
|
-
if (typeof accountExpiresAt !== 'string' || !accountExpiresAt.trim()) {
|
|
189
|
-
return res.status(400).json({ success: false, message: 'accountExpiresAt must be an ISO 8601 date or null' });
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const normalizedAccountExpiresAt = accountExpiresAt.trim();
|
|
193
|
-
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
194
|
-
const expiresAt = new Date(normalizedAccountExpiresAt);
|
|
195
|
-
if (!isoDatePattern.test(normalizedAccountExpiresAt) || Number.isNaN(expiresAt.getTime())) {
|
|
196
|
-
return res.status(400).json({ success: false, message: 'accountExpiresAt must be a valid ISO 8601 date' });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const result = updateAccountExpiration(email, expiresAt.toISOString());
|
|
200
|
-
return res.status(result.success ? 200 : 404).json(result);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const result = updateAccountExpiration(email, null);
|
|
204
|
-
return res.status(result.success ? 200 : 404).json(result);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
175
|
export async function handleRefreshActiveAccount(req, res) {
|
|
208
176
|
const result = await refreshActiveAccount();
|
|
209
177
|
res.json(result);
|
|
@@ -264,75 +232,6 @@ export async function handleGetQuota(req, res) {
|
|
|
264
232
|
}
|
|
265
233
|
}
|
|
266
234
|
|
|
267
|
-
/**
|
|
268
|
-
* Lists an account's rate-limit reset credits.
|
|
269
|
-
*/
|
|
270
|
-
export async function handleGetRateLimitResetCredits(req, res) {
|
|
271
|
-
const { email } = req.query;
|
|
272
|
-
const account = email
|
|
273
|
-
? loadAccounts().accounts.find(a => a.email === email)
|
|
274
|
-
: getActiveAccount();
|
|
275
|
-
|
|
276
|
-
if (!account) {
|
|
277
|
-
return res.status(404).json({
|
|
278
|
-
success: false,
|
|
279
|
-
error: email ? `Account not found: ${email}` : 'No active account'
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
try {
|
|
284
|
-
const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
|
|
285
|
-
res.json({ success: true, email: account.email, credits });
|
|
286
|
-
} catch (error) {
|
|
287
|
-
logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
|
|
288
|
-
res.status(502).json({ success: false, error: error.message });
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Redeems one available rate-limit reset credit for an account.
|
|
294
|
-
*/
|
|
295
|
-
export async function handleConsumeRateLimitResetCredit(req, res) {
|
|
296
|
-
const { email, creditId, redeemRequestId } = req.body || {};
|
|
297
|
-
const account = email
|
|
298
|
-
? loadAccounts().accounts.find(a => a.email === email)
|
|
299
|
-
: getActiveAccount();
|
|
300
|
-
|
|
301
|
-
if (!account) {
|
|
302
|
-
return res.status(404).json({
|
|
303
|
-
success: false,
|
|
304
|
-
error: email ? `Account not found: ${email}` : 'No active account'
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
if (redeemRequestId !== undefined && (
|
|
309
|
-
typeof redeemRequestId !== 'string' ||
|
|
310
|
-
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(redeemRequestId.trim())
|
|
311
|
-
)) {
|
|
312
|
-
return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
|
|
316
|
-
return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
const idempotencyKey = redeemRequestId?.trim() || randomUUID();
|
|
320
|
-
|
|
321
|
-
try {
|
|
322
|
-
const result = await consumeRateLimitResetCredit(
|
|
323
|
-
account.accessToken,
|
|
324
|
-
account.accountId,
|
|
325
|
-
idempotencyKey,
|
|
326
|
-
creditId?.trim() || null
|
|
327
|
-
);
|
|
328
|
-
logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
|
|
329
|
-
res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
|
|
330
|
-
} catch (error) {
|
|
331
|
-
logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
|
|
332
|
-
res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
235
|
export async function handleGetAllQuotas(req, res) {
|
|
337
236
|
const { accounts: accountList } = listAccounts();
|
|
338
237
|
const results = [];
|
|
@@ -405,12 +304,9 @@ export default {
|
|
|
405
304
|
handleSwitchAccount,
|
|
406
305
|
handleRefreshAccount,
|
|
407
306
|
handleRefreshAllAccounts,
|
|
408
|
-
handleUpdateAccountExpiration,
|
|
409
307
|
handleRefreshActiveAccount,
|
|
410
308
|
handleRemoveAccount,
|
|
411
309
|
handleImportAccount,
|
|
412
310
|
handleGetQuota,
|
|
413
|
-
handleGetRateLimitResetCredits,
|
|
414
|
-
handleConsumeRateLimitResetCredit,
|
|
415
311
|
handleGetAllQuotas
|
|
416
312
|
};
|
package/src/routes/api-routes.js
CHANGED
|
@@ -7,18 +7,15 @@
|
|
|
7
7
|
import express from 'express';
|
|
8
8
|
import { createRequire } from 'module';
|
|
9
9
|
import { join, dirname } from 'path';
|
|
10
|
-
import { readFileSync } from 'fs';
|
|
11
10
|
import { fileURLToPath } from 'url';
|
|
12
11
|
|
|
13
12
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
14
13
|
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
15
|
-
import { getAdminPath } from '../admin-path.js';
|
|
16
14
|
|
|
17
15
|
// Route handlers
|
|
18
16
|
import { handleMessages } from './messages-route.js';
|
|
19
17
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
20
18
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
21
|
-
import { handleGetClientQuota } from './client-quota-route.js';
|
|
22
19
|
import {
|
|
23
20
|
handleGetAccountStrategy,
|
|
24
21
|
handleSetAccountStrategy,
|
|
@@ -42,13 +39,10 @@ import {
|
|
|
42
39
|
handleSwitchAccount,
|
|
43
40
|
handleRefreshAccount,
|
|
44
41
|
handleRefreshAllAccounts,
|
|
45
|
-
handleUpdateAccountExpiration,
|
|
46
42
|
handleRefreshActiveAccount,
|
|
47
43
|
handleRemoveAccount,
|
|
48
44
|
handleImportAccount,
|
|
49
45
|
handleGetQuota,
|
|
50
|
-
handleGetRateLimitResetCredits,
|
|
51
|
-
handleConsumeRateLimitResetCredit,
|
|
52
46
|
handleGetAllQuotas
|
|
53
47
|
} from './accounts-route.js';
|
|
54
48
|
|
|
@@ -57,24 +51,8 @@ const require = createRequire(import.meta.url);
|
|
|
57
51
|
const packageJson = require('../../package.json');
|
|
58
52
|
|
|
59
53
|
export function registerApiRoutes(app, { port }) {
|
|
60
|
-
const adminPath = getAdminPath();
|
|
61
|
-
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
62
|
-
const adminRouter = express.Router();
|
|
63
|
-
const sendAdminHtml = (fileName) => {
|
|
64
|
-
const html = readFileSync(join(publicDirectory, fileName), 'utf8')
|
|
65
|
-
.replace(/(href|src)="\//g, `$1="${adminPath}/`)
|
|
66
|
-
.replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
|
|
67
|
-
return (req, res) => res.type('html').send(html);
|
|
68
|
-
};
|
|
69
|
-
|
|
70
54
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
|
|
74
|
-
|
|
75
|
-
adminRouter.get('/login', sendAdminHtml('login.html'));
|
|
76
|
-
|
|
77
|
-
app.use(adminPath, adminRouter);
|
|
55
|
+
app.use(express.static(join(__dirname, '..', '..', 'public')));
|
|
78
56
|
|
|
79
57
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
80
58
|
app.get('/health', (req, res) => {
|
|
@@ -101,55 +79,51 @@ export function registerApiRoutes(app, { port }) {
|
|
|
101
79
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
102
80
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
103
81
|
|
|
104
|
-
// ─── Models
|
|
82
|
+
// ─── Models ────────────────────────────────────────────────────────────────
|
|
105
83
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
106
|
-
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
107
84
|
|
|
108
|
-
|
|
85
|
+
app.use(requireAdminAuth);
|
|
109
86
|
|
|
110
|
-
|
|
111
|
-
|
|
87
|
+
app.get('/accounts/models', handleAccountModels);
|
|
88
|
+
app.get('/accounts/usage', handleAccountUsage);
|
|
112
89
|
|
|
113
90
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
91
|
+
app.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
92
|
+
app.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
93
|
+
app.get('/settings/model-map', handleGetModelMap);
|
|
94
|
+
app.post('/settings/model-map', handleSetModelMap);
|
|
95
|
+
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
96
|
+
app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
97
|
+
app.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
98
|
+
app.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
99
|
+
app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
100
|
+
app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
124
101
|
|
|
125
102
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
adminRouter.put('/accounts/:email/expiration', handleUpdateAccountExpiration);
|
|
142
|
-
|
|
143
|
-
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
103
|
+
app.get('/accounts', handleListAccounts);
|
|
104
|
+
app.get('/accounts/status', handleAccountStatus);
|
|
105
|
+
app.get('/accounts/quota', handleGetQuota);
|
|
106
|
+
app.get('/accounts/quota/all', handleGetAllQuotas);
|
|
107
|
+
|
|
108
|
+
app.post('/accounts/add', handleAddAccount);
|
|
109
|
+
app.post('/accounts/add/manual', handleAddAccountManual);
|
|
110
|
+
app.post('/accounts/switch', handleSwitchAccount);
|
|
111
|
+
app.post('/accounts/import', handleImportAccount);
|
|
112
|
+
app.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
113
|
+
app.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
114
|
+
app.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
115
|
+
app.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
116
|
+
|
|
117
|
+
app.delete('/accounts/:email', handleRemoveAccount);
|
|
144
118
|
|
|
145
119
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
120
|
+
app.get('/claude/config', handleGetClaudeConfig);
|
|
121
|
+
app.post('/claude/config/direct', handleSetDirectMode);
|
|
122
|
+
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
149
123
|
|
|
150
124
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
151
|
-
|
|
152
|
-
|
|
125
|
+
app.get('/api/logs', handleGetLogs);
|
|
126
|
+
app.get('/api/logs/stream', handleStreamLogs);
|
|
153
127
|
}
|
|
154
128
|
|
|
155
129
|
export default { registerApiRoutes };
|
package/src/routes/chat-route.js
CHANGED
|
@@ -9,9 +9,7 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
9
9
|
import { getCredentialsOrError, sendAuthError } from '../middleware/credentials.js';
|
|
10
10
|
import { handleStreamError } from '../middleware/sse.js';
|
|
11
11
|
import { logger } from '../utils/logger.js';
|
|
12
|
-
import {
|
|
13
|
-
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
14
|
-
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
12
|
+
import { getServerSettings } from '../server-settings.js';
|
|
15
13
|
|
|
16
14
|
/**
|
|
17
15
|
* POST /v1/chat/completions
|
|
@@ -30,10 +28,11 @@ function getRequestContext(req) {
|
|
|
30
28
|
export async function handleChatCompletion(req, res) {
|
|
31
29
|
const startTime = Date.now();
|
|
32
30
|
const body = req.body;
|
|
33
|
-
|
|
31
|
+
const settings = getServerSettings();
|
|
32
|
+
if (settings.logRawProxyPayloads === true) {
|
|
34
33
|
logger.info('[Client Request]', body);
|
|
35
34
|
}
|
|
36
|
-
const requestedModel = body.model;
|
|
35
|
+
const requestedModel = body.model || 'gpt-5.2';
|
|
37
36
|
|
|
38
37
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
39
38
|
|
|
@@ -54,7 +53,6 @@ export async function handleChatCompletion(req, res) {
|
|
|
54
53
|
|
|
55
54
|
try {
|
|
56
55
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, getRequestContext(req));
|
|
57
|
-
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
58
56
|
|
|
59
57
|
const duration = Date.now() - startTime;
|
|
60
58
|
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
@@ -111,25 +109,6 @@ export function handleCountTokens(req, res) {
|
|
|
111
109
|
|
|
112
110
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
113
111
|
|
|
114
|
-
function recordRequestUsage(clientKeyId, model, usage) {
|
|
115
|
-
if (!clientKeyId) return;
|
|
116
|
-
|
|
117
|
-
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
118
|
-
...usage,
|
|
119
|
-
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
120
|
-
input_tokens_details: {
|
|
121
|
-
...(usage?.input_tokens_details || {}),
|
|
122
|
-
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
if (costMicrousd === null) {
|
|
126
|
-
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
112
|
/**
|
|
134
113
|
* Converts an OpenAI Chat Completions request body into an Anthropic-style request.
|
|
135
114
|
* @param {object} body
|
|
@@ -58,26 +58,15 @@ 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}`);
|
|
74
61
|
const commands = {
|
|
75
|
-
bash:
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
62
|
+
bash: [
|
|
63
|
+
`claude config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
64
|
+
`claude config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`
|
|
65
|
+
],
|
|
66
|
+
powershell: [
|
|
67
|
+
`claude config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
68
|
+
`claude config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`
|
|
69
|
+
]
|
|
81
70
|
};
|
|
82
71
|
|
|
83
72
|
res.json({
|
|
@@ -86,10 +75,14 @@ export async function handleSetProxyMode(req, res, { port }) {
|
|
|
86
75
|
message: 'Claude CLI config was not modified. Run the returned commands on the client machine that uses Claude Code.',
|
|
87
76
|
env: {
|
|
88
77
|
ANTHROPIC_BASE_URL: proxyUrl,
|
|
89
|
-
ANTHROPIC_API_KEY: apiKeyPlaceholder
|
|
90
|
-
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
78
|
+
ANTHROPIC_API_KEY: apiKeyPlaceholder
|
|
91
79
|
},
|
|
92
|
-
commands
|
|
80
|
+
commands,
|
|
81
|
+
models: {
|
|
82
|
+
opus: 'claude-opus',
|
|
83
|
+
sonnet: 'claude-sonnet',
|
|
84
|
+
haiku: 'claude-haiku'
|
|
85
|
+
}
|
|
93
86
|
});
|
|
94
87
|
} catch (error) {
|
|
95
88
|
res.status(500).json({ success: false, error: error.message });
|
package/src/routes/logs-route.js
CHANGED
|
@@ -7,31 +7,12 @@
|
|
|
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
|
-
|
|
18
10
|
/**
|
|
19
11
|
* GET /api/logs
|
|
20
|
-
* Returns
|
|
12
|
+
* Returns the in-memory log history as JSON.
|
|
21
13
|
*/
|
|
22
14
|
export function handleGetLogs(req, res) {
|
|
23
|
-
|
|
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
|
-
});
|
|
15
|
+
res.json({ status: 'ok', logs: logger.getHistory() });
|
|
35
16
|
}
|
|
36
17
|
|
|
37
18
|
/**
|
|
@@ -4,11 +4,8 @@ import { sendAuthError, getCredentialsForAccount } from '../middleware/credentia
|
|
|
4
4
|
import { initSSEResponse, pipeSSEStream, handleStreamError } from '../middleware/sse.js';
|
|
5
5
|
import { logger } from '../utils/logger.js';
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
|
-
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save
|
|
7
|
+
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
|
-
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
-
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
-
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
12
9
|
|
|
13
10
|
const MAX_RETRIES = 5;
|
|
14
11
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -53,10 +50,10 @@ export async function handleMessages(req, res) {
|
|
|
53
50
|
const startTime = Date.now();
|
|
54
51
|
const body = req.body;
|
|
55
52
|
const settings = getServerSettings();
|
|
56
|
-
if (
|
|
53
|
+
if (settings.logRawProxyPayloads === true) {
|
|
57
54
|
logger.info('[Claude Request]', body);
|
|
58
55
|
}
|
|
59
|
-
const requestedModel = body.model;
|
|
56
|
+
const requestedModel = body.model || 'gpt-5.2';
|
|
60
57
|
const isStreaming = body.stream !== false;
|
|
61
58
|
|
|
62
59
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -68,17 +65,15 @@ export async function handleMessages(req, res) {
|
|
|
68
65
|
const maxAttempts = Math.max(MAX_RETRIES, listAccounts().total);
|
|
69
66
|
|
|
70
67
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (!account && rotator.isAllRateLimited(upstreamModel)) {
|
|
68
|
+
if (rotator.isAllRateLimited(upstreamModel)) {
|
|
74
69
|
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
79
|
-
}
|
|
70
|
+
const waitSeconds = minWait > 0 ? Math.round(minWait / 1000) : 'unknown';
|
|
71
|
+
logger.info(`[Messages] All accounts rate-limited, not retrying. Next possible reset: ${waitSeconds}s`);
|
|
72
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
80
73
|
}
|
|
81
74
|
|
|
75
|
+
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
76
|
+
|
|
82
77
|
if (!account) {
|
|
83
78
|
if (waitMs > 0) {
|
|
84
79
|
await sleep(waitMs);
|
|
@@ -102,9 +97,9 @@ export async function handleMessages(req, res) {
|
|
|
102
97
|
|
|
103
98
|
try {
|
|
104
99
|
if (isStreaming) {
|
|
105
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
100
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
106
101
|
} else {
|
|
107
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
102
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
108
103
|
}
|
|
109
104
|
rotator.notifySuccess(account, upstreamModel);
|
|
110
105
|
return;
|
|
@@ -139,41 +134,20 @@ export async function handleMessages(req, res) {
|
|
|
139
134
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
140
135
|
}
|
|
141
136
|
|
|
142
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
137
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
143
138
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
144
139
|
initSSEResponse(res);
|
|
145
140
|
const usage = await pipeSSEStream(res, stream);
|
|
146
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
147
141
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
148
142
|
}
|
|
149
143
|
|
|
150
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
144
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
151
145
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
152
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
153
146
|
const duration = Date.now() - startTime;
|
|
154
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
155
148
|
res.json({ ...response, model: responseModel });
|
|
156
149
|
}
|
|
157
150
|
|
|
158
|
-
function recordRequestUsage(clientKeyId, model, usage) {
|
|
159
|
-
if (!clientKeyId) return;
|
|
160
|
-
|
|
161
|
-
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
162
|
-
...usage,
|
|
163
|
-
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
164
|
-
input_tokens_details: {
|
|
165
|
-
...(usage?.input_tokens_details || {}),
|
|
166
|
-
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
if (costMicrousd === null) {
|
|
170
|
-
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
151
|
function syncActiveAccount(email) {
|
|
178
152
|
const active = getActiveAccount();
|
|
179
153
|
if (active?.email === email) return;
|
|
@@ -10,30 +10,13 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import crypto from 'crypto';
|
|
13
|
-
import {
|
|
14
|
-
getServerSettings,
|
|
15
|
-
setServerSettings,
|
|
16
|
-
DEFAULT_MODEL_MAP,
|
|
17
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
18
|
-
} from '../server-settings.js';
|
|
19
|
-
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
13
|
+
import { getServerSettings, setServerSettings, DEFAULT_MODEL_MAP } from '../server-settings.js';
|
|
20
14
|
|
|
21
15
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
22
16
|
|
|
23
17
|
function getSafeClientApiKey(clientApiKey) {
|
|
24
18
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
25
|
-
return
|
|
26
|
-
...safeClientApiKey,
|
|
27
|
-
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd)
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function validateWeeklyLimitUsd(weeklyLimitUsd) {
|
|
32
|
-
if (typeof weeklyLimitUsd !== 'number' || !Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) {
|
|
33
|
-
return 'weeklyLimitUsd must be a non-negative number';
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return null;
|
|
19
|
+
return safeClientApiKey;
|
|
37
20
|
}
|
|
38
21
|
|
|
39
22
|
function createClientApiKeyValue() {
|
|
@@ -185,23 +168,17 @@ export function handleListClientApiKeys(req, res) {
|
|
|
185
168
|
* Creates a Claude Code client API key.
|
|
186
169
|
*/
|
|
187
170
|
export function handleCreateClientApiKey(req, res) {
|
|
188
|
-
const { name = '', remark = ''
|
|
171
|
+
const { name = '', remark = '' } = req.body || {};
|
|
189
172
|
|
|
190
173
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
191
174
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
192
175
|
}
|
|
193
176
|
|
|
194
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
195
|
-
if (weeklyLimitError) {
|
|
196
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
177
|
const clientApiKey = {
|
|
200
178
|
id: crypto.randomUUID(),
|
|
201
179
|
key: createClientApiKeyValue(),
|
|
202
180
|
name: name.trim(),
|
|
203
181
|
remark: remark.trim(),
|
|
204
|
-
weeklyLimitUsd,
|
|
205
182
|
createdAt: new Date().toISOString()
|
|
206
183
|
};
|
|
207
184
|
const settings = getServerSettings();
|
|
@@ -216,7 +193,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
216
193
|
*/
|
|
217
194
|
export function handleUpdateClientApiKey(req, res) {
|
|
218
195
|
const { id } = req.params;
|
|
219
|
-
const { name, remark
|
|
196
|
+
const { name, remark } = req.body || {};
|
|
220
197
|
|
|
221
198
|
if (name !== undefined && typeof name !== 'string') {
|
|
222
199
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -224,12 +201,6 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
224
201
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
225
202
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
226
203
|
}
|
|
227
|
-
if (weeklyLimitUsd !== undefined) {
|
|
228
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
229
|
-
if (weeklyLimitError) {
|
|
230
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
204
|
|
|
234
205
|
const settings = getServerSettings();
|
|
235
206
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -241,8 +212,7 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
241
212
|
const clientApiKey = {
|
|
242
213
|
...current,
|
|
243
214
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
244
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
245
|
-
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
215
|
+
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
246
216
|
};
|
|
247
217
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
248
218
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -265,7 +235,6 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
265
235
|
}
|
|
266
236
|
|
|
267
237
|
setServerSettings({ clientApiKeys });
|
|
268
|
-
deleteClientKeyUsage(id);
|
|
269
238
|
res.json({ success: true });
|
|
270
239
|
}
|
|
271
240
|
|