claude-codex-proxy 1.0.5-beta.4 → 1.0.5-beta.40
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/js/app.js +105 -26
- package/public/views/accounts-modals.html +90 -29
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +10 -1
- package/public/views/client-api-keys.html +68 -39
- package/public/views/logs.html +10 -3
- package/public/views/settings.html +11 -1
- package/src/account-manager.js +34 -3
- package/src/account-rotation/index.js +6 -0
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/round-robin-strategy.js +78 -3
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -125
- package/src/daily-anchor-ping.js +149 -0
- package/src/direct-api.js +6 -5
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +23 -20
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +72 -30
- package/src/model-api.js +86 -13
- package/src/model-pricing.js +187 -96
- package/src/response-streamer.js +18 -2
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +5 -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 +135 -55
- package/src/routes/models-route.js +5 -0
- package/src/routes/settings-route.js +40 -10
- package/src/server-settings.js +9 -2
- package/src/server.js +4 -0
- package/src/utils/logger.js +34 -2
- package/src/utils/proxy-logging.js +5 -5
package/src/format-converter.js
CHANGED
|
@@ -8,6 +8,7 @@ import { cleanCacheControl, processAssistantContent, hasUnsignedThinkingBlocks }
|
|
|
8
8
|
import { getCachedSignature, cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
9
9
|
|
|
10
10
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
11
|
+
const SUPPORTED_REASONING_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Convert Anthropic tool ID to OpenAI fc_ format
|
|
@@ -146,11 +147,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
146
147
|
const instructions = extractSystemPrompt(system);
|
|
147
148
|
|
|
148
149
|
const request = {
|
|
149
|
-
model: model
|
|
150
|
+
model: model,
|
|
150
151
|
input: convertMessagesToInput(cleanedMessages),
|
|
151
152
|
tools: tools ? convertAnthropicToolsToOpenAI(tools) : [],
|
|
152
|
-
tool_choice:
|
|
153
|
-
parallel_tool_calls: true,
|
|
153
|
+
tool_choice: 'auto',
|
|
154
|
+
parallel_tool_calls: tool_choice?.disable_parallel_tool_use !== true,
|
|
154
155
|
store: false,
|
|
155
156
|
stream: true,
|
|
156
157
|
include: []
|
|
@@ -162,6 +163,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
162
163
|
request.instructions = '';
|
|
163
164
|
}
|
|
164
165
|
|
|
166
|
+
const effort = anthropicRequest.output_config?.effort;
|
|
167
|
+
if (SUPPORTED_REASONING_EFFORTS.has(effort)) {
|
|
168
|
+
request.reasoning = { effort };
|
|
169
|
+
}
|
|
170
|
+
|
|
165
171
|
return request;
|
|
166
172
|
}
|
|
167
173
|
|
|
@@ -177,23 +183,7 @@ function convertMessagesToInput(messages) {
|
|
|
177
183
|
|
|
178
184
|
for (const msg of messages) {
|
|
179
185
|
if (msg.role === 'user') {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (textParts.length > 0) {
|
|
183
|
-
// API accepts: string OR array of {type: 'input_text', text: '...'}
|
|
184
|
-
const content = textParts.length === 1
|
|
185
|
-
? textParts[0] // Use string for single text
|
|
186
|
-
: textParts.map(text => ({ type: 'input_text', text }));
|
|
187
|
-
input.push({
|
|
188
|
-
type: 'message',
|
|
189
|
-
role: 'user',
|
|
190
|
-
content
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
for (const result of toolResults) {
|
|
195
|
-
input.push(result);
|
|
196
|
-
}
|
|
186
|
+
input.push(...convertUserContent(msg.content));
|
|
197
187
|
} else if (msg.role === 'assistant') {
|
|
198
188
|
// Process assistant content: restore signatures, reorder, sanitize
|
|
199
189
|
let msgContent = msg.content;
|
|
@@ -225,34 +215,62 @@ function convertMessagesToInput(messages) {
|
|
|
225
215
|
}
|
|
226
216
|
|
|
227
217
|
/**
|
|
228
|
-
* Convert user content
|
|
218
|
+
* Convert Anthropic user content while preserving block order.
|
|
229
219
|
*/
|
|
230
220
|
function convertUserContent(content) {
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
221
|
+
const inputItems = [];
|
|
222
|
+
let messageParts = [];
|
|
223
|
+
|
|
224
|
+
const flushMessageParts = () => {
|
|
225
|
+
if (messageParts.length === 0) return;
|
|
226
|
+
|
|
227
|
+
const messageContent =
|
|
228
|
+
messageParts.length === 1 && messageParts[0].type === 'input_text'
|
|
229
|
+
? messageParts[0].text
|
|
230
|
+
: messageParts;
|
|
231
|
+
|
|
232
|
+
inputItems.push({
|
|
233
|
+
type: 'message',
|
|
234
|
+
role: 'user',
|
|
235
|
+
content: messageContent
|
|
236
|
+
});
|
|
237
|
+
messageParts = [];
|
|
238
|
+
};
|
|
239
|
+
|
|
234
240
|
if (typeof content === 'string') {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
textParts.push(block.text);
|
|
240
|
-
} else if (block.type === 'tool_result') {
|
|
241
|
-
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
241
|
+
messageParts.push({ type: 'input_text', text: content });
|
|
242
|
+
flushMessageParts();
|
|
243
|
+
return inputItems;
|
|
244
|
+
}
|
|
242
245
|
|
|
243
|
-
|
|
244
|
-
|
|
246
|
+
if (!Array.isArray(content)) {
|
|
247
|
+
return inputItems;
|
|
248
|
+
}
|
|
245
249
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
250
|
+
for (const block of content) {
|
|
251
|
+
if (!block || typeof block !== 'object') continue;
|
|
252
|
+
|
|
253
|
+
if (block.type === 'text') {
|
|
254
|
+
messageParts.push({ type: 'input_text', text: block.text || '' });
|
|
255
|
+
} else if (block.type === 'image') {
|
|
256
|
+
const image = convertAnthropicImageToResponsesInputImage(block);
|
|
257
|
+
if (image) messageParts.push(image);
|
|
258
|
+
} else if (block.type === 'tool_result') {
|
|
259
|
+
flushMessageParts();
|
|
260
|
+
|
|
261
|
+
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
262
|
+
const callId = toOpenAIToolId(block.tool_use_id);
|
|
263
|
+
|
|
264
|
+
inputItems.push({
|
|
265
|
+
type: 'function_call_output',
|
|
266
|
+
call_id: callId,
|
|
267
|
+
output: block.is_error ? prefixToolErrorOutput(outputContent) : outputContent
|
|
268
|
+
});
|
|
252
269
|
}
|
|
253
270
|
}
|
|
254
|
-
|
|
255
|
-
|
|
271
|
+
|
|
272
|
+
flushMessageParts();
|
|
273
|
+
return inputItems;
|
|
256
274
|
}
|
|
257
275
|
|
|
258
276
|
/**
|
|
@@ -310,19 +328,36 @@ function convertAssistantContentToOpenAI(content) {
|
|
|
310
328
|
}
|
|
311
329
|
|
|
312
330
|
/**
|
|
313
|
-
* Convert Anthropic tools to OpenAI
|
|
331
|
+
* Convert Anthropic tools to OpenAI Responses API tool format.
|
|
314
332
|
*/
|
|
315
333
|
function convertAnthropicToolsToOpenAI(tools) {
|
|
316
334
|
if (!Array.isArray(tools)) {
|
|
317
335
|
return [];
|
|
318
336
|
}
|
|
319
337
|
|
|
320
|
-
return tools.map(tool =>
|
|
321
|
-
type
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
338
|
+
return tools.map(tool => {
|
|
339
|
+
if (tool.type === 'web_search_20250305' && tool.name === 'web_search') {
|
|
340
|
+
const webSearchTool = {
|
|
341
|
+
type: 'web_search',
|
|
342
|
+
external_web_access: true
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
if (Array.isArray(tool.allowed_domains)) {
|
|
346
|
+
webSearchTool.filters = {
|
|
347
|
+
allowed_domains: tool.allowed_domains
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return webSearchTool;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
type: 'function',
|
|
356
|
+
name: tool.name,
|
|
357
|
+
description: tool.description || '',
|
|
358
|
+
parameters: sanitizeSchema(tool.input_schema || { type: 'object' })
|
|
359
|
+
};
|
|
360
|
+
});
|
|
326
361
|
}
|
|
327
362
|
|
|
328
363
|
function sanitizeAnthropicToolInput(name, input) {
|
package/src/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
+
import { getAdminPath } from './admin-path.js';
|
|
8
9
|
import { startServer } from './server.js';
|
|
9
10
|
import { logger } from './utils/logger.js';
|
|
10
11
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -21,6 +22,14 @@ try {
|
|
|
21
22
|
}
|
|
22
23
|
const HOST = getServerHost();
|
|
23
24
|
const BASE_URL = getLocalBaseUrl(PORT);
|
|
25
|
+
let ADMIN_PATH;
|
|
26
|
+
try {
|
|
27
|
+
ADMIN_PATH = getAdminPath();
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error(error.message);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
const ADMIN_URL = `${BASE_URL}${ADMIN_PATH}`;
|
|
24
33
|
const BANNER_WIDTH = 62;
|
|
25
34
|
|
|
26
35
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -45,10 +54,10 @@ console.log(`
|
|
|
45
54
|
╠══════════════════════════════════════════════════════════════╣
|
|
46
55
|
${bannerLine('Host:', HOST)}
|
|
47
56
|
${bannerLine('Server:', BASE_URL)}
|
|
48
|
-
${bannerLine('WebUI:',
|
|
57
|
+
${bannerLine('WebUI:', ADMIN_URL)}
|
|
49
58
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
50
|
-
${bannerLine('Accounts:', `${
|
|
51
|
-
${bannerLine('Logs:', `${
|
|
59
|
+
${bannerLine('Accounts:', `${ADMIN_URL}/accounts`)}
|
|
60
|
+
${bannerLine('Logs:', `${ADMIN_URL}/api/logs/stream`)}
|
|
52
61
|
╠══════════════════════════════════════════════════════════════╣
|
|
53
62
|
║ Features: ║
|
|
54
63
|
║ ✓ Native tool calling support ║
|
|
@@ -66,7 +75,7 @@ const status = getStatus();
|
|
|
66
75
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
67
76
|
|
|
68
77
|
if (status.total === 0) {
|
|
69
|
-
logger.warn(`No accounts configured. Open ${
|
|
78
|
+
logger.warn(`No accounts configured. Open ${ADMIN_URL} to add one.`);
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
// Expose config path in logs for convenience
|
package/src/middleware/auth.js
CHANGED
|
@@ -2,6 +2,7 @@ import crypto from 'crypto';
|
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
3
|
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
4
|
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
5
|
+
import { createErrorResponse } from './sse.js';
|
|
5
6
|
|
|
6
7
|
function timingSafeEqualString(a, b) {
|
|
7
8
|
const left = Buffer.from(String(a));
|
|
@@ -26,7 +27,7 @@ function getRequestApiKey(req) {
|
|
|
26
27
|
return String(headerKey).trim();
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
const queryKey = req.query?.api_key
|
|
30
|
+
const queryKey = req.query?.api_key;
|
|
30
31
|
if (queryKey) {
|
|
31
32
|
return String(queryKey).trim();
|
|
32
33
|
}
|
|
@@ -36,10 +37,9 @@ function getRequestApiKey(req) {
|
|
|
36
37
|
|
|
37
38
|
function sendUnauthorized(req, res) {
|
|
38
39
|
if (req.path?.startsWith('/v1/')) {
|
|
39
|
-
return res.status(401).json(
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
});
|
|
40
|
+
return res.status(401).json(
|
|
41
|
+
createErrorResponse('authentication_error', 'Invalid API key')
|
|
42
|
+
);
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
@@ -65,14 +65,10 @@ function requireKeys(getExpectedKeys) {
|
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
function sendQuotaExceeded(res,
|
|
69
|
-
return res.status(429).json(
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
type: 'rate_limit_error',
|
|
73
|
-
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
-
}
|
|
75
|
-
});
|
|
68
|
+
function sendQuotaExceeded(res, period, resetsAt) {
|
|
69
|
+
return res.status(429).json(
|
|
70
|
+
createErrorResponse('rate_limit_error', `${period} client key quota exhausted. Resets at ${resetsAt}`)
|
|
71
|
+
);
|
|
76
72
|
}
|
|
77
73
|
|
|
78
74
|
function findClientKey(requestKey) {
|
|
@@ -84,25 +80,32 @@ const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
|
84
80
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
85
81
|
|
|
86
82
|
export function requireClientAuth(req, res, next) {
|
|
87
|
-
if (!isPublicDeployment()) {
|
|
88
|
-
return next();
|
|
89
|
-
}
|
|
90
|
-
|
|
91
83
|
const requestKey = getRequestApiKey(req);
|
|
92
84
|
const clientKey = findClientKey(requestKey);
|
|
93
|
-
if (!clientKey) {
|
|
85
|
+
if (isPublicDeployment() && !clientKey) {
|
|
94
86
|
return sendUnauthorized(req, res);
|
|
95
87
|
}
|
|
96
88
|
|
|
89
|
+
if (!clientKey) {
|
|
90
|
+
return next();
|
|
91
|
+
}
|
|
92
|
+
|
|
97
93
|
const quota = getClientKeyQuota(
|
|
98
94
|
clientKey.id,
|
|
99
|
-
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
95
|
+
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
96
|
+
{
|
|
97
|
+
enabled: clientKey.fiveHourLimitEnabled,
|
|
98
|
+
usd: clientKey.fiveHourLimitUsd
|
|
99
|
+
}
|
|
100
100
|
);
|
|
101
101
|
const isModelRequest = req.method === 'POST' && (
|
|
102
102
|
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
103
|
);
|
|
104
|
+
if (isModelRequest && quota.fiveHourLimitEnabled && quota.fiveHourRemainingMicrousd <= 0) {
|
|
105
|
+
return sendQuotaExceeded(res, 'Five-hour', quota.nextFiveHourPeriodStart);
|
|
106
|
+
}
|
|
104
107
|
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
105
|
-
return sendQuotaExceeded(res, quota);
|
|
108
|
+
return sendQuotaExceeded(res, 'Weekly', quota.nextPeriodStart);
|
|
106
109
|
}
|
|
107
110
|
|
|
108
111
|
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
@@ -8,9 +8,11 @@ import {
|
|
|
8
8
|
getActiveAccount,
|
|
9
9
|
refreshAccountToken,
|
|
10
10
|
isTokenExpiredOrExpiringSoon,
|
|
11
|
+
isAccountExpired,
|
|
11
12
|
loadAccounts
|
|
12
13
|
} from '../account-manager.js';
|
|
13
14
|
import { logger } from '../utils/logger.js';
|
|
15
|
+
import { createErrorResponse } from './sse.js';
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* Resolves the active account credentials, refreshing the token if needed.
|
|
@@ -26,6 +28,11 @@ export async function getCredentialsOrError() {
|
|
|
26
28
|
return null;
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
if (isAccountExpired(account)) {
|
|
32
|
+
logger.info(`Account ${account.email} has expired`);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
29
36
|
if (!account.accessToken || !account.accountId) {
|
|
30
37
|
logger.info(`Account ${account.email} missing token or accountId`);
|
|
31
38
|
return null;
|
|
@@ -41,8 +48,8 @@ export async function getCredentialsOrError() {
|
|
|
41
48
|
}
|
|
42
49
|
|
|
43
50
|
const refreshedAccount = getActiveAccount();
|
|
44
|
-
if (!refreshedAccount) {
|
|
45
|
-
logger.error('Failed to get refreshed account');
|
|
51
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) {
|
|
52
|
+
logger.error('Failed to get refreshed active account');
|
|
46
53
|
return null;
|
|
47
54
|
}
|
|
48
55
|
|
|
@@ -74,6 +81,10 @@ export async function getCredentialsForAccount(email) {
|
|
|
74
81
|
return null;
|
|
75
82
|
}
|
|
76
83
|
|
|
84
|
+
if (isAccountExpired(account)) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
77
88
|
if (!account.accessToken || !account.accountId) {
|
|
78
89
|
return null;
|
|
79
90
|
}
|
|
@@ -85,7 +96,7 @@ export async function getCredentialsForAccount(email) {
|
|
|
85
96
|
}
|
|
86
97
|
const refreshedData = loadAccounts();
|
|
87
98
|
const refreshedAccount = refreshedData.accounts.find(a => a.email === email);
|
|
88
|
-
if (!refreshedAccount) return null;
|
|
99
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) return null;
|
|
89
100
|
|
|
90
101
|
return {
|
|
91
102
|
accessToken: refreshedAccount.accessToken,
|
|
@@ -107,10 +118,9 @@ export async function getCredentialsForAccount(email) {
|
|
|
107
118
|
* @param {string} [message]
|
|
108
119
|
*/
|
|
109
120
|
export function sendAuthError(res, message = 'No active account with valid credentials. Add an account via /accounts/add') {
|
|
110
|
-
return res.status(401).json(
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
});
|
|
121
|
+
return res.status(401).json(
|
|
122
|
+
createErrorResponse('authentication_error', message)
|
|
123
|
+
);
|
|
114
124
|
}
|
|
115
125
|
|
|
116
126
|
export default { getCredentialsOrError, getCredentialsForAccount, sendAuthError };
|
package/src/middleware/sse.js
CHANGED
|
@@ -7,6 +7,24 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
7
7
|
import { formatSSEEvent } from '../response-streamer.js';
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
+
function createEmptyUsage() {
|
|
11
|
+
return {
|
|
12
|
+
input_tokens: 0,
|
|
13
|
+
output_tokens: 0,
|
|
14
|
+
cache_creation_input_tokens: 0,
|
|
15
|
+
cache_read_input_tokens: 0
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createErrorResponse(errorType, message, extraErrorFields = {}) {
|
|
20
|
+
return {
|
|
21
|
+
type: 'error',
|
|
22
|
+
error: { type: errorType, message, ...extraErrorFields },
|
|
23
|
+
// Claude Code may still read usage on exceptional responses (for example Agent startup failures).
|
|
24
|
+
usage: createEmptyUsage()
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
/**
|
|
11
29
|
* Sets the standard SSE response headers and flushes them.
|
|
12
30
|
* @param {import('express').Response} res
|
|
@@ -48,32 +66,58 @@ export async function pipeSSEStream(res, eventStream) {
|
|
|
48
66
|
* @param {Error} error
|
|
49
67
|
* @param {string} model
|
|
50
68
|
* @param {number} startTime
|
|
69
|
+
* @param {string} [requestedModel] Client-provided model name before routing.
|
|
51
70
|
*/
|
|
52
|
-
export function handleStreamError(res, error, model, startTime) {
|
|
71
|
+
export function handleStreamError(res, error, model, startTime, requestedModel) {
|
|
53
72
|
const duration = Date.now() - startTime;
|
|
54
73
|
const status = getErrorStatus(error);
|
|
55
74
|
const errorType = getAnthropicErrorType(error, status);
|
|
56
75
|
const loggedModel = typeof model === 'string' && model.toLowerCase().startsWith('claude-')
|
|
57
76
|
? resolveModelRouting(model).upstreamModel
|
|
58
77
|
: model;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
78
|
+
const isStreamError = res.headersSent;
|
|
79
|
+
const logDetails = {
|
|
80
|
+
model: loggedModel,
|
|
81
|
+
requestedModel,
|
|
82
|
+
transport: isStreamError ? 'sse' : 'http',
|
|
83
|
+
clientHttpStatus: isStreamError ? res.statusCode : status,
|
|
84
|
+
errorType,
|
|
85
|
+
retrySignal: errorType === 'overloaded_error',
|
|
86
|
+
errorName: error?.name,
|
|
87
|
+
errorCode: error?.code,
|
|
88
|
+
upstreamStatus: error?.upstreamStatus,
|
|
89
|
+
isUpstreamError: error?.isUpstreamError === true,
|
|
90
|
+
error: error?.message,
|
|
91
|
+
duration
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
if (isStreamError) {
|
|
95
|
+
const socketDestroyed = res.destroyed === true || res.socket?.destroyed === true;
|
|
96
|
+
const writableEnded = res.writableEnded === true;
|
|
97
|
+
const sseWriteAttempted = !socketDestroyed && !writableEnded;
|
|
98
|
+
let sseWriteBackpressure = false;
|
|
99
|
+
if (sseWriteAttempted) {
|
|
100
|
+
sseWriteBackpressure = !res.write(
|
|
101
|
+
`event: error\ndata: ${JSON.stringify(createErrorResponse(errorType, getClientErrorMessage(error)))}\n\n`
|
|
102
|
+
);
|
|
103
|
+
res.end();
|
|
104
|
+
}
|
|
105
|
+
logger.response(status, {
|
|
106
|
+
...logDetails,
|
|
107
|
+
sseWriteAttempted,
|
|
108
|
+
sseWriteBackpressure,
|
|
109
|
+
socketDestroyed,
|
|
110
|
+
writableEnded
|
|
111
|
+
});
|
|
69
112
|
return;
|
|
70
113
|
}
|
|
71
114
|
|
|
115
|
+
logger.response(status, logDetails);
|
|
116
|
+
|
|
72
117
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
73
|
-
return res.status(401).json(
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
});
|
|
118
|
+
return res.status(401).json(
|
|
119
|
+
createErrorResponse('authentication_error', 'Token expired. Please refresh or re-authenticate.')
|
|
120
|
+
);
|
|
77
121
|
}
|
|
78
122
|
|
|
79
123
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -81,28 +125,23 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
81
125
|
const resetMs = parseInt(parts[1], 10);
|
|
82
126
|
const errorText = parts.slice(2).join(':') || error.message;
|
|
83
127
|
|
|
84
|
-
return res.status(429).json(
|
|
85
|
-
|
|
86
|
-
error: {
|
|
87
|
-
type: 'rate_limit_error',
|
|
88
|
-
message: errorText,
|
|
128
|
+
return res.status(429).json(
|
|
129
|
+
createErrorResponse('rate_limit_error', errorText, {
|
|
89
130
|
resetMs: resetMs,
|
|
90
131
|
resetSeconds: Math.round(resetMs / 1000)
|
|
91
|
-
}
|
|
92
|
-
|
|
132
|
+
})
|
|
133
|
+
);
|
|
93
134
|
}
|
|
94
135
|
|
|
95
136
|
if (error.message.includes('RESOURCE_EXHAUSTED')) {
|
|
96
|
-
return res.status(429).json(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
});
|
|
137
|
+
return res.status(429).json(
|
|
138
|
+
createErrorResponse('rate_limit_error', error.message)
|
|
139
|
+
);
|
|
100
140
|
}
|
|
101
141
|
|
|
102
|
-
res.status(status).json(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
});
|
|
142
|
+
res.status(status).json(
|
|
143
|
+
createErrorResponse(errorType, getClientErrorMessage(error))
|
|
144
|
+
);
|
|
106
145
|
}
|
|
107
146
|
|
|
108
147
|
function getErrorStatus(error) {
|
|
@@ -115,6 +154,9 @@ function getErrorStatus(error) {
|
|
|
115
154
|
}
|
|
116
155
|
|
|
117
156
|
function getAnthropicErrorType(error, status) {
|
|
157
|
+
// Claude Code retries streamed overload errors by their Anthropic error type.
|
|
158
|
+
// HTTP status is already committed after SSE starts, so preserve 5xx semantics here.
|
|
159
|
+
if (status >= 500) return 'overloaded_error';
|
|
118
160
|
if (error?.anthropicErrorType) return error.anthropicErrorType;
|
|
119
161
|
if (status === 401) return 'authentication_error';
|
|
120
162
|
if (status === 429) return 'rate_limit_error';
|
package/src/model-api.js
CHANGED
|
@@ -72,27 +72,40 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
72
72
|
|
|
73
73
|
const data = await response.json();
|
|
74
74
|
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
const usedPercent = Number.isFinite(usedPercentRaw) ? usedPercentRaw : 0;
|
|
75
|
+
const normalizeWindow = (window) => {
|
|
76
|
+
if (!window) return null;
|
|
78
77
|
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
const usedPercentRaw = Number(window.used_percent);
|
|
79
|
+
const usedPercent = Number.isFinite(usedPercentRaw) ? usedPercentRaw : 0;
|
|
80
|
+
const limitWindowSecondsRaw = Number(window.limit_window_seconds);
|
|
81
|
+
const resetAfterSecondsRaw = Number(window.reset_after_seconds);
|
|
82
|
+
const resetAtEpoch = Number(window.reset_at);
|
|
81
83
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
+
return {
|
|
85
|
+
usedPercent,
|
|
86
|
+
remainingPercent: Math.max(0, 100 - usedPercent),
|
|
87
|
+
limitWindowSeconds: Number.isFinite(limitWindowSecondsRaw) ? limitWindowSecondsRaw : null,
|
|
88
|
+
resetAfterSeconds: Number.isFinite(resetAfterSecondsRaw) ? resetAfterSecondsRaw : null,
|
|
89
|
+
resetAt: Number.isFinite(resetAtEpoch) && resetAtEpoch > 0
|
|
90
|
+
? new Date(resetAtEpoch * 1000).toISOString()
|
|
91
|
+
: null
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const primaryWindow = normalizeWindow(data.rate_limit?.primary_window);
|
|
96
|
+
const secondaryWindow = normalizeWindow(data.rate_limit?.secondary_window);
|
|
97
|
+
const usedPercent = primaryWindow?.usedPercent ?? 0;
|
|
84
98
|
|
|
85
|
-
const resetAtEpoch = Number(primaryWindow?.reset_at);
|
|
86
|
-
const resetAt = Number.isFinite(resetAtEpoch) ? new Date(resetAtEpoch * 1000).toISOString() : null;
|
|
87
|
-
|
|
88
99
|
return {
|
|
89
100
|
totalTokenUsage: usedPercent,
|
|
90
101
|
limit: 100,
|
|
91
102
|
remaining: 100 - usedPercent,
|
|
92
103
|
percentage: usedPercent,
|
|
93
|
-
resetAt: resetAt,
|
|
94
|
-
resetAfterSeconds: resetAfterSeconds,
|
|
95
|
-
limitWindowSeconds: limitWindowSeconds,
|
|
104
|
+
resetAt: primaryWindow?.resetAt ?? null,
|
|
105
|
+
resetAfterSeconds: primaryWindow?.resetAfterSeconds ?? null,
|
|
106
|
+
limitWindowSeconds: primaryWindow?.limitWindowSeconds ?? null,
|
|
107
|
+
primaryWindow,
|
|
108
|
+
secondaryWindow,
|
|
96
109
|
planType: data.plan_type || null,
|
|
97
110
|
limitReached: data.rate_limit?.limit_reached || false,
|
|
98
111
|
allowed: data.rate_limit?.allowed ?? true,
|
|
@@ -100,6 +113,64 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
100
113
|
};
|
|
101
114
|
}
|
|
102
115
|
|
|
116
|
+
/**
|
|
117
|
+
* Lists the account's available rate-limit reset credits.
|
|
118
|
+
* @param {string} accessToken
|
|
119
|
+
* @param {string} accountId
|
|
120
|
+
* @returns {Promise<object>}
|
|
121
|
+
*/
|
|
122
|
+
export async function fetchRateLimitResetCredits(accessToken, accountId) {
|
|
123
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
|
|
124
|
+
method: 'GET',
|
|
125
|
+
headers: {
|
|
126
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
127
|
+
'ChatGPT-Account-ID': accountId,
|
|
128
|
+
'Accept': 'application/json',
|
|
129
|
+
'User-Agent': 'codex-cli'
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
if (!response.ok) {
|
|
134
|
+
const errorText = await response.text();
|
|
135
|
+
throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return await response.json();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Redeems a rate-limit reset credit for an account.
|
|
143
|
+
* @param {string} accessToken
|
|
144
|
+
* @param {string} accountId
|
|
145
|
+
* @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
|
|
146
|
+
* @param {string|null} creditId Specific credit to redeem, or null for server selection.
|
|
147
|
+
* @returns {Promise<object>}
|
|
148
|
+
*/
|
|
149
|
+
export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
|
|
150
|
+
const body = { redeem_request_id: redeemRequestId };
|
|
151
|
+
if (creditId) body.credit_id = creditId;
|
|
152
|
+
|
|
153
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
|
|
154
|
+
method: 'POST',
|
|
155
|
+
headers: {
|
|
156
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
157
|
+
'ChatGPT-Account-ID': accountId,
|
|
158
|
+
'Content-Type': 'application/json',
|
|
159
|
+
'Accept': 'application/json',
|
|
160
|
+
'User-Agent': 'codex-cli'
|
|
161
|
+
},
|
|
162
|
+
body: JSON.stringify(body)
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
if (!response.ok) {
|
|
166
|
+
const errorText = await response.text();
|
|
167
|
+
throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const text = await response.text();
|
|
171
|
+
return text ? JSON.parse(text) : {};
|
|
172
|
+
}
|
|
173
|
+
|
|
103
174
|
export async function fetchAccountCheck(accessToken, accountId) {
|
|
104
175
|
const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
|
|
105
176
|
|
|
@@ -182,6 +253,8 @@ export function clearModelCache() {
|
|
|
182
253
|
export default {
|
|
183
254
|
fetchModels,
|
|
184
255
|
fetchUsage,
|
|
256
|
+
fetchRateLimitResetCredits,
|
|
257
|
+
consumeRateLimitResetCredit,
|
|
185
258
|
fetchAccountCheck,
|
|
186
259
|
getAccountQuota,
|
|
187
260
|
getModelsAndQuota,
|