claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.4
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/package.json +1 -1
- package/public/index.html +60 -60
- package/public/js/app.js +116 -116
- package/public/login.html +32 -32
- package/public/views/client-api-keys-modals.html +5 -0
- package/public/views/client-api-keys.html +9 -1
- package/src/client-key-usage.js +125 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +12 -13
- package/src/middleware/auth.js +46 -11
- package/src/model-pricing.js +96 -0
- package/src/response-streamer.js +5 -5
- package/src/routes/chat-route.js +25 -4
- package/src/routes/messages-route.js +30 -6
- package/src/routes/settings-route.js +36 -5
- package/src/server-settings.js +18 -2
- package/src/utils/proxy-logging.js +5 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { CONFIG_DIR } from './account-manager.js';
|
|
4
|
+
|
|
5
|
+
const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
|
|
6
|
+
export const MICRO_USD_PER_USD = 1_000_000;
|
|
7
|
+
|
|
8
|
+
function loadUsage() {
|
|
9
|
+
if (!existsSync(USAGE_FILE)) return {};
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const data = JSON.parse(readFileSync(USAGE_FILE, 'utf8'));
|
|
13
|
+
return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
|
14
|
+
} catch (error) {
|
|
15
|
+
console.error('[ClientKeyUsage] Failed to read usage:', error.message);
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function saveUsage(usage) {
|
|
21
|
+
if (!existsSync(CONFIG_DIR)) {
|
|
22
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
23
|
+
}
|
|
24
|
+
writeFileSync(USAGE_FILE, JSON.stringify(usage, null, 2), { mode: 0o600 });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the current weekly period start in the server's local time zone.
|
|
29
|
+
* A period begins at Monday 08:00 and ends at the following Monday 08:00.
|
|
30
|
+
*/
|
|
31
|
+
export function getCurrentPeriodStart(now = new Date()) {
|
|
32
|
+
const periodStart = new Date(now);
|
|
33
|
+
const daysSinceMonday = (periodStart.getDay() + 6) % 7;
|
|
34
|
+
periodStart.setDate(periodStart.getDate() - daysSinceMonday);
|
|
35
|
+
periodStart.setHours(8, 0, 0, 0);
|
|
36
|
+
|
|
37
|
+
if (now < periodStart) {
|
|
38
|
+
periodStart.setDate(periodStart.getDate() - 7);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return periodStart.toISOString();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getNextPeriodStart(now = new Date()) {
|
|
45
|
+
const nextPeriodStart = new Date(getCurrentPeriodStart(now));
|
|
46
|
+
nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
|
|
47
|
+
return nextPeriodStart.toISOString();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function usdToMicrousd(usd) {
|
|
51
|
+
return Math.round(Number(usd) * MICRO_USD_PER_USD);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function microusdToUsd(microusd) {
|
|
55
|
+
return Number(microusd) / MICRO_USD_PER_USD;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Returns a key's usage after lazily resetting it for a new weekly period.
|
|
60
|
+
*/
|
|
61
|
+
export function getClientKeyUsage(keyId, now = new Date()) {
|
|
62
|
+
const usage = loadUsage();
|
|
63
|
+
const periodStart = getCurrentPeriodStart(now);
|
|
64
|
+
const entry = usage[keyId];
|
|
65
|
+
const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
|
|
66
|
+
? Math.max(0, entry.consumedMicrousd)
|
|
67
|
+
: 0;
|
|
68
|
+
|
|
69
|
+
if (!entry || entry.periodStart !== periodStart || entry.consumedMicrousd !== consumedMicrousd) {
|
|
70
|
+
usage[keyId] = { periodStart, consumedMicrousd };
|
|
71
|
+
saveUsage(usage);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
periodStart,
|
|
76
|
+
nextPeriodStart: getNextPeriodStart(now),
|
|
77
|
+
consumedMicrousd
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Records actual USD consumption for a client key. Call this only after an
|
|
83
|
+
* upstream response provides a verified per-request charge.
|
|
84
|
+
*/
|
|
85
|
+
export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
|
|
86
|
+
if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
|
|
87
|
+
throw new TypeError('consumedMicrousd must be a non-negative safe integer');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const current = getClientKeyUsage(keyId, now);
|
|
91
|
+
const usage = loadUsage();
|
|
92
|
+
usage[keyId] = {
|
|
93
|
+
periodStart: current.periodStart,
|
|
94
|
+
consumedMicrousd: current.consumedMicrousd + consumedMicrousd
|
|
95
|
+
};
|
|
96
|
+
saveUsage(usage);
|
|
97
|
+
return usage[keyId];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function deleteClientKeyUsage(keyId) {
|
|
101
|
+
const usage = loadUsage();
|
|
102
|
+
if (!(keyId in usage)) return;
|
|
103
|
+
delete usage[keyId];
|
|
104
|
+
saveUsage(usage);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Returns a key's current quota summary without charging any request.
|
|
109
|
+
*/
|
|
110
|
+
export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
|
|
111
|
+
const usage = getClientKeyUsage(keyId, now);
|
|
112
|
+
const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
|
|
113
|
+
const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
...usage,
|
|
117
|
+
weeklyLimitMicrousd,
|
|
118
|
+
remainingMicrousd,
|
|
119
|
+
weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
|
|
120
|
+
consumedUsd: microusdToUsd(usage.consumedMicrousd),
|
|
121
|
+
remainingUsd: microusdToUsd(remainingMicrousd)
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export { USAGE_FILE };
|
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,17 +7,14 @@ 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';
|
|
11
10
|
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
|
-
|
|
18
|
-
function shouldLogRawProxyPayloads() {
|
|
19
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
20
|
-
}
|
|
17
|
+
const UPSTREAM_REQUEST_TIMEOUT_MS = 120000;
|
|
21
18
|
|
|
22
19
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
20
|
const usage = {
|
|
@@ -30,6 +27,10 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
30
27
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
28
|
enumerable: false
|
|
32
29
|
});
|
|
30
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
31
|
+
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
32
|
+
enumerable: false
|
|
33
|
+
});
|
|
33
34
|
return usage;
|
|
34
35
|
}
|
|
35
36
|
|
|
@@ -128,15 +129,14 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
128
129
|
const response = await fetch(API_URL, {
|
|
129
130
|
method: 'POST',
|
|
130
131
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
131
|
-
body: JSON.stringify(request)
|
|
132
|
+
body: JSON.stringify(request),
|
|
133
|
+
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
132
134
|
});
|
|
133
135
|
|
|
134
136
|
if (response.ok) return response;
|
|
135
137
|
|
|
136
138
|
const errorText = await response.text();
|
|
137
|
-
|
|
138
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
-
}
|
|
139
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
140
140
|
|
|
141
141
|
if (response.status === 401) {
|
|
142
142
|
if (accountRotator && currentEmail) {
|
|
@@ -197,14 +197,13 @@ 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)
|
|
200
|
+
body: JSON.stringify(request),
|
|
201
|
+
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
201
202
|
});
|
|
202
203
|
|
|
203
204
|
if (!response.ok) {
|
|
204
205
|
const errorText = await response.text();
|
|
205
|
-
|
|
206
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
-
}
|
|
206
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
208
207
|
|
|
209
208
|
if (response.status === 401) {
|
|
210
209
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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';
|
|
4
5
|
|
|
5
6
|
function timingSafeEqualString(a, b) {
|
|
6
7
|
const left = Buffer.from(String(a));
|
|
@@ -44,10 +45,8 @@ function sendUnauthorized(req, res) {
|
|
|
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,50 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
67
|
|
|
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
|
+
|
|
69
82
|
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
83
|
|
|
75
84
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
-
|
|
85
|
+
|
|
86
|
+
export function requireClientAuth(req, res, next) {
|
|
87
|
+
if (!isPublicDeployment()) {
|
|
88
|
+
return next();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const requestKey = getRequestApiKey(req);
|
|
92
|
+
const clientKey = findClientKey(requestKey);
|
|
93
|
+
if (!clientKey) {
|
|
94
|
+
return sendUnauthorized(req, res);
|
|
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
|
+
}
|
|
77
112
|
|
|
78
113
|
export { isPublicDeployment };
|
|
79
114
|
|
|
@@ -0,0 +1,96 @@
|
|
|
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
|
+
|
|
9
|
+
const STANDARD_PRICING = {
|
|
10
|
+
'gpt-5.6-sol': {
|
|
11
|
+
input: 5,
|
|
12
|
+
cachedInput: 0.5,
|
|
13
|
+
cacheWrite: 6.25,
|
|
14
|
+
output: 30
|
|
15
|
+
},
|
|
16
|
+
'gpt-5.6-terra': {
|
|
17
|
+
input: 2.5,
|
|
18
|
+
cachedInput: 0.25,
|
|
19
|
+
cacheWrite: 3.125,
|
|
20
|
+
output: 15
|
|
21
|
+
},
|
|
22
|
+
'gpt-5.4-mini': {
|
|
23
|
+
input: 0.75,
|
|
24
|
+
cachedInput: 0.075,
|
|
25
|
+
cacheWrite: 0,
|
|
26
|
+
output: 4.5
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const LONG_CONTEXT_PRICING = {
|
|
31
|
+
'gpt-5.6-sol': {
|
|
32
|
+
input: 10,
|
|
33
|
+
cachedInput: 1,
|
|
34
|
+
cacheWrite: 12.5,
|
|
35
|
+
output: 45
|
|
36
|
+
},
|
|
37
|
+
'gpt-5.6-terra': {
|
|
38
|
+
input: 5,
|
|
39
|
+
cachedInput: 0.5,
|
|
40
|
+
cacheWrite: 6.25,
|
|
41
|
+
output: 22.5
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Returns the applicable USD-per-million-token price record for an upstream
|
|
47
|
+
* model. Models without a configured price return null.
|
|
48
|
+
*/
|
|
49
|
+
export function getModelPricing(model, inputTokens = 0) {
|
|
50
|
+
const normalizedModel = String(model || '').toLowerCase();
|
|
51
|
+
const standard = STANDARD_PRICING[normalizedModel];
|
|
52
|
+
if (!standard) return null;
|
|
53
|
+
|
|
54
|
+
const usesLongContext = Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
|
|
55
|
+
const longContext = usesLongContext ? LONG_CONTEXT_PRICING[normalizedModel] : null;
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
...standard,
|
|
59
|
+
...(longContext || {}),
|
|
60
|
+
model: normalizedModel,
|
|
61
|
+
priceUnitTokens: PRICE_UNIT_TOKENS,
|
|
62
|
+
longContext: Boolean(longContext)
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Calculates a request charge from Responses API usage and returns it in
|
|
68
|
+
* integer microdollars. Cached input and cache-write tokens are included in
|
|
69
|
+
* input_tokens, so both are removed from standard input before applying their
|
|
70
|
+
* respective prices.
|
|
71
|
+
*/
|
|
72
|
+
export function calculateUsageCostMicrousd(model, usage = {}) {
|
|
73
|
+
const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
|
|
74
|
+
const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
|
|
75
|
+
const cachedInputTokens = Math.min(
|
|
76
|
+
inputTokens,
|
|
77
|
+
Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
|
|
78
|
+
);
|
|
79
|
+
const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
|
|
80
|
+
const pricing = getModelPricing(model, inputTokens);
|
|
81
|
+
if (!pricing) return null;
|
|
82
|
+
|
|
83
|
+
const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
|
|
84
|
+
const usd = (
|
|
85
|
+
(uncachedInputTokens * pricing.input)
|
|
86
|
+
+ (cachedInputTokens * pricing.cachedInput)
|
|
87
|
+
+ (cacheWriteTokens * pricing.cacheWrite)
|
|
88
|
+
+ (outputTokens * pricing.output)
|
|
89
|
+
) / PRICE_UNIT_TOKENS;
|
|
90
|
+
|
|
91
|
+
return Math.round(usd * 1_000_000);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
|
|
95
|
+
|
|
96
|
+
export default { getModelPricing, calculateUsageCostMicrousd };
|
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;
|
|
@@ -117,6 +113,10 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
117
113
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
114
|
enumerable: false
|
|
119
115
|
});
|
|
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/chat-route.js
CHANGED
|
@@ -9,7 +9,9 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
9
9
|
import { getCredentialsOrError, sendAuthError } from '../middleware/credentials.js';
|
|
10
10
|
import { handleStreamError } from '../middleware/sse.js';
|
|
11
11
|
import { logger } from '../utils/logger.js';
|
|
12
|
-
import {
|
|
12
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
13
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
14
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* POST /v1/chat/completions
|
|
@@ -28,11 +30,10 @@ function getRequestContext(req) {
|
|
|
28
30
|
export async function handleChatCompletion(req, res) {
|
|
29
31
|
const startTime = Date.now();
|
|
30
32
|
const body = req.body;
|
|
31
|
-
|
|
32
|
-
if (settings.logRawProxyPayloads === true) {
|
|
33
|
+
if (shouldLogRawProxyPayloads()) {
|
|
33
34
|
logger.info('[Client Request]', body);
|
|
34
35
|
}
|
|
35
|
-
const requestedModel = body.model
|
|
36
|
+
const requestedModel = body.model;
|
|
36
37
|
|
|
37
38
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
38
39
|
|
|
@@ -53,6 +54,7 @@ export async function handleChatCompletion(req, res) {
|
|
|
53
54
|
|
|
54
55
|
try {
|
|
55
56
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, getRequestContext(req));
|
|
57
|
+
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
56
58
|
|
|
57
59
|
const duration = Date.now() - startTime;
|
|
58
60
|
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
@@ -109,6 +111,25 @@ export function handleCountTokens(req, res) {
|
|
|
109
111
|
|
|
110
112
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
111
113
|
|
|
114
|
+
function recordRequestUsage(clientKeyId, model, usage) {
|
|
115
|
+
if (!clientKeyId) return;
|
|
116
|
+
|
|
117
|
+
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
118
|
+
...usage,
|
|
119
|
+
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
120
|
+
input_tokens_details: {
|
|
121
|
+
...(usage?.input_tokens_details || {}),
|
|
122
|
+
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
if (costMicrousd === null) {
|
|
126
|
+
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
131
|
+
}
|
|
132
|
+
|
|
112
133
|
/**
|
|
113
134
|
* Converts an OpenAI Chat Completions request body into an Anthropic-style request.
|
|
114
135
|
* @param {object} body
|
|
@@ -6,6 +6,9 @@ import { logger } from '../utils/logger.js';
|
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
7
|
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
9
12
|
|
|
10
13
|
const MAX_RETRIES = 5;
|
|
11
14
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -50,10 +53,10 @@ export async function handleMessages(req, res) {
|
|
|
50
53
|
const startTime = Date.now();
|
|
51
54
|
const body = req.body;
|
|
52
55
|
const settings = getServerSettings();
|
|
53
|
-
if (
|
|
56
|
+
if (shouldLogRawProxyPayloads()) {
|
|
54
57
|
logger.info('[Claude Request]', body);
|
|
55
58
|
}
|
|
56
|
-
const requestedModel = body.model
|
|
59
|
+
const requestedModel = body.model;
|
|
57
60
|
const isStreaming = body.stream !== false;
|
|
58
61
|
|
|
59
62
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -97,9 +100,9 @@ export async function handleMessages(req, res) {
|
|
|
97
100
|
|
|
98
101
|
try {
|
|
99
102
|
if (isStreaming) {
|
|
100
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
103
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
101
104
|
} else {
|
|
102
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
105
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
103
106
|
}
|
|
104
107
|
rotator.notifySuccess(account, upstreamModel);
|
|
105
108
|
return;
|
|
@@ -134,20 +137,41 @@ export async function handleMessages(req, res) {
|
|
|
134
137
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
135
138
|
}
|
|
136
139
|
|
|
137
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
140
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
138
141
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
139
142
|
initSSEResponse(res);
|
|
140
143
|
const usage = await pipeSSEStream(res, stream);
|
|
144
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
141
145
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
142
146
|
}
|
|
143
147
|
|
|
144
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
148
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
145
149
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
146
151
|
const duration = Date.now() - startTime;
|
|
147
152
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
148
153
|
res.json({ ...response, model: responseModel });
|
|
149
154
|
}
|
|
150
155
|
|
|
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
|
+
|
|
151
175
|
function syncActiveAccount(email) {
|
|
152
176
|
const active = getActiveAccount();
|
|
153
177
|
if (active?.email === email) return;
|