claude-codex-proxy 1.0.5-beta.4 → 1.0.5-beta.41

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.
Files changed (43) hide show
  1. package/README.md +0 -272
  2. package/bin/cli.js +37 -2
  3. package/package.json +1 -1
  4. package/public/css/style.css +132 -0
  5. package/public/js/app.js +105 -26
  6. package/public/views/accounts-modals.html +90 -29
  7. package/public/views/accounts.html +29 -10
  8. package/public/views/client-api-keys-modals.html +10 -1
  9. package/public/views/client-api-keys.html +68 -39
  10. package/public/views/logs.html +10 -3
  11. package/public/views/settings.html +11 -1
  12. package/src/account-manager.js +34 -3
  13. package/src/account-rotation/index.js +6 -0
  14. package/src/account-rotation/rate-limits.js +4 -0
  15. package/src/account-rotation/strategies/base-strategy.js +4 -0
  16. package/src/account-rotation/strategies/round-robin-strategy.js +78 -3
  17. package/src/account-rotation/strategies/sticky-strategy.js +7 -0
  18. package/src/admin-path.js +33 -0
  19. package/src/client-key-usage.js +193 -125
  20. package/src/daily-anchor-ping.js +149 -0
  21. package/src/direct-api.js +6 -5
  22. package/src/format-converter.js +83 -48
  23. package/src/index.js +13 -4
  24. package/src/middleware/auth.js +23 -20
  25. package/src/middleware/credentials.js +17 -7
  26. package/src/middleware/sse.js +72 -30
  27. package/src/model-api.js +86 -13
  28. package/src/model-mapper.js +3 -4
  29. package/src/model-pricing.js +187 -96
  30. package/src/response-streamer.js +18 -2
  31. package/src/routes/accounts-route.js +106 -2
  32. package/src/routes/api-routes.js +59 -42
  33. package/src/routes/chat-route.js +5 -4
  34. package/src/routes/claude-config-route.js +19 -10
  35. package/src/routes/client-quota-route.js +31 -0
  36. package/src/routes/logs-route.js +21 -2
  37. package/src/routes/messages-route.js +135 -55
  38. package/src/routes/models-route.js +5 -0
  39. package/src/routes/settings-route.js +40 -10
  40. package/src/server-settings.js +10 -3
  41. package/src/server.js +4 -0
  42. package/src/utils/logger.js +34 -2
  43. package/src/utils/proxy-logging.js +5 -5
