claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.30
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 +194 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +61 -2
- 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 +60 -0
- 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
package/src/routes/api-routes.js
CHANGED
|
@@ -7,15 +7,18 @@
|
|
|
7
7
|
import express from 'express';
|
|
8
8
|
import { createRequire } from 'module';
|
|
9
9
|
import { join, dirname } from 'path';
|
|
10
|
+
import { readFileSync } from 'fs';
|
|
10
11
|
import { fileURLToPath } from 'url';
|
|
11
12
|
|
|
12
13
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
13
14
|
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
15
|
+
import { getAdminPath } from '../admin-path.js';
|
|
14
16
|
|
|
15
17
|
// Route handlers
|
|
16
18
|
import { handleMessages } from './messages-route.js';
|
|
17
19
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
18
20
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
21
|
+
import { handleGetClientQuota } from './client-quota-route.js';
|
|
19
22
|
import {
|
|
20
23
|
handleGetAccountStrategy,
|
|
21
24
|
handleSetAccountStrategy,
|
|
@@ -39,10 +42,13 @@ import {
|
|
|
39
42
|
handleSwitchAccount,
|
|
40
43
|
handleRefreshAccount,
|
|
41
44
|
handleRefreshAllAccounts,
|
|
45
|
+
handleUpdateAccountExpiration,
|
|
42
46
|
handleRefreshActiveAccount,
|
|
43
47
|
handleRemoveAccount,
|
|
44
48
|
handleImportAccount,
|
|
45
49
|
handleGetQuota,
|
|
50
|
+
handleGetRateLimitResetCredits,
|
|
51
|
+
handleConsumeRateLimitResetCredit,
|
|
46
52
|
handleGetAllQuotas
|
|
47
53
|
} from './accounts-route.js';
|
|
48
54
|
|
|
@@ -51,17 +57,24 @@ const require = createRequire(import.meta.url);
|
|
|
51
57
|
const packageJson = require('../../package.json');
|
|
52
58
|
|
|
53
59
|
export function registerApiRoutes(app, { port }) {
|
|
54
|
-
|
|
60
|
+
const adminPath = getAdminPath();
|
|
55
61
|
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
56
|
-
|
|
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
|
+
};
|
|
57
69
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
});
|
|
70
|
+
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
71
|
+
adminRouter.use(express.static(publicDirectory, { index: false }));
|
|
61
72
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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);
|
|
65
78
|
|
|
66
79
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
67
80
|
app.get('/health', (req, res) => {
|
|
@@ -88,51 +101,55 @@ export function registerApiRoutes(app, { port }) {
|
|
|
88
101
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
89
102
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
90
103
|
|
|
91
|
-
// ─── Models
|
|
104
|
+
// ─── Models and Client Quota ───────────────────────────────────────────────
|
|
92
105
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
106
|
+
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
93
107
|
|
|
94
|
-
|
|
108
|
+
adminRouter.use(requireAdminAuth);
|
|
95
109
|
|
|
96
|
-
|
|
97
|
-
|
|
110
|
+
adminRouter.get('/accounts/models', handleAccountModels);
|
|
111
|
+
adminRouter.get('/accounts/usage', handleAccountUsage);
|
|
98
112
|
|
|
99
113
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
114
|
+
adminRouter.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
115
|
+
adminRouter.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
116
|
+
adminRouter.get('/settings/model-map', handleGetModelMap);
|
|
117
|
+
adminRouter.post('/settings/model-map', handleSetModelMap);
|
|
118
|
+
adminRouter.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
119
|
+
adminRouter.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
120
|
+
adminRouter.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
121
|
+
adminRouter.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
122
|
+
adminRouter.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
123
|
+
adminRouter.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
110
124
|
|
|
111
125
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
126
|
+
adminRouter.get('/accounts', handleListAccounts);
|
|
127
|
+
adminRouter.get('/accounts/status', handleAccountStatus);
|
|
128
|
+
adminRouter.get('/accounts/quota', handleGetQuota);
|
|
129
|
+
adminRouter.get('/accounts/quota/all', handleGetAllQuotas);
|
|
130
|
+
adminRouter.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
|
|
131
|
+
adminRouter.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
|
|
132
|
+
|
|
133
|
+
adminRouter.post('/accounts/add', handleAddAccount);
|
|
134
|
+
adminRouter.post('/accounts/add/manual', handleAddAccountManual);
|
|
135
|
+
adminRouter.post('/accounts/switch', handleSwitchAccount);
|
|
136
|
+
adminRouter.post('/accounts/import', handleImportAccount);
|
|
137
|
+
adminRouter.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
138
|
+
adminRouter.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
139
|
+
adminRouter.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
140
|
+
adminRouter.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
141
|
+
adminRouter.put('/accounts/:email/expiration', handleUpdateAccountExpiration);
|
|
142
|
+
|
|
143
|
+
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
127
144
|
|
|
128
145
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
146
|
+
adminRouter.get('/claude/config', handleGetClaudeConfig);
|
|
147
|
+
adminRouter.post('/claude/config/direct', handleSetDirectMode);
|
|
148
|
+
adminRouter.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
132
149
|
|
|
133
150
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
134
|
-
|
|
135
|
-
|
|
151
|
+
adminRouter.get('/api/logs', handleGetLogs);
|
|
152
|
+
adminRouter.get('/api/logs/stream', handleStreamLogs);
|
|
136
153
|
}
|
|
137
154
|
|
|
138
155
|
export default { registerApiRoutes };
|
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,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
|
/**
|
|
@@ -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 };
|