claude-codex-proxy 1.0.5-beta.10 β†’ 1.0.5-beta.11

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 CHANGED
@@ -1,289 +1 @@
1
1
  # Claude Codex Proxy
2
-
3
- ![Architecture banner](./images/f757093f-507b-4453-994e-f8275f8b07a9.png)
4
-
5
- [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/)
6
- [![Node.js Version](https://img.shields.io/badge/Node.js-18%2B-blue.svg)](https://nodejs.org/)
7
- [![GitHub stars](https://img.shields.io/github/stars/zzy-life/claude-codex-proxy?style=social)](https://github.com/zzy-life/claude-codex-proxy)
8
-
9
- > **Use Claude Code CLI with the power of ChatGPT Codex models.**
10
- > A local proxy that translates Anthropic API requests into ChatGPT Codex calls, enabling you to use the `claude` CLI tool with your ChatGPT Free/Plus/Pro subscription.
11
-
12
- > This project is forked from the original Claude/Codex proxy project and maintained with additional changes for this distribution.
13
-
14
- ---
15
-
16
- ## πŸš€ Features
17
-
18
- - **Seamless Translation**: Translates Anthropic Messages API calls to ChatGPT Codex format.
19
- - **Model Mapping**: automatically maps `claude-sonnet` and `claude-opus` to their Codex equivalents.
20
- - **Multi-Account Support**: Manage multiple ChatGPT accounts with easy switching and auto-refresh.
21
- - **Web Dashboard**: Built-in UI (`http://localhost:8081`) for managing accounts, viewing logs, and testing prompts.
22
- - **Raw Proxy Payload Logs**: Optional debug logging for Claude Code requests, upstream Codex payloads, completed responses, and upstream errors.
23
- - **Streaming Support**: Full Server-Sent Events (SSE) support for real-time responses.
24
- - **Native Tool Calling**: Supports Claude's tool use capabilities by translating them to Codex function calls.
25
-
26
- ---
27
-
28
- ## οΏ½ Security & Privacy
29
-
30
- **Is this a malicious proxy? No.**
31
-
32
- - **Local Execution**: This server runs entirely on your local machine (`localhost`).
33
- - **Direct Communication**: It connects *directly* to OpenAI/ChatGPT endpoints. No data is sent to any third-party server.
34
- - **Open Source**: The full source code is available here for you to audit.
35
- - **No Data Collection**: We do not track your prompts, keys, or personal data.
36
-
37
- ---
38
-
39
- ## βš™οΈ How it works
40
-
41
- This tool acts as a "translation layer" between the Claude CLI and ChatGPT's Codex backend.
42
-
43
- 1. **Intercept**: Claude Code CLI sends a request to `localhost:8081` (thinking it's Anthropic's API).
44
- 2. **Translate**: The proxy converts the Anthropic-format JSON into the specific payload format required by ChatGPT's internal Codex API.
45
- 3. **Forward**: The request is sent securely to ChatGPT using your own authenticated session.
46
- 4. **Stream**: The response from ChatGPT is converted back into Anthropic's Server-Sent Events (SSE) format and streamed to your terminal.
47
-
48
- ```
49
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
50
- β”‚ Claude Code │────▢│ This Proxy Server │────▢│ ChatGPT Codex Backend API β”‚
51
- β”‚ (Anthropic API) β”‚ β”‚ (Anthropic ⇄ OpenAI)β”‚ β”‚ (codex/responses) β”‚
52
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
53
- ```
54
-
55
- ---
56
-
57
- ## οΏ½πŸ“¦ Installation
58
-
59
- You don't need to install anything if you just want to run it:
60
-
61
- ```bash
62
- # Run directly with npx
63
- npx claude-codex-proxy@latest start
64
- ```
65
-
66
- Or install globally to use the CLI commands anywhere:
67
-
68
- ```bash
69
- npm install -g claude-codex-proxy
70
- claude-codex-proxy start
71
- ```
72
-
73
- ---
74
-
75
- ## βœ… Recommended Claude Code Version
76
-
77
- Recommended Claude Code CLI versions:
78
-
79
- - `2.1.79`
80
- - `2.1.88`
81
-
82
- Other versions may work, but these versions are recommended for better compatibility with this proxy.
83
-
84
- ---
85
-
86
- ## 🚦 Quick Start
87
-
88
- ### 1. Start the Proxy
89
-
90
- ```bash
91
- npx claude-codex-proxy@latest start
92
- ```
93
- The startup prompt asks you to choose **local deployment** or **public deployment**.
94
-
95
- - Local deployment: no access key is required.
96
- - Public deployment: enter the UI/admin access key to unlock the Web Dashboard and management APIs. After startup, create and manage Claude Code client API keys from **Settings β†’ Claude Code Client API Keys**.
97
-
98
- For non-interactive deployments, pass the mode and admin key directly. The command-line options take precedence over environment variables:
99
-
100
- ```bash
101
- claude-codex-proxy start --mode public --admin-key "your-admin-key"
102
- ```
103
-
104
- ```bash
105
- PROXY_DEPLOYMENT_MODE=public PROXY_ADMIN_KEY="your-admin-key" claude-codex-proxy start
106
- ```
107
-
108
- PowerShell:
109
-
110
- ```powershell
111
- $env:PROXY_DEPLOYMENT_MODE="public"; $env:PROXY_ADMIN_KEY="your-admin-key"; npm start
112
- ```
113
-
114
- The server will start at `http://localhost:8081` by default. To use another port:
115
-
116
- ```bash
117
- PORT=8082 claude-codex-proxy start
118
- ```
119
-
120
- PowerShell:
121
-
122
- ```powershell
123
- $env:PORT=9000; npm start
124
- ```
125
-
126
- ### 2. Add Your Account
127
-
128
- #### **Option A: Web Dashboard (Local Desktop)**
129
-
130
- 1. Open the dashboard at **[http://localhost:8081](http://localhost:8081)**
131
- 2. Go to the **Accounts** tab
132
- 3. Click **Add Account** and login with your ChatGPT account
133
-
134
- #### **Option B: CLI (Desktop or Headless/VM)**
135
-
136
- ```bash
137
- # Desktop (opens browser)
138
- claude-codex-proxy accounts add
139
-
140
- # Headless/VM server (manual code input)
141
- claude-codex-proxy accounts add --no-browser
142
- ```
143
-
144
- For **headless/VM servers** without a browser:
145
- 1. Run the command with `--no-browser`
146
- 2. It will print a URL - copy and open it on a device with a browser
147
- 3. Complete login on that device
148
- 4. After redirect, copy the callback URL (or just the code)
149
- 5. Paste it back in the terminal
150
-
151
- ### 3. Configure Claude Code
152
- Run this command to configure your `claude` CLI to use the proxy:
153
- ```bash
154
- curl -X POST http://localhost:8081/claude/config/proxy
155
- ```
156
-
157
- In local deployment, this writes the local Claude Code configuration on the machine running the proxy.
158
-
159
- In public deployment, this endpoint does **not** modify the server machine's Claude Code configuration. It only returns the client-side values to set:
160
- ```json
161
- {
162
- "env": {
163
- "ANTHROPIC_BASE_URL": "http://your-server:8081",
164
- "ANTHROPIC_API_KEY": "<client-api-key>"
165
- }
166
- }
167
- ```
168
-
169
- Create a Claude Code client API key in **Settings β†’ Claude Code Client API Keys**, then use it as `ANTHROPIC_API_KEY`.
170
-
171
- *Alternatively, set the environment variables manually:*
172
- ```bash
173
- export ANTHROPIC_BASE_URL=http://localhost:8081
174
- export ANTHROPIC_API_KEY=<client-api-key>
175
- ```
176
-
177
- To skip Claude Code's login/onboarding prompt, edit `~/.claude.json` and add:
178
- ```json
179
- {
180
- "hasCompletedOnboarding": true
181
- }
182
- ```
183
-
184
- 4. **Run Claude**:
185
- ```bash
186
- claude
187
- ```
188
-
189
- ---
190
-
191
- ## 🧠 Model Mapping
192
-
193
- The proxy resolves model names dynamically, so Claude Code can request Claude-style names while the proxy routes them to Codex models through your ChatGPT account.
194
-
195
- Default mapping:
196
-
197
- | Requested Model | Upstream Model | Auth Required | Description |
198
- | :--- | :--- | :---: | :--- |
199
- | `claude-*sonnet*` | `gpt-5.5` | βœ… | Uses the configured Sonnet-family Codex model. |
200
- | `claude-*opus*` | `gpt-5.5` | βœ… | Uses the configured Opus-family Codex model. |
201
- | `claude-*haiku*` | `gpt-5.4-mini` | βœ… | Uses the configured Haiku-family Codex model by default. |
202
- | `gpt-*` | unchanged | βœ… | Direct Codex model IDs pass through without remapping. |
203
- | unknown model | `gpt-5.5` | βœ… | Falls back to the configured default Codex model. |
204
-
205
- You can customize mappings from the Web Dashboard, go to the model settings, and choose the Codex model used for each Claude family.
206
-
207
- ---
208
-
209
- ## πŸ› οΈ Configuration & API
210
-
211
- ### Web Dashboard
212
- Visit `http://localhost:8081` to:
213
- - **Manage Accounts**: Add, remove, or switch active ChatGPT accounts.
214
- - **View Logs**: See real-time request/response logs for debugging.
215
- - **Test Models**: Run quick tests against the configured models.
216
- - **Configure Raw Proxy Payload Logs**: Enable detailed debugging logs from the Settings tab when you need to inspect raw Claude Code requests and upstream Codex payloads.
217
-
218
- ### Raw Proxy Payload Logs
219
- Raw payload logging is disabled by default because it may include prompts, tool results, file contents, and upstream response bodies. When enabled, the Logs tab captures:
220
-
221
- - `[Claude Request]`: the original Anthropic-compatible request body received from Claude Code.
222
- - `[Client Request]`: the original OpenAI Chat Completions-compatible request body, when using `/v1/chat/completions`.
223
- - `[OpenAI Request]`: the converted payload sent to the ChatGPT Codex Responses API.
224
- - `[OpenAI Response Completed]`: the completed upstream response object.
225
- - `[OpenAI Error]`: non-2xx upstream status and error body.
226
-
227
- You can enable it from the Web Dashboard under **Settings β†’ Raw Proxy Payload Logs**, or via API:
228
-
229
- ```bash
230
- curl -X POST http://localhost:8081/settings/raw-proxy-logs \
231
- -H "Content-Type: application/json" \
232
- -H "Authorization: Bearer <ui-admin-key>" \
233
- -d '{"enabled":true}'
234
- ```
235
-
236
- Disable it again with:
237
-
238
- ```bash
239
- curl -X POST http://localhost:8081/settings/raw-proxy-logs \
240
- -H "Content-Type: application/json" \
241
- -H "Authorization: Bearer <ui-admin-key>" \
242
- -d '{"enabled":false}'
243
- ```
244
-
245
- Check the current state:
246
-
247
- ```bash
248
- curl http://localhost:8081/settings/raw-proxy-logs \
249
- -H "Authorization: Bearer <ui-admin-key>"
250
- ```
251
-
252
- Authentication headers and access tokens are not logged.
253
-
254
- ### API Endpoints
255
- - `GET /health`: Check server status.
256
- - `GET /accounts`: List configured accounts. In public deployment, requires the UI/admin access key.
257
- - `POST /v1/messages`: Anthropic-compatible chat completion endpoint. In public deployment, requires the Claude Code client API key.
258
- - `POST /claude/config/proxy`: Returns Claude Code proxy configuration. In public deployment, this is public and dry-run only.
259
-
260
- See [API Documentation](./docs/API.md) for full details.
261
-
262
- ---
263
-
264
- ## 🀝 Contributing
265
-
266
- Contributions are welcome! Please feel free to submit a Pull Request.
267
-
268
- 1. Fork the repository
269
- 2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
270
- 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
271
- 4. Push to the branch (`git push origin feature/AmazingFeature`)
272
- 5. Open a Pull Request
273
-
274
- ---
275
-
276
- ## πŸ“„ License
277
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
278
-
279
- ## ⚠️ Disclaimer
280
- This project is an independent open-source tool and is not affiliated with, endorsed by, or sponsored by Anthropic or OpenAI. "Claude" is a trademark of Anthropic PBC. "ChatGPT" and "Codex" are trademarks of OpenAI. Use responsibly and in accordance with applicable Terms of Service.
281
-
282
- ---
283
-
284
- <div align="center">
285
- <p>If you find this project useful, please give it a star! ⭐️</p>
286
- <a href="https://github.com/zzy-life/claude-codex-proxy">
287
- <img src="https://img.shields.io/github/stars/zzy-life/claude-codex-proxy?style=social" alt="Star on GitHub">
288
- </a>
289
- </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.10",
3
+ "version": "1.0.5-beta.11",
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",
package/public/js/app.js CHANGED
@@ -9,6 +9,7 @@ document.addEventListener('alpine:init', () => {
9
9
  clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
10
10
  clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
11
  showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
+ resetCreditsLoading: false, resetCreditsRedeeming: false, resetCredits: [], resetCreditsAccountEmail: '', resetCreditRedeemRequestId: '',
12
13
  oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
14
  testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
15
  serverUrl: window.location.origin, logs: [], logSearchQuery: '', logPage: 1, logPageSize: 30, logTotal: 0, logTotalPages: 0, logLoading: false,
@@ -100,7 +101,12 @@ document.addEventListener('alpine:init', () => {
100
101
  async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
102
  async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
103
  async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
- async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
+ async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, async showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; await this.loadRateLimitResetCredits(acc.email); },
105
+ normalizeRateLimitResetCredits(payload) { if (Array.isArray(payload)) return payload; for (const key of ['credits', 'items', 'data']) { if (Array.isArray(payload?.[key])) return payload[key]; } return []; },
106
+ async loadRateLimitResetCredits(email) { this.resetCreditsLoading = true; this.resetCredits = []; this.resetCreditsAccountEmail = email; this.resetCreditRedeemRequestId = ''; const { ok, data } = await this.api(`/accounts/rate-limit-reset-credits?email=${encodeURIComponent(email)}`); this.resetCreditsLoading = false; if (this.resetCreditsAccountEmail !== email) return; if (ok) this.resetCredits = this.normalizeRateLimitResetCredits(data?.credits); else this.showToast(data?.error || 'Failed to load reset credits', 'error'); },
107
+ availableRateLimitResetCredits() { return this.resetCredits.filter(credit => credit?.status === 'available').sort((a, b) => new Date(b.expires_at || 0).getTime() - new Date(a.expires_at || 0).getTime()); },
108
+ resetCreditExpiryLabel(credit) { const date = credit?.expires_at && new Date(credit.expires_at); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : '-'; },
109
+ async redeemRateLimitResetCredit(creditId = null) { if (!this.selectedAccount || this.resetCreditsRedeeming) return; this.resetCreditsRedeeming = true; if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = crypto.randomUUID(); const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', { method: 'POST', body: JSON.stringify({ email: this.selectedAccount.email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId }) }); this.resetCreditsRedeeming = false; if (ok && data?.success) { this.showToast('Quota reset credit redeemed', 'success'); this.resetCreditRedeemRequestId = ''; await Promise.all([this.loadRateLimitResetCredits(this.selectedAccount.email), this.refreshAccounts()]); } else this.showToast(data?.error || 'Failed to redeem reset credit', 'error'); },
104
110
  async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
111
  async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
112
  async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
@@ -152,6 +152,43 @@
152
152
  </div>
153
153
  </div>
154
154
 
155
+ <div class="mt-4 p-3 bg-space-800/50 border border-space-border/30 rounded-lg">
156
+ <div class="flex items-center justify-between gap-3 mb-2">
157
+ <div>
158
+ <h4 class="text-sm font-semibold text-gray-200">Rate-limit reset credits</h4>
159
+ <p class="text-xs text-gray-500">Redeeming a credit resets this account's upstream quota.</p>
160
+ </div>
161
+ <button class="btn btn-xs btn-outline text-gray-400" @click="loadRateLimitResetCredits(selectedAccount.email)" :disabled="resetCreditsLoading || resetCreditsRedeeming">Refresh</button>
162
+ </div>
163
+ <template x-if="resetCreditsLoading">
164
+ <p class="text-xs text-gray-500">Loading reset credits...</p>
165
+ </template>
166
+ <template x-if="!resetCreditsLoading && !availableRateLimitResetCredits().length">
167
+ <p class="text-xs text-gray-500">No available reset credits.</p>
168
+ </template>
169
+ <template x-if="!resetCreditsLoading && availableRateLimitResetCredits().length">
170
+ <div class="space-y-2">
171
+ <template x-for="credit in availableRateLimitResetCredits()" :key="credit.id">
172
+ <div class="flex items-center justify-between gap-4 rounded-lg border border-space-border/30 bg-space-900/40 p-3">
173
+ <div class="min-w-0 flex-1">
174
+ <div class="flex items-center gap-2">
175
+ <span class="truncate text-sm font-semibold text-gray-200" x-text="credit.title || 'Full reset'"></span>
176
+ <span class="shrink-0 rounded border border-neon-green/30 bg-neon-green/10 px-1.5 py-0.5 text-[9px] font-bold uppercase text-neon-green">Available</span>
177
+ </div>
178
+ <p class="mt-1 truncate text-xs text-gray-500" x-text="credit.description || credit.id"></p>
179
+ <div class="mt-2 flex items-center gap-1.5 text-[10px] text-gray-500">
180
+ <svg class="h-3 w-3 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 2m6-2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
181
+ <span>Expires</span>
182
+ <span class="font-mono text-gray-400" x-text="resetCreditExpiryLabel(credit)"></span>
183
+ </div>
184
+ </div>
185
+ <button class="btn btn-xs shrink-0 bg-neon-purple hover:bg-purple-600 border-none text-white" @click="redeemRateLimitResetCredit(credit.id)" :disabled="resetCreditsRedeeming" x-text="resetCreditsRedeeming ? 'Resetting...' : 'Reset quota'"></button>
186
+ </div>
187
+ </template>
188
+ </div>
189
+ </template>
190
+ </div>
191
+
155
192
  <div class="mt-6 flex justify-end">
156
193
  <button class="btn btn-outline btn-sm text-gray-400" @click="showQuotaModalView = false">Close</button>
157
194
  </div>
package/src/model-api.js CHANGED
@@ -100,6 +100,64 @@ export async function fetchUsage(accessToken, accountId) {
100
100
  };
101
101
  }
102
102
 
103
+ /**
104
+ * Lists the account's available rate-limit reset credits.
105
+ * @param {string} accessToken
106
+ * @param {string} accountId
107
+ * @returns {Promise<object>}
108
+ */
109
+ export async function fetchRateLimitResetCredits(accessToken, accountId) {
110
+ const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
111
+ method: 'GET',
112
+ headers: {
113
+ 'Authorization': `Bearer ${accessToken}`,
114
+ 'ChatGPT-Account-ID': accountId,
115
+ 'Accept': 'application/json',
116
+ 'User-Agent': 'codex-cli'
117
+ }
118
+ });
119
+
120
+ if (!response.ok) {
121
+ const errorText = await response.text();
122
+ throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
123
+ }
124
+
125
+ return await response.json();
126
+ }
127
+
128
+ /**
129
+ * Redeems a rate-limit reset credit for an account.
130
+ * @param {string} accessToken
131
+ * @param {string} accountId
132
+ * @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
133
+ * @param {string|null} creditId Specific credit to redeem, or null for server selection.
134
+ * @returns {Promise<object>}
135
+ */
136
+ export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
137
+ const body = { redeem_request_id: redeemRequestId };
138
+ if (creditId) body.credit_id = creditId;
139
+
140
+ const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
141
+ method: 'POST',
142
+ headers: {
143
+ 'Authorization': `Bearer ${accessToken}`,
144
+ 'ChatGPT-Account-ID': accountId,
145
+ 'Content-Type': 'application/json',
146
+ 'Accept': 'application/json',
147
+ 'User-Agent': 'codex-cli'
148
+ },
149
+ body: JSON.stringify(body)
150
+ });
151
+
152
+ if (!response.ok) {
153
+ const errorText = await response.text();
154
+ throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
155
+ }
156
+
157
+ const text = await response.text();
158
+ return text ? JSON.parse(text) : {};
159
+ }
160
+
103
161
  export async function fetchAccountCheck(accessToken, accountId) {
104
162
  const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
105
163
 
@@ -182,6 +240,8 @@ export function clearModelCache() {
182
240
  export default {
183
241
  fetchModels,
184
242
  fetchUsage,
243
+ fetchRateLimitResetCredits,
244
+ consumeRateLimitResetCredit,
185
245
  fetchAccountCheck,
186
246
  getAccountQuota,
187
247
  getModelsAndQuota,
@@ -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
@@ -45,9 +47,13 @@ import {
45
47
  } from '../oauth.js';
46
48
 
47
49
  import {
48
- getAccountQuota as fetchAccountQuota
50
+ getAccountQuota as fetchAccountQuota,
51
+ fetchRateLimitResetCredits,
52
+ consumeRateLimitResetCredit
49
53
  } from '../model-api.js';
50
54
 
55
+ import { randomUUID } from 'crypto';
56
+
51
57
  import { logger } from '../utils/logger.js';
52
58
 
53
59
  // Tracks active OAuth callback servers keyed by port
@@ -232,6 +238,75 @@ export async function handleGetQuota(req, res) {
232
238
  }
233
239
  }
234
240
 
241
+ /**
242
+ * Lists an account's rate-limit reset credits.
243
+ */
244
+ export async function handleGetRateLimitResetCredits(req, res) {
245
+ const { email } = req.query;
246
+ const account = email
247
+ ? loadAccounts().accounts.find(a => a.email === email)
248
+ : getActiveAccount();
249
+
250
+ if (!account) {
251
+ return res.status(404).json({
252
+ success: false,
253
+ error: email ? `Account not found: ${email}` : 'No active account'
254
+ });
255
+ }
256
+
257
+ try {
258
+ const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
259
+ res.json({ success: true, email: account.email, credits });
260
+ } catch (error) {
261
+ logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
262
+ res.status(502).json({ success: false, error: error.message });
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Redeems one available rate-limit reset credit for an account.
268
+ */
269
+ export async function handleConsumeRateLimitResetCredit(req, res) {
270
+ const { email, creditId, redeemRequestId } = req.body || {};
271
+ const account = email
272
+ ? loadAccounts().accounts.find(a => a.email === email)
273
+ : getActiveAccount();
274
+
275
+ if (!account) {
276
+ return res.status(404).json({
277
+ success: false,
278
+ error: email ? `Account not found: ${email}` : 'No active account'
279
+ });
280
+ }
281
+
282
+ if (redeemRequestId !== undefined && (
283
+ typeof redeemRequestId !== 'string' ||
284
+ !/^[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())
285
+ )) {
286
+ return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
287
+ }
288
+
289
+ if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
290
+ return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
291
+ }
292
+
293
+ const idempotencyKey = redeemRequestId?.trim() || randomUUID();
294
+
295
+ try {
296
+ const result = await consumeRateLimitResetCredit(
297
+ account.accessToken,
298
+ account.accountId,
299
+ idempotencyKey,
300
+ creditId?.trim() || null
301
+ );
302
+ logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
303
+ res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
304
+ } catch (error) {
305
+ logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
306
+ res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
307
+ }
308
+ }
309
+
235
310
  export async function handleGetAllQuotas(req, res) {
236
311
  const { accounts: accountList } = listAccounts();
237
312
  const results = [];
@@ -308,5 +383,7 @@ export default {
308
383
  handleRemoveAccount,
309
384
  handleImportAccount,
310
385
  handleGetQuota,
386
+ handleGetRateLimitResetCredits,
387
+ handleConsumeRateLimitResetCredit,
311
388
  handleGetAllQuotas
312
389
  };
@@ -44,6 +44,8 @@ import {
44
44
  handleRemoveAccount,
45
45
  handleImportAccount,
46
46
  handleGetQuota,
47
+ handleGetRateLimitResetCredits,
48
+ handleConsumeRateLimitResetCredit,
47
49
  handleGetAllQuotas
48
50
  } from './accounts-route.js';
49
51
 
@@ -115,6 +117,8 @@ export function registerApiRoutes(app, { port }) {
115
117
  app.get('/accounts/status', handleAccountStatus);
116
118
  app.get('/accounts/quota', handleGetQuota);
117
119
  app.get('/accounts/quota/all', handleGetAllQuotas);
120
+ app.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
121
+ app.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
118
122
 
119
123
  app.post('/accounts/add', handleAddAccount);
120
124
  app.post('/accounts/add/manual', handleAddAccountManual);