claude-gateway 2.0.0

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 (44) hide show
  1. package/CHANGELOG.md +329 -0
  2. package/LICENSE +21 -0
  3. package/README.md +272 -0
  4. package/dist/cli.d.ts +13 -0
  5. package/dist/cli.d.ts.map +1 -0
  6. package/dist/cli.js +409 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +30 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +106 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/oauth.d.ts +44 -0
  13. package/dist/oauth.d.ts.map +1 -0
  14. package/dist/oauth.js +135 -0
  15. package/dist/oauth.js.map +1 -0
  16. package/dist/router/logger.d.ts +19 -0
  17. package/dist/router/logger.d.ts.map +1 -0
  18. package/dist/router/logger.js +104 -0
  19. package/dist/router/logger.js.map +1 -0
  20. package/dist/router/middleware.d.ts +9 -0
  21. package/dist/router/middleware.d.ts.map +1 -0
  22. package/dist/router/middleware.js +46 -0
  23. package/dist/router/middleware.js.map +1 -0
  24. package/dist/router/models.d.ts +11 -0
  25. package/dist/router/models.d.ts.map +1 -0
  26. package/dist/router/models.js +61 -0
  27. package/dist/router/models.js.map +1 -0
  28. package/dist/router/server.d.ts +14 -0
  29. package/dist/router/server.d.ts.map +1 -0
  30. package/dist/router/server.js +423 -0
  31. package/dist/router/server.js.map +1 -0
  32. package/dist/router/translator.d.ts +33 -0
  33. package/dist/router/translator.d.ts.map +1 -0
  34. package/dist/router/translator.js +302 -0
  35. package/dist/router/translator.js.map +1 -0
  36. package/dist/token-manager.d.ts +32 -0
  37. package/dist/token-manager.d.ts.map +1 -0
  38. package/dist/token-manager.js +79 -0
  39. package/dist/token-manager.js.map +1 -0
  40. package/dist/types.d.ts +247 -0
  41. package/dist/types.d.ts.map +1 -0
  42. package/dist/types.js +12 -0
  43. package/dist/types.js.map +1 -0
  44. package/package.json +75 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,329 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
