claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.31
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 +195 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +90 -29
- 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 +86 -13
- 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/middleware/auth.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings } from '../server-settings.js';
|
|
3
|
+
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
|
+
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
5
|
+
import { createErrorResponse } from './sse.js';
|
|
4
6
|
|
|
5
7
|
function timingSafeEqualString(a, b) {
|
|
6
8
|
const left = Buffer.from(String(a));
|
|
@@ -25,7 +27,7 @@ function getRequestApiKey(req) {
|
|
|
25
27
|
return String(headerKey).trim();
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
const queryKey = req.query?.api_key
|
|
30
|
+
const queryKey = req.query?.api_key;
|
|
29
31
|
if (queryKey) {
|
|
30
32
|
return String(queryKey).trim();
|
|
31
33
|
}
|
|
@@ -35,19 +37,16 @@ function getRequestApiKey(req) {
|
|
|
35
37
|
|
|
36
38
|
function sendUnauthorized(req, res) {
|
|
37
39
|
if (req.path?.startsWith('/v1/')) {
|
|
38
|
-
return res.status(401).json(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
});
|
|
40
|
+
return res.status(401).json(
|
|
41
|
+
createErrorResponse('authentication_error', 'Invalid API key')
|
|
42
|
+
);
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
function
|
|
48
|
-
return
|
|
49
|
-
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
-
));
|
|
48
|
+
function matchesKey(requestKey, expectedKey) {
|
|
49
|
+
return expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey);
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
function requireKeys(getExpectedKeys) {
|
|
@@ -58,7 +57,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
58
57
|
|
|
59
58
|
const expectedKeys = getExpectedKeys();
|
|
60
59
|
const requestKey = getRequestApiKey(req);
|
|
61
|
-
if (!
|
|
60
|
+
if (!expectedKeys.some((expectedKey) => matchesKey(requestKey, expectedKey))) {
|
|
62
61
|
return sendUnauthorized(req, res);
|
|
63
62
|
}
|
|
64
63
|
|
|
@@ -66,14 +65,53 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
67
|
|
|
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
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function findClientKey(requestKey) {
|
|
75
|
+
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
76
|
+
}
|
|
77
|
+
|
|
69
78
|
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);
|
|
74
79
|
|
|
75
80
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
-
|
|
81
|
+
|
|
82
|
+
export function requireClientAuth(req, res, next) {
|
|
83
|
+
const requestKey = getRequestApiKey(req);
|
|
84
|
+
const clientKey = findClientKey(requestKey);
|
|
85
|
+
if (isPublicDeployment() && !clientKey) {
|
|
86
|
+
return sendUnauthorized(req, res);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!clientKey) {
|
|
90
|
+
return next();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const quota = getClientKeyQuota(
|
|
94
|
+
clientKey.id,
|
|
95
|
+
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
96
|
+
{
|
|
97
|
+
enabled: clientKey.fiveHourLimitEnabled,
|
|
98
|
+
usd: clientKey.fiveHourLimitUsd
|
|
99
|
+
}
|
|
100
|
+
);
|
|
101
|
+
const isModelRequest = req.method === 'POST' && (
|
|
102
|
+
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
+
);
|
|
104
|
+
if (isModelRequest && quota.fiveHourLimitEnabled && quota.fiveHourRemainingMicrousd <= 0) {
|
|
105
|
+
return sendQuotaExceeded(res, 'Five-hour', quota.nextFiveHourPeriodStart);
|
|
106
|
+
}
|
|
107
|
+
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
108
|
+
return sendQuotaExceeded(res, 'Weekly', quota.nextPeriodStart);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
112
|
+
req.clientApiKeyQuota = quota;
|
|
113
|
+
return next();
|
|
114
|
+
}
|
|
77
115
|
|
|
78
116
|
export { isPublicDeployment };
|
|
79
117
|
|
|
@@ -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
|
|
@@ -56,24 +74,48 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
56
74
|
const loggedModel = typeof model === 'string' && model.toLowerCase().startsWith('claude-')
|
|
57
75
|
? resolveModelRouting(model).upstreamModel
|
|
58
76
|
: model;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
77
|
+
const isStreamError = res.headersSent;
|
|
78
|
+
const logDetails = {
|
|
79
|
+
model: loggedModel,
|
|
80
|
+
transport: isStreamError ? 'sse' : 'http',
|
|
81
|
+
clientHttpStatus: isStreamError ? res.statusCode : status,
|
|
82
|
+
errorType,
|
|
83
|
+
retrySignal: errorType === 'overloaded_error',
|
|
84
|
+
errorName: error?.name,
|
|
85
|
+
errorCode: error?.code,
|
|
86
|
+
upstreamStatus: error?.upstreamStatus,
|
|
87
|
+
isUpstreamError: error?.isUpstreamError === true,
|
|
88
|
+
error: error?.message,
|
|
89
|
+
duration
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
if (isStreamError) {
|
|
93
|
+
const socketDestroyed = res.destroyed === true || res.socket?.destroyed === true;
|
|
94
|
+
const writableEnded = res.writableEnded === true;
|
|
95
|
+
const sseWriteAttempted = !socketDestroyed && !writableEnded;
|
|
96
|
+
let sseWriteBackpressure = false;
|
|
97
|
+
if (sseWriteAttempted) {
|
|
98
|
+
sseWriteBackpressure = !res.write(
|
|
99
|
+
`event: error\ndata: ${JSON.stringify(createErrorResponse(errorType, getClientErrorMessage(error)))}\n\n`
|
|
100
|
+
);
|
|
101
|
+
res.end();
|
|
102
|
+
}
|
|
103
|
+
logger.response(status, {
|
|
104
|
+
...logDetails,
|
|
105
|
+
sseWriteAttempted,
|
|
106
|
+
sseWriteBackpressure,
|
|
107
|
+
socketDestroyed,
|
|
108
|
+
writableEnded
|
|
109
|
+
});
|
|
69
110
|
return;
|
|
70
111
|
}
|
|
71
112
|
|
|
113
|
+
logger.response(status, logDetails);
|
|
114
|
+
|
|
72
115
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
73
|
-
return res.status(401).json(
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
});
|
|
116
|
+
return res.status(401).json(
|
|
117
|
+
createErrorResponse('authentication_error', 'Token expired. Please refresh or re-authenticate.')
|
|
118
|
+
);
|
|
77
119
|
}
|
|
78
120
|
|
|
79
121
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -81,28 +123,23 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
81
123
|
const resetMs = parseInt(parts[1], 10);
|
|
82
124
|
const errorText = parts.slice(2).join(':') || error.message;
|
|
83
125
|
|
|
84
|
-
return res.status(429).json(
|
|
85
|
-
|
|
86
|
-
error: {
|
|
87
|
-
type: 'rate_limit_error',
|
|
88
|
-
message: errorText,
|
|
126
|
+
return res.status(429).json(
|
|
127
|
+
createErrorResponse('rate_limit_error', errorText, {
|
|
89
128
|
resetMs: resetMs,
|
|
90
129
|
resetSeconds: Math.round(resetMs / 1000)
|
|
91
|
-
}
|
|
92
|
-
|
|
130
|
+
})
|
|
131
|
+
);
|
|
93
132
|
}
|
|
94
133
|
|
|
95
134
|
if (error.message.includes('RESOURCE_EXHAUSTED')) {
|
|
96
|
-
return res.status(429).json(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
});
|
|
135
|
+
return res.status(429).json(
|
|
136
|
+
createErrorResponse('rate_limit_error', error.message)
|
|
137
|
+
);
|
|
100
138
|
}
|
|
101
139
|
|
|
102
|
-
res.status(status).json(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
});
|
|
140
|
+
res.status(status).json(
|
|
141
|
+
createErrorResponse(errorType, getClientErrorMessage(error))
|
|
142
|
+
);
|
|
106
143
|
}
|
|
107
144
|
|
|
108
145
|
function getErrorStatus(error) {
|
|
@@ -115,6 +152,9 @@ function getErrorStatus(error) {
|
|
|
115
152
|
}
|
|
116
153
|
|
|
117
154
|
function getAnthropicErrorType(error, status) {
|
|
155
|
+
// Claude Code retries streamed overload errors by their Anthropic error type.
|
|
156
|
+
// HTTP status is already committed after SSE starts, so preserve 5xx semantics here.
|
|
157
|
+
if (status >= 500) return 'overloaded_error';
|
|
118
158
|
if (error?.anthropicErrorType) return error.anthropicErrorType;
|
|
119
159
|
if (status === 401) return 'authentication_error';
|
|
120
160
|
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,
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upstream Codex model pricing in USD per one million tokens.
|
|
3
|
+
* Long-context pricing applies when input tokens exceed 272,000.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const PRICE_UNIT_TOKENS = 1_000_000;
|
|
7
|
+
export const LONG_CONTEXT_THRESHOLD_TOKENS = 272_000;
|
|
8
|
+
// For models without a configured price, billing is uniformly based on this model.
|
|
9
|
+
export const DEFAULT_PRICING_MODEL = 'gpt-5.6-sol';
|
|
10
|
+
|
|
11
|
+
const STANDARD_PRICING = {
|
|
12
|
+
'gpt-5.6-sol': {
|
|
13
|
+
input: 5,
|
|
14
|
+
cachedInput: 0.5,
|
|
15
|
+
cacheWrite: 6.25,
|
|
16
|
+
output: 30
|
|
17
|
+
},
|
|
18
|
+
'gpt-5.6-terra': {
|
|
19
|
+
input: 2,
|
|
20
|
+
cachedInput: 0.2,
|
|
21
|
+
cacheWrite: 2.5,
|
|
22
|
+
output: 12
|
|
23
|
+
},
|
|
24
|
+
'gpt-5.4-mini': {
|
|
25
|
+
input: 0.75,
|
|
26
|
+
cachedInput: 0.075,
|
|
27
|
+
cacheWrite: 0,
|
|
28
|
+
output: 4.5
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const LONG_CONTEXT_PRICING = {
|
|
33
|
+
'gpt-5.6-sol': {
|
|
34
|
+
input: 10,
|
|
35
|
+
cachedInput: 1,
|
|
36
|
+
cacheWrite: 12.5,
|
|
37
|
+
output: 45
|
|
38
|
+
},
|
|
39
|
+
'gpt-5.6-terra': {
|
|
40
|
+
input: 4,
|
|
41
|
+
cachedInput: 0.4,
|
|
42
|
+
cacheWrite: 5,
|
|
43
|
+
output: 18
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Returns the applicable USD-per-million-token price record for an upstream
|
|
49
|
+
* model. Models without a configured price use DEFAULT_PRICING_MODEL.
|
|
50
|
+
*/
|
|
51
|
+
export function getModelPricing(model, inputTokens = 0) {
|
|
52
|
+
const requestedModel = String(model || '').trim().toLowerCase();
|
|
53
|
+
|
|
54
|
+
// Use the current model if it has a price;
|
|
55
|
+
// use the default pricing model if no price is configured.
|
|
56
|
+
const pricingModel = STANDARD_PRICING[requestedModel]
|
|
57
|
+
? requestedModel
|
|
58
|
+
: DEFAULT_PRICING_MODEL;
|
|
59
|
+
|
|
60
|
+
const standard = STANDARD_PRICING[pricingModel];
|
|
61
|
+
|
|
62
|
+
// Prevent DEFAULT_PRICING_MODEL configuration errors.
|
|
63
|
+
if (!standard) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`Default pricing model "${DEFAULT_PRICING_MODEL}" is not configured`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const usesLongContext =
|
|
70
|
+
Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
|
|
71
|
+
|
|
72
|
+
const longContext = usesLongContext
|
|
73
|
+
? LONG_CONTEXT_PRICING[pricingModel]
|
|
74
|
+
: null;
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
...standard,
|
|
78
|
+
...(longContext || {}),
|
|
79
|
+
|
|
80
|
+
// The model actually requested
|
|
81
|
+
model: requestedModel,
|
|
82
|
+
|
|
83
|
+
// The model actually used to calculate the price
|
|
84
|
+
pricingModel,
|
|
85
|
+
|
|
86
|
+
// Was the default price used?
|
|
87
|
+
fallbackPricing: requestedModel !== pricingModel,
|
|
88
|
+
|
|
89
|
+
priceUnitTokens: PRICE_UNIT_TOKENS,
|
|
90
|
+
longContext: Boolean(longContext)
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Calculates a request charge from Responses API usage and returns it in
|
|
96
|
+
* integer microdollars. Cached input and cache-write tokens are included in
|
|
97
|
+
* input_tokens, so both are removed from standard input before applying their
|
|
98
|
+
* respective prices.
|
|
99
|
+
*/
|
|
100
|
+
export function calculateUsageCostMicrousd(model, usage = {}) {
|
|
101
|
+
const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
|
|
102
|
+
const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
|
|
103
|
+
const cachedInputTokens = Math.min(
|
|
104
|
+
inputTokens,
|
|
105
|
+
Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
|
|
106
|
+
);
|
|
107
|
+
const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
|
|
108
|
+
const pricing = getModelPricing(model, inputTokens);
|
|
109
|
+
|
|
110
|
+
const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
|
|
111
|
+
const usd = (
|
|
112
|
+
(uncachedInputTokens * pricing.input)
|
|
113
|
+
+ (cachedInputTokens * pricing.cachedInput)
|
|
114
|
+
+ (cacheWriteTokens * pricing.cacheWrite)
|
|
115
|
+
+ (outputTokens * pricing.output)
|
|
116
|
+
) / PRICE_UNIT_TOKENS;
|
|
117
|
+
|
|
118
|
+
return Math.round(usd * 1_000_000);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
|
|
122
|
+
|
|
123
|
+
export default {
|
|
124
|
+
getModelPricing,
|
|
125
|
+
calculateUsageCostMicrousd,
|
|
126
|
+
DEFAULT_PRICING_MODEL
|
|
127
|
+
};
|
package/src/response-streamer.js
CHANGED
|
@@ -5,15 +5,11 @@
|
|
|
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';
|
|
9
8
|
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
|
-
|
|
17
13
|
export function createResponsesAPIError(message, status = 502) {
|
|
18
14
|
const error = new Error(message);
|
|
19
15
|
error.status = status;
|
|
@@ -76,6 +72,7 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
76
72
|
let stopReason = 'end_turn';
|
|
77
73
|
let pendingArguments = '';
|
|
78
74
|
let usage = { input_tokens: 0, output_tokens: 0 };
|
|
75
|
+
let hasCompletedResponse = false;
|
|
79
76
|
|
|
80
77
|
const reader = response.body.getReader();
|
|
81
78
|
const decoder = new TextDecoder();
|
|
@@ -102,6 +99,7 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
102
99
|
|
|
103
100
|
// Extract usage from completed response
|
|
104
101
|
if (eventType === 'response.completed' && event.response?.usage) {
|
|
102
|
+
hasCompletedResponse = true;
|
|
105
103
|
if (shouldLogRawProxyPayloads()) {
|
|
106
104
|
logger.info('[OpenAI Response Completed]', event.response);
|
|
107
105
|
}
|
|
@@ -117,12 +115,22 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
117
115
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
116
|
enumerable: false
|
|
119
117
|
});
|
|
118
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
119
|
+
value: event.response.usage.input_tokens_details?.cache_write_tokens || 0,
|
|
120
|
+
enumerable: false
|
|
121
|
+
});
|
|
120
122
|
}
|
|
121
123
|
|
|
122
124
|
// Handle output item added
|
|
123
125
|
if (eventType === 'response.output_item.added') {
|
|
124
126
|
const item = event.item;
|
|
125
|
-
|
|
127
|
+
|
|
128
|
+
// Codex executes hosted web searches upstream. Claude Code only
|
|
129
|
+
// needs the final output_text, not a client-side tool_use block.
|
|
130
|
+
if (item?.type === 'web_search_call') {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
|
|
126
134
|
if (!hasEmittedStart) {
|
|
127
135
|
hasEmittedStart = true;
|
|
128
136
|
yield {
|
|
@@ -162,9 +170,13 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
162
170
|
data: { type: 'content_block_stop', index: blockIndex }
|
|
163
171
|
};
|
|
164
172
|
blockIndex++;
|
|
173
|
+
currentBlockType = null;
|
|
174
|
+
currentBlockId = null;
|
|
175
|
+
currentToolName = null;
|
|
165
176
|
}
|
|
166
177
|
|
|
167
|
-
// Start new block based on item type
|
|
178
|
+
// Start new block based on item type. Hosted web_search_call
|
|
179
|
+
// items are executed upstream and do not become Claude tool_use blocks.
|
|
168
180
|
if (item.type === 'message') {
|
|
169
181
|
currentBlockType = 'text';
|
|
170
182
|
currentBlockId = item.id;
|
|
@@ -331,6 +343,10 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
331
343
|
}
|
|
332
344
|
}
|
|
333
345
|
|
|
346
|
+
if (!hasCompletedResponse) {
|
|
347
|
+
throw createResponsesAPIError('Upstream stream ended before response.completed');
|
|
348
|
+
}
|
|
349
|
+
|
|
334
350
|
// Handle no content received
|
|
335
351
|
if (!hasEmittedStart) {
|
|
336
352
|
hasEmittedStart = true;
|