claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.5

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.
@@ -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
@@ -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 { getServerSettings } from '../server-settings.js';
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
- const settings = getServerSettings();
32
- if (settings.logRawProxyPayloads === true) {
33
+ if (shouldLogRawProxyPayloads()) {
33
34
  logger.info('[Client Request]', body);
34
35
  }
35
- const requestedModel = body.model || 'gpt-5.2';
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 (settings.logRawProxyPayloads === true) {
56
+ if (shouldLogRawProxyPayloads()) {
54
57
  logger.info('[Claude Request]', body);
55
58
  }
56
- const requestedModel = body.model || 'gpt-5.2';
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;
@@ -10,13 +10,30 @@
10
10
  */
11
11
 
12
12
  import crypto from 'crypto';
13
- import { getServerSettings, setServerSettings, DEFAULT_MODEL_MAP } from '../server-settings.js';
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';
14
20
 
15
21
  const VALID_STRATEGIES = ['sticky', 'round-robin'];
16
22
 
17
23
  function getSafeClientApiKey(clientApiKey) {
18
24
  const { key, ...safeClientApiKey } = clientApiKey;
19
- return safeClientApiKey;
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;
20
37
  }
21
38
 
22
39
  function createClientApiKeyValue() {
@@ -168,17 +185,23 @@ export function handleListClientApiKeys(req, res) {
168
185
  * Creates a Claude Code client API key.
169
186
  */
170
187
  export function handleCreateClientApiKey(req, res) {
171
- const { name = '', remark = '' } = req.body || {};
188
+ const { name = '', remark = '', weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } = req.body || {};
172
189
 
173
190
  if (typeof name !== 'string' || typeof remark !== 'string') {
174
191
  return res.status(400).json({ success: false, error: 'name and remark must be strings' });
175
192
  }
176
193
 
194
+ const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
195
+ if (weeklyLimitError) {
196
+ return res.status(400).json({ success: false, error: weeklyLimitError });
197
+ }
198
+
177
199
  const clientApiKey = {
178
200
  id: crypto.randomUUID(),
179
201
  key: createClientApiKeyValue(),
180
202
  name: name.trim(),
181
203
  remark: remark.trim(),
204
+ weeklyLimitUsd,
182
205
  createdAt: new Date().toISOString()
183
206
  };
184
207
  const settings = getServerSettings();
@@ -193,7 +216,7 @@ export function handleCreateClientApiKey(req, res) {
193
216
  */
194
217
  export function handleUpdateClientApiKey(req, res) {
195
218
  const { id } = req.params;
196
- const { name, remark } = req.body || {};
219
+ const { name, remark, weeklyLimitUsd } = req.body || {};
197
220
 
198
221
  if (name !== undefined && typeof name !== 'string') {
199
222
  return res.status(400).json({ success: false, error: 'name must be a string' });
@@ -201,6 +224,12 @@ export function handleUpdateClientApiKey(req, res) {
201
224
  if (remark !== undefined && typeof remark !== 'string') {
202
225
  return res.status(400).json({ success: false, error: 'remark must be a string' });
203
226
  }
227
+ if (weeklyLimitUsd !== undefined) {
228
+ const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
229
+ if (weeklyLimitError) {
230
+ return res.status(400).json({ success: false, error: weeklyLimitError });
231
+ }
232
+ }
204
233
 
205
234
  const settings = getServerSettings();
206
235
  const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
@@ -212,7 +241,8 @@ export function handleUpdateClientApiKey(req, res) {
212
241
  const clientApiKey = {
213
242
  ...current,
214
243
  ...(name === undefined ? {} : { name: name.trim() }),
215
- ...(remark === undefined ? {} : { remark: remark.trim() })
244
+ ...(remark === undefined ? {} : { remark: remark.trim() }),
245
+ ...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
216
246
  };
217
247
  const clientApiKeys = [...settings.clientApiKeys];
218
248
  clientApiKeys[index] = clientApiKey;
@@ -235,6 +265,7 @@ export function handleDeleteClientApiKey(req, res) {
235
265
  }
236
266
 
237
267
  setServerSettings({ clientApiKeys });
268
+ deleteClientKeyUsage(id);
238
269
  res.json({ success: true });
239
270
  }
240
271
 
@@ -10,6 +10,8 @@ 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
+
13
15
  export const DEFAULT_SETTINGS = {
14
16
  accountStrategy: 'sticky',
15
17
  defaultCodexModel: 'gpt-5.5',
@@ -24,6 +26,16 @@ function ensureConfigDir() {
24
26
  }
25
27
  }
26
28
 
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
+
27
39
  function mergeSettings(data = {}) {
28
40
  return {
29
41
  ...DEFAULT_SETTINGS,
@@ -31,7 +43,10 @@ function mergeSettings(data = {}) {
31
43
  modelMap: {
32
44
  ...DEFAULT_MODEL_MAP,
33
45
  ...(data.modelMap || {})
34
- }
46
+ },
47
+ clientApiKeys: Array.isArray(data.clientApiKeys)
48
+ ? data.clientApiKeys.map(normalizeClientApiKey)
49
+ : []
35
50
  };
36
51
  }
37
52
 
@@ -65,5 +80,6 @@ export default {
65
80
  setServerSettings,
66
81
  SETTINGS_FILE,
67
82
  DEFAULT_SETTINGS,
68
- DEFAULT_MODEL_MAP
83
+ DEFAULT_MODEL_MAP,
84
+ DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
69
85
  };
@@ -0,0 +1,5 @@
1
+ import { getServerSettings } from '../server-settings.js';
2
+
3
+ export function shouldLogRawProxyPayloads() {
4
+ return getServerSettings().logRawProxyPayloads === true;
5
+ }