+
7
+ ## [2.0.0] - 2026-01-01
8
+
9
+ ### Changed
10
+ - **Project forked and renamed** to Claude Gateway
11
+ - Simplified focus: OpenAI-compatible gateway only
12
+ - Removed native Anthropic endpoint support
13
+ - Removed CLI chat/test features
14
+ - Streamlined to be a pure OpenAI-to-Claude translation gateway
15
+ - New repository: https://gitlab.com/soapbox-pub/claude-gateway
16
+ - New maintainer: Alex Gleason <alex@alexgleason.me>
17
+ - Original project: https://github.com/nsxdavid/anthropic-max-router by David Whatley
18
+ - **Command renamed** from `anthropic-max-router` to `claude-gateway`
19
+ - **Package renamed** from `anthropic-max-router` to `claude-gateway`
20
+ - **README completely overhauled** - Simplified to focus on OpenAI compatibility
21
+ - Removed references to dual endpoints
22
+ - Removed Anthropic native endpoint documentation
23
+ - Streamlined to emphasize OpenAI-compatible usage only
24
+ - Updated all examples and documentation
25
+ - Added fork attribution and credits
26
+
27
+ ### Removed
28
+ - Native Anthropic `/v1/messages` endpoint (OpenAI `/v1/chat/completions` only)
29
+ - CLI chat mode
30
+ - CLI test mode
31
+ - Dual endpoint functionality
32
+ - Bearer token passthrough documentation (feature may still exist in code)
33
+
34
+ ## [1.4.2] - 2025-12-12
35
+
36
+ ### Added
37
+ - **High-tier model mapping to Claude Opus 4.5** - Premium OpenAI models now map to Claude's most capable model
38
+ - `-pro`, `-max`, `-ultra` suffixes → `claude-opus-4-5`
39
+ - o-series reasoning models (o1, o3, o4, etc.) → `claude-opus-4-5`
40
+ - o-series `-mini` variants remain mapped to Sonnet (e.g., `o3-mini` → `claude-sonnet-4-5`)
41
+ - Examples: `gpt-5.2-pro`, `gpt-6-ultra`, `o3` → `claude-opus-4-5`
42
+
43
+ ### Changed
44
+ - **Model mapping tiers** - Now three tiers instead of two:
45
+ - High-tier (Opus): `-pro`, `-max`, `-ultra` suffixes, o-series (non-mini)
46
+ - Low-tier (Haiku): `-nano`, `gpt-3.5`, `gpt-3`
47
+ - Default (Sonnet): Everything else (`gpt-4`, `gpt-5.2`, `-mini`, `-turbo`, etc.)
48
+ - Updated `getModelMappingReason()` to report high-tier pattern matches in logs
49
+
50
+ ## [1.4.1] - 2025-12-04
51
+
52
+ ### Changed
53
+ - Code quality improvements: replaced `any` types with proper TypeScript types
54
+ - Removed unused imports and variables
55
+ - Fixed all ESLint warnings (22 total)
56
+ - Improved type safety throughout the codebase
57
+
58
+ ## [1.4.0] - 2025-12-04
59
+
60
+ ### Added
61
+ - **Bearer token passthrough** - Requests with bearer tokens can now use their own Anthropic API credentials
62
+ - Enabled by default - clients can provide their own API keys via `Authorization: Bearer` header
63
+ - Router will use the provided bearer token instead of OAuth credentials when present
64
+ - Allows mixing of OAuth MAX Plan usage with regular API key usage
65
+ - Useful for tools that already have Anthropic API keys
66
+ - `--disable-bearer-passthrough` flag to force all requests through OAuth (previous behavior)
67
+ - Works with both `/v1/messages` (Anthropic) and `/v1/chat/completions` (OpenAI) endpoints
68
+ - Verbose logging shows which authentication method is used for each request
69
+ - System prompt injection still applies regardless of authentication method
70
+ - See `BEARER-TOKEN-PASSTHROUGH.md` for detailed documentation
71
+
72
+ ### Changed
73
+ - OAuth tokens are now optional when bearer passthrough is enabled
74
+ - Router can start in "passthrough-only" mode without OAuth tokens
75
+ - Startup messages now show bearer passthrough status
76
+
77
+
78
+ ## [1.3.0] - 2025-11-29
79
+
80
+ ### Added
81
+ - **`GET /v1/models` endpoint** - List available Claude models from Anthropic
82
+ - Proxies to Anthropic's `/v1/models` API endpoint
83
+ - Requires Anthropic API key authentication (not OAuth)
84
+ - Returns current list of available Claude models
85
+ - Compatible with OpenAI-compatible tools that query model lists (e.g., n8n)
86
+ - Clear error message when API key is not provided, explaining it's only needed for this endpoint
87
+
88
+ ### Changed
89
+ - **Documentation** - Added comprehensive `/v1/models` endpoint documentation
90
+ - Explains why API key is required (Anthropic's endpoint doesn't support OAuth)
91
+ - Clarifies API key is ONLY used for `/v1/models`, not other endpoints
92
+ - Usage examples with curl
93
+ - Error response documentation
94
+
95
+ ### Notes
96
+ - The `/v1/models` endpoint is the only endpoint that requires an API key
97
+ - All other endpoints (`/v1/messages`, `/v1/chat/completions`) continue to use OAuth authentication
98
+ - This enables better compatibility with tools like N8n that expect to query available models
99
+
100
+ ## [1.2.2] - 2025-11-25
101
+
102
+ ### Fixed
103
+ - **npm package documentation** - Fixed screenshot image not displaying on npm package page
104
+ - Changed image path from relative (`assets/screenshot.png`) to absolute GitHub URL
105
+ - Image now loads correctly on both GitHub and npm package pages
106
+
107
+ ### Security
108
+ - **Dependencies** - Updated dependencies and verified clear of Shai-Hulud 1/2 worm vulnerability
109
+
110
+ ## [1.2.1] - 2025-11-15
111
+
112
+ ### Fixed
113
+ - **System prompt handling** - Fixed crash when system prompt is a string instead of array
114
+ - Added `normalizeSystemPrompt()` function in middleware to handle both string and array formats
115
+ - Prevents "TypeError: system.map is not a function" error
116
+ - Thanks to @geoh for the contribution (PR #1)
117
+ - **PORT variable initialization** - Fixed reference error where PORT was used before initialization
118
+ - Moved PORT declaration before parseArgs() call to ensure proper initialization order
119
+ - Thanks to @geoh for the contribution (PR #1)
120
+
121
+ ## [1.2.0] - 2025-11-15
122
+
123
+ ### Added
124
+ - **OpenAI API Compatibility** - Router now supports OpenAI Chat Completions API format
125
+ - New endpoint: `POST /v1/chat/completions`
126
+ - Zero-code integration with tools built for OpenAI (Python SDK, LangChain, etc.)
127
+ - Bidirectional API translation (OpenAI ↔ Anthropic format)
128
+ - Pattern-based model mapping (gpt-4 → claude-sonnet-4-5, etc.)
129
+ - Full streaming support with SSE format translation
130
+ - Tool/function calling translation
131
+ - Configurable via CLI flags (opt-in for backward compatibility)
132
+ - **Endpoint Control Flags**
133
+ - Both endpoints enabled by default (Anthropic + OpenAI)
134
+ - `--enable-openai` - Enable OpenAI compatibility endpoint (default: enabled)
135
+ - `--disable-openai` - Disable OpenAI endpoint
136
+ - `--enable-anthropic` - Enable Anthropic endpoint (default: enabled)
137
+ - `--disable-anthropic` - Disable Anthropic endpoint
138
+ - `--enable-all-endpoints` - Enable both endpoints (same as default)
139
+ - Validation ensures at least one endpoint is enabled
140
+ - **Model Mapping System** (`src/router/model-mapper.ts`)
141
+ - Pattern-based intelligent mapping (future-proof for new OpenAI models)
142
+ - Low-tier detection (nano, gpt-3.5, gpt-3) → `claude-haiku-4-5`
143
+ - All other models → `claude-sonnet-4-5` (best for MAX Plan)
144
+ - Custom mapping support via `.router-mappings.json` file
145
+ - Environment variable override: `ANTHROPIC_DEFAULT_MODEL`
146
+ - **Translation Layer** (`src/router/translator.ts`)
147
+ - Request translation: OpenAI → Anthropic format
148
+ - System message extraction and consolidation
149
+ - Message alternation enforcement (required by Anthropic)
150
+ - Tool definition translation
151
+ - Parameter mapping (temperature, max_tokens, etc.)
152
+ - Response translation: Anthropic → OpenAI format
153
+ - Content block to choices array conversion
154
+ - Token usage mapping (input_tokens → prompt_tokens)
155
+ - Finish reason translation (end_turn → stop, max_tokens → length)
156
+ - Tool use translation
157
+ - Streaming translation with SSE format conversion
158
+ - Request validation with helpful error messages for unsupported features
159
+ - **Enhanced Logging** - Logger now distinguishes between Anthropic and OpenAI requests
160
+ - Minimal: `[OpenAI]` / `[Anthropic]` prefix
161
+ - Medium: "Incoming OpenAI request" / "Incoming Anthropic request"
162
+ - Verbose: Full translation details
163
+ - **Type Definitions** - Added comprehensive OpenAI types to `src/types.ts`
164
+ - `OpenAIChatCompletionRequest` / `OpenAIChatCompletionResponse`
165
+ - `OpenAIMessage`, `OpenAITool`, `OpenAIToolCall`
166
+ - `OpenAIChatCompletionChunk` for streaming
167
+ - `OpenAIErrorResponse` for error translation
168
+
169
+ ### Changed
170
+ - **Help text** - Updated with new endpoint control flags and environment variables
171
+ - **Startup logging** - Router now displays which endpoints are enabled
172
+ - **README.md** - Extensive documentation of OpenAI compatibility
173
+ - Model mapping table with examples
174
+ - Python and JavaScript usage examples with OpenAI SDK
175
+ - Streaming examples
176
+ - Custom mapping configuration instructions
177
+ - Feature support matrix
178
+ - Troubleshooting section for OpenAI compatibility
179
+ - **Command line options table** - Reorganized with endpoint control section
180
+ - **Project files structure** - Updated to show new modules
181
+
182
+ ### Features
183
+ - ✅ OpenAI Chat Completions API endpoint (`/v1/chat/completions`)
184
+ - ✅ Automatic model name translation (gpt-4, gpt-5, o1, o3, etc.)
185
+ - ✅ Request/response format translation
186
+ - ✅ Streaming support with OpenAI format
187
+ - ✅ Tool calling translation
188
+ - ✅ Both endpoints enabled by default for maximum compatibility
189
+ - ✅ Flexible model mapping (pattern-based + custom overrides)
190
+ - ✅ Works with Python OpenAI SDK, JavaScript OpenAI SDK, and any OpenAI-compatible tool
191
+
192
+ ### OpenAI Compatibility Notes
193
+ - **Supported**: Messages, streaming, tools, basic parameters
194
+ - **Not Supported**: Multiple completions (n > 1), logprobs
195
+ - **Ignored with warning**: presence_penalty, frequency_penalty, logit_bias
196
+ - Both endpoints enabled by default - use whichever format your tool supports!
197
+
198
+ ## [1.1.4] - 2025-11-08
199
+
200
+ ### Fixed
201
+ - **Streaming support** - Router now properly handles streaming responses from Anthropic API
202
+ - Detects `text/event-stream` content type and pipes the stream directly to client
203
+ - Fixes issues with tools that require streaming responses
204
+ - Maintains proper headers and connection handling for SSE
205
+
206
+ ## [1.1.3] - 2025-11-05
207
+
208
+ ### Fixed
209
+ - **Payload size limit** - Increased Express body-parser limit from 100kb to 50mb
210
+ - Fixes "PayloadTooLargeError: request entity too large" when handling large API responses
211
+ - Particularly important for requests with extensive accessibility trees or large screenshots
212
+ - Router now handles large payloads from tools like Stagehand without errors
213
+
214
+ ## [1.1.2] - 2025-11-03
215
+
216
+ ### Fixed
217
+ - **npx compatibility** - Package now properly compiles TypeScript before publishing
218
+ - Added `build` script to compile TypeScript to `dist/`
219
+ - Added `prepublishOnly` hook to auto-build before publishing
220
+ - Updated `bin` paths to point to compiled `.js` files instead of source `.ts` files
221
+ - Added `files` field to control npm package contents
222
+ - `npx anthropic-max-router` now works correctly
223
+
224
+ ## [1.1.1] - 2025-11-02
225
+
226
+ ### Changed
227
+ - Enhanced router startup with ASCII art banner displaying "MAX PLAN" logo
228
+ - Added decorative "═══════ Router ═══════" subtitle to startup sequence
229
+
230
+ ## [1.1.0] - 2025-11-02
231
+
232
+ ### Added
233
+ - **API Router Application** - Standalone HTTP proxy server that allows any AI tool to use MAX Plan billing
234
+ - Automatic OAuth authentication on first run
235
+ - Transparent system prompt injection
236
+ - Token auto-refresh with 8-hour expiration handling
237
+ - Express-based proxy server on configurable port
238
+ - **Command Line Interface** for router
239
+ - `--help` / `-h` - Display usage information
240
+ - `--version` / `-v` - Show version number
241
+ - `--port` / `-p` - Specify custom port (default: 3000)
242
+ - Verbosity levels:
243
+ - `--quiet` / `-q` - No request logging
244
+ - `--minimal` / `-m` - One-line per request
245
+ - Default (medium) - Summary per request
246
+ - `--verbose` / `-V` - Full request/response bodies
247
+ - **Smart Logging System** - Verbosity-aware logger with request tracking
248
+ - Request IDs and timestamps
249
+ - Token usage reporting
250
+ - Conditional system prompt injection logging
251
+ - Error handling with detailed messages
252
+ - **Health Check Endpoint** - `GET /health` for monitoring router status
253
+ - **npx Support** - Can now run directly from GitHub without cloning
254
+ - Added `bin` field to package.json
255
+ - Added shebang to router server
256
+ - Supports both `anthropic-max-router` and `max-router` commands
257
+ - Run with: `npx github:nsxdavid/anthropic-max-router`
258
+ - **Comprehensive Documentation**
259
+ - Restructured README to equally highlight CLI, Router, and Implementation Guide
260
+ - Complete command-line options documentation
261
+ - PowerShell and Bash curl test examples
262
+ - Use case examples (JavaScript, Python)
263
+ - API key usage clarification
264
+ - npx installation instructions
265
+ - Troubleshooting guide
266
+
267
+ ### Changed
268
+ - **Repository renamed** from `anthropic-oauth-max-plan` to `anthropic-max-router`
269
+ - Package name updated to `anthropic-max-router`
270
+ - Better reflects that router is now the main feature
271
+ - GitHub will auto-redirect old URLs
272
+ - README restructured to highlight both educational purpose and practical router application
273
+ - Documentation now emphasizes router as main feature while maintaining educational focus
274
+ - Improved project structure organization with router as separate application
275
+ - Updated description to better reflect router functionality
276
+
277
+ ### Fixed
278
+ - TypeScript compilation error in client.ts with unknown type casting
279
+
280
+ ### Features
281
+ - ✅ Standalone router - run with `npm run router`
282
+ - ✅ Zero-configuration OAuth (prompts on first run)
283
+ - ✅ Automatic system prompt injection if missing
284
+ - ✅ Works with any tool that supports custom base URLs
285
+ - ✅ Live activity monitoring with adjustable verbosity
286
+ - ✅ Configurable port via CLI or environment variable
287
+
288
+ ## [1.0.0] - 2025-11-01
289
+
290
+ ### Added
291
+ - Initial release of Anthropic MAX Plan OAuth implementation
292
+ - Interactive CLI with menu-driven interface
293
+ - OAuth authentication flow (PKCE)
294
+ - Token management with automatic refresh
295
+ - Chat mode for sending messages to Claude
296
+ - Proof of MAX Plan validation test feature
297
+ - Comprehensive documentation (README + Implementation Guide)
298
+ - MIT License
299
+ - Security-focused .gitignore
300
+
301
+ ### Features
302
+ - ✅ Authenticate with Anthropic MAX Plan OAuth
303
+ - ✅ Access premium models (Sonnet 4.5, Opus) with flat-rate billing
304
+ - ✅ Automatic token refresh (8-hour expiration)
305
+ - ✅ Chat mode with continuous conversation
306
+ - ✅ Token storage and management
307
+ - ✅ Logout/delete tokens option
308
+ - ✅ Educational validation test to prove MAX plan enforcement
309
+
310
+ ### Documentation
311
+ - Detailed implementation guide with system prompt validation tests
312
+ - Quick start guide in README
313
+ - Code examples for basic and advanced usage
314
+ - Troubleshooting section
315
+ - Security best practices
316
+
317
+ ### Security
318
+ - OAuth tokens never committed to git
319
+ - Comprehensive .gitignore for secrets, tokens, and sensitive files
320
+ - Educational disclaimers throughout
321
+ - CSRF protection with state parameter validation
322
+
323
+ ---
324
+
325
+ ## Development Notes
326
+
327
+ This project demonstrates using Anthropic's official OAuth flow with Claude MAX subscription for flat-rate billing instead of pay-per-token pricing.
328
+
329
+ Tested and verified working as of November 1st, 2025.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 nsxdavid (David Whatley)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,272 @@
1
+ # Claude Gateway
2
+
3
+ Use your Claude Code subscription with any OpenAI-compatible tool
4
+
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
7
+ [![Node](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/)
8
+ [![OpenAI Compatible](https://img.shields.io/badge/OpenAI-Compatible-412991.svg)](https://gitlab.com/soapbox-pub/claude-gateway)
9
+
10
+ ## What is Claude Gateway?
11
+
12
+ Claude Gateway is an OpenAI-compatible HTTP proxy that lets you use your **Claude Code subscription** with any tool built for OpenAI's API.
13
+
14
+ ## Features
15
+
16
+ - ✅ **OpenAI-compatible API** - Drop-in replacement for OpenAI endpoints
17
+ - ✅ **Automatic authentication** - OAuth flow handled for you
18
+ - ✅ **Streaming support** - Full streaming response support
19
+ - ✅ **Zero code changes** - Just point your tool to the gateway
20
+ - ✅ **Token auto-refresh** - Handles 8-hour token expiration automatically
21
+ - ✅ **Model listing** - Query available Claude models via `/v1/models`
22
+
23
+ ## Requirements
24
+
25
+ - **Claude Code subscription** from [claude.ai](https://claude.ai)
26
+ - **Node.js** 18+
27
+
28
+ ## Quick Start
29
+
30
+ **No installation needed** - run directly with npx:
31
+
32
+ ```bash
33
+ npx claude-gateway start
34
+ ```
35
+
36
+ That's it! The gateway will:
37
+ 1. Authenticate you via OAuth (first run only)
38
+ 2. Start the proxy server on `http://localhost:45554`
39
+ 3. Let you use your Claude Code subscription from any OpenAI-compatible tool!
40
+
41
+ ### CLI Commands
42
+
43
+ ```bash
44
+ npx claude-gateway start # Start the gateway server
45
+ npx claude-gateway start --port 8080 # Use custom port
46
+ npx claude-gateway start --verbose # Full request logging
47
+ npx claude-gateway login # Authenticate with OAuth
48
+ npx claude-gateway status # Check authentication status
49
+ ```
50
+
51
+ ### Alternative: Clone and Run
52
+
53
+ ```bash
54
+ git clone https://gitlab.com/soapbox-pub/claude-gateway.git
55
+ cd claude-gateway
56
+ npm install
57
+ npm start
58
+ ```
59
+
60
+ ## Usage Examples
61
+
62
+ ### Python (OpenAI SDK)
63
+
64
+ ```python
65
+ from openai import OpenAI
66
+
67
+ client = OpenAI(
68
+ api_key="not-used", # Can be anything - gateway handles auth
69
+ base_url="http://localhost:45554/v1",
70
+ )
71
+
72
+ response = client.chat.completions.create(
73
+ model="claude-sonnet-4-5-20250929", # Use actual Claude model names
74
+ messages=[
75
+ {"role": "system", "content": "You are a helpful assistant."},
76
+ {"role": "user", "content": "Hello!"}
77
+ ]
78
+ )
79
+
80
+ print(response.choices[0].message.content)
81
+ ```
82
+
83
+ ### JavaScript/TypeScript (OpenAI SDK)
84
+
85
+ ```javascript
86
+ import OpenAI from 'openai';
87
+
88
+ const client = new OpenAI({
89
+ apiKey: 'not-used', // Can be anything - gateway handles auth
90
+ baseURL: 'http://localhost:45554/v1',
91
+ });
92
+
93
+ const response = await client.chat.completions.create({
94
+ model: 'claude-sonnet-4-5-20250929', // Use actual Claude model names
95
+ messages: [
96
+ { role: 'system', content: 'You are a helpful assistant.' },
97
+ { role: 'user', content: 'Hello!' }
98
+ ]
99
+ });
100
+
101
+ console.log(response.choices[0].message.content);
102
+ ```
103
+
104
+ ### cURL
105
+
106
+ ```bash
107
+ curl -X POST http://localhost:45554/v1/chat/completions \
108
+ -H "Content-Type: application/json" \
109
+ -d '{
110
+ "model": "claude-sonnet-4-5-20250929",
111
+ "messages": [
112
+ {"role": "system", "content": "You are a helpful assistant."},
113
+ {"role": "user", "content": "Hello!"}
114
+ ]
115
+ }'
116
+ ```
117
+
118
+ ### Streaming
119
+
120
+ ```python
121
+ from openai import OpenAI
122
+
123
+ client = OpenAI(
124
+ api_key="not-used",
125
+ base_url="http://localhost:45554/v1",
126
+ )
127
+
128
+ stream = client.chat.completions.create(
129
+ model="claude-sonnet-4-5-20250929",
130
+ messages=[{"role": "user", "content": "Write a story"}],
131
+ stream=True
132
+ )
133
+
134
+ for chunk in stream:
135
+ if chunk.choices[0].delta.content:
136
+ print(chunk.choices[0].delta.content, end='')
137
+ ```
138
+
139
+ ## How It Works
140
+
141
+ ```
142
+ ┌─────────────────────────┐
143
+ │ OpenAI-compatible Tool │
144
+ │ (Python SDK, etc.) │
145
+ └───────────┬─────────────┘
146
+ │ POST /v1/chat/completions
147
+ │ OpenAI format request
148
+
149
+ ┌──────────────────────────────────────────┐
150
+ │ Claude Gateway │
151
+ │ 1. Translate OpenAI → Anthropic format │
152
+ │ 2. Inject required system prompt │
153
+ │ 3. Authenticate with OAuth │
154
+ │ 4. Forward to Anthropic API │
155
+ │ 5. Translate response back to OpenAI │
156
+ └───────────┬──────────────────────────────┘
157
+ │ Authenticated request
158
+
159
+ ┌──────────────────────────┐
160
+ │ Anthropic API │
161
+ │ (Claude Code billing) │
162
+ └──────────────────────────┘
163
+ ```
164
+
165
+ ## Available Models
166
+
167
+ Models can be discovered through the `/v1/models` endpoint.
168
+
169
+ **Available Claude models:**
170
+ - `claude-opus-4-5-20251101` - Most capable
171
+ - `claude-sonnet-4-5-20250929` - Balanced performance
172
+ - `claude-haiku-4-5-20251001` - Fast and efficient
173
+ - And older versions...
174
+
175
+ **To get the current model list:**
176
+ ```bash
177
+ curl http://localhost:45554/v1/models \
178
+ -H "x-api-key: sk-ant-api03-..."
179
+ ```
180
+
181
+ ## Configuration
182
+
183
+ ### Command Line Options
184
+
185
+ ```bash
186
+ npx claude-gateway start [options]
187
+ ```
188
+
189
+ | Option | Short | Description |
190
+ |--------|-------|-------------|
191
+ | `--port PORT` | `-p` | Set port (default: 45554) |
192
+ | `--verbose` | `-V` | Full request/response logging |
193
+ | `--minimal` | `-m` | One line per request |
194
+ | `--quiet` | `-q` | No request logging |
195
+ | `--help` | `-h` | Show help |
196
+
197
+ ## API Endpoints
198
+
199
+ ### `POST /v1/chat/completions`
200
+ OpenAI Chat Completions API - the main endpoint you'll use.
201
+
202
+ ### `GET /v1/models`
203
+ List available models (requires Anthropic API key in `x-api-key` header).
204
+
205
+ ## Authentication
206
+
207
+ Claude Gateway uses OAuth to authenticate with your Claude Code subscription.
208
+
209
+ **First run:**
210
+ 1. Gateway displays an authorization URL
211
+ 2. Visit the URL and authorize
212
+ 3. Copy the `code#state` from the page
213
+ 4. Paste it back into the terminal
214
+ 5. Done! Tokens are saved for future use
215
+
216
+ **Subsequent runs:**
217
+ - Gateway loads saved tokens automatically
218
+ - Tokens are auto-refreshed when needed (8-hour expiration)
219
+
220
+ ## Troubleshooting
221
+
222
+ **"No OAuth tokens found"**
223
+ → Gateway will automatically prompt you to authenticate on first run.
224
+
225
+ **Port already in use**
226
+ → Use `npx claude-gateway start --port 8080`
227
+
228
+ **Authentication fails**
229
+ → Delete `.oauth-tokens.json` and restart to re-authenticate.
230
+
231
+ **Want to see what's happening?**
232
+ → Use `npx claude-gateway start --verbose`
233
+
234
+ **Tool calling behaves differently**
235
+ → Anthropic's tool calling is more strict than OpenAI's. Some parallel tool calls may not work.
236
+
237
+ **"Multiple completions (n > 1) not supported"**
238
+ → Anthropic only returns one completion. Set `n=1` or omit the parameter.
239
+
240
+ ## What's Supported
241
+
242
+ **Supported:**
243
+ - ✅ Message format translation (system/user/assistant roles)
244
+ - ✅ Model name mapping (gpt-4 → claude-sonnet-4-5)
245
+ - ✅ Streaming responses
246
+ - ✅ Tool/function calling
247
+ - ✅ Token usage reporting
248
+ - ✅ Temperature, max_tokens, stop sequences
249
+
250
+ **Not Supported (Anthropic limitations):**
251
+ - ❌ Multiple completions (`n > 1`)
252
+ - ❌ Log probabilities (`logprobs`)
253
+ - ❌ `presence_penalty` / `frequency_penalty` (ignored with warning)
254
+
255
+ ## Credits
256
+
257
+ Claude Gateway is a fork of [anthropic-max-router](https://github.com/nsxdavid/anthropic-max-router) by David Whatley, simplified to focus on OpenAI compatibility.
258
+
259
+ **Original Author:** [nsxdavid (David Whatley)](https://davidwhatley.com)
260
+ **Fork Maintainer:** Alex Gleason <alex@alexgleason.me>
261
+
262
+ Special thanks to [OpenCode](https://github.com/sst/opencode) for OAuth implementation reference.
263
+
264
+ ## License
265
+
266
+ MIT
267
+
268
+ ## Disclaimer
269
+
270
+ > **⚠️ EDUCATIONAL AND RESEARCH PURPOSES**
271
+ >
272
+ > This project is provided for educational, research, and entertainment purposes only. It is not affiliated with, endorsed by, or sponsored by Anthropic PBC. Use of this software is at your own risk. The authors and contributors make no warranties and accept no liability for any damages or issues arising from use of this code. Users are responsible for ensuring their use complies with Anthropic's Terms of Service and all applicable laws. This software is provided "as-is" without any express or implied warranties.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EDUCATIONAL AND ENTERTAINMENT PURPOSES ONLY
4
+ *
5
+ * This software is provided for educational, research, and entertainment purposes only.
6
+ * It is not affiliated with, endorsed by, or sponsored by Anthropic PBC.
7
+ * Use at your own risk. No warranties provided. Users are solely responsible for
8
+ * ensuring compliance with Anthropic's Terms of Service and all applicable laws.
9
+ *
10
+ * Copyright (c) 2025 - Licensed under MIT License
11
+ */
12
+ export {};
13
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;;;;;;;GASG"}