claude-codex-proxy 1.0.5-beta.13 → 1.0.5-beta.3
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 +0 -127
- package/public/index.html +60 -60
- package/public/js/app.js +116 -133
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +0 -56
- package/public/views/accounts.html +10 -29
- package/public/views/client-api-keys-modals.html +1 -6
- package/public/views/client-api-keys.html +31 -54
- package/public/views/logs.html +3 -10
- package/src/account-manager.js +3 -34
- package/src/account-rotation/rate-limits.js +0 -4
- package/src/account-rotation/strategies/base-strategy.js +0 -4
- package/src/account-rotation/strategies/sticky-strategy.js +0 -7
- 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/middleware/credentials.js +3 -13
- package/src/model-api.js +0 -60
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +2 -106
- package/src/routes/api-routes.js +42 -59
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +10 -19
- package/src/routes/logs-route.js +2 -21
- package/src/routes/messages-route.js +13 -39
- package/src/routes/settings-route.js +5 -36
- package/src/server-settings.js +2 -18
- package/src/utils/logger.js +0 -18
- 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
package/src/routes/logs-route.js
CHANGED
|
@@ -7,31 +7,12 @@
|
|
|
7
7
|
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
-
const LOGS_PER_PAGE = 30;
|
|
11
|
-
const MAX_PAGE_SIZE = 100;
|
|
12
|
-
|
|
13
|
-
function parsePositiveInteger(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
|
|
14
|
-
const parsed = Number.parseInt(value, 10);
|
|
15
|
-
return Number.isInteger(parsed) && parsed > 0 ? Math.min(parsed, maximum) : fallback;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
10
|
/**
|
|
19
11
|
* GET /api/logs
|
|
20
|
-
* Returns
|
|
12
|
+
* Returns the in-memory log history as JSON.
|
|
21
13
|
*/
|
|
22
14
|
export function handleGetLogs(req, res) {
|
|
23
|
-
|
|
24
|
-
const pageSize = parsePositiveInteger(req.query.pageSize, LOGS_PER_PAGE, MAX_PAGE_SIZE);
|
|
25
|
-
const { logs, total } = logger.getHistoryPage(page, pageSize);
|
|
26
|
-
|
|
27
|
-
res.json({
|
|
28
|
-
status: 'ok',
|
|
29
|
-
logs,
|
|
30
|
-
page,
|
|
31
|
-
pageSize,
|
|
32
|
-
total,
|
|
33
|
-
totalPages: Math.ceil(total / pageSize)
|
|
34
|
-
});
|
|
15
|
+
res.json({ status: 'ok', logs: logger.getHistory() });
|
|
35
16
|
}
|
|
36
17
|
|
|
37
18
|
/**
|
|
@@ -4,11 +4,8 @@ import { sendAuthError, getCredentialsForAccount } from '../middleware/credentia
|
|
|
4
4
|
import { initSSEResponse, pipeSSEStream, handleStreamError } from '../middleware/sse.js';
|
|
5
5
|
import { logger } from '../utils/logger.js';
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
|
-
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save
|
|
7
|
+
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
|
-
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
-
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
-
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
12
9
|
|
|
13
10
|
const MAX_RETRIES = 5;
|
|
14
11
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -53,10 +50,10 @@ export async function handleMessages(req, res) {
|
|
|
53
50
|
const startTime = Date.now();
|
|
54
51
|
const body = req.body;
|
|
55
52
|
const settings = getServerSettings();
|
|
56
|
-
if (
|
|
53
|
+
if (settings.logRawProxyPayloads === true) {
|
|
57
54
|
logger.info('[Claude Request]', body);
|
|
58
55
|
}
|
|
59
|
-
const requestedModel = body.model;
|
|
56
|
+
const requestedModel = body.model || 'gpt-5.2';
|
|
60
57
|
const isStreaming = body.stream !== false;
|
|
61
58
|
|
|
62
59
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -68,17 +65,15 @@ export async function handleMessages(req, res) {
|
|
|
68
65
|
const maxAttempts = Math.max(MAX_RETRIES, listAccounts().total);
|
|
69
66
|
|
|
70
67
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (!account && rotator.isAllRateLimited(upstreamModel)) {
|
|
68
|
+
if (rotator.isAllRateLimited(upstreamModel)) {
|
|
74
69
|
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
79
|
-
}
|
|
70
|
+
const waitSeconds = minWait > 0 ? Math.round(minWait / 1000) : 'unknown';
|
|
71
|
+
logger.info(`[Messages] All accounts rate-limited, not retrying. Next possible reset: ${waitSeconds}s`);
|
|
72
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
80
73
|
}
|
|
81
74
|
|
|
75
|
+
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
76
|
+
|
|
82
77
|
if (!account) {
|
|
83
78
|
if (waitMs > 0) {
|
|
84
79
|
await sleep(waitMs);
|
|
@@ -102,9 +97,9 @@ export async function handleMessages(req, res) {
|
|
|
102
97
|
|
|
103
98
|
try {
|
|
104
99
|
if (isStreaming) {
|
|
105
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
100
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
106
101
|
} else {
|
|
107
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
102
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
108
103
|
}
|
|
109
104
|
rotator.notifySuccess(account, upstreamModel);
|
|
110
105
|
return;
|
|
@@ -139,41 +134,20 @@ export async function handleMessages(req, res) {
|
|
|
139
134
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
140
135
|
}
|
|
141
136
|
|
|
142
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
137
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
143
138
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
144
139
|
initSSEResponse(res);
|
|
145
140
|
const usage = await pipeSSEStream(res, stream);
|
|
146
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
147
141
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
148
142
|
}
|
|
149
143
|
|
|
150
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
144
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
151
145
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
152
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
153
146
|
const duration = Date.now() - startTime;
|
|
154
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
155
148
|
res.json({ ...response, model: responseModel });
|
|
156
149
|
}
|
|
157
150
|
|
|
158
|
-
function recordRequestUsage(clientKeyId, model, usage) {
|
|
159
|
-
if (!clientKeyId) return;
|
|
160
|
-
|
|
161
|
-
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
162
|
-
...usage,
|
|
163
|
-
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
164
|
-
input_tokens_details: {
|
|
165
|
-
...(usage?.input_tokens_details || {}),
|
|
166
|
-
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
if (costMicrousd === null) {
|
|
170
|
-
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
151
|
function syncActiveAccount(email) {
|
|
178
152
|
const active = getActiveAccount();
|
|
179
153
|
if (active?.email === email) return;
|
|
@@ -10,30 +10,13 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import crypto from 'crypto';
|
|
13
|
-
import {
|
|
14
|
-
getServerSettings,
|
|
15
|
-
setServerSettings,
|
|
16
|
-
DEFAULT_MODEL_MAP,
|
|
17
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
18
|
-
} from '../server-settings.js';
|
|
19
|
-
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
13
|
+
import { getServerSettings, setServerSettings, DEFAULT_MODEL_MAP } from '../server-settings.js';
|
|
20
14
|
|
|
21
15
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
22
16
|
|
|
23
17
|
function getSafeClientApiKey(clientApiKey) {
|
|
24
18
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
25
|
-
return
|
|
26
|
-
...safeClientApiKey,
|
|
27
|
-
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd)
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function validateWeeklyLimitUsd(weeklyLimitUsd) {
|
|
32
|
-
if (typeof weeklyLimitUsd !== 'number' || !Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) {
|
|
33
|
-
return 'weeklyLimitUsd must be a non-negative number';
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return null;
|
|
19
|
+
return safeClientApiKey;
|
|
37
20
|
}
|
|
38
21
|
|
|
39
22
|
function createClientApiKeyValue() {
|
|
@@ -185,23 +168,17 @@ export function handleListClientApiKeys(req, res) {
|
|
|
185
168
|
* Creates a Claude Code client API key.
|
|
186
169
|
*/
|
|
187
170
|
export function handleCreateClientApiKey(req, res) {
|
|
188
|
-
const { name = '', remark = ''
|
|
171
|
+
const { name = '', remark = '' } = req.body || {};
|
|
189
172
|
|
|
190
173
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
191
174
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
192
175
|
}
|
|
193
176
|
|
|
194
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
195
|
-
if (weeklyLimitError) {
|
|
196
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
177
|
const clientApiKey = {
|
|
200
178
|
id: crypto.randomUUID(),
|
|
201
179
|
key: createClientApiKeyValue(),
|
|
202
180
|
name: name.trim(),
|
|
203
181
|
remark: remark.trim(),
|
|
204
|
-
weeklyLimitUsd,
|
|
205
182
|
createdAt: new Date().toISOString()
|
|
206
183
|
};
|
|
207
184
|
const settings = getServerSettings();
|
|
@@ -216,7 +193,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
216
193
|
*/
|
|
217
194
|
export function handleUpdateClientApiKey(req, res) {
|
|
218
195
|
const { id } = req.params;
|
|
219
|
-
const { name, remark
|
|
196
|
+
const { name, remark } = req.body || {};
|
|
220
197
|
|
|
221
198
|
if (name !== undefined && typeof name !== 'string') {
|
|
222
199
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -224,12 +201,6 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
224
201
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
225
202
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
226
203
|
}
|
|
227
|
-
if (weeklyLimitUsd !== undefined) {
|
|
228
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
229
|
-
if (weeklyLimitError) {
|
|
230
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
204
|
|
|
234
205
|
const settings = getServerSettings();
|
|
235
206
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -241,8 +212,7 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
241
212
|
const clientApiKey = {
|
|
242
213
|
...current,
|
|
243
214
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
244
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
245
|
-
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
215
|
+
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
246
216
|
};
|
|
247
217
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
248
218
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -265,7 +235,6 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
265
235
|
}
|
|
266
236
|
|
|
267
237
|
setServerSettings({ clientApiKeys });
|
|
268
|
-
deleteClientKeyUsage(id);
|
|
269
238
|
res.json({ success: true });
|
|
270
239
|
}
|
|
271
240
|
|
package/src/server-settings.js
CHANGED
|
@@ -10,8 +10,6 @@ export const DEFAULT_MODEL_MAP = {
|
|
|
10
10
|
haiku: 'gpt-5.4-mini'
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
-
export const DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD = 50;
|
|
14
|
-
|
|
15
13
|
export const DEFAULT_SETTINGS = {
|
|
16
14
|
accountStrategy: 'sticky',
|
|
17
15
|
defaultCodexModel: 'gpt-5.5',
|
|
@@ -26,16 +24,6 @@ function ensureConfigDir() {
|
|
|
26
24
|
}
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
function normalizeClientApiKey(clientApiKey) {
|
|
30
|
-
const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
|
|
31
|
-
return {
|
|
32
|
-
...clientApiKey,
|
|
33
|
-
weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
|
|
34
|
-
? weeklyLimitUsd
|
|
35
|
-
: DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
27
|
function mergeSettings(data = {}) {
|
|
40
28
|
return {
|
|
41
29
|
...DEFAULT_SETTINGS,
|
|
@@ -43,10 +31,7 @@ function mergeSettings(data = {}) {
|
|
|
43
31
|
modelMap: {
|
|
44
32
|
...DEFAULT_MODEL_MAP,
|
|
45
33
|
...(data.modelMap || {})
|
|
46
|
-
}
|
|
47
|
-
clientApiKeys: Array.isArray(data.clientApiKeys)
|
|
48
|
-
? data.clientApiKeys.map(normalizeClientApiKey)
|
|
49
|
-
: []
|
|
34
|
+
}
|
|
50
35
|
};
|
|
51
36
|
}
|
|
52
37
|
|
|
@@ -80,6 +65,5 @@ export default {
|
|
|
80
65
|
setServerSettings,
|
|
81
66
|
SETTINGS_FILE,
|
|
82
67
|
DEFAULT_SETTINGS,
|
|
83
|
-
DEFAULT_MODEL_MAP
|
|
84
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
68
|
+
DEFAULT_MODEL_MAP
|
|
85
69
|
};
|
package/src/utils/logger.js
CHANGED
|
@@ -40,24 +40,6 @@ class Logger extends EventEmitter {
|
|
|
40
40
|
return [...this.history];
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
/**
|
|
44
|
-
* Returns a newest-first page of in-memory log entries.
|
|
45
|
-
*
|
|
46
|
-
* @param {number} page - One-based page number.
|
|
47
|
-
* @param {number} pageSize - Maximum number of entries per page.
|
|
48
|
-
* @returns {{ logs: object[], total: number }} Requested page and total entry count.
|
|
49
|
-
*/
|
|
50
|
-
getHistoryPage(page, pageSize) {
|
|
51
|
-
const total = this.history.length;
|
|
52
|
-
const end = Math.max(0, total - (page - 1) * pageSize);
|
|
53
|
-
const start = Math.max(0, end - pageSize);
|
|
54
|
-
|
|
55
|
-
return {
|
|
56
|
-
logs: this.history.slice(start, end).reverse(),
|
|
57
|
-
total
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
|
|
61
43
|
clear() {
|
|
62
44
|
this.history = [];
|
|
63
45
|
}
|
package/src/admin-path.js
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Resolves the non-public prefix used for the management UI and its APIs.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
const DEFAULT_ADMIN_PATH = '/admin';
|
|
6
|
-
const VALID_ADMIN_PATH = /^\/[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
|
|
7
|
-
const RESERVED_PATHS = ['/v1', '/health', '/claude'];
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Returns the validated management UI path prefix.
|
|
11
|
-
* @returns {string}
|
|
12
|
-
*/
|
|
13
|
-
export function getAdminPath() {
|
|
14
|
-
const adminPath = process.env.PROXY_ADMIN_PATH || DEFAULT_ADMIN_PATH;
|
|
15
|
-
if (!VALID_ADMIN_PATH.test(adminPath)) {
|
|
16
|
-
throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". Use an absolute path without trailing slashes, query strings, or ".." segments.`);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const overlapsReservedPath = RESERVED_PATHS.some((reservedPath) => (
|
|
20
|
-
adminPath === reservedPath
|
|
21
|
-
|| adminPath.startsWith(`${reservedPath}/`)
|
|
22
|
-
|| reservedPath.startsWith(`${adminPath}/`)
|
|
23
|
-
));
|
|
24
|
-
if (overlapsReservedPath) {
|
|
25
|
-
throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". The path must not overlap reserved routes: ${RESERVED_PATHS.join(', ')}.`);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
return adminPath;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export { DEFAULT_ADMIN_PATH };
|
|
32
|
-
|
|
33
|
-
export default { getAdminPath, DEFAULT_ADMIN_PATH };
|
package/src/client-key-usage.js
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
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/model-pricing.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
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 };
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Returns the authenticated client key's weekly quota using Claude Code's
|
|
5
|
-
* utilization response shape, so the terminal can consume it directly.
|
|
6
|
-
*/
|
|
7
|
-
export function handleGetClientQuota(req, res) {
|
|
8
|
-
const quota = req.clientApiKeyQuota;
|
|
9
|
-
const weeklyLimitUsd = quota?.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD;
|
|
10
|
-
const utilization = quota && weeklyLimitUsd > 0
|
|
11
|
-
? Math.min(100, Math.max(0, (quota.consumedUsd / weeklyLimitUsd) * 100))
|
|
12
|
-
: null;
|
|
13
|
-
|
|
14
|
-
return res.json({
|
|
15
|
-
five_hour: null,
|
|
16
|
-
seven_day: quota ? {
|
|
17
|
-
utilization,
|
|
18
|
-
resets_at: quota.nextPeriodStart
|
|
19
|
-
} : null,
|
|
20
|
-
seven_day_oauth_apps: null,
|
|
21
|
-
seven_day_opus: null,
|
|
22
|
-
seven_day_sonnet: null,
|
|
23
|
-
extra_usage: null
|
|
24
|
-
});
|
|
25
|
-
}
|