claude-codex-proxy 1.0.5-beta.29 → 1.0.5-beta.30

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.29",
3
+ "version": "1.0.5-beta.30",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -443,7 +443,7 @@ table .btn-outline:hover {
443
443
  .client-keys-list { padding: 0.75rem; }
444
444
  .client-key-card {
445
445
  display: grid;
446
- grid-template-columns: minmax(270px, 1.45fr) minmax(230px, 1.15fr) 130px 110px auto;
446
+ grid-template-columns: minmax(250px, 1.25fr) minmax(230px, 1.15fr) 140px 105px auto;
447
447
  align-items: center;
448
448
  gap: 1.5rem;
449
449
  padding: 1.1rem 1rem;
@@ -478,6 +478,8 @@ table .btn-outline:hover {
478
478
  .client-key-fields input { padding: 0 0.7rem; }
479
479
  .client-key-fields input:focus, .client-key-limit input:focus { border-color: rgba(168, 85, 247, 0.72); background: rgba(26, 26, 40, 0.9); }
480
480
 
481
+ .client-key-quotas, .client-key-limits { display: grid; gap: 0.7rem; }
482
+ .client-key-quota-disabled { opacity: 0.45; }
481
483
  .client-key-quota-heading { display: flex; align-items: end; justify-content: space-between; gap: 1rem; }
482
484
  .client-key-quota-heading strong { color: #f8fafc; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; font-weight: 600; white-space: nowrap; }
483
485
  .client-key-quota-heading small { color: #64748b; font-size: 0.6875rem; font-weight: 400; }
@@ -488,6 +490,9 @@ table .btn-outline:hover {
488
490
  .client-key-limit > div { display: flex; height: 2.15rem; border: 1px solid rgba(42, 42, 62, 0.75); border-radius: 0.45rem; background: rgba(15, 15, 26, 0.62); }
489
491
  .client-key-limit b { display: grid; width: 1.9rem; place-items: center; border-right: 1px solid rgba(42, 42, 62, 0.75); color: #64748b; font-size: 0.75rem; font-weight: 500; }
490
492
  .client-key-limit input { height: auto; padding: 0 0.55rem; border: 0; background: transparent; font-family: 'JetBrains Mono', monospace; }
493
+ .client-key-limit input:disabled { opacity: 0.4; cursor: not-allowed; }
494
+ .client-key-limit-toggle { display: flex; align-items: center; gap: 0.45rem; color: #94a3b8; font-size: 0.65rem; font-weight: 600; }
495
+ .client-key-limit-toggle input { accent-color: #a855f7; }
491
496
 
492
497
  .client-key-meta strong, .client-key-meta small { display: block; font-family: 'JetBrains Mono', monospace; white-space: nowrap; }
493
498
  .client-key-meta strong { color: #a1a1aa; font-size: 0.6875rem; font-weight: 500; }
package/public/js/app.js CHANGED
@@ -9,7 +9,8 @@ document.addEventListener('alpine:init', () => {
9
9
  accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
10
10
  accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
11
11
  modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
12
- clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
12
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50,
13
+ clientApiKeyFiveHourLimitEnabled: false, clientApiKeyFiveHourLimitUsd: 0, clientApiKeysLoading: false,
13
14
  clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
14
15
  showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
15
16
  showAccountExpirationModalView: false, expirationTarget: null, accountExpirationInput: '', accountExpirationSaving: false,
@@ -185,9 +186,9 @@ document.addEventListener('alpine:init', () => {
185
186
  async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
186
187
  async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
187
188
  async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
188
- async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
189
+ async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); const fiveHourLimitUsd = Number(this.clientApiKeyFiveHourLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } if (!Number.isFinite(fiveHourLimitUsd) || fiveHourLimitUsd < 0) { this.showToast('5-hour limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd, fiveHourLimitEnabled: this.clientApiKeyFiveHourLimitEnabled, fiveHourLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.clientApiKeyFiveHourLimitEnabled = false; this.clientApiKeyFiveHourLimitUsd = 0; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
189
190
  async loadClientProxyConfig() { try { const response = await fetch('/claude/config/proxy', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); if (response.ok && data?.success && data?.env) this.clientProxyConfig = data; } catch {} }, async copyClientText(text, successMessage) { if (!text) return; try { if (navigator.clipboard?.writeText && window.isSecureContext) await navigator.clipboard.writeText(text); else { const textarea = document.createElement('textarea'); textarea.value = text; textarea.setAttribute('readonly', ''); textarea.style.cssText = 'position:absolute;opacity:0;left:-999999px;top:-999999px'; document.body.appendChild(textarea); textarea.focus(); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('Clipboard copy was rejected'); } this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const configureCommands = this.clientProxyConfig?.commands?.powershell; const clearCommands = this.clientProxyConfig?.commands?.clear?.powershell; const commands = [...(Array.isArray(configureCommands) ? configureCommands : []), ...(Array.isArray(clearCommands) ? clearCommands : [])]; return commands.length ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
190
- async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
191
+ async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); const fiveHourLimitUsd = Number(clientApiKey.fiveHourLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } if (!Number.isFinite(fiveHourLimitUsd) || fiveHourLimitUsd < 0) { this.showToast('5-hour limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd, fiveHourLimitEnabled: clientApiKey.fiveHourLimitEnabled === true, fiveHourLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
191
192
  showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, async loadLogs(page = 1) { if (this.logLoading) return; this.logLoading = true; const { ok, data } = await this.api(`/api/logs?page=${page}&pageSize=${this.logPageSize}`); this.logLoading = false; if (!ok || !Array.isArray(data?.logs)) { this.showToast(data?.error || 'Failed to load logs', 'error'); return; } this.logs = data.logs; this.logPage = data.page; this.logTotal = data.total; this.logTotalPages = data.totalPages; }, async changeLogPage(page) { if (page < 1 || page > this.logTotalPages || page === this.logPage) return; await this.loadLogs(page); }, startLogStream() { if (!this.isAuthenticated) return; this.loadLogs(); this.logEventSource?.close(); const params = new URLSearchParams(); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(adminUrl(`/api/logs/stream?${params}`)); this.logEventSource.onmessage = event => { try { this.logTotal += 1; this.logTotalPages = Math.ceil(this.logTotal / this.logPageSize); if (this.logPage === 1) this.logs = [JSON.parse(event.data), ...this.logs].slice(0, this.logPageSize); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; this.logTotal = 0; this.logTotalPages = 0; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
192
193
  }));
193
194
  });
@@ -19,6 +19,15 @@
19
19
  <input type="number" min="0" step="0.01" x-model="clientApiKeyWeeklyLimitUsd"
20
20
  class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
21
21
  </label>
22
+ <label class="flex items-center justify-between gap-4 rounded-lg border border-space-border bg-space-800 px-3 py-2.5">
23
+ <span class="text-xs text-gray-300">Enable fixed 5-hour limit</span>
24
+ <input type="checkbox" x-model="clientApiKeyFiveHourLimitEnabled" class="h-4 w-4 accent-purple-500">
25
+ </label>
26
+ <label class="block">
27
+ <span class="block text-xs text-gray-400 mb-2">5-hour limit (USD)</span>
28
+ <input type="number" min="0" step="0.01" x-model="clientApiKeyFiveHourLimitUsd" :disabled="!clientApiKeyFiveHourLimitEnabled"
29
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm disabled:opacity-40" @keydown.enter="createClientApiKey()">
30
+ </label>
22
31
  </div>
23
32
  <div class="mt-6 flex justify-end gap-2">
24
33
  <button class="btn btn-outline btn-sm text-gray-400" @click="showCreateClientApiKeyModal = false" :disabled="clientApiKeySaving">Cancel</button>
@@ -42,16 +42,30 @@
42
42
  </div>
43
43
  </div>
44
44
 
45
- <div class="client-key-quota">
46
- <div class="client-key-quota-heading">
47
- <span>Weekly usage</span>
48
- <strong><span x-text="`$${(clientApiKey.quota?.consumedUsd ?? 0).toFixed(2)}`"></span><small x-text="` / $${Number(clientApiKey.weeklyLimitUsd || 0).toFixed(2)}`"></small></strong>
45
+ <div class="client-key-quotas">
46
+ <div class="client-key-quota">
47
+ <div class="client-key-quota-heading">
48
+ <span>Weekly usage</span>
49
+ <strong><span x-text="`$${(clientApiKey.quota?.consumedUsd ?? 0).toFixed(2)}`"></span><small x-text="` / $${Number(clientApiKey.weeklyLimitUsd || 0).toFixed(2)}`"></small></strong>
50
+ </div>
51
+ <div class="client-key-progress"><i :style="`width: ${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100))}%`"></i></div>
52
+ <div class="client-key-quota-foot"><span x-text="`$${(clientApiKey.quota?.remainingUsd ?? (Number(clientApiKey.weeklyLimitUsd) || 0)).toFixed(2)} remaining`"></span><span x-text="`${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100)).toFixed(1)}% used`"></span></div>
53
+ </div>
54
+ <div class="client-key-quota" :class="{ 'client-key-quota-disabled': !clientApiKey.fiveHourLimitEnabled }">
55
+ <div class="client-key-quota-heading">
56
+ <span>5-hour usage</span>
57
+ <strong x-text="clientApiKey.fiveHourLimitEnabled ? `$${(clientApiKey.quota?.fiveHourConsumedUsd ?? 0).toFixed(2)} / $${Number(clientApiKey.fiveHourLimitUsd || 0).toFixed(2)}` : 'Off'"></strong>
58
+ </div>
59
+ <div class="client-key-progress"><i :style="`width: ${clientApiKey.fiveHourLimitEnabled ? Math.min(100, Math.max(0, ((clientApiKey.quota?.fiveHourConsumedUsd ?? 0) / Math.max(Number(clientApiKey.fiveHourLimitUsd) || 0, 0.000001)) * 100)) : 0}%`"></i></div>
60
+ <div class="client-key-quota-foot"><span x-text="clientApiKey.fiveHourLimitEnabled ? `$${(clientApiKey.quota?.fiveHourRemainingUsd ?? (Number(clientApiKey.fiveHourLimitUsd) || 0)).toFixed(2)} remaining` : 'Limit disabled'"></span><span x-text="clientApiKey.fiveHourLimitEnabled && clientApiKey.quota?.nextFiveHourPeriodStart ? new Date(clientApiKey.quota.nextFiveHourPeriodStart).toLocaleTimeString() : ''"></span></div>
49
61
  </div>
50
- <div class="client-key-progress"><i :style="`width: ${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100))}%`"></i></div>
51
- <div class="client-key-quota-foot"><span x-text="`$${(clientApiKey.quota?.remainingUsd ?? (Number(clientApiKey.weeklyLimitUsd) || 0)).toFixed(2)} remaining`"></span><span x-text="`${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100)).toFixed(1)}% used`"></span></div>
52
62
  </div>
53
63
 
54
- <label class="client-key-limit"><span>Weekly limit</span><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.weeklyLimitUsd"></div></label>
64
+ <div class="client-key-limits">
65
+ <label class="client-key-limit"><span>Weekly limit</span><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.weeklyLimitUsd"></div></label>
66
+ <label class="client-key-limit-toggle"><input type="checkbox" x-model="clientApiKey.fiveHourLimitEnabled"><span>5-hour limit</span></label>
67
+ <label class="client-key-limit"><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.fiveHourLimitUsd" :disabled="!clientApiKey.fiveHourLimitEnabled"></div></label>
68
+ </div>
55
69
 
56
70
  <div class="client-key-meta"><span>Created</span><strong x-text="new Date(clientApiKey.createdAt).toLocaleDateString()"></strong><small x-text="new Date(clientApiKey.createdAt).toLocaleTimeString()"></small></div>
57
71
 
@@ -63,6 +63,21 @@ export function getNextPeriodStart(now = new Date()) {
63
63
  return nextPeriodStart.toISOString();
64
64
  }
65
65
 
66
+ const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
67
+
68
+ /**
69
+ * Returns the start of the current globally aligned five-hour window.
70
+ * Boundaries occur every five hours from the Unix epoch and always fall on
71
+ * an exact hour.
72
+ */
73
+ export function getCurrentFiveHourPeriodStart(now = new Date()) {
74
+ return new Date(Math.floor(now.getTime() / FIVE_HOURS_MS) * FIVE_HOURS_MS).toISOString();
75
+ }
76
+
77
+ export function getNextFiveHourPeriodStart(now = new Date()) {
78
+ return new Date(new Date(getCurrentFiveHourPeriodStart(now)).getTime() + FIVE_HOURS_MS).toISOString();
79
+ }
80
+
66
81
  export function usdToMicrousd(usd) {
67
82
  return Math.round(Number(usd) * MICRO_USD_PER_USD);
68
83
  }
@@ -77,20 +92,37 @@ export function microusdToUsd(microusd) {
77
92
  export function getClientKeyUsage(keyId, now = new Date()) {
78
93
  const usage = loadUsage();
79
94
  const periodStart = getCurrentPeriodStart(now);
95
+ const fiveHourPeriodStart = getCurrentFiveHourPeriodStart(now);
80
96
  const entry = usage[keyId];
81
97
  const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
82
98
  ? Math.max(0, entry.consumedMicrousd)
83
99
  : 0;
100
+ const fiveHourConsumedMicrousd = entry?.fiveHourPeriodStart === fiveHourPeriodStart
101
+ && Number.isSafeInteger(entry.fiveHourConsumedMicrousd)
102
+ ? Math.max(0, entry.fiveHourConsumedMicrousd)
103
+ : 0;
84
104
 
85
- if (!entry || entry.periodStart !== periodStart || entry.consumedMicrousd !== consumedMicrousd) {
86
- usage[keyId] = { periodStart, consumedMicrousd };
105
+ if (!entry
106
+ || entry.periodStart !== periodStart
107
+ || entry.consumedMicrousd !== consumedMicrousd
108
+ || entry.fiveHourPeriodStart !== fiveHourPeriodStart
109
+ || entry.fiveHourConsumedMicrousd !== fiveHourConsumedMicrousd) {
110
+ usage[keyId] = {
111
+ periodStart,
112
+ consumedMicrousd,
113
+ fiveHourPeriodStart,
114
+ fiveHourConsumedMicrousd
115
+ };
87
116
  saveUsage(usage);
88
117
  }
89
118
 
90
119
  return {
91
120
  periodStart,
92
121
  nextPeriodStart: getNextPeriodStart(now),
93
- consumedMicrousd
122
+ consumedMicrousd,
123
+ fiveHourPeriodStart,
124
+ nextFiveHourPeriodStart: getNextFiveHourPeriodStart(now),
125
+ fiveHourConsumedMicrousd
94
126
  };
95
127
  }
96
128
 
@@ -107,7 +139,9 @@ export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date())
107
139
  const usage = loadUsage();
108
140
  usage[keyId] = {
109
141
  periodStart: current.periodStart,
110
- consumedMicrousd: current.consumedMicrousd + consumedMicrousd
142
+ consumedMicrousd: current.consumedMicrousd + consumedMicrousd,
143
+ fiveHourPeriodStart: current.fiveHourPeriodStart,
144
+ fiveHourConsumedMicrousd: current.fiveHourConsumedMicrousd + consumedMicrousd
111
145
  };
112
146
  saveUsage(usage);
113
147
  return usage[keyId];
@@ -123,10 +157,22 @@ export function deleteClientKeyUsage(keyId) {
123
157
  /**
124
158
  * Returns a key's current quota summary without charging any request.
125
159
  */
126
- export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
160
+ export function getClientKeyQuota(keyId, weeklyLimitUsd, fiveHourLimit = {}, now = new Date()) {
161
+ // Preserve the previous third-argument `now` form for internal callers and tests.
162
+ if (fiveHourLimit instanceof Date) {
163
+ now = fiveHourLimit;
164
+ fiveHourLimit = {};
165
+ }
166
+
127
167
  const usage = getClientKeyUsage(keyId, now);
128
168
  const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
129
169
  const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
170
+ const fiveHourLimitEnabled = fiveHourLimit.enabled === true;
171
+ const fiveHourLimitMicrousd = usdToMicrousd(fiveHourLimit.usd ?? 0);
172
+ const fiveHourRemainingMicrousd = Math.max(
173
+ 0,
174
+ fiveHourLimitMicrousd - usage.fiveHourConsumedMicrousd
175
+ );
130
176
 
131
177
  return {
132
178
  ...usage,
@@ -134,7 +180,13 @@ export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
134
180
  remainingMicrousd,
135
181
  weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
136
182
  consumedUsd: microusdToUsd(usage.consumedMicrousd),
137
- remainingUsd: microusdToUsd(remainingMicrousd)
183
+ remainingUsd: microusdToUsd(remainingMicrousd),
184
+ fiveHourLimitEnabled,
185
+ fiveHourLimitMicrousd,
186
+ fiveHourRemainingMicrousd,
187
+ fiveHourLimitUsd: microusdToUsd(fiveHourLimitMicrousd),
188
+ fiveHourConsumedUsd: microusdToUsd(usage.fiveHourConsumedMicrousd),
189
+ fiveHourRemainingUsd: microusdToUsd(fiveHourRemainingMicrousd)
138
190
  };
139
191
  }
140
192
 
@@ -65,9 +65,9 @@ function requireKeys(getExpectedKeys) {
65
65
  };
66
66
  }
67
67
 
68
- function sendQuotaExceeded(res, quota) {
68
+ function sendQuotaExceeded(res, period, resetsAt) {
69
69
  return res.status(429).json(
70
- createErrorResponse('rate_limit_error', `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`)
70
+ createErrorResponse('rate_limit_error', `${period} client key quota exhausted. Resets at ${resetsAt}`)
71
71
  );
72
72
  }
73
73
 
@@ -92,13 +92,20 @@ export function requireClientAuth(req, res, next) {
92
92
 
93
93
  const quota = getClientKeyQuota(
94
94
  clientKey.id,
95
- clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
95
+ clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
96
+ {
97
+ enabled: clientKey.fiveHourLimitEnabled,
98
+ usd: clientKey.fiveHourLimitUsd
99
+ }
96
100
  );
97
101
  const isModelRequest = req.method === 'POST' && (
98
102
  req.path === '/v1/messages' || req.path === '/v1/chat/completions'
99
103
  );
104
+ if (isModelRequest && quota.fiveHourLimitEnabled && quota.fiveHourRemainingMicrousd <= 0) {
105
+ return sendQuotaExceeded(res, 'Five-hour', quota.nextFiveHourPeriodStart);
106
+ }
100
107
  if (isModelRequest && quota.remainingMicrousd <= 0) {
101
- return sendQuotaExceeded(res, quota);
108
+ return sendQuotaExceeded(res, 'Weekly', quota.nextPeriodStart);
102
109
  }
103
110
 
104
111
  req.clientApiKey = { id: clientKey.id, name: clientKey.name };
@@ -1,20 +1,26 @@
1
1
  import { DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
2
2
 
3
+ function getUtilization(consumedUsd, limitUsd) {
4
+ return limitUsd > 0
5
+ ? Math.min(100, Math.max(0, (consumedUsd / limitUsd) * 100))
6
+ : null;
7
+ }
8
+
3
9
  /**
4
- * Returns the authenticated client key's weekly quota using Claude Code's
5
- * utilization response shape, so the terminal can consume it directly.
10
+ * Returns the authenticated client key's five-hour and weekly quota using
11
+ * Claude Code's utilization response shape, so the terminal can consume it directly.
6
12
  */
7
13
  export function handleGetClientQuota(req, res) {
8
14
  const quota = req.clientApiKeyQuota;
9
15
  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
16
 
14
17
  return res.json({
15
- five_hour: null,
18
+ five_hour: quota?.fiveHourLimitEnabled ? {
19
+ utilization: getUtilization(quota.fiveHourConsumedUsd, quota.fiveHourLimitUsd),
20
+ resets_at: quota.nextFiveHourPeriodStart
21
+ } : null,
16
22
  seven_day: quota ? {
17
- utilization,
23
+ utilization: getUtilization(quota.consumedUsd, weeklyLimitUsd),
18
24
  resets_at: quota.nextPeriodStart
19
25
  } : null,
20
26
  seven_day_oauth_apps: null,
@@ -14,7 +14,8 @@ import {
14
14
  getServerSettings,
15
15
  setServerSettings,
16
16
  DEFAULT_MODEL_MAP,
17
- DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
17
+ DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
18
+ DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
18
19
  } from '../server-settings.js';
19
20
  import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
20
21
 
@@ -24,13 +25,16 @@ function getSafeClientApiKey(clientApiKey) {
24
25
  const { key, ...safeClientApiKey } = clientApiKey;
25
26
  return {
26
27
  ...safeClientApiKey,
27
- quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd)
28
+ quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd, {
29
+ enabled: clientApiKey.fiveHourLimitEnabled,
30
+ usd: clientApiKey.fiveHourLimitUsd
31
+ })
28
32
  };
29
33
  }
30
34
 
31
- function validateWeeklyLimitUsd(weeklyLimitUsd) {
32
- if (typeof weeklyLimitUsd !== 'number' || !Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) {
33
- return 'weeklyLimitUsd must be a non-negative number';
35
+ function validateLimitUsd(value, fieldName) {
36
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
37
+ return `${fieldName} must be a non-negative number`;
34
38
  }
35
39
 
36
40
  return null;
@@ -185,16 +189,29 @@ export function handleListClientApiKeys(req, res) {
185
189
  * Creates a Claude Code client API key.
186
190
  */
187
191
  export function handleCreateClientApiKey(req, res) {
188
- const { name = '', remark = '', weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } = req.body || {};
192
+ const {
193
+ name = '',
194
+ remark = '',
195
+ weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
196
+ fiveHourLimitEnabled = false,
197
+ fiveHourLimitUsd = DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
198
+ } = req.body || {};
189
199
 
190
200
  if (typeof name !== 'string' || typeof remark !== 'string') {
191
201
  return res.status(400).json({ success: false, error: 'name and remark must be strings' });
192
202
  }
203
+ if (typeof fiveHourLimitEnabled !== 'boolean') {
204
+ return res.status(400).json({ success: false, error: 'fiveHourLimitEnabled must be a boolean' });
205
+ }
193
206
 
194
- const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
207
+ const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
195
208
  if (weeklyLimitError) {
196
209
  return res.status(400).json({ success: false, error: weeklyLimitError });
197
210
  }
211
+ const fiveHourLimitError = validateLimitUsd(fiveHourLimitUsd, 'fiveHourLimitUsd');
212
+ if (fiveHourLimitError) {
213
+ return res.status(400).json({ success: false, error: fiveHourLimitError });
214
+ }
198
215
 
199
216
  const clientApiKey = {
200
217
  id: crypto.randomUUID(),
@@ -202,6 +219,8 @@ export function handleCreateClientApiKey(req, res) {
202
219
  name: name.trim(),
203
220
  remark: remark.trim(),
204
221
  weeklyLimitUsd,
222
+ fiveHourLimitEnabled,
223
+ fiveHourLimitUsd,
205
224
  createdAt: new Date().toISOString()
206
225
  };
207
226
  const settings = getServerSettings();
@@ -216,7 +235,7 @@ export function handleCreateClientApiKey(req, res) {
216
235
  */
217
236
  export function handleUpdateClientApiKey(req, res) {
218
237
  const { id } = req.params;
219
- const { name, remark, weeklyLimitUsd } = req.body || {};
238
+ const { name, remark, weeklyLimitUsd, fiveHourLimitEnabled, fiveHourLimitUsd } = req.body || {};
220
239
 
221
240
  if (name !== undefined && typeof name !== 'string') {
222
241
  return res.status(400).json({ success: false, error: 'name must be a string' });
@@ -225,11 +244,20 @@ export function handleUpdateClientApiKey(req, res) {
225
244
  return res.status(400).json({ success: false, error: 'remark must be a string' });
226
245
  }
227
246
  if (weeklyLimitUsd !== undefined) {
228
- const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
247
+ const weeklyLimitError = validateLimitUsd(weeklyLimitUsd, 'weeklyLimitUsd');
229
248
  if (weeklyLimitError) {
230
249
  return res.status(400).json({ success: false, error: weeklyLimitError });
231
250
  }
232
251
  }
252
+ if (fiveHourLimitEnabled !== undefined && typeof fiveHourLimitEnabled !== 'boolean') {
253
+ return res.status(400).json({ success: false, error: 'fiveHourLimitEnabled must be a boolean' });
254
+ }
255
+ if (fiveHourLimitUsd !== undefined) {
256
+ const fiveHourLimitError = validateLimitUsd(fiveHourLimitUsd, 'fiveHourLimitUsd');
257
+ if (fiveHourLimitError) {
258
+ return res.status(400).json({ success: false, error: fiveHourLimitError });
259
+ }
260
+ }
233
261
 
234
262
  const settings = getServerSettings();
235
263
  const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
@@ -242,7 +270,9 @@ export function handleUpdateClientApiKey(req, res) {
242
270
  ...current,
243
271
  ...(name === undefined ? {} : { name: name.trim() }),
244
272
  ...(remark === undefined ? {} : { remark: remark.trim() }),
245
- ...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
273
+ ...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd }),
274
+ ...(fiveHourLimitEnabled === undefined ? {} : { fiveHourLimitEnabled }),
275
+ ...(fiveHourLimitUsd === undefined ? {} : { fiveHourLimitUsd })
246
276
  };
247
277
  const clientApiKeys = [...settings.clientApiKeys];
248
278
  clientApiKeys[index] = clientApiKey;
@@ -11,6 +11,7 @@ export const DEFAULT_MODEL_MAP = {
11
11
  };
12
12
 
13
13
  export const DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD = 50;
14
+ export const DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD = 0;
14
15
 
15
16
  export const DEFAULT_SETTINGS = {
16
17
  accountStrategy: 'sticky',
@@ -28,11 +29,16 @@ function ensureConfigDir() {
28
29
 
29
30
  function normalizeClientApiKey(clientApiKey) {
30
31
  const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
32
+ const fiveHourLimitUsd = Number(clientApiKey?.fiveHourLimitUsd);
31
33
  return {
32
34
  ...clientApiKey,
33
35
  weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
34
36
  ? weeklyLimitUsd
35
- : DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
37
+ : DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
38
+ fiveHourLimitEnabled: clientApiKey?.fiveHourLimitEnabled === true,
39
+ fiveHourLimitUsd: Number.isFinite(fiveHourLimitUsd) && fiveHourLimitUsd >= 0
40
+ ? fiveHourLimitUsd
41
+ : DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
36
42
  };
37
43
  }
38
44
 
@@ -81,5 +87,6 @@ export default {
81
87
  SETTINGS_FILE,
82
88
  DEFAULT_SETTINGS,
83
89
  DEFAULT_MODEL_MAP,
84
- DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
90
+ DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
91
+ DEFAULT_CLIENT_KEY_FIVE_HOUR_LIMIT_USD
85
92
  };