copilot-api-node20 0.6.0 → 0.8.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.
package/README.md CHANGED
@@ -1,373 +1,281 @@
1
- # Copilot API Proxy
2
-
3
- > [!NOTE]
4
- > **This is a temporary Node v20+ compatible fork**
5
- > This fork maintains compatibility with Node v20+ by downgrading dependencies. Full credit goes to the original author **[Erick Christian](https://github.com/ericc-ch)** for creating this amazing project.
6
- >
7
- > **Original repository**: https://github.com/ericc-ch/copilot-api
8
- > **Original package**: `copilot-api` on npm
9
- >
10
- > This fork will be discontinued once the original package supports Node v20+. Please use the original package when possible.
11
-
12
- > [!WARNING]
13
- > This is a reverse-engineered proxy of GitHub Copilot API. It is not supported by GitHub, and may break unexpectedly. Use at your own risk.
14
-
15
- > [!WARNING]
16
- > **GitHub Security Notice:**
17
- > Excessive automated or scripted use of Copilot (including rapid or bulk requests, such as via automated tools) may trigger GitHub's abuse-detection systems.
18
- > You may receive a warning from GitHub Security, and further anomalous activity could result in temporary suspension of your Copilot access.
19
- >
20
- > GitHub prohibits use of their servers for excessive automated bulk activity or any activity that places undue burden on their infrastructure.
21
- >
22
- > Please review:
23
- >
24
- > - [GitHub Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies/github-acceptable-use-policies#4-spam-and-inauthentic-activity-on-github)
25
- > - [GitHub Copilot Terms](https://docs.github.com/site-policy/github-terms/github-terms-for-additional-products-and-features#github-copilot)
26
- >
27
- > Use this proxy responsibly to avoid account restrictions.
1
+ # 🚀 Copilot API Proxy (Node 20+ Compatible)
28
2
 
29
- [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/E1E519XS7W)
30
-
31
- ---
3
+ > **Transform GitHub Copilot into OpenAI/Anthropic API** • **Claude Code Ready** • **One Command Setup**
32
4
 
33
- **Note:** If you are using [opencode](https://github.com/sst/opencode), you do not need this project. Opencode supports GitHub Copilot provider out of the box.
34
-
35
- ---
5
+ [![npm version](https://img.shields.io/npm/v/copilot-api-node20)](https://www.npmjs.com/package/copilot-api-node20)
6
+ [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ [![GitHub stars](https://img.shields.io/github/stars/johnib/copilot-api)](https://github.com/johnib/copilot-api)
36
8
 
37
- ## Project Overview
9
+ Turn your existing **GitHub Copilot subscription** into a powerful OpenAI/Anthropic-compatible API server. Perfect for powering [Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview), custom tools, and any application expecting OpenAI or Anthropic APIs.
38
10
 
39
- A reverse-engineered proxy for the GitHub Copilot API that exposes it as an OpenAI and Anthropic compatible service. This allows you to use GitHub Copilot with any tool that supports the OpenAI Chat Completions API or the Anthropic Messages API, including to power [Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview).
11
+ ## Why This Proxy?
40
12
 
41
- ## Features
13
+ - **🎯 One Command Launch**: Get Claude Code running with Copilot in seconds
14
+ - **💰 Use What You Pay For**: Leverage your existing Copilot subscription
15
+ - **🔄 Dual API Support**: Both OpenAI (`/v1/chat/completions`) and Anthropic (`/v1/messages`) endpoints
16
+ - **📊 Usage Dashboard**: Beautiful web interface to monitor your API usage
17
+ - **⚡ Node 20+ Ready**: Optimized fork with modern Node.js compatibility
18
+ - **🛡️ Rate Limiting**: Built-in controls to respect GitHub's limits
42
19
 
43
- - **OpenAI & Anthropic Compatibility**: Exposes GitHub Copilot as an OpenAI-compatible (`/v1/chat/completions`, `/v1/models`, `/v1/embeddings`) and Anthropic-compatible (`/v1/messages`) API.
44
- - **Claude Code Integration**: Easily configure and launch [Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview) to use Copilot as its backend with a simple command-line flag (`--claude-code`).
45
- - **Usage Dashboard**: A web-based dashboard to monitor your Copilot API usage, view quotas, and see detailed statistics.
46
- - **Rate Limit Control**: Manage API usage with rate-limiting options (`--rate-limit`) and a waiting mechanism (`--wait`) to prevent errors from rapid requests.
47
- - **Manual Request Approval**: Manually approve or deny each API request for fine-grained control over usage (`--manual`).
48
- - **Token Visibility**: Option to display GitHub and Copilot tokens during authentication and refresh for debugging (`--show-token`).
49
- - **Flexible Authentication**: Authenticate interactively or provide a GitHub token directly, suitable for CI/CD environments.
50
- - **Support for Different Account Types**: Works with individual, business, and enterprise GitHub Copilot plans.
51
-
52
- ## Demo
53
-
54
- https://github.com/user-attachments/assets/7654b383-669d-4eb9-b23c-06d7aefee8c5
55
-
56
- ## Prerequisites
20
+ ---
57
21
 
58
- - Bun (>= 1.2.x)
59
- - GitHub account with Copilot subscription (individual, business, or enterprise)
22
+ ## 🎮 Quick Start with Claude Code
60
23
 
61
- ## Installation
24
+ The fastest way to get Claude Code working with your Copilot subscription:
62
25
 
63
- To install dependencies, run:
26
+ ```bash
27
+ # 1. Launch the proxy with Claude Code integration
28
+ npx copilot-api-node20@latest start --claude-code
64
29
 
65
- ```sh
66
- bun install
30
+ # 2. Follow the interactive setup (select your models)
31
+ # 3. Copy the generated command and run it in a new terminal
32
+ # 4. Start coding with Claude Code powered by your Copilot subscription! 🎉
67
33
  ```
68
34
 
69
- ## Using with Docker
70
-
71
- Build image
72
-
73
- ```sh
74
- docker build -t copilot-api .
75
- ```
35
+ That's it! Claude Code will now use your GitHub Copilot subscription instead of requiring separate API keys.
76
36
 
77
- Run the container
37
+ ---
78
38
 
79
- ```sh
80
- # Create a directory on your host to persist the GitHub token and related data
81
- mkdir -p ./copilot-data
39
+ ## 📋 Prerequisites
82
40
 
83
- # Run the container with a bind mount to persist the token
84
- # This ensures your authentication survives container restarts
41
+ - **Node.js 20+** (this fork is optimized for modern Node versions)
42
+ - **GitHub account** with active Copilot subscription (Individual, Business, or Enterprise)
43
+ - **No additional API keys needed!** Uses your existing Copilot access
85
44
 
86
- docker run -p 4141:4141 -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api
87
- ```
88
-
89
- > **Note:**
90
- > The GitHub token and related data will be stored in `copilot-data` on your host. This is mapped to `/root/.local/share/copilot-api` inside the container, ensuring persistence across restarts.
91
-
92
- ### Docker with Environment Variables
45
+ ---
93
46
 
94
- You can pass the GitHub token directly to the container using environment variables:
47
+ ## 🚀 Installation & Usage
95
48
 
96
- ```sh
97
- # Build with GitHub token
98
- docker build --build-arg GH_TOKEN=your_github_token_here -t copilot-api .
49
+ ### Option 1: NPX (Recommended)
99
50
 
100
- # Run with GitHub token
101
- docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api
51
+ ```bash
52
+ # Quick start - launches server and opens usage dashboard
53
+ npx copilot-api-node20@latest start
102
54
 
103
- # Run with additional options
104
- docker run -p 4141:4141 -e GH_TOKEN=your_token copilot-api start --verbose --port 4141
105
- ```
55
+ # With Claude Code integration
56
+ npx copilot-api-node20@latest start --claude-code
106
57
 
107
- ### Docker Compose Example
108
-
109
- ```yaml
110
- version: "3.8"
111
- services:
112
- copilot-api:
113
- build: .
114
- ports:
115
- - "4141:4141"
116
- environment:
117
- - GH_TOKEN=your_github_token_here
118
- restart: unless-stopped
58
+ # Custom port and verbose logging
59
+ npx copilot-api-node20@latest start --port 8080 --verbose
119
60
  ```
120
61
 
121
- The Docker image includes:
122
-
123
- - Multi-stage build for optimized image size
124
- - Non-root user for enhanced security
125
- - Health check for container monitoring
126
- - Pinned base image version for reproducible builds
62
+ ### Option 2: Global Install
127
63
 
128
- ## Using with npx
129
-
130
- You can run this Node v20+ compatible fork directly using npx:
131
-
132
- ```sh
133
- npx copilot-api-node20@latest start
64
+ ```bash
65
+ npm install -g copilot-api-node20
66
+ copilot-api start --claude-code
134
67
  ```
135
68
 
136
- With options:
137
-
138
- ```sh
139
- npx copilot-api-node20@latest start --port 8080
140
- ```
69
+ ### Option 3: Docker
141
70
 
142
- For authentication only:
71
+ ```bash
72
+ # Build and run
73
+ docker build -t copilot-api .
74
+ docker run -p 4141:4141 -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api
143
75
 
144
- ```sh
145
- npx copilot-api-node20@latest auth
76
+ # With environment variables
77
+ docker run -p 4141:4141 -e GH_TOKEN=your_token copilot-api
146
78
  ```
147
79
 
148
- ## Command Structure
149
-
150
- Copilot API now uses a subcommand structure with these main commands:
151
-
152
- - `start`: Start the Copilot API server. This command will also handle authentication if needed.
153
- - `auth`: Run GitHub authentication flow without starting the server. This is typically used if you need to generate a token for use with the `--github-token` option, especially in non-interactive environments.
154
- - `check-usage`: Show your current GitHub Copilot usage and quota information directly in the terminal (no server required).
155
- - `debug`: Display diagnostic information including version, runtime details, file paths, and authentication status. Useful for troubleshooting and support.
80
+ ---
156
81
 
157
- ## Command Line Options
82
+ ## 🎯 Core Features
158
83
 
159
- ### Start Command Options
84
+ ### 🤖 Claude Code Integration
160
85
 
161
- The following command line options are available for the `start` command:
86
+ - **One-command setup** with `--claude-code` flag
87
+ - **Interactive model selection** or specify models directly
88
+ - **Automatic configuration** - no manual JSON editing needed
89
+ - **Works out of the box** with all Claude Code features
162
90
 
163
- | Option | Description | Default | Alias |
164
- | -------------- | ----------------------------------------------------------------------------- | ---------- | ----- |
165
- | --port | Port to listen on | 4141 | -p |
166
- | --verbose | Enable verbose logging | false | -v |
167
- | --account-type | Account type to use (individual, business, enterprise) | individual | -a |
168
- | --manual | Enable manual request approval | false | none |
169
- | --rate-limit | Rate limit in seconds between requests | none | -r |
170
- | --wait | Wait instead of error when rate limit is hit | false | -w |
171
- | --timeout | API timeout in milliseconds | 120000 | -t |
172
- | --github-token | Provide GitHub token directly (must be generated using the `auth` subcommand) | none | -g |
173
- | --claude-code | Generate a command to launch Claude Code with Copilot API config | false | -c |
174
- | --model | Model to use with Claude Code (requires --claude-code) | none | -m |
175
- | --small-model | Small/fast model to use with Claude Code (requires --claude-code) | none | -s |
176
- | --show-token | Show GitHub and Copilot tokens on fetch and refresh | false | none |
91
+ ### 🔄 Dual API Compatibility
177
92
 
178
- ### Auth Command Options
93
+ | OpenAI Format | Anthropic Format | Description |
94
+ |---------------|------------------|-------------|
95
+ | `POST /v1/chat/completions` | `POST /v1/messages` | Chat completions |
96
+ | `GET /v1/models` | - | Available models |
97
+ | `POST /v1/embeddings` | - | Text embeddings |
98
+ | - | `POST /v1/messages/count_tokens` | Token counting |
179
99
 
180
- | Option | Description | Default | Alias |
181
- | ------------ | ------------------------- | ------- | ----- |
182
- | --verbose | Enable verbose logging | false | -v |
183
- | --show-token | Show GitHub token on auth | false | none |
100
+ ### 📊 Usage Monitoring
184
101
 
185
- ### Debug Command Options
102
+ - **Web Dashboard**: Beautiful interface at `/usage` endpoint
103
+ - **Real-time Stats**: Monitor quotas, requests, and usage patterns
104
+ - **Terminal Usage**: Quick check with `copilot-api check-usage`
186
105
 
187
- | Option | Description | Default | Alias |
188
- | ------ | ------------------------- | ------- | ----- |
189
- | --json | Output debug info as JSON | false | none |
106
+ ### 🛡️ Smart Rate Limiting
190
107
 
191
- ## API Endpoints
108
+ ```bash
109
+ # Manual approval for each request
110
+ copilot-api start --manual
192
111
 
193
- The server exposes several endpoints to interact with the Copilot API. It provides OpenAI-compatible endpoints and now also includes support for Anthropic-compatible endpoints, allowing for greater flexibility with different tools and services.
112
+ # 30-second minimum between requests
113
+ copilot-api start --rate-limit 30
194
114
 
195
- ### OpenAI Compatible Endpoints
115
+ # Wait instead of erroring on rate limits
116
+ copilot-api start --rate-limit 30 --wait
117
+ ```
196
118
 
197
- These endpoints mimic the OpenAI API structure.
119
+ ---
198
120
 
199
- | Endpoint | Method | Description |
200
- | --------------------------- | ------ | --------------------------------------------------------- |
201
- | `POST /v1/chat/completions` | `POST` | Creates a model response for the given chat conversation. |
202
- | `GET /v1/models` | `GET` | Lists the currently available models. |
203
- | `POST /v1/embeddings` | `POST` | Creates an embedding vector representing the input text. |
121
+ ## 💡 Advanced Usage Examples
204
122
 
205
- ### Anthropic Compatible Endpoints
123
+ ### Claude Code with Specific Models
206
124
 
207
- These endpoints are designed to be compatible with the Anthropic Messages API.
125
+ ```bash
126
+ # Skip interactive setup - specify models directly
127
+ npx copilot-api-node20@latest start \
128
+ --claude-code \
129
+ --model "claude-sonnet-4" \
130
+ --small-model "claude-sonnet-4"
131
+ ```
208
132
 
209
- | Endpoint | Method | Description |
210
- | -------------------------------- | ------ | ------------------------------------------------------------ |
211
- | `POST /v1/messages` | `POST` | Creates a model response for a given conversation. |
212
- | `POST /v1/messages/count_tokens` | `POST` | Calculates the number of tokens for a given set of messages. |
133
+ ### Enterprise/Business Accounts
213
134
 
214
- ### Usage Monitoring Endpoints
135
+ ```bash
136
+ # For GitHub Business/Enterprise Copilot
137
+ npx copilot-api-node20@latest start --account-type business
138
+ npx copilot-api-node20@latest start --account-type enterprise
139
+ ```
215
140
 
216
- New endpoints for monitoring your Copilot usage and quotas.
141
+ ### Production Deployment
217
142
 
218
- | Endpoint | Method | Description |
219
- | ------------ | ------ | ------------------------------------------------------------ |
220
- | `GET /usage` | `GET` | Get detailed Copilot usage statistics and quota information. |
221
- | `GET /token` | `GET` | Get the current Copilot token being used by the API. |
143
+ ```bash
144
+ # With comprehensive settings
145
+ npx copilot-api-node20@latest start \
146
+ --port 8080 \
147
+ --rate-limit 10 \
148
+ --wait \
149
+ --timeout 180000 \
150
+ --account-type business
151
+ ```
222
152
 
223
- ## Example Usage
153
+ ### CI/CD Integration
224
154
 
225
- Using with npx:
155
+ ```bash
156
+ # Authenticate separately for token reuse
157
+ npx copilot-api-node20@latest auth --show-token
226
158
 
227
- ```sh
228
- # Basic usage with start command
229
- npx copilot-api-node20@latest start
159
+ # Use token in production
160
+ npx copilot-api-node20@latest start --github-token $GITHUB_TOKEN
161
+ ```
230
162
 
231
- # Run on custom port with verbose logging
232
- npx copilot-api-node20@latest start --port 8080 --verbose
163
+ ---
233
164
 
234
- # Use with a business plan GitHub account
235
- npx copilot-api-node20@latest start --account-type business
165
+ ## 🔧 Command Reference
236
166
 
237
- # Use with an enterprise plan GitHub account
238
- npx copilot-api-node20@latest start --account-type enterprise
167
+ ### Main Commands
239
168
 
240
- # Enable manual approval for each request
241
- npx copilot-api-node20@latest start --manual
169
+ | Command | Description |
170
+ |---------|-------------|
171
+ | `start` | Launch the API proxy server |
172
+ | `auth` | Run GitHub authentication only |
173
+ | `check-usage` | Show usage stats in terminal |
174
+ | `debug` | Display diagnostic information |
242
175
 
243
- # Set rate limit to 30 seconds between requests
244
- npx copilot-api-node20@latest start --rate-limit 30
176
+ ### Key Options
245
177
 
246
- # Wait instead of error when rate limit is hit
247
- npx copilot-api-node20@latest start --rate-limit 30 --wait
178
+ | Flag | Description | Example |
179
+ |------|-------------|---------|
180
+ | `--claude-code` | Generate Claude Code launch command | `start --claude-code` |
181
+ | `--model` | Primary model for Claude Code | `--model "claude-sonnet-4"` |
182
+ | `--small-model` | Fast model for background tasks | `--small-model "claude-sonnet-4"` |
183
+ | `--rate-limit` | Seconds between requests | `--rate-limit 30` |
184
+ | `--manual` | Manual request approval | `--manual` |
185
+ | `--account-type` | GitHub plan type | `--account-type business` |
248
186
 
249
- # Set API timeout to 3 minutes (180000 milliseconds)
250
- npx copilot-api-node20@latest start --timeout 180000
187
+ ---
251
188
 
252
- # Provide GitHub token directly
253
- npx copilot-api-node20@latest start --github-token ghp_YOUR_TOKEN_HERE
189
+ ## 🌐 API Endpoints
254
190
 
255
- # Run only the auth flow
256
- npx copilot-api-node20@latest auth
191
+ Once running (default: `http://localhost:4141`):
257
192
 
258
- # Run auth flow with verbose logging
259
- npx copilot-api-node20@latest auth --verbose
193
+ ### OpenAI Compatible
260
194
 
261
- # Show your Copilot usage/quota in the terminal (no server needed)
262
- npx copilot-api-node20@latest check-usage
195
+ ```bash
196
+ curl -X POST http://localhost:4141/v1/chat/completions \
197
+ -H "Content-Type: application/json" \
198
+ -d '{
199
+ "model": "claude-sonnet-4",
200
+ "messages": [{"role": "user", "content": "Hello!"}]
201
+ }'
202
+ ```
263
203
 
264
- # Display debug information for troubleshooting
265
- npx copilot-api-node20@latest debug
204
+ ### Anthropic Compatible
266
205
 
267
- # Display debug information in JSON format
268
- npx copilot-api-node20@latest debug --json
206
+ ```bash
207
+ curl -X POST http://localhost:4141/v1/messages \
208
+ -H "Content-Type: application/json" \
209
+ -d '{
210
+ "model": "claude-3-5-sonnet-20241022",
211
+ "max_tokens": 1024,
212
+ "messages": [{"role": "user", "content": "Hello!"}]
213
+ }'
269
214
  ```
270
215
 
271
- ## Using the Usage Viewer
272
-
273
- After starting the server, a URL to the Copilot Usage Dashboard will be displayed in your console. This dashboard is a web interface for monitoring your API usage.
216
+ ### Usage Dashboard
274
217
 
275
- 1. Start the server. For example, using npx:
276
- ```sh
277
- npx copilot-api@latest start
278
- ```
279
- 2. The server will output a URL to the usage viewer. Copy and paste this URL into your browser. It will look something like this:
280
- `https://ericc-ch.github.io/copilot-api?endpoint=http://localhost:4141/usage`
281
- - If you use the `start.bat` script on Windows, this page will open automatically.
218
+ Open `http://localhost:4141/usage` in your browser for a beautiful usage monitoring interface.
282
219
 
283
- The dashboard provides a user-friendly interface to view your Copilot usage data:
220
+ ---
284
221
 
285
- - **API Endpoint URL**: The dashboard is pre-configured to fetch data from your local server endpoint via the URL query parameter. You can change this URL to point to any other compatible API endpoint.
286
- - **Fetch Data**: Click the "Fetch" button to load or refresh the usage data. The dashboard will automatically fetch data on load.
287
- - **Usage Quotas**: View a summary of your usage quotas for different services like Chat and Completions, displayed with progress bars for a quick overview.
288
- - **Detailed Information**: See the full JSON response from the API for a detailed breakdown of all available usage statistics.
289
- - **URL-based Configuration**: You can also specify the API endpoint directly in the URL using a query parameter. This is useful for bookmarks or sharing links. For example:
290
- `https://ericc-ch.github.io/copilot-api?endpoint=http://your-api-server/usage`
222
+ ## ⚠️ Important Notices
291
223
 
292
- ## Using with Claude Code
224
+ > **Reverse-Engineered Proxy**: This tool reverse-engineers GitHub Copilot's API. It's not officially supported by GitHub and may break unexpectedly.
293
225
 
294
- This proxy can be used to power [Claude Code](https://docs.anthropic.com/en/claude-code), an experimental conversational AI assistant for developers from Anthropic.
226
+ > **Rate Limiting**: Excessive automated use may trigger GitHub's abuse detection. Use responsibly with appropriate rate limiting.
295
227
 
296
- There are two ways to configure Claude Code to use this proxy:
228
+ > **Terms of Service**: Review [GitHub's Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies/github-acceptable-use-policies) and [Copilot Terms](https://docs.github.com/site-policy/github-terms/github-terms-for-additional-products-and-features#github-copilot) before use.
297
229
 
298
- ### Interactive Setup with `--claude-code` flag
230
+ ---
299
231
 
300
- To get started, run the `start` command with the `--claude-code` flag:
232
+ ## 🙏 Attribution & License
301
233
 
302
- ```sh
303
- npx copilot-api-node20@latest start --claude-code
304
- ```
234
+ This is a **Node 20+ compatible fork** of the original project by **[Erick Christian](https://github.com/ericc-ch)**.
305
235
 
306
- You will be prompted to select a primary model and a "small, fast" model for background tasks. After selecting the models, a command will be copied to your clipboard. This command sets the necessary environment variables for Claude Code to use the proxy.
236
+ **Original Repository**: <https://github.com/ericc-ch/copilot-api>
237
+ **Original Package**: `copilot-api` on npm
307
238
 
308
- ### Non-Interactive Setup with Model Selection
239
+ **Full credit goes to Erick Christian** for creating this amazing project. This fork exists solely to maintain Node 20+ compatibility and will be discontinued once the original package supports modern Node versions.
309
240
 
310
- You can also specify the models directly on the command line to skip the interactive prompts:
241
+ ### License
311
242
 
312
- ```sh
313
- # Specify both models directly (example with common model names)
314
- npx copilot-api-node20@latest start --claude-code --model "claude-3.5-sonnet" --small-model "claude-3.5-haiku"
243
+ MIT License - see [LICENSE](LICENSE) file for details.
315
244
 
316
- # Short aliases also work
317
- npx copilot-api-node20@latest start -c -m "claude-3.5-sonnet" -s "claude-3.5-haiku"
318
- ```
245
+ ### Support the Original Author
319
246
 
320
- This is particularly useful for:
321
- - Automation scripts and CI/CD pipelines
322
- - Avoiding repetitive model selection during development
323
- - Quickly switching between different model configurations
247
+ If this project helps you, consider supporting the original creator:
248
+ [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/E1E519XS7W)
324
249
 
325
- Note: Both `--model` and `--small-model` must be specified together when using command-line model selection. The models you specify must be available in your Copilot account.
250
+ ---
326
251
 
327
- After running the command with `--claude-code`, paste and run the command copied to your clipboard in a new terminal to launch Claude Code.
252
+ ## 🐛 Troubleshooting
328
253
 
329
- ### Manual Configuration with `settings.json`
254
+ ### Common Issues
330
255
 
331
- Alternatively, you can configure Claude Code by creating a `.claude/settings.json` file in your project's root directory. This file should contain the environment variables needed by Claude Code. This way you don't need to run the interactive setup every time.
256
+ - **Authentication Failed**: Run `copilot-api auth --verbose` to debug
257
+ - **Rate Limited**: Use `--rate-limit` and `--wait` flags
258
+ - **Node Version**: Ensure Node.js 20+ is installed
259
+ - **Port Conflicts**: Change port with `--port 8080`
332
260
 
333
- Here is an example `.claude/settings.json` file:
261
+ ### Debug Information
334
262
 
335
- ```json
336
- {
337
- "env": {
338
- "ANTHROPIC_BASE_URL": "http://localhost:4141",
339
- "ANTHROPIC_AUTH_TOKEN": "dummy",
340
- "ANTHROPIC_MODEL": "gpt-4.1",
341
- "ANTHROPIC_SMALL_FAST_MODEL": "gpt-4.1"
342
- }
343
- }
263
+ ```bash
264
+ # Get detailed diagnostic info
265
+ npx copilot-api-node20@latest debug --json
344
266
  ```
345
267
 
346
- You can find more options here: [Claude Code settings](https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables)
347
-
348
- You can also read more about IDE integration here: [Add Claude Code to your IDE](https://docs.anthropic.com/en/docs/claude-code/ide-integrations)
349
-
350
- ## Running from Source
268
+ ### Need Help?
351
269
 
352
- The project can be run from source in several ways:
270
+ - Check the [original repository](https://github.com/ericc-ch/copilot-api) for issues and discussions
271
+ - Review [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/overview) for integration help
353
272
 
354
- ### Development Mode
355
-
356
- ```sh
357
- bun run dev
358
- ```
273
+ ---
359
274
 
360
- ### Production Mode
275
+ <div align="center">
361
276
 
362
- ```sh
363
- bun run start
364
- ```
277
+ **Made with ❤️ by the community • Original work by [Erick Christian](https://github.com/ericc-ch)**
365
278
 
366
- ## Usage Tips
279
+ [⭐ Star this repo](https://github.com/johnib/copilot-api) • [🐛 Report issues](https://github.com/johnib/copilot-api/issues) • [📖 Original repo](https://github.com/ericc-ch/copilot-api)
367
280
 
368
- - To avoid hitting GitHub Copilot's rate limits, you can use the following flags:
369
- - `--manual`: Enables manual approval for each request, giving you full control over when requests are sent.
370
- - `--rate-limit <seconds>`: Enforces a minimum time interval between requests. For example, `copilot-api start --rate-limit 30` will ensure there's at least a 30-second gap between requests.
371
- - `--wait`: Use this with `--rate-limit`. It makes the server wait for the cooldown period to end instead of rejecting the request with an error. This is useful for clients that don't automatically retry on rate limit errors.
372
- - `--timeout <milliseconds>`: Sets the API timeout in milliseconds. For example, `copilot-api start --timeout 180000` will set a 3-minute timeout for all API calls. Default is 120000 (2 minutes).
373
- - If you have a GitHub business or enterprise plan account with Copilot, use the `--account-type` flag (e.g., `--account-type business`). See the [official documentation](https://docs.github.com/en/enterprise-cloud@latest/copilot/managing-copilot/managing-github-copilot-in-your-organization/managing-access-to-github-copilot-in-your-organization/managing-github-copilot-access-to-your-organizations-network#configuring-copilot-subscription-based-network-routing-for-your-enterprise-or-organization) for more details.
281
+ </div>
@@ -0,0 +1 @@
1
+ import e from"consola";import t from"node:fs/promises";import n from"node:os";import r from"node:path";import{createHash as i,randomBytes as a,randomUUID as o}from"node:crypto";const s=r.join(n.homedir(),`.local`,`share`,`copilot-api`),c=r.join(s,`github_token`),l=r.join(s,`machine_id`),u=r.join(s,`session_id`),d={APP_DIR:s,GITHUB_TOKEN_PATH:c,MACHINE_ID_PATH:l,SESSION_ID_PATH:u};async function f(){await t.mkdir(d.APP_DIR,{recursive:!0}),await p(d.GITHUB_TOKEN_PATH),await p(d.SESSION_ID_PATH)}async function p(e){try{await t.access(e,t.constants.W_OK)}catch{await t.writeFile(e,``),await t.chmod(e,384)}}const m={accountType:`individual`,manualApprove:!1,rateLimitWait:!1,showToken:!1,connectivity:{enabled:!0,probeEndpoints:[`https://api.github.com`,`https://www.google.com`,`https://1.1.1.1`],fastProbeInterval:5e3,slowProbeInterval:6e4,timeoutMs:5e3,jitterMaxMs:1e3,connectionPooling:!0,dnsCache:!0}},h=()=>({"content-type":`application/json`,accept:`application/json`}),g=`0.32.2025100203`,_=`copilot-chat/${g}`,v=`GitHubCopilotChat/${g}`,y=`2025-08-20`,b=e=>{let t=i(`sha256`);return t.update(process.platform),t.update(process.arch),t.update(process.env.USER||process.env.USERNAME||`anonymous`),t.update(n.hostname()),t.update(e),t.update(Date.now().toString()),t.update(a(16)),t.digest(`hex`)},x=e=>{let t=e.replaceAll(/[^\w.-]/g,`_`).trim();if(t.length===0||t===`.`||t===`..`||/^[_.]+$/.test(t))throw Error(`Invalid GitHub username: cannot be empty or consist only of special characters after sanitization`);return`${d.MACHINE_ID_PATH}_${t}`},S=async e=>{let n=x(e);try{let e=await t.readFile(n,`utf8`);if(e.trim())return e.trim()}catch{}let r=b(e);return await t.writeFile(n,r),await t.chmod(n,384),r},C=async()=>{try{let e=await t.readFile(d.SESSION_ID_PATH,`utf8`);if(e.trim())return e.trim()}catch{}let e=o();return await t.writeFile(d.SESSION_ID_PATH,e),await t.chmod(d.SESSION_ID_PATH,384),e},w=async(e,t)=>{e.machineId||=await S(t),e.sessionId||=await C()},T=e=>e.accountType===`individual`?`https://api.githubcopilot.com`:`https://api.${e.accountType}.githubcopilot.com`,E=(e,t=!1)=>{if(!e.machineId||!e.sessionId)throw Error(`VSCode identifiers not initialized. Call initializeVSCodeIdentifiers() during startup.`);let n={Authorization:`Bearer ${e.copilotToken}`,"Content-Type":`application/json`,accept:`*/*`,"accept-encoding":`br, gzip, deflate`,"accept-language":`*`,"sec-fetch-mode":`cors`,"Copilot-Integration-Id":`vscode-chat`,"Editor-Version":`vscode/${e.vsCodeVersion}`,"Editor-Plugin-Version":_,"User-Agent":v,"VScode-MachineId":e.machineId,"VScode-SessionId":e.sessionId,"OpenAI-Intent":`conversation-agent`,"X-Interaction-Type":`conversation-agent`,"X-VSCode-User-Agent-Library-Version":`node-fetch`,"X-GitHub-Api-Version":y,"X-Interaction-Id":o(),"X-Request-Id":o(),"openai-intent":`conversation-agent`,"x-interaction-type":`conversation-agent`};return t&&(n[`copilot-vision-request`]=`true`),n},D=`https://api.github.com`,O=e=>({...h(),authorization:`token ${e.githubToken}`,"editor-version":`vscode/${e.vsCodeVersion}`,"editor-plugin-version":_,"user-agent":v,"x-github-api-version":y,"x-vscode-user-agent-library-version":`node-fetch`}),k=`https://github.com`,A=`01ab8ac9400c4e429b23`,j=[`user:email`].join(` `),M=e=>e>=1e5||e>=1e4?`${Math.round(e/1e3)}K`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString(),N=(e,t)=>e.padEnd(t),P=(e,t)=>{if(!m.models)return``;let n=m.models.data.find(e=>e.id===t);if(!n)return``;let r=n.capabilities.limits.max_context_window_tokens;if(!r)return``;let i=(e/r*100).toFixed(1);return` (${i}%)`},F=e=>{let t=[];if(e.model){let n=N(e.model,18);t.push(n)}if(e.tokenUsage){let n=e.tokenUsage,r=(n.inputTokens||0)+(n.outputTokens||0),i=e.model?P(r,e.model):``,a=M(n.inputTokens||0).padStart(5),o=M(n.outputTokens||0).padStart(5),s=`↑${a} │ ↓${o}`,c=N(s,18),l=M(r),u=i?`${l}${i.padStart(15-l.length)}`:l.padEnd(15);t.push(`Tokens: ${c} | Context: ${u}`)}else if(e.model){let e=N(`N/A`,18),n=`N/A`.padEnd(15);t.push(`Tokens: ${e} | Context: ${n}`)}if(e.copilotDuration){let n=N(`${Math.round(e.copilotDuration)}ms`,8);t.push(`API: ${n}`)}return t.length>0?` | ${t.join(` | `)}`:``},I={completionCallbacks:new Map,registerCompletion(e,t,n){this.completionCallbacks.set(e,{context:t,startTime:n,requestId:e})},executeCompletion(e){let t=this.completionCallbacks.get(e);t&&(this.logCompletion(t),this.completionCallbacks.delete(e))},logCompletion(t){let{context:n,startTime:r}=t,i=Date.now(),a=i-r,o=n.get(`requestData`),s=N(n.req.method,4),c=N(n.req.path,21),l=N(n.res.status.toString(),3),u=N(`${a}ms`,8),d=` --> ${s}${c}${l} ${u}`;o&&(d+=F(o)),e.info(d)},logRateLimit(t,n){let{context:r,startTime:i}=t,a=Date.now(),o=a-i,s=n.headers.get(`x-ratelimit-exceeded`)||``,c=s.split(`:`)[1]||`unknown`,l=n.headers.get(`retry-after`)||n.headers.get(`x-ratelimit-user-retry-after`)||`?`,u=N(r.req.method,4),d=N(r.req.path,21),f=N(`429`,3),p=N(`${o}ms`,8),m=`⚠ --> ${u}${d}${f} ${p}`;m+=` | Rate limited (${l}s retry) | ${c}`;let h=r.get(`requestData`);if(h?.copilotDuration){let e=N(`${Math.round(h.copilotDuration)}ms`,8);m+=` | API: ${e}`}e.info(m)},cleanup(){let e=1e3,t=Date.now()-300*1e3;for(let[e,n]of this.completionCallbacks)n.startTime<t&&this.completionCallbacks.delete(e);if(this.completionCallbacks.size>e){let t=Array.from(this.completionCallbacks.entries()).sort(([,e],[,t])=>e.startTime-t.startTime),n=t.slice(0,t.length-e);for(let[e]of n)this.completionCallbacks.delete(e)}}};setInterval(()=>I.cleanup(),60*1e3);var L=class extends Error{response;constructor(e,t){super(e),this.response=t}};async function R(t,n){if(n instanceof L&&n.response.status===429){let e=t.get(`requestId`),r=I.completionCallbacks.get(e);r&&(I.logRateLimit(r,n.response),I.completionCallbacks.delete(e));let i=await n.response.text(),a;try{a=JSON.parse(i)}catch{a={error:{message:i,type:`error`}}}return t.json(a,429)}if(e.error(`Error occurred:`,n),n instanceof L){let r=await n.response.text(),i;try{i=JSON.parse(r)}catch{i=r}return e.error(`HTTP error:`,i),t.json({error:{message:r,type:`error`}},n.response.status)}return t.json({error:{message:n.message,type:`error`}},500)}async function z(){let e=new AbortController,t=m.timeoutMs??12e4,n=setTimeout(()=>{e.abort()},t);try{let t=await fetch(`${D}/user`,{headers:{authorization:`token ${m.githubToken}`,...h()},signal:e.signal});if(!t.ok)throw new L(`Failed to get GitHub user`,t);return await t.json()}finally{clearTimeout(n)}}export{I as CompletionLogger,D as GITHUB_API_BASE_URL,j as GITHUB_APP_SCOPES,k as GITHUB_BASE_URL,A as GITHUB_CLIENT_ID,L as HTTPError,d as PATHS,T as copilotBaseUrl,E as copilotHeaders,f as ensurePaths,R as forwardError,z as getGitHubUser,O as githubHeaders,w as initializeVSCodeIdentifiers,h as standardHeaders,m as state};
@@ -0,0 +1 @@
1
+ import{getGitHubUser as e}from"./get-user-BJ4s6iMX.js";export{e as getGitHubUser};