claude-codex-proxy 1.0.5-beta.8 → 1.0.5
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 +6 -55
- package/bin/cli.js +0 -71
- package/docs/API.md +0 -22
- package/package.json +2 -3
- package/public/css/style.css +9 -210
- package/public/index.html +811 -32
- package/public/js/app.js +617 -104
- package/src/account-rotation/rate-limits.js +26 -0
- package/src/claude-config.js +18 -0
- package/src/direct-api.js +13 -12
- package/src/index.js +8 -26
- package/src/response-streamer.js +5 -5
- package/src/routes/api-routes.js +9 -44
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +10 -45
- package/src/routes/logs-route.js +2 -21
- package/src/routes/messages-route.js +6 -30
- package/src/routes/settings-route.js +2 -131
- package/src/server-settings.js +3 -20
- package/src/server.js +6 -10
- package/src/utils/logger.js +0 -18
- package/public/login.html +0 -32
- package/public/views/accounts-modals.html +0 -159
- package/public/views/accounts.html +0 -183
- 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/client-key-usage.js +0 -125
- package/src/deployment.js +0 -49
- package/src/middleware/auth.js +0 -115
- package/src/model-pricing.js +0 -96
- package/src/routes/client-quota-route.js +0 -25
- package/src/utils/proxy-logging.js +0 -5
|
@@ -117,6 +117,18 @@ export function clearExpiredLimits(accounts) {
|
|
|
117
117
|
return clearedCount;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Reset all rate limits for all accounts (optimistic retry)
|
|
122
|
+
* @param {Array} accounts - Array of account objects
|
|
123
|
+
*/
|
|
124
|
+
export function resetAllRateLimits(accounts) {
|
|
125
|
+
if (!accounts || accounts.length === 0) return;
|
|
126
|
+
for (const account of accounts) {
|
|
127
|
+
account.modelRateLimits = {};
|
|
128
|
+
}
|
|
129
|
+
logger.info('Reset all rate limits for all accounts (optimistic retry)');
|
|
130
|
+
}
|
|
131
|
+
|
|
120
132
|
/**
|
|
121
133
|
* Mark an account as rate-limited for a specific model
|
|
122
134
|
* @param {Array} accounts - Array of account objects
|
|
@@ -223,6 +235,20 @@ export function getMinWaitTimeMs(accounts, modelId) {
|
|
|
223
235
|
return minWait === Infinity ? 0 : minWait;
|
|
224
236
|
}
|
|
225
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Get rate limit info for a specific account and model
|
|
240
|
+
* @param {Array} accounts - Array of account objects
|
|
241
|
+
* @param {string} email - Account email
|
|
242
|
+
* @param {string} modelId - Model identifier
|
|
243
|
+
* @returns {Object|null} Rate limit info object or null
|
|
244
|
+
*/
|
|
245
|
+
export function getRateLimitInfo(accounts, email, modelId) {
|
|
246
|
+
const account = accounts?.find(a => a.email === email);
|
|
247
|
+
if (!account) return null;
|
|
248
|
+
|
|
249
|
+
return account.modelRateLimits?.[modelId] || null;
|
|
250
|
+
}
|
|
251
|
+
|
|
226
252
|
/**
|
|
227
253
|
* Check if an account is currently cooling down
|
|
228
254
|
* @param {Object} account - Account object
|
package/src/claude-config.js
CHANGED
|
@@ -75,6 +75,23 @@ export async function updateClaudeConfig(updates) {
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
export async function setProxyMode(proxyUrl, models = {}) {
|
|
79
|
+
const updates = {
|
|
80
|
+
env: {
|
|
81
|
+
ANTHROPIC_BASE_URL: proxyUrl,
|
|
82
|
+
ANTHROPIC_API_KEY: 'sk-ant-proxy',
|
|
83
|
+
ANTHROPIC_AUTH_TOKEN: undefined, // Explicitly unset to avoid conflict
|
|
84
|
+
ANTHROPIC_DEFAULT_OPUS_MODEL: models.opus || 'claude-opus',
|
|
85
|
+
ANTHROPIC_DEFAULT_SONNET_MODEL: models.sonnet || 'claude-sonnet',
|
|
86
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: models.haiku || 'claude-haiku',
|
|
87
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
88
|
+
},
|
|
89
|
+
autoCompactEnabled: true
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return await updateClaudeConfig(updates);
|
|
93
|
+
}
|
|
94
|
+
|
|
78
95
|
export async function setDirectMode(apiKey) {
|
|
79
96
|
const updates = {
|
|
80
97
|
env: {
|
|
@@ -131,6 +148,7 @@ export default {
|
|
|
131
148
|
readClaudeConfig,
|
|
132
149
|
readClaudeConfigSync,
|
|
133
150
|
updateClaudeConfig,
|
|
151
|
+
setProxyMode,
|
|
134
152
|
setDirectMode,
|
|
135
153
|
setApiEndpoint
|
|
136
154
|
};
|
package/src/direct-api.js
CHANGED
|
@@ -7,14 +7,17 @@ import os from 'os';
|
|
|
7
7
|
import { createRequire } from 'module';
|
|
8
8
|
import { convertAnthropicToResponsesAPI, convertOutputToAnthropic, generateMessageId } from './format-converter.js';
|
|
9
9
|
import { streamResponsesAPI, parseResponsesAPIResponse, createResponsesAPIError } from './response-streamer.js';
|
|
10
|
+
import { getServerSettings } from './server-settings.js';
|
|
10
11
|
import { logger } from './utils/logger.js';
|
|
11
|
-
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
12
12
|
|
|
13
13
|
const require = createRequire(import.meta.url);
|
|
14
14
|
const packageJson = require('../package.json');
|
|
15
15
|
const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
|
16
16
|
const APP_VERSION = packageJson.version;
|
|
17
|
-
|
|
17
|
+
|
|
18
|
+
function shouldLogRawProxyPayloads() {
|
|
19
|
+
return getServerSettings().logRawProxyPayloads === true;
|
|
20
|
+
}
|
|
18
21
|
|
|
19
22
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
20
23
|
const usage = {
|
|
@@ -27,10 +30,6 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
27
30
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
28
31
|
enumerable: false
|
|
29
32
|
});
|
|
30
|
-
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
31
|
-
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
32
|
-
enumerable: false
|
|
33
|
-
});
|
|
34
33
|
return usage;
|
|
35
34
|
}
|
|
36
35
|
|
|
@@ -129,14 +128,15 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
129
128
|
const response = await fetch(API_URL, {
|
|
130
129
|
method: 'POST',
|
|
131
130
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
132
|
-
body: JSON.stringify(request)
|
|
133
|
-
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
131
|
+
body: JSON.stringify(request)
|
|
134
132
|
});
|
|
135
133
|
|
|
136
134
|
if (response.ok) return response;
|
|
137
135
|
|
|
138
136
|
const errorText = await response.text();
|
|
139
|
-
|
|
137
|
+
if (shouldLogRawProxyPayloads()) {
|
|
138
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
+
}
|
|
140
140
|
|
|
141
141
|
if (response.status === 401) {
|
|
142
142
|
if (accountRotator && currentEmail) {
|
|
@@ -197,13 +197,14 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
197
197
|
const response = await fetch(API_URL, {
|
|
198
198
|
method: 'POST',
|
|
199
199
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
200
|
-
body: JSON.stringify(request)
|
|
201
|
-
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
200
|
+
body: JSON.stringify(request)
|
|
202
201
|
});
|
|
203
202
|
|
|
204
203
|
if (!response.ok) {
|
|
205
204
|
const errorText = await response.text();
|
|
206
|
-
|
|
205
|
+
if (shouldLogRawProxyPayloads()) {
|
|
206
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
+
}
|
|
207
208
|
|
|
208
209
|
if (response.status === 401) {
|
|
209
210
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
package/src/index.js
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
|
-
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
7
|
import { startServer } from './server.js';
|
|
9
8
|
import { logger } from './utils/logger.js';
|
|
10
9
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -12,21 +11,7 @@ import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
|
12
11
|
const require = createRequire(import.meta.url);
|
|
13
12
|
const packageJson = require('../package.json');
|
|
14
13
|
const PORT = Number(process.env.PORT || 8081);
|
|
15
|
-
let DEPLOYMENT_MODE;
|
|
16
|
-
try {
|
|
17
|
-
DEPLOYMENT_MODE = getDeploymentMode();
|
|
18
|
-
} catch (error) {
|
|
19
|
-
console.error(error.message);
|
|
20
|
-
process.exit(1);
|
|
21
|
-
}
|
|
22
|
-
const HOST = getServerHost();
|
|
23
|
-
const BASE_URL = getLocalBaseUrl(PORT);
|
|
24
14
|
const BANNER_WIDTH = 62;
|
|
25
|
-
|
|
26
|
-
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
27
|
-
console.error('Public deployment mode requires a UI/admin access key.');
|
|
28
|
-
process.exit(1);
|
|
29
|
-
}
|
|
30
15
|
const centerBannerText = (text) => {
|
|
31
16
|
const padding = Math.max(0, BANNER_WIDTH - text.length);
|
|
32
17
|
const left = Math.floor(padding / 2);
|
|
@@ -34,21 +19,18 @@ const centerBannerText = (text) => {
|
|
|
34
19
|
return `${' '.repeat(left)}${text}${' '.repeat(right)}`;
|
|
35
20
|
};
|
|
36
21
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
startServer({ port: PORT, host: HOST });
|
|
22
|
+
startServer({ port: PORT });
|
|
40
23
|
|
|
41
24
|
console.log(`
|
|
42
25
|
╔══════════════════════════════════════════════════════════════╗
|
|
43
26
|
║${centerBannerText(`Claude Codex Proxy v${packageJson.version}`)}║
|
|
44
|
-
|
|
27
|
+
║ (Direct API Mode) ║
|
|
45
28
|
╠══════════════════════════════════════════════════════════════╣
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
${bannerLine('Logs:', `${BASE_URL}/api/logs/stream`)}
|
|
29
|
+
║ Server: http://localhost:${PORT} ║
|
|
30
|
+
║ WebUI: http://localhost:${PORT} ║
|
|
31
|
+
║ Health: http://localhost:${PORT}/health ║
|
|
32
|
+
║ Accounts: http://localhost:${PORT}/accounts ║
|
|
33
|
+
║ Logs: http://localhost:${PORT}/api/logs/stream ║
|
|
52
34
|
╠══════════════════════════════════════════════════════════════╣
|
|
53
35
|
║ Features: ║
|
|
54
36
|
║ ✓ Native tool calling support ║
|
|
@@ -66,7 +48,7 @@ const status = getStatus();
|
|
|
66
48
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
67
49
|
|
|
68
50
|
if (status.total === 0) {
|
|
69
|
-
logger.warn(`No accounts configured. Open
|
|
51
|
+
logger.warn(`No accounts configured. Open http://localhost:${PORT} to add one.`);
|
|
70
52
|
}
|
|
71
53
|
|
|
72
54
|
// Expose config path in logs for convenience
|
package/src/response-streamer.js
CHANGED
|
@@ -5,11 +5,15 @@
|
|
|
5
5
|
|
|
6
6
|
import { generateMessageId, sanitizeAnthropicToolInputJson, toAnthropicToolId } from './format-converter.js';
|
|
7
7
|
import { cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
8
|
+
import { getServerSettings } from './server-settings.js';
|
|
8
9
|
import { logger } from './utils/logger.js';
|
|
9
|
-
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
10
10
|
|
|
11
11
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
12
12
|
|
|
13
|
+
function shouldLogRawProxyPayloads() {
|
|
14
|
+
return getServerSettings().logRawProxyPayloads === true;
|
|
15
|
+
}
|
|
16
|
+
|
|
13
17
|
export function createResponsesAPIError(message, status = 502) {
|
|
14
18
|
const error = new Error(message);
|
|
15
19
|
error.status = status;
|
|
@@ -113,10 +117,6 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
113
117
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
114
118
|
enumerable: false
|
|
115
119
|
});
|
|
116
|
-
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
117
|
-
value: event.response.usage.input_tokens_details?.cache_write_tokens || 0,
|
|
118
|
-
enumerable: false
|
|
119
|
-
});
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
// Handle output item added
|
package/src/routes/api-routes.js
CHANGED
|
@@ -10,24 +10,18 @@ import { join, dirname } from 'path';
|
|
|
10
10
|
import { fileURLToPath } from 'url';
|
|
11
11
|
|
|
12
12
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
13
|
-
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
14
13
|
|
|
15
14
|
// Route handlers
|
|
16
15
|
import { handleMessages } from './messages-route.js';
|
|
17
16
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
18
17
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
19
|
-
import { handleGetClientQuota } from './client-quota-route.js';
|
|
20
18
|
import {
|
|
21
19
|
handleGetAccountStrategy,
|
|
22
20
|
handleSetAccountStrategy,
|
|
23
21
|
handleGetModelMap,
|
|
24
22
|
handleSetModelMap,
|
|
25
23
|
handleGetRawProxyLogs,
|
|
26
|
-
handleSetRawProxyLogs
|
|
27
|
-
handleListClientApiKeys,
|
|
28
|
-
handleCreateClientApiKey,
|
|
29
|
-
handleUpdateClientApiKey,
|
|
30
|
-
handleDeleteClientApiKey
|
|
24
|
+
handleSetRawProxyLogs
|
|
31
25
|
} from './settings-route.js';
|
|
32
26
|
import { handleGetLogs, handleStreamLogs } from './logs-route.js';
|
|
33
27
|
import { handleGetClaudeConfig, handleSetProxyMode, handleSetDirectMode, handleSetClaudeApiEndpoint } from './claude-config-route.js';
|
|
@@ -53,48 +47,22 @@ const packageJson = require('../../package.json');
|
|
|
53
47
|
|
|
54
48
|
export function registerApiRoutes(app, { port }) {
|
|
55
49
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
56
|
-
|
|
57
|
-
app.use(express.static(publicDirectory));
|
|
58
|
-
|
|
59
|
-
app.get(['/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], (req, res) => {
|
|
60
|
-
res.sendFile(join(publicDirectory, 'index.html'));
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
app.get('/login', (req, res) => {
|
|
64
|
-
res.sendFile(join(publicDirectory, 'login.html'));
|
|
65
|
-
});
|
|
50
|
+
app.use(express.static(join(__dirname, '..', '..', 'public')));
|
|
66
51
|
|
|
67
52
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
68
53
|
app.get('/health', (req, res) => {
|
|
69
|
-
|
|
70
|
-
status: 'ok',
|
|
71
|
-
version: packageJson.version,
|
|
72
|
-
publicMode: isPublicDeployment()
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
if (!isPublicDeployment()) {
|
|
76
|
-
Object.assign(health, getStatus(), { configPath: ACCOUNTS_FILE });
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
res.json(health);
|
|
54
|
+
res.json({ status: 'ok', version: packageJson.version, ...getStatus(), configPath: ACCOUNTS_FILE });
|
|
80
55
|
});
|
|
81
56
|
|
|
82
|
-
// ─── Public Claude CLI Configuration Helper ───────────────────────────────
|
|
83
|
-
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
84
|
-
|
|
85
57
|
// ─── Anthropic Messages API ────────────────────────────────────────────────
|
|
86
|
-
app.post('/v1/messages',
|
|
87
|
-
app.post('/v1/messages/count_tokens',
|
|
58
|
+
app.post('/v1/messages', handleMessages);
|
|
59
|
+
app.post('/v1/messages/count_tokens', handleCountTokens);
|
|
88
60
|
|
|
89
61
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
90
|
-
app.post('/v1/chat/completions',
|
|
91
|
-
|
|
92
|
-
// ─── Models and Client Quota ───────────────────────────────────────────────
|
|
93
|
-
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
94
|
-
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
95
|
-
|
|
96
|
-
app.use(requireAdminAuth);
|
|
62
|
+
app.post('/v1/chat/completions', handleChatCompletion);
|
|
97
63
|
|
|
64
|
+
// ─── Models ────────────────────────────────────────────────────────────────
|
|
65
|
+
app.get('/v1/models', handleListModels);
|
|
98
66
|
app.get('/accounts/models', handleAccountModels);
|
|
99
67
|
app.get('/accounts/usage', handleAccountUsage);
|
|
100
68
|
|
|
@@ -105,10 +73,6 @@ export function registerApiRoutes(app, { port }) {
|
|
|
105
73
|
app.post('/settings/model-map', handleSetModelMap);
|
|
106
74
|
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
107
75
|
app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
108
|
-
app.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
109
|
-
app.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
110
|
-
app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
111
|
-
app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
112
76
|
|
|
113
77
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
114
78
|
app.get('/accounts', handleListAccounts);
|
|
@@ -129,6 +93,7 @@ export function registerApiRoutes(app, { port }) {
|
|
|
129
93
|
|
|
130
94
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
131
95
|
app.get('/claude/config', handleGetClaudeConfig);
|
|
96
|
+
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
132
97
|
app.post('/claude/config/direct', handleSetDirectMode);
|
|
133
98
|
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
134
99
|
|
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
|
|
@@ -9,32 +9,11 @@
|
|
|
9
9
|
|
|
10
10
|
import {
|
|
11
11
|
readClaudeConfig,
|
|
12
|
+
setProxyMode,
|
|
12
13
|
setDirectMode,
|
|
13
14
|
setApiEndpoint,
|
|
14
15
|
getClaudeConfigPath
|
|
15
16
|
} from '../claude-config.js';
|
|
16
|
-
import { getLocalBaseUrl } from '../deployment.js';
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Resolves the proxy URL shown to users without writing local config files.
|
|
20
|
-
* @param {object} req
|
|
21
|
-
* @param {number|string} port
|
|
22
|
-
* @returns {string}
|
|
23
|
-
*/
|
|
24
|
-
function getProxyConfigBaseUrl(req, port) {
|
|
25
|
-
if (process.env.PROXY_PUBLIC_BASE_URL) {
|
|
26
|
-
return process.env.PROXY_PUBLIC_BASE_URL.replace(/\/$/, '');
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const host = req.get?.('host');
|
|
30
|
-
if (host) {
|
|
31
|
-
const forwardedProto = req.get?.('x-forwarded-proto')?.split(',')[0]?.trim();
|
|
32
|
-
const protocol = forwardedProto || req.protocol || 'http';
|
|
33
|
-
return `${protocol}://${host}`;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return getLocalBaseUrl(port);
|
|
37
|
-
}
|
|
38
17
|
|
|
39
18
|
/**
|
|
40
19
|
* GET /claude/config
|
|
@@ -52,35 +31,21 @@ export async function handleGetClaudeConfig(req, res) {
|
|
|
52
31
|
|
|
53
32
|
/**
|
|
54
33
|
* POST /claude/config/proxy
|
|
55
|
-
*
|
|
34
|
+
* Configures Claude CLI to use this proxy server.
|
|
56
35
|
*/
|
|
57
36
|
export async function handleSetProxyMode(req, res, { port }) {
|
|
58
37
|
try {
|
|
59
|
-
const proxyUrl =
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
65
|
-
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
66
|
-
],
|
|
67
|
-
powershell: [
|
|
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
|
-
]
|
|
38
|
+
const proxyUrl = `http://localhost:${port}`;
|
|
39
|
+
const models = {
|
|
40
|
+
opus: 'claude-opus',
|
|
41
|
+
sonnet: 'claude-sonnet',
|
|
42
|
+
haiku: 'claude-haiku'
|
|
72
43
|
};
|
|
73
|
-
|
|
44
|
+
const config = await setProxyMode(proxyUrl, models);
|
|
74
45
|
res.json({
|
|
75
46
|
success: true,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
env: {
|
|
79
|
-
ANTHROPIC_BASE_URL: proxyUrl,
|
|
80
|
-
ANTHROPIC_API_KEY: apiKeyPlaceholder,
|
|
81
|
-
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
82
|
-
},
|
|
83
|
-
commands
|
|
47
|
+
message: `Claude CLI configured to use proxy at ${proxyUrl}`,
|
|
48
|
+
config
|
|
84
49
|
});
|
|
85
50
|
} catch (error) {
|
|
86
51
|
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
|
/**
|
|
@@ -6,9 +6,6 @@ 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';
|
|
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);
|
|
@@ -100,9 +97,9 @@ export async function handleMessages(req, res) {
|
|
|
100
97
|
|
|
101
98
|
try {
|
|
102
99
|
if (isStreaming) {
|
|
103
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
100
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
104
101
|
} else {
|
|
105
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
102
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
106
103
|
}
|
|
107
104
|
rotator.notifySuccess(account, upstreamModel);
|
|
108
105
|
return;
|
|
@@ -137,41 +134,20 @@ export async function handleMessages(req, res) {
|
|
|
137
134
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
138
135
|
}
|
|
139
136
|
|
|
140
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
137
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
141
138
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
142
139
|
initSSEResponse(res);
|
|
143
140
|
const usage = await pipeSSEStream(res, stream);
|
|
144
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
145
141
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
146
142
|
}
|
|
147
143
|
|
|
148
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
144
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
149
145
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
151
146
|
const duration = Date.now() - startTime;
|
|
152
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
153
148
|
res.json({ ...response, model: responseModel });
|
|
154
149
|
}
|
|
155
150
|
|
|
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
|
-
|
|
175
151
|
function syncActiveAccount(email) {
|
|
176
152
|
const active = getActiveAccount();
|
|
177
153
|
if (active?.email === email) return;
|