claude-codex-proxy 1.0.5-beta.12 → 1.0.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +272 -0
- package/bin/cli.js +2 -37
- package/package.json +1 -1
- package/public/css/style.css +9 -210
- package/public/index.html +926 -32
- package/public/js/app.js +744 -108
- package/src/account-rotation/rate-limits.js +26 -0
- package/src/claude-config.js +18 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +13 -12
- package/src/index.js +4 -13
- package/src/middleware/auth.js +11 -46
- package/src/model-api.js +0 -60
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +1 -78
- package/src/routes/api-routes.js +35 -59
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +15 -22
- package/src/routes/logs-route.js +2 -21
- package/src/routes/messages-route.js +6 -30
- package/src/routes/settings-route.js +5 -36
- package/src/server-settings.js +2 -18
- package/src/utils/logger.js +0 -18
- package/public/login.html +0 -32
- package/public/views/accounts-modals.html +0 -196
- 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/admin-path.js +0 -33
- package/src/client-key-usage.js +0 -125
- package/src/model-pricing.js +0 -96
- package/src/routes/client-quota-route.js +0 -25
- package/src/utils/proxy-logging.js +0 -5
|
@@ -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/deployment.js
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Deployment policy helpers shared by server, routes and auth middleware.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Returns the validated deployment mode, defaulting to local when unset.
|
|
9
|
-
* @returns {'local'|'public'}
|
|
10
|
-
*/
|
|
11
|
-
export function getDeploymentMode() {
|
|
12
|
-
const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
13
|
-
if (!VALID_DEPLOYMENT_MODES.has(mode)) {
|
|
14
|
-
throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
|
|
15
|
-
}
|
|
16
|
-
return mode;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Indicates whether the proxy is running in public deployment mode.
|
|
21
|
-
* @returns {boolean}
|
|
22
|
-
*/
|
|
23
|
-
export function isPublicDeployment() {
|
|
24
|
-
return getDeploymentMode() === 'public';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Returns the host address the main HTTP server should bind to.
|
|
29
|
-
* @returns {string}
|
|
30
|
-
*/
|
|
31
|
-
export function getServerHost() {
|
|
32
|
-
if (process.env.HOST) {
|
|
33
|
-
return process.env.HOST;
|
|
34
|
-
}
|
|
35
|
-
return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Returns a display URL for logs and local helper responses.
|
|
40
|
-
* @param {number|string} port
|
|
41
|
-
* @returns {string}
|
|
42
|
-
*/
|
|
43
|
-
export function getLocalBaseUrl(port) {
|
|
44
|
-
const host = getServerHost();
|
|
45
|
-
const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
46
|
-
return `http://${displayHost}:${port}`;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
|
|
1
|
+
/**
|
|
2
|
+
* Deployment policy helpers shared by server, routes and auth middleware.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Returns the validated deployment mode, defaulting to local when unset.
|
|
9
|
+
* @returns {'local'|'public'}
|
|
10
|
+
*/
|
|
11
|
+
export function getDeploymentMode() {
|
|
12
|
+
const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
13
|
+
if (!VALID_DEPLOYMENT_MODES.has(mode)) {
|
|
14
|
+
throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
|
|
15
|
+
}
|
|
16
|
+
return mode;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Indicates whether the proxy is running in public deployment mode.
|
|
21
|
+
* @returns {boolean}
|
|
22
|
+
*/
|
|
23
|
+
export function isPublicDeployment() {
|
|
24
|
+
return getDeploymentMode() === 'public';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the host address the main HTTP server should bind to.
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
export function getServerHost() {
|
|
32
|
+
if (process.env.HOST) {
|
|
33
|
+
return process.env.HOST;
|
|
34
|
+
}
|
|
35
|
+
return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns a display URL for logs and local helper responses.
|
|
40
|
+
* @param {number|string} port
|
|
41
|
+
* @returns {string}
|
|
42
|
+
*/
|
|
43
|
+
export function getLocalBaseUrl(port) {
|
|
44
|
+
const host = getServerHost();
|
|
45
|
+
const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
46
|
+
return `http://${displayHost}:${port}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
|
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
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
-
import { getAdminPath } from './admin-path.js';
|
|
9
8
|
import { startServer } from './server.js';
|
|
10
9
|
import { logger } from './utils/logger.js';
|
|
11
10
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -22,14 +21,6 @@ try {
|
|
|
22
21
|
}
|
|
23
22
|
const HOST = getServerHost();
|
|
24
23
|
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}`;
|
|
33
24
|
const BANNER_WIDTH = 62;
|
|
34
25
|
|
|
35
26
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -54,10 +45,10 @@ console.log(`
|
|
|
54
45
|
╠══════════════════════════════════════════════════════════════╣
|
|
55
46
|
${bannerLine('Host:', HOST)}
|
|
56
47
|
${bannerLine('Server:', BASE_URL)}
|
|
57
|
-
${bannerLine('WebUI:',
|
|
48
|
+
${bannerLine('WebUI:', BASE_URL)}
|
|
58
49
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
59
|
-
${bannerLine('Accounts:', `${
|
|
60
|
-
${bannerLine('Logs:', `${
|
|
50
|
+
${bannerLine('Accounts:', `${BASE_URL}/accounts`)}
|
|
51
|
+
${bannerLine('Logs:', `${BASE_URL}/api/logs/stream`)}
|
|
61
52
|
╠══════════════════════════════════════════════════════════════╣
|
|
62
53
|
║ Features: ║
|
|
63
54
|
║ ✓ Native tool calling support ║
|
|
@@ -75,7 +66,7 @@ const status = getStatus();
|
|
|
75
66
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
76
67
|
|
|
77
68
|
if (status.total === 0) {
|
|
78
|
-
logger.warn(`No accounts configured. Open ${
|
|
69
|
+
logger.warn(`No accounts configured. Open ${BASE_URL} to add one.`);
|
|
79
70
|
}
|
|
80
71
|
|
|
81
72
|
// Expose config path in logs for convenience
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings
|
|
4
|
-
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
3
|
+
import { getServerSettings } from '../server-settings.js';
|
|
5
4
|
|
|
6
5
|
function timingSafeEqualString(a, b) {
|
|
7
6
|
const left = Buffer.from(String(a));
|
|
@@ -45,8 +44,10 @@ function sendUnauthorized(req, res) {
|
|
|
45
44
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
46
45
|
}
|
|
47
46
|
|
|
48
|
-
function
|
|
49
|
-
return expectedKey
|
|
47
|
+
function matchesAnyKey(requestKey, expectedKeys) {
|
|
48
|
+
return expectedKeys.some((expectedKey) => (
|
|
49
|
+
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
+
));
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
function requireKeys(getExpectedKeys) {
|
|
@@ -57,7 +58,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
57
58
|
|
|
58
59
|
const expectedKeys = getExpectedKeys();
|
|
59
60
|
const requestKey = getRequestApiKey(req);
|
|
60
|
-
if (!
|
|
61
|
+
if (!matchesAnyKey(requestKey, expectedKeys)) {
|
|
61
62
|
return sendUnauthorized(req, res);
|
|
62
63
|
}
|
|
63
64
|
|
|
@@ -65,50 +66,14 @@ function requireKeys(getExpectedKeys) {
|
|
|
65
66
|
};
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
function sendQuotaExceeded(res, quota) {
|
|
69
|
-
return res.status(429).json({
|
|
70
|
-
type: 'error',
|
|
71
|
-
error: {
|
|
72
|
-
type: 'rate_limit_error',
|
|
73
|
-
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function findClientKey(requestKey) {
|
|
79
|
-
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
80
|
-
}
|
|
81
|
-
|
|
82
69
|
const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
70
|
+
const getClientKeys = () => [
|
|
71
|
+
...getServerSettings().clientApiKeys.map(({ key }) => key),
|
|
72
|
+
process.env.PROXY_CLIENT_KEY
|
|
73
|
+
].filter(Boolean);
|
|
83
74
|
|
|
84
75
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
85
|
-
|
|
86
|
-
export function requireClientAuth(req, res, next) {
|
|
87
|
-
const requestKey = getRequestApiKey(req);
|
|
88
|
-
const clientKey = findClientKey(requestKey);
|
|
89
|
-
if (isPublicDeployment() && !clientKey) {
|
|
90
|
-
return sendUnauthorized(req, res);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
if (!clientKey) {
|
|
94
|
-
return next();
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const quota = getClientKeyQuota(
|
|
98
|
-
clientKey.id,
|
|
99
|
-
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
100
|
-
);
|
|
101
|
-
const isModelRequest = req.method === 'POST' && (
|
|
102
|
-
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
-
);
|
|
104
|
-
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
105
|
-
return sendQuotaExceeded(res, quota);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
109
|
-
req.clientApiKeyQuota = quota;
|
|
110
|
-
return next();
|
|
111
|
-
}
|
|
76
|
+
export const requireClientAuth = requireKeys(getClientKeys);
|
|
112
77
|
|
|
113
78
|
export { isPublicDeployment };
|
|
114
79
|
|
package/src/model-api.js
CHANGED
|
@@ -100,64 +100,6 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
/**
|
|
104
|
-
* Lists the account's available rate-limit reset credits.
|
|
105
|
-
* @param {string} accessToken
|
|
106
|
-
* @param {string} accountId
|
|
107
|
-
* @returns {Promise<object>}
|
|
108
|
-
*/
|
|
109
|
-
export async function fetchRateLimitResetCredits(accessToken, accountId) {
|
|
110
|
-
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
|
|
111
|
-
method: 'GET',
|
|
112
|
-
headers: {
|
|
113
|
-
'Authorization': `Bearer ${accessToken}`,
|
|
114
|
-
'ChatGPT-Account-ID': accountId,
|
|
115
|
-
'Accept': 'application/json',
|
|
116
|
-
'User-Agent': 'codex-cli'
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
if (!response.ok) {
|
|
121
|
-
const errorText = await response.text();
|
|
122
|
-
throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return await response.json();
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Redeems a rate-limit reset credit for an account.
|
|
130
|
-
* @param {string} accessToken
|
|
131
|
-
* @param {string} accountId
|
|
132
|
-
* @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
|
|
133
|
-
* @param {string|null} creditId Specific credit to redeem, or null for server selection.
|
|
134
|
-
* @returns {Promise<object>}
|
|
135
|
-
*/
|
|
136
|
-
export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
|
|
137
|
-
const body = { redeem_request_id: redeemRequestId };
|
|
138
|
-
if (creditId) body.credit_id = creditId;
|
|
139
|
-
|
|
140
|
-
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
|
|
141
|
-
method: 'POST',
|
|
142
|
-
headers: {
|
|
143
|
-
'Authorization': `Bearer ${accessToken}`,
|
|
144
|
-
'ChatGPT-Account-ID': accountId,
|
|
145
|
-
'Content-Type': 'application/json',
|
|
146
|
-
'Accept': 'application/json',
|
|
147
|
-
'User-Agent': 'codex-cli'
|
|
148
|
-
},
|
|
149
|
-
body: JSON.stringify(body)
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
if (!response.ok) {
|
|
153
|
-
const errorText = await response.text();
|
|
154
|
-
throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const text = await response.text();
|
|
158
|
-
return text ? JSON.parse(text) : {};
|
|
159
|
-
}
|
|
160
|
-
|
|
161
103
|
export async function fetchAccountCheck(accessToken, accountId) {
|
|
162
104
|
const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
|
|
163
105
|
|
|
@@ -240,8 +182,6 @@ export function clearModelCache() {
|
|
|
240
182
|
export default {
|
|
241
183
|
fetchModels,
|
|
242
184
|
fetchUsage,
|
|
243
|
-
fetchRateLimitResetCredits,
|
|
244
|
-
consumeRateLimitResetCredit,
|
|
245
185
|
fetchAccountCheck,
|
|
246
186
|
getAccountQuota,
|
|
247
187
|
getModelsAndQuota,
|
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
|
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
* GET /accounts/status
|
|
6
6
|
* GET /accounts/quota
|
|
7
7
|
* GET /accounts/quota/all
|
|
8
|
-
* GET /accounts/rate-limit-reset-credits
|
|
9
|
-
* POST /accounts/rate-limit-reset-credits/consume
|
|
10
8
|
* POST /accounts/add
|
|
11
9
|
* POST /accounts/add/manual
|
|
12
10
|
* POST /accounts/switch
|
|
@@ -47,13 +45,9 @@ import {
|
|
|
47
45
|
} from '../oauth.js';
|
|
48
46
|
|
|
49
47
|
import {
|
|
50
|
-
getAccountQuota as fetchAccountQuota
|
|
51
|
-
fetchRateLimitResetCredits,
|
|
52
|
-
consumeRateLimitResetCredit
|
|
48
|
+
getAccountQuota as fetchAccountQuota
|
|
53
49
|
} from '../model-api.js';
|
|
54
50
|
|
|
55
|
-
import { randomUUID } from 'crypto';
|
|
56
|
-
|
|
57
51
|
import { logger } from '../utils/logger.js';
|
|
58
52
|
|
|
59
53
|
// Tracks active OAuth callback servers keyed by port
|
|
@@ -238,75 +232,6 @@ export async function handleGetQuota(req, res) {
|
|
|
238
232
|
}
|
|
239
233
|
}
|
|
240
234
|
|
|
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
|
-
|
|
310
235
|
export async function handleGetAllQuotas(req, res) {
|
|
311
236
|
const { accounts: accountList } = listAccounts();
|
|
312
237
|
const results = [];
|
|
@@ -383,7 +308,5 @@ export default {
|
|
|
383
308
|
handleRemoveAccount,
|
|
384
309
|
handleImportAccount,
|
|
385
310
|
handleGetQuota,
|
|
386
|
-
handleGetRateLimitResetCredits,
|
|
387
|
-
handleConsumeRateLimitResetCredit,
|
|
388
311
|
handleGetAllQuotas
|
|
389
312
|
};
|