@@ -1,96 +1,187 @@
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
+ /**
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-6.1-sol': {
13
+ input: 2,
14
+ cachedInput: 0.1,
15
+ cacheWrite: 2.5,
16
+ output: 10
17
+ },
18
+ 'gpt-6-sol': {
19
+ input: 2,
20
+ cachedInput: 0.2,
21
+ cacheWrite: 2.5,
22
+ output: 10
23
+ },
24
+ 'gpt-6-luna': {
25
+ input: 0.1,
26
+ cachedInput: 0.01,
27
+ cacheWrite: 0.125,
28
+ output: 0.5
29
+ },
30
+ 'gpt-6-astra': {
31
+ input: 10,
32
+ cachedInput: 1,
33
+ cacheWrite: 12.5,
34
+ output: 50
35
+ },
36
+ 'gpt-5.6-sol': {
37
+ input: 4,
38
+ cachedInput: 0.4,
39
+ cacheWrite: 5,
40
+ output: 20
41
+ },
42
+ 'gpt-5.6-terra': {
43
+ input: 2,
44
+ cachedInput: 0.2,
45
+ cacheWrite: 2.5,
46
+ output: 12
47
+ },
48
+ 'gpt-5.6-luna': {
49
+ input: 0.2,
50
+ cachedInput: 0.02,
51
+ cacheWrite: 0.25,
52
+ output: 1.2
53
+ },
54
+ 'gpt-5.4-mini': {
55
+ input: 0.75,
56
+ cachedInput: 0.075,
57
+ cacheWrite: 0,
58
+ output: 4.5
59
+ }
60
+ };
61
+
62
+ const LONG_CONTEXT_PRICING = {
63
+ 'gpt-6.1-sol': {
64
+ input: 4,
65
+ cachedInput: 0.2,
66
+ cacheWrite: 5,
67
+ output: 15
68
+ },
69
+ 'gpt-6-sol': {
70
+ input: 4,
71
+ cachedInput: 0.4,
72
+ cacheWrite: 5,
73
+ output: 15
74
+ },
75
+ 'gpt-6-luna': {
76
+ input: 0.2,
77
+ cachedInput: 0.02,
78
+ cacheWrite: 0.25,
79
+ output: 0.75
80
+ },
81
+ 'gpt-6-astra': {
82
+ input: 20,
83
+ cachedInput: 2,
84
+ cacheWrite: 25,
85
+ output: 75
86
+ },
87
+ 'gpt-5.6-sol': {
88
+ input: 8,
89
+ cachedInput: 0.8,
90
+ cacheWrite: 10,
91
+ output: 30
92
+ },
93
+ 'gpt-5.6-terra': {
94
+ input: 4,
95
+ cachedInput: 0.4,
96
+ cacheWrite: 5,
97
+ output: 18
98
+ },
99
+ 'gpt-5.6-luna': {
100
+ input: 0.4,
101
+ cachedInput: 0.04,
102
+ cacheWrite: 0.5,
103
+ output: 1.8
104
+ }
105
+ };
106
+
107
+ /**
108
+ * Returns the applicable USD-per-million-token price record for an upstream
109
+ * model. Models without a configured price use DEFAULT_PRICING_MODEL.
110
+ */
111
+ export function getModelPricing(model, inputTokens = 0) {
112
+ const requestedModel = String(model || '').trim().toLowerCase();
113
+
114
+ // Use the current model if it has a price;
115
+ // use the default pricing model if no price is configured.
116
+ const pricingModel = STANDARD_PRICING[requestedModel]
117
+ ? requestedModel
118
+ : DEFAULT_PRICING_MODEL;
119
+
120
+ const standard = STANDARD_PRICING[pricingModel];
121
+
122
+ // Prevent DEFAULT_PRICING_MODEL configuration errors.
123
+ if (!standard) {
124
+ throw new Error(
125
+ `Default pricing model "${DEFAULT_PRICING_MODEL}" is not configured`
126
+ );
127
+ }
128
+
129
+ const usesLongContext =
130
+ Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
131
+
132
+ const longContext = usesLongContext
133
+ ? LONG_CONTEXT_PRICING[pricingModel]
134
+ : null;
135
+
136
+ return {
137
+ ...standard,
138
+ ...(longContext || {}),
139
+
140
+ // The model actually requested
141
+ model: requestedModel,
142
+
143
+ // The model actually used to calculate the price
144
+ pricingModel,
145
+
146
+ // Was the default price used?
147
+ fallbackPricing: requestedModel !== pricingModel,
148
+
149
+ priceUnitTokens: PRICE_UNIT_TOKENS,
150
+ longContext: Boolean(longContext)
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Calculates a request charge from Responses API usage and returns it in
156
+ * integer microdollars. Cached input and cache-write tokens are included in
157
+ * input_tokens, so both are removed from standard input before applying their
158
+ * respective prices.
159
+ */
160
+ export function calculateUsageCostMicrousd(model, usage = {}) {
161
+ const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
162
+ const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
163
+ const cachedInputTokens = Math.min(
164
+ inputTokens,
165
+ Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
166
+ );
167
+ const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
168
+ const pricing = getModelPricing(model, inputTokens);
169
+
170
+ const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
171
+ const usd = (
172
+ (uncachedInputTokens * pricing.input)
173
+ + (cachedInputTokens * pricing.cachedInput)
174
+ + (cacheWriteTokens * pricing.cacheWrite)
175
+ + (outputTokens * pricing.output)
176
+ ) / PRICE_UNIT_TOKENS;
177
+
178
+ return Math.round(usd * 1_000_000);
179
+ }
180
+
181
+ export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
182
+
183
+ export default {
184
+ getModelPricing,
185
+ calculateUsageCostMicrousd,
186
+ DEFAULT_PRICING_MODEL
187
+ };
@@ -72,6 +72,7 @@ export async function* streamResponsesAPI(response, model) {
72
72
  let stopReason = 'end_turn';
73
73
  let pendingArguments = '';
74
74
  let usage = { input_tokens: 0, output_tokens: 0 };
75
+ let hasCompletedResponse = false;
75
76
 
76
77
  const reader = response.body.getReader();
77
78
  const decoder = new TextDecoder();
@@ -98,6 +99,7 @@ export async function* streamResponsesAPI(response, model) {
98
99
 
99
100
  // Extract usage from completed response
100
101
  if (eventType === 'response.completed' && event.response?.usage) {
102
+ hasCompletedResponse = true;
101
103
  if (shouldLogRawProxyPayloads()) {
102
104
  logger.info('[OpenAI Response Completed]', event.response);
103
105
  }
@@ -122,7 +124,13 @@ export async function* streamResponsesAPI(response, model) {
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;
@@ -5,6 +5,8 @@
5
5
  * GET /accounts/status
6
6
  * GET /accounts/quota
7
7
  * GET /accounts/quota/all
8
+ * GET /accounts/rate-limit-reset-credits
9
+ * POST /accounts/rate-limit-reset-credits/consume
8
10
  * POST /accounts/add
9
11
  * POST /accounts/add/manual
10
12
  * POST /accounts/switch
@@ -12,6 +14,7 @@
12
14
  * POST /accounts/refresh
13
15
  * POST /accounts/refresh/all
14
16
  * POST /accounts/:email/refresh
17
+ * PUT /accounts/:email/expiration
15
18
  * POST /accounts/oauth/cleanup
16
19
  * DELETE /accounts/:email
17
20
  */
@@ -30,7 +33,8 @@ import {
30
33
  saveAccounts,
31
34
  updateAccountAuth,
32
35
  updateAccountQuota,
33
- getAccountQuota
36
+ getAccountQuota,
37
+ updateAccountExpiration
34
38
  } from '../account-manager.js';
35
39
 
36
40
  import {
@@ -45,9 +49,13 @@ import {
45
49
  } from '../oauth.js';
46
50
 
47
51
  import {
48
- getAccountQuota as fetchAccountQuota
52
+ getAccountQuota as fetchAccountQuota,
53
+ fetchRateLimitResetCredits,
54
+ consumeRateLimitResetCredit
49
55
  } from '../model-api.js';
50
56
 
57
+ import { randomUUID } from 'crypto';
58
+
51
59
  import { logger } from '../utils/logger.js';
52
60
 
53
61
  // Tracks active OAuth callback servers keyed by port
@@ -172,6 +180,30 @@ export async function handleRefreshAllAccounts(req, res) {
172
180
  res.json(result);
173
181
  }
174
182
 
183
+ export function handleUpdateAccountExpiration(req, res) {
184
+ const email = decodeURIComponent(req.params.email);
185
+ const { accountExpiresAt } = req.body || {};
186
+
187
+ if (accountExpiresAt !== null && accountExpiresAt !== undefined) {
188
+ if (typeof accountExpiresAt !== 'string' || !accountExpiresAt.trim()) {
189
+ return res.status(400).json({ success: false, message: 'accountExpiresAt must be an ISO 8601 date or null' });
190
+ }
191
+
192
+ const normalizedAccountExpiresAt = accountExpiresAt.trim();
193
+ const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
194
+ const expiresAt = new Date(normalizedAccountExpiresAt);
195
+ if (!isoDatePattern.test(normalizedAccountExpiresAt) || Number.isNaN(expiresAt.getTime())) {
196
+ return res.status(400).json({ success: false, message: 'accountExpiresAt must be a valid ISO 8601 date' });
197
+ }
198
+
199
+ const result = updateAccountExpiration(email, expiresAt.toISOString());
200
+ return res.status(result.success ? 200 : 404).json(result);
201
+ }
202
+
203
+ const result = updateAccountExpiration(email, null);
204
+ return res.status(result.success ? 200 : 404).json(result);
205
+ }
206
+
175
207
  export async function handleRefreshActiveAccount(req, res) {
176
208
  const result = await refreshActiveAccount();
177
209
  res.json(result);
@@ -232,6 +264,75 @@ export async function handleGetQuota(req, res) {
232
264
  }
233
265
  }
234
266
 
267
+ /**
268
+ * Lists an account's rate-limit reset credits.
269
+ */
270
+ export async function handleGetRateLimitResetCredits(req, res) {
271
+ const { email } = req.query;
272
+ const account = email
273
+ ? loadAccounts().accounts.find(a => a.email === email)
274
+ : getActiveAccount();
275
+
276
+ if (!account) {
277
+ return res.status(404).json({
278
+ success: false,
279
+ error: email ? `Account not found: ${email}` : 'No active account'
280
+ });
281
+ }
282
+
283
+ try {
284
+ const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
285
+ res.json({ success: true, email: account.email, credits });
286
+ } catch (error) {
287
+ logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
288
+ res.status(502).json({ success: false, error: error.message });
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Redeems one available rate-limit reset credit for an account.
294
+ */
295
+ export async function handleConsumeRateLimitResetCredit(req, res) {
296
+ const { email, creditId, redeemRequestId } = req.body || {};
297
+ const account = email
298
+ ? loadAccounts().accounts.find(a => a.email === email)
299
+ : getActiveAccount();
300
+
301
+ if (!account) {
302
+ return res.status(404).json({
303
+ success: false,
304
+ error: email ? `Account not found: ${email}` : 'No active account'
305
+ });
306
+ }
307
+
308
+ if (redeemRequestId !== undefined && (
309
+ typeof redeemRequestId !== 'string' ||
310
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(redeemRequestId.trim())
311
+ )) {
312
+ return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
313
+ }
314
+
315
+ if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
316
+ return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
317
+ }
318
+
319
+ const idempotencyKey = redeemRequestId?.trim() || randomUUID();
320
+
321
+ try {
322
+ const result = await consumeRateLimitResetCredit(
323
+ account.accessToken,
324
+ account.accountId,
325
+ idempotencyKey,
326
+ creditId?.trim() || null
327
+ );
328
+ logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
329
+ res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
330
+ } catch (error) {
331
+ logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
332
+ res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
333
+ }
334
+ }
335
+
235
336
  export async function handleGetAllQuotas(req, res) {
236
337
  const { accounts: accountList } = listAccounts();
237
338
  const results = [];
@@ -304,9 +405,12 @@ export default {
304
405
  handleSwitchAccount,
305
406
  handleRefreshAccount,
306
407
  handleRefreshAllAccounts,
408
+ handleUpdateAccountExpiration,
307
409
  handleRefreshActiveAccount,
308
410
  handleRemoveAccount,
309
411
  handleImportAccount,
310
412
  handleGetQuota,
413
+ handleGetRateLimitResetCredits,
414
+ handleConsumeRateLimitResetCredit,
311
415
  handleGetAllQuotas
312
416
  };
@@ -7,15 +7,18 @@
7
7
  import express from 'express';
8
8
  import { createRequire } from 'module';
9
9
  import { join, dirname } from 'path';
10
+ import { readFileSync } from 'fs';
10
11
  import { fileURLToPath } from 'url';
11
12
 
12
13
  import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
13
14
  import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
15
+ import { getAdminPath } from '../admin-path.js';
14
16
 
15
17
  // Route handlers
16
18
  import { handleMessages } from './messages-route.js';
17
19
  import { handleChatCompletion, handleCountTokens } from './chat-route.js';
18
20
  import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
21
+ import { handleGetClientQuota } from './client-quota-route.js';
19
22
  import {
20
23
  handleGetAccountStrategy,
21
24
  handleSetAccountStrategy,
@@ -39,10 +42,13 @@ import {
39
42
  handleSwitchAccount,
40
43
  handleRefreshAccount,
41
44
  handleRefreshAllAccounts,
45
+ handleUpdateAccountExpiration,
42
46
  handleRefreshActiveAccount,
43
47
  handleRemoveAccount,
44
48
  handleImportAccount,
45
49
  handleGetQuota,
50
+ handleGetRateLimitResetCredits,
51
+ handleConsumeRateLimitResetCredit,
46
52
  handleGetAllQuotas
47
53
  } from './accounts-route.js';
48
54
 
@@ -51,17 +57,24 @@ const require = createRequire(import.meta.url);
51
57
  const packageJson = require('../../package.json');
52
58
 
53
59
  export function registerApiRoutes(app, { port }) {
54
- // ─── Static Web UI ─────────────────────────────────────────────────────────
60
+ const adminPath = getAdminPath();
55
61
  const publicDirectory = join(__dirname, '..', '..', 'public');
56
- app.use(express.static(publicDirectory));
62
+ const adminRouter = express.Router();
63
+ const sendAdminHtml = (fileName) => {
64
+ const html = readFileSync(join(publicDirectory, fileName), 'utf8')
65
+ .replace(/(href|src)="\//g, `$1="${adminPath}/`)
66
+ .replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
67
+ return (req, res) => res.type('html').send(html);
68
+ };
57
69
 
58
- app.get(['/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], (req, res) => {
59
- res.sendFile(join(publicDirectory, 'index.html'));
60
- });
70
+ // ─── Static Web UI ─────────────────────────────────────────────────────────
71
+ adminRouter.use(express.static(publicDirectory, { index: false }));
61
72
 
62
- app.get('/login', (req, res) => {
63
- res.sendFile(join(publicDirectory, 'login.html'));
64
- });
73
+ adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
74
+
75
+ adminRouter.get('/login', sendAdminHtml('login.html'));
76
+
77
+ app.use(adminPath, adminRouter);
65
78
 
66
79
  // ─── Health ────────────────────────────────────────────────────────────────
67
80
  app.get('/health', (req, res) => {
@@ -88,51 +101,55 @@ export function registerApiRoutes(app, { port }) {
88
101
  // ─── OpenAI Chat Completions API ───────────────────────────────────────────
89
102
  app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
90
103
 
91
- // ─── Models ────────────────────────────────────────────────────────────────
104
+ // ─── Models and Client Quota ───────────────────────────────────────────────
92
105
  app.get('/v1/models', requireClientAuth, handleListModels);
106
+ app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
93
107
 
94
- app.use(requireAdminAuth);
108
+ adminRouter.use(requireAdminAuth);
95
109
 
96
- app.get('/accounts/models', handleAccountModels);
97
- app.get('/accounts/usage', handleAccountUsage);
110
+ adminRouter.get('/accounts/models', handleAccountModels);
111
+ adminRouter.get('/accounts/usage', handleAccountUsage);
98
112
 
99
113
  // ─── Settings ──────────────────────────────────────────────────────────────
100
- app.get('/settings/account-strategy', handleGetAccountStrategy);
101
- app.post('/settings/account-strategy', handleSetAccountStrategy);
102
- app.get('/settings/model-map', handleGetModelMap);
103
- app.post('/settings/model-map', handleSetModelMap);
104
- app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
105
- app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
106
- app.get('/settings/client-api-keys', handleListClientApiKeys);
107
- app.post('/settings/client-api-keys', handleCreateClientApiKey);
108
- app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
109
- app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
114
+ adminRouter.get('/settings/account-strategy', handleGetAccountStrategy);
115
+ adminRouter.post('/settings/account-strategy', handleSetAccountStrategy);
116
+ adminRouter.get('/settings/model-map', handleGetModelMap);
117
+ adminRouter.post('/settings/model-map', handleSetModelMap);
118
+ adminRouter.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
119
+ adminRouter.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
120
+ adminRouter.get('/settings/client-api-keys', handleListClientApiKeys);
121
+ adminRouter.post('/settings/client-api-keys', handleCreateClientApiKey);
122
+ adminRouter.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
123
+ adminRouter.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
110
124
 
111
125
  // ─── Account Management ───────────────────────────────────────────────────
112
- app.get('/accounts', handleListAccounts);
113
- app.get('/accounts/status', handleAccountStatus);
114
- app.get('/accounts/quota', handleGetQuota);
115
- app.get('/accounts/quota/all', handleGetAllQuotas);
116
-
117
- app.post('/accounts/add', handleAddAccount);
118
- app.post('/accounts/add/manual', handleAddAccountManual);
119
- app.post('/accounts/switch', handleSwitchAccount);
120
- app.post('/accounts/import', handleImportAccount);
121
- app.post('/accounts/refresh', handleRefreshActiveAccount);
122
- app.post('/accounts/refresh/all', handleRefreshAllAccounts);
123
- app.post('/accounts/oauth/cleanup', handleOAuthCleanup);
124
- app.post('/accounts/:email/refresh', handleRefreshAccount);
125
-
126
- app.delete('/accounts/:email', handleRemoveAccount);
126
+ adminRouter.get('/accounts', handleListAccounts);
127
+ adminRouter.get('/accounts/status', handleAccountStatus);
128
+ adminRouter.get('/accounts/quota', handleGetQuota);
129
+ adminRouter.get('/accounts/quota/all', handleGetAllQuotas);
130
+ adminRouter.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
131
+ adminRouter.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
132
+
133
+ adminRouter.post('/accounts/add', handleAddAccount);
134
+ adminRouter.post('/accounts/add/manual', handleAddAccountManual);
135
+ adminRouter.post('/accounts/switch', handleSwitchAccount);
136
+ adminRouter.post('/accounts/import', handleImportAccount);
137
+ adminRouter.post('/accounts/refresh', handleRefreshActiveAccount);
138
+ adminRouter.post('/accounts/refresh/all', handleRefreshAllAccounts);
139
+ adminRouter.post('/accounts/oauth/cleanup', handleOAuthCleanup);
140
+ adminRouter.post('/accounts/:email/refresh', handleRefreshAccount);
141
+ adminRouter.put('/accounts/:email/expiration', handleUpdateAccountExpiration);
142
+
143
+ adminRouter.delete('/accounts/:email', handleRemoveAccount);
127
144
 
128
145
  // ─── Claude CLI Configuration ──────────────────────────────────────────────
129
- app.get('/claude/config', handleGetClaudeConfig);
130
- app.post('/claude/config/direct', handleSetDirectMode);
131
- app.post('/claude/config/set', handleSetClaudeApiEndpoint);
146
+ adminRouter.get('/claude/config', handleGetClaudeConfig);
147
+ adminRouter.post('/claude/config/direct', handleSetDirectMode);
148
+ adminRouter.post('/claude/config/set', handleSetClaudeApiEndpoint);
132
149
 
133
150
  // ─── Logs ──────────────────────────────────────────────────────────────────
134
- app.get('/api/logs', handleGetLogs);
135
- app.get('/api/logs/stream', handleStreamLogs);
151
+ adminRouter.get('/api/logs', handleGetLogs);
152
+ adminRouter.get('/api/logs/stream', handleStreamLogs);
136
153
  }
137
154
 
138
155
  export default { registerApiRoutes };