claude-codex-proxy 1.0.5-beta.1 → 1.0.5-beta.11
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 +30 -2
- package/package.json +1 -1
- package/public/css/style.css +210 -9
- package/public/index.html +32 -926
- package/public/js/app.js +104 -744
- package/public/login.html +32 -0
- package/public/views/accounts-modals.html +196 -0
- package/public/views/accounts.html +183 -0
- package/public/views/client-api-keys-modals.html +55 -0
- package/public/views/client-api-keys.html +69 -0
- package/public/views/dashboard.html +90 -0
- package/public/views/empty.html +0 -0
- package/public/views/logs.html +99 -0
- package/public/views/settings.html +123 -0
- package/src/account-rotation/rate-limits.js +0 -26
- package/src/claude-config.js +0 -18
- package/src/client-key-usage.js +125 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +12 -13
- package/src/middleware/auth.js +46 -11
- package/src/model-api.js +60 -0
- package/src/model-pricing.js +96 -0
- package/src/oauth.js +26 -65
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +92 -31
- package/src/routes/api-routes.js +17 -2
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +22 -15
- package/src/routes/client-quota-route.js +25 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +30 -6
- package/src/routes/settings-route.js +36 -5
- package/src/server-settings.js +18 -2
- package/src/utils/logger.js +18 -0
- package/src/utils/proxy-logging.js +5 -0
|
@@ -5,6 +5,8 @@
|
|
|
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
|
|
8
10
|
* POST /accounts/add
|
|
9
11
|
* POST /accounts/add/manual
|
|
10
12
|
* POST /accounts/switch
|
|
@@ -37,19 +39,21 @@ import {
|
|
|
37
39
|
getAuthorizationUrl,
|
|
38
40
|
generatePKCE,
|
|
39
41
|
generateState,
|
|
40
|
-
getOAuthCallbackHost,
|
|
41
42
|
startCallbackServer,
|
|
42
43
|
exchangeCodeForTokens,
|
|
43
|
-
handleOAuthCallback,
|
|
44
44
|
OAUTH_CONFIG,
|
|
45
45
|
extractCodeFromInput,
|
|
46
46
|
extractAccountInfo
|
|
47
47
|
} from '../oauth.js';
|
|
48
48
|
|
|
49
49
|
import {
|
|
50
|
-
getAccountQuota as fetchAccountQuota
|
|
50
|
+
getAccountQuota as fetchAccountQuota,
|
|
51
|
+
fetchRateLimitResetCredits,
|
|
52
|
+
consumeRateLimitResetCredit
|
|
51
53
|
} from '../model-api.js';
|
|
52
54
|
|
|
55
|
+
import { randomUUID } from 'crypto';
|
|
56
|
+
|
|
53
57
|
import { logger } from '../utils/logger.js';
|
|
54
58
|
|
|
55
59
|
// Tracks active OAuth callback servers keyed by port
|
|
@@ -75,32 +79,22 @@ export function handleOAuthCleanup(req, res) {
|
|
|
75
79
|
|
|
76
80
|
export async function handleAddAccount(req, res) {
|
|
77
81
|
const { port } = req.body || {};
|
|
78
|
-
const
|
|
79
|
-
const callbackHost = process.env.OAUTH_CALLBACK_HOST || req.hostname || getOAuthCallbackHost();
|
|
80
|
-
|
|
81
|
-
// Close any existing server on the requested primary port.
|
|
82
|
-
if (activeCallbackServers.has(requestedPort)) {
|
|
83
|
-
const existing = activeCallbackServers.get(requestedPort);
|
|
84
|
-
if (existing.abort) existing.abort();
|
|
85
|
-
activeCallbackServers.delete(requestedPort);
|
|
86
|
-
}
|
|
82
|
+
const callbackPort = port || OAUTH_CONFIG.callbackPort;
|
|
87
83
|
|
|
88
84
|
const { verifier } = generatePKCE();
|
|
89
85
|
const state = generateState();
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
status: 'error'
|
|
98
|
-
});
|
|
86
|
+
const oauthUrl = getAuthorizationUrl(verifier, state, callbackPort);
|
|
87
|
+
|
|
88
|
+
// Close any existing server on this port
|
|
89
|
+
if (activeCallbackServers.has(callbackPort)) {
|
|
90
|
+
const existing = activeCallbackServers.get(callbackPort);
|
|
91
|
+
if (existing.abort) existing.abort();
|
|
92
|
+
activeCallbackServers.delete(callbackPort);
|
|
99
93
|
}
|
|
100
94
|
|
|
101
|
-
let
|
|
95
|
+
let serverResult;
|
|
102
96
|
try {
|
|
103
|
-
|
|
97
|
+
serverResult = startCallbackServer(state, 120000);
|
|
104
98
|
} catch (err) {
|
|
105
99
|
return res.status(500).json({
|
|
106
100
|
error: 'Failed to start OAuth callback server',
|
|
@@ -109,7 +103,6 @@ export async function handleAddAccount(req, res) {
|
|
|
109
103
|
});
|
|
110
104
|
}
|
|
111
105
|
|
|
112
|
-
const oauthUrl = getAuthorizationUrl(verifier, state, callbackPort, callbackHost);
|
|
113
106
|
activeCallbackServers.set(callbackPort, serverResult);
|
|
114
107
|
|
|
115
108
|
serverResult.promise
|
|
@@ -117,7 +110,7 @@ export async function handleAddAccount(req, res) {
|
|
|
117
110
|
activeCallbackServers.delete(callbackPort);
|
|
118
111
|
if (!code) return null;
|
|
119
112
|
|
|
120
|
-
return exchangeCodeForTokens(code, verifier, callbackPort
|
|
113
|
+
return exchangeCodeForTokens(code, verifier, callbackPort)
|
|
121
114
|
.then(async tokens => {
|
|
122
115
|
const accountInfo = createAccountInfoFromTokens(tokens);
|
|
123
116
|
await _upsertAccount(accountInfo);
|
|
@@ -134,7 +127,6 @@ export async function handleAddAccount(req, res) {
|
|
|
134
127
|
oauth_url: oauthUrl,
|
|
135
128
|
verifier,
|
|
136
129
|
state,
|
|
137
|
-
callback_host: callbackHost,
|
|
138
130
|
callback_port: callbackPort
|
|
139
131
|
});
|
|
140
132
|
}
|
|
@@ -147,11 +139,9 @@ export async function handleAddAccountManual(req, res) {
|
|
|
147
139
|
}
|
|
148
140
|
|
|
149
141
|
try {
|
|
150
|
-
const { code: extractedCode
|
|
151
|
-
const tokens =
|
|
152
|
-
|
|
153
|
-
: await exchangeCodeForTokens(extractedCode, verifier, OAUTH_CONFIG.callbackPort);
|
|
154
|
-
const accountInfo = tokens.email ? tokens : createAccountInfoFromTokens(tokens);
|
|
142
|
+
const { code: extractedCode } = extractCodeFromInput(code);
|
|
143
|
+
const tokens = await exchangeCodeForTokens(extractedCode, verifier);
|
|
144
|
+
const accountInfo = createAccountInfoFromTokens(tokens);
|
|
155
145
|
|
|
156
146
|
await _upsertAccount(accountInfo);
|
|
157
147
|
logger.info(`Added account via manual OAuth: ${accountInfo.email}`);
|
|
@@ -248,6 +238,75 @@ export async function handleGetQuota(req, res) {
|
|
|
248
238
|
}
|
|
249
239
|
}
|
|
250
240
|
|
|
241
|
+
/**
|
|
242
|
+
* Lists an account's rate-limit reset credits.
|
|
243
|
+
*/
|
|
244
|
+
export async function handleGetRateLimitResetCredits(req, res) {
|
|
245
|
+
const { email } = req.query;
|
|
246
|
+
const account = email
|
|
247
|
+
? loadAccounts().accounts.find(a => a.email === email)
|
|
248
|
+
: getActiveAccount();
|
|
249
|
+
|
|
250
|
+
if (!account) {
|
|
251
|
+
return res.status(404).json({
|
|
252
|
+
success: false,
|
|
253
|
+
error: email ? `Account not found: ${email}` : 'No active account'
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
|
|
259
|
+
res.json({ success: true, email: account.email, credits });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
|
|
262
|
+
res.status(502).json({ success: false, error: error.message });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Redeems one available rate-limit reset credit for an account.
|
|
268
|
+
*/
|
|
269
|
+
export async function handleConsumeRateLimitResetCredit(req, res) {
|
|
270
|
+
const { email, creditId, redeemRequestId } = req.body || {};
|
|
271
|
+
const account = email
|
|
272
|
+
? loadAccounts().accounts.find(a => a.email === email)
|
|
273
|
+
: getActiveAccount();
|
|
274
|
+
|
|
275
|
+
if (!account) {
|
|
276
|
+
return res.status(404).json({
|
|
277
|
+
success: false,
|
|
278
|
+
error: email ? `Account not found: ${email}` : 'No active account'
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (redeemRequestId !== undefined && (
|
|
283
|
+
typeof redeemRequestId !== 'string' ||
|
|
284
|
+
!/^[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())
|
|
285
|
+
)) {
|
|
286
|
+
return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
|
|
290
|
+
return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const idempotencyKey = redeemRequestId?.trim() || randomUUID();
|
|
294
|
+
|
|
295
|
+
try {
|
|
296
|
+
const result = await consumeRateLimitResetCredit(
|
|
297
|
+
account.accessToken,
|
|
298
|
+
account.accountId,
|
|
299
|
+
idempotencyKey,
|
|
300
|
+
creditId?.trim() || null
|
|
301
|
+
);
|
|
302
|
+
logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
|
|
303
|
+
res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
|
|
304
|
+
} catch (error) {
|
|
305
|
+
logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
|
|
306
|
+
res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
251
310
|
export async function handleGetAllQuotas(req, res) {
|
|
252
311
|
const { accounts: accountList } = listAccounts();
|
|
253
312
|
const results = [];
|
|
@@ -324,5 +383,7 @@ export default {
|
|
|
324
383
|
handleRemoveAccount,
|
|
325
384
|
handleImportAccount,
|
|
326
385
|
handleGetQuota,
|
|
386
|
+
handleGetRateLimitResetCredits,
|
|
387
|
+
handleConsumeRateLimitResetCredit,
|
|
327
388
|
handleGetAllQuotas
|
|
328
389
|
};
|
package/src/routes/api-routes.js
CHANGED
|
@@ -16,6 +16,7 @@ import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../midd
|
|
|
16
16
|
import { handleMessages } from './messages-route.js';
|
|
17
17
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
18
18
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
19
|
+
import { handleGetClientQuota } from './client-quota-route.js';
|
|
19
20
|
import {
|
|
20
21
|
handleGetAccountStrategy,
|
|
21
22
|
handleSetAccountStrategy,
|
|
@@ -43,6 +44,8 @@ import {
|
|
|
43
44
|
handleRemoveAccount,
|
|
44
45
|
handleImportAccount,
|
|
45
46
|
handleGetQuota,
|
|
47
|
+
handleGetRateLimitResetCredits,
|
|
48
|
+
handleConsumeRateLimitResetCredit,
|
|
46
49
|
handleGetAllQuotas
|
|
47
50
|
} from './accounts-route.js';
|
|
48
51
|
|
|
@@ -52,7 +55,16 @@ const packageJson = require('../../package.json');
|
|
|
52
55
|
|
|
53
56
|
export function registerApiRoutes(app, { port }) {
|
|
54
57
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
55
|
-
|
|
58
|
+
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
59
|
+
app.use(express.static(publicDirectory));
|
|
60
|
+
|
|
61
|
+
app.get(['/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], (req, res) => {
|
|
62
|
+
res.sendFile(join(publicDirectory, 'index.html'));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
app.get('/login', (req, res) => {
|
|
66
|
+
res.sendFile(join(publicDirectory, 'login.html'));
|
|
67
|
+
});
|
|
56
68
|
|
|
57
69
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
58
70
|
app.get('/health', (req, res) => {
|
|
@@ -79,8 +91,9 @@ export function registerApiRoutes(app, { port }) {
|
|
|
79
91
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
80
92
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
81
93
|
|
|
82
|
-
// ─── Models
|
|
94
|
+
// ─── Models and Client Quota ───────────────────────────────────────────────
|
|
83
95
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
96
|
+
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
84
97
|
|
|
85
98
|
app.use(requireAdminAuth);
|
|
86
99
|
|
|
@@ -104,6 +117,8 @@ export function registerApiRoutes(app, { port }) {
|
|
|
104
117
|
app.get('/accounts/status', handleAccountStatus);
|
|
105
118
|
app.get('/accounts/quota', handleGetQuota);
|
|
106
119
|
app.get('/accounts/quota/all', handleGetAllQuotas);
|
|
120
|
+
app.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
|
|
121
|
+
app.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
|
|
107
122
|
|
|
108
123
|
app.post('/accounts/add', handleAddAccount);
|
|
109
124
|
app.post('/accounts/add/manual', handleAddAccountManual);
|
package/src/routes/chat-route.js
CHANGED
|
@@ -9,7 +9,9 @@ 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 {
|
|
12
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
13
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
14
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* POST /v1/chat/completions
|
|
@@ -28,11 +30,10 @@ function getRequestContext(req) {
|
|
|
28
30
|
export async function handleChatCompletion(req, res) {
|
|
29
31
|
const startTime = Date.now();
|
|
30
32
|
const body = req.body;
|
|
31
|
-
|
|
32
|
-
if (settings.logRawProxyPayloads === true) {
|
|
33
|
+
if (shouldLogRawProxyPayloads()) {
|
|
33
34
|
logger.info('[Client Request]', body);
|
|
34
35
|
}
|
|
35
|
-
const requestedModel = body.model
|
|
36
|
+
const requestedModel = body.model;
|
|
36
37
|
|
|
37
38
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
38
39
|
|
|
@@ -53,6 +54,7 @@ export async function handleChatCompletion(req, res) {
|
|
|
53
54
|
|
|
54
55
|
try {
|
|
55
56
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, getRequestContext(req));
|
|
57
|
+
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
56
58
|
|
|
57
59
|
const duration = Date.now() - startTime;
|
|
58
60
|
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
@@ -109,6 +111,25 @@ export function handleCountTokens(req, res) {
|
|
|
109
111
|
|
|
110
112
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
111
113
|
|
|
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
|
+
|
|
112
133
|
/**
|
|
113
134
|
* Converts an OpenAI Chat Completions request body into an Anthropic-style request.
|
|
114
135
|
* @param {object} body
|
|
@@ -58,15 +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
|
-
`claude config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`
|
|
69
|
-
]
|
|
75
|
+
bash: configureCommands,
|
|
76
|
+
powershell: configureCommands,
|
|
77
|
+
clear: {
|
|
78
|
+
bash: clearCommands,
|
|
79
|
+
powershell: clearCommands
|
|
80
|
+
}
|
|
70
81
|
};
|
|
71
82
|
|
|
72
83
|
res.json({
|
|
@@ -75,14 +86,10 @@ export async function handleSetProxyMode(req, res, { port }) {
|
|
|
75
86
|
message: 'Claude CLI config was not modified. Run the returned commands on the client machine that uses Claude Code.',
|
|
76
87
|
env: {
|
|
77
88
|
ANTHROPIC_BASE_URL: proxyUrl,
|
|
78
|
-
ANTHROPIC_API_KEY: apiKeyPlaceholder
|
|
89
|
+
ANTHROPIC_API_KEY: apiKeyPlaceholder,
|
|
90
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
79
91
|
},
|
|
80
|
-
commands
|
|
81
|
-
models: {
|
|
82
|
-
opus: 'claude-opus',
|
|
83
|
-
sonnet: 'claude-sonnet',
|
|
84
|
-
haiku: 'claude-haiku'
|
|
85
|
-
}
|
|
92
|
+
commands
|
|
86
93
|
});
|
|
87
94
|
} catch (error) {
|
|
88
95
|
res.status(500).json({ success: false, error: error.message });
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the authenticated client key's weekly quota using Claude Code's
|
|
5
|
+
* utilization response shape, so the terminal can consume it directly.
|
|
6
|
+
*/
|
|
7
|
+
export function handleGetClientQuota(req, res) {
|
|
8
|
+
const quota = req.clientApiKeyQuota;
|
|
9
|
+
const weeklyLimitUsd = quota?.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD;
|
|
10
|
+
const utilization = quota && weeklyLimitUsd > 0
|
|
11
|
+
? Math.min(100, Math.max(0, (quota.consumedUsd / weeklyLimitUsd) * 100))
|
|
12
|
+
: null;
|
|
13
|
+
|
|
14
|
+
return res.json({
|
|
15
|
+
five_hour: null,
|
|
16
|
+
seven_day: quota ? {
|
|
17
|
+
utilization,
|
|
18
|
+
resets_at: quota.nextPeriodStart
|
|
19
|
+
} : null,
|
|
20
|
+
seven_day_oauth_apps: null,
|
|
21
|
+
seven_day_opus: null,
|
|
22
|
+
seven_day_sonnet: null,
|
|
23
|
+
extra_usage: null
|
|
24
|
+
});
|
|
25
|
+
}
|
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
|
/**
|
|
@@ -6,6 +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
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
9
12
|
|
|
10
13
|
const MAX_RETRIES = 5;
|
|
11
14
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -50,10 +53,10 @@ export async function handleMessages(req, res) {
|
|
|
50
53
|
const startTime = Date.now();
|
|
51
54
|
const body = req.body;
|
|
52
55
|
const settings = getServerSettings();
|
|
53
|
-
if (
|
|
56
|
+
if (shouldLogRawProxyPayloads()) {
|
|
54
57
|
logger.info('[Claude Request]', body);
|
|
55
58
|
}
|
|
56
|
-
const requestedModel = body.model
|
|
59
|
+
const requestedModel = body.model;
|
|
57
60
|
const isStreaming = body.stream !== false;
|
|
58
61
|
|
|
59
62
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -97,9 +100,9 @@ export async function handleMessages(req, res) {
|
|
|
97
100
|
|
|
98
101
|
try {
|
|
99
102
|
if (isStreaming) {
|
|
100
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
103
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
101
104
|
} else {
|
|
102
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
105
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
103
106
|
}
|
|
104
107
|
rotator.notifySuccess(account, upstreamModel);
|
|
105
108
|
return;
|
|
@@ -134,20 +137,41 @@ export async function handleMessages(req, res) {
|
|
|
134
137
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
135
138
|
}
|
|
136
139
|
|
|
137
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
140
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
138
141
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
139
142
|
initSSEResponse(res);
|
|
140
143
|
const usage = await pipeSSEStream(res, stream);
|
|
144
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
141
145
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
142
146
|
}
|
|
143
147
|
|
|
144
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
148
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
145
149
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
146
151
|
const duration = Date.now() - startTime;
|
|
147
152
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
148
153
|
res.json({ ...response, model: responseModel });
|
|
149
154
|
}
|
|
150
155
|
|
|
156
|
+
function recordRequestUsage(clientKeyId, model, usage) {
|
|
157
|
+
if (!clientKeyId) return;
|
|
158
|
+
|
|
159
|
+
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
160
|
+
...usage,
|
|
161
|
+
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
162
|
+
input_tokens_details: {
|
|
163
|
+
...(usage?.input_tokens_details || {}),
|
|
164
|
+
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
if (costMicrousd === null) {
|
|
168
|
+
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
173
|
+
}
|
|
174
|
+
|
|
151
175
|
function syncActiveAccount(email) {
|
|
152
176
|
const active = getActiveAccount();
|
|
153
177
|
if (active?.email === email) return;
|
|
@@ -10,13 +10,30 @@
|
|
|
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
|
+
} from '../server-settings.js';
|
|
19
|
+
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
14
20
|
|
|
15
21
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
16
22
|
|
|
17
23
|
function getSafeClientApiKey(clientApiKey) {
|
|
18
24
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
19
|
-
return
|
|
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;
|
|
20
37
|
}
|
|
21
38
|
|
|
22
39
|
function createClientApiKeyValue() {
|
|
@@ -168,17 +185,23 @@ export function handleListClientApiKeys(req, res) {
|
|
|
168
185
|
* Creates a Claude Code client API key.
|
|
169
186
|
*/
|
|
170
187
|
export function handleCreateClientApiKey(req, res) {
|
|
171
|
-
const { name = '', remark = '' } = req.body || {};
|
|
188
|
+
const { name = '', remark = '', weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } = req.body || {};
|
|
172
189
|
|
|
173
190
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
174
191
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
175
192
|
}
|
|
176
193
|
|
|
194
|
+
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
195
|
+
if (weeklyLimitError) {
|
|
196
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
|
+
}
|
|
198
|
+
|
|
177
199
|
const clientApiKey = {
|
|
178
200
|
id: crypto.randomUUID(),
|
|
179
201
|
key: createClientApiKeyValue(),
|
|
180
202
|
name: name.trim(),
|
|
181
203
|
remark: remark.trim(),
|
|
204
|
+
weeklyLimitUsd,
|
|
182
205
|
createdAt: new Date().toISOString()
|
|
183
206
|
};
|
|
184
207
|
const settings = getServerSettings();
|
|
@@ -193,7 +216,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
193
216
|
*/
|
|
194
217
|
export function handleUpdateClientApiKey(req, res) {
|
|
195
218
|
const { id } = req.params;
|
|
196
|
-
const { name, remark } = req.body || {};
|
|
219
|
+
const { name, remark, weeklyLimitUsd } = req.body || {};
|
|
197
220
|
|
|
198
221
|
if (name !== undefined && typeof name !== 'string') {
|
|
199
222
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -201,6 +224,12 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
201
224
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
202
225
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
203
226
|
}
|
|
227
|
+
if (weeklyLimitUsd !== undefined) {
|
|
228
|
+
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
229
|
+
if (weeklyLimitError) {
|
|
230
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
204
233
|
|
|
205
234
|
const settings = getServerSettings();
|
|
206
235
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -212,7 +241,8 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
212
241
|
const clientApiKey = {
|
|
213
242
|
...current,
|
|
214
243
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
215
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
244
|
+
...(remark === undefined ? {} : { remark: remark.trim() }),
|
|
245
|
+
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
216
246
|
};
|
|
217
247
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
218
248
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -235,6 +265,7 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
235
265
|
}
|
|
236
266
|
|
|
237
267
|
setServerSettings({ clientApiKeys });
|
|
268
|
+
deleteClientKeyUsage(id);
|
|
238
269
|
res.json({ success: true });
|
|
239
270
|
}
|
|
240
271
|
|
package/src/server-settings.js
CHANGED
|
@@ -10,6 +10,8 @@ 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
|
+
|
|
13
15
|
export const DEFAULT_SETTINGS = {
|
|
14
16
|
accountStrategy: 'sticky',
|
|
15
17
|
defaultCodexModel: 'gpt-5.5',
|
|
@@ -24,6 +26,16 @@ function ensureConfigDir() {
|
|
|
24
26
|
}
|
|
25
27
|
}
|
|
26
28
|
|
|
29
|
+
function normalizeClientApiKey(clientApiKey) {
|
|
30
|
+
const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
|
|
31
|
+
return {
|
|
32
|
+
...clientApiKey,
|
|
33
|
+
weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
|
|
34
|
+
? weeklyLimitUsd
|
|
35
|
+
: DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
27
39
|
function mergeSettings(data = {}) {
|
|
28
40
|
return {
|
|
29
41
|
...DEFAULT_SETTINGS,
|
|
@@ -31,7 +43,10 @@ function mergeSettings(data = {}) {
|
|
|
31
43
|
modelMap: {
|
|
32
44
|
...DEFAULT_MODEL_MAP,
|
|
33
45
|
...(data.modelMap || {})
|
|
34
|
-
}
|
|
46
|
+
},
|
|
47
|
+
clientApiKeys: Array.isArray(data.clientApiKeys)
|
|
48
|
+
? data.clientApiKeys.map(normalizeClientApiKey)
|
|
49
|
+
: []
|
|
35
50
|
};
|
|
36
51
|
}
|
|
37
52
|
|
|
@@ -65,5 +80,6 @@ export default {
|
|
|
65
80
|
setServerSettings,
|
|
66
81
|
SETTINGS_FILE,
|
|
67
82
|
DEFAULT_SETTINGS,
|
|
68
|
-
DEFAULT_MODEL_MAP
|
|
83
|
+
DEFAULT_MODEL_MAP,
|
|
84
|
+
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
69
85
|
};
|
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
|
}
|