@nick3/copilot-api 1.0.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Erick Christian Purwanto
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,599 @@
1
+ # Copilot API Proxy
2
+
3
+ > [!WARNING]
4
+ > 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.
5
+
6
+ > [!WARNING]
7
+ > **GitHub Security Notice:**
8
+ > Excessive automated or scripted use of Copilot (including rapid or bulk requests, such as via automated tools) may trigger GitHub's abuse-detection systems.
9
+ > You may receive a warning from GitHub Security, and further anomalous activity could result in temporary suspension of your Copilot access.
10
+ >
11
+ > GitHub prohibits use of their servers for excessive automated bulk activity or any activity that places undue burden on their infrastructure.
12
+ >
13
+ > Please review:
14
+ >
15
+ > - [GitHub Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies/github-acceptable-use-policies#4-spam-and-inauthentic-activity-on-github)
16
+ > - [GitHub Copilot Terms](https://docs.github.com/site-policy/github-terms/github-terms-for-additional-products-and-features#github-copilot)
17
+ >
18
+ > Use this proxy responsibly to avoid account restrictions.
19
+
20
+ [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/E1E519XS7W)
21
+
22
+ ---
23
+
24
+ **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.
25
+
26
+ ---
27
+
28
+ ## Project Overview
29
+
30
+ 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).
31
+
32
+ ## Features
33
+
34
+ - **OpenAI & Anthropic Compatibility**: Exposes GitHub Copilot as an OpenAI-compatible (`/v1/responses`, `/v1/chat/completions`, `/v1/models`, `/v1/embeddings`) and Anthropic-compatible (`/v1/messages`) API.
35
+ - **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`).
36
+ - **Usage Dashboard**: A web-based dashboard to monitor your Copilot API usage, view quotas, and see detailed statistics.
37
+ - **Admin UI**: Modern admin console (`/admin`) to inspect account runtime status and request history, with rich filtering and a request-detail JSON viewer (search/copy/download). Includes theme (system/light/dark) and motion (magic/subtle/off) toggles.
38
+ - **Rate Limit Control**: Manage API usage with rate-limiting options (`--rate-limit`) and a waiting mechanism (`--wait`) to prevent errors from rapid requests.
39
+ - **Manual Request Approval**: Manually approve or deny each API request for fine-grained control over usage (`--manual`).
40
+ - **Token Visibility**: Option to display GitHub and Copilot tokens during authentication and refresh for debugging (`--show-token`).
41
+ - **Flexible Authentication**: Authenticate interactively or provide a GitHub token directly, suitable for CI/CD environments.
42
+ - **Support for Different Account Types**: Works with individual, business, and enterprise GitHub Copilot plans.
43
+ - **Multi-Account Support**: Use multiple GitHub Copilot accounts with automatic routing: premium models use accounts in order and fall back on quota exhaustion; free models are distributed round-robin across accounts by default (configurable in config.json).
44
+
45
+ ## Demo
46
+
47
+ https://github.com/user-attachments/assets/7654b383-669d-4eb9-b23c-06d7aefee8c5
48
+
49
+ ## Prerequisites
50
+
51
+ - Bun (>= 1.2.x)
52
+ - GitHub account with Copilot subscription (individual, business, or enterprise)
53
+
54
+ ## Installation
55
+
56
+ To install dependencies, run:
57
+
58
+ ```sh
59
+ bun install
60
+ ```
61
+
62
+ ## Using with Docker
63
+
64
+ Build image
65
+
66
+ ```sh
67
+ docker build -t copilot-api .
68
+ ```
69
+
70
+ Run the container
71
+
72
+ ```sh
73
+ # Create a directory on your host to persist the GitHub token and related data
74
+ mkdir -p ./copilot-data
75
+
76
+ # Run the container with a bind mount to persist the token
77
+ # This ensures your authentication survives container restarts
78
+
79
+ docker run -p 4141:4141 -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api
80
+ ```
81
+
82
+ > **Note:**
83
+ > 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. This directory also stores the admin request history database (`admin.sqlite`) used by `/admin`.
84
+
85
+ ### Adding Multiple Accounts in Docker
86
+
87
+ To add multiple accounts when running in Docker:
88
+
89
+ > **Note:** The Docker image uses an entrypoint that runs the `start` command by default. To run `auth` subcommands inside the container, prefix them with `--auth` (e.g. `--auth add`).
90
+
91
+ ```sh
92
+ # Add accounts interactively (one at a time)
93
+ docker run -it -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api --auth add
94
+ docker run -it -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api --auth add
95
+
96
+ # List registered accounts
97
+ docker run -it -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api --auth ls -q
98
+ ```
99
+
100
+ > **Note:** When using multiple accounts, all account data (tokens and registry) is stored in the mounted `copilot-data` directory.
101
+ > Premium-model requests use accounts in order and automatically switch when premium quota is exhausted; free-model requests are distributed round-robin across accounts by default (configurable in config.json).
102
+
103
+ ### Docker with Environment Variables
104
+
105
+ You can pass the GitHub token directly to the container using environment variables:
106
+
107
+ ```sh
108
+ # Build with GitHub token
109
+ docker build --build-arg GH_TOKEN=your_github_token_here -t copilot-api .
110
+
111
+ # Run with GitHub token
112
+ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api
113
+
114
+ # (Optional) Enable remote admin UI/API access
115
+ # This requires setting ADMIN_TOKEN and sending it via request headers (x-admin-token / Authorization: Bearer)
116
+ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here -e ADMIN_TOKEN=your_admin_token_here copilot-api
117
+
118
+ # (Optional) Protect selected API endpoints with an API key
119
+ # This protects /v1/*, /token, /usage(/usage/*), and also the non-/v1 OpenAI-style endpoints (/chat/completions, /models, /embeddings, /responses)
120
+ # Clients must send Authorization: Bearer <key> or x-api-key: <key>
121
+ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here -e COPILOT_API_KEY=your_api_key_here copilot-api
122
+
123
+ # Run with additional options
124
+ docker run -p 4141:4141 -e GH_TOKEN=your_token copilot-api --verbose --port 4141
125
+ ```
126
+
127
+ ### Docker Compose Example
128
+
129
+ ```yaml
130
+ version: "3.8"
131
+ services:
132
+ copilot-api:
133
+ build: .
134
+ ports:
135
+ - "4141:4141"
136
+ environment:
137
+ - GH_TOKEN=your_github_token_here
138
+ - ADMIN_TOKEN=your_admin_token_here
139
+ - COPILOT_API_KEY=your_api_key_here
140
+ restart: unless-stopped
141
+ ```
142
+
143
+ The Docker image includes:
144
+
145
+ - Multi-stage build for optimized image size
146
+ - Non-root user for enhanced security
147
+ - Health check for container monitoring
148
+ - Pinned base image version for reproducible builds
149
+
150
+ ## Using with npx
151
+
152
+ You can run the project directly using npx:
153
+
154
+ ```sh
155
+ npx @nick3/copilot-api@latest start
156
+ ```
157
+
158
+ With options:
159
+
160
+ ```sh
161
+ npx @nick3/copilot-api@latest start --port 8080
162
+ ```
163
+
164
+ For authentication only:
165
+
166
+ ```sh
167
+ npx @nick3/copilot-api@latest auth
168
+ ```
169
+
170
+ ## Command Structure
171
+
172
+ Copilot API now uses a subcommand structure with these main commands:
173
+
174
+ - `start`: Start the Copilot API server. This command will also handle authentication if needed.
175
+ - `auth`: Manage GitHub Copilot accounts. Supports subcommands:
176
+ - `auth add`: Add a new account via GitHub OAuth flow
177
+ - `auth ls`: List all registered accounts (use `-q` to show quota)
178
+ - `auth rm <id|index>`: Remove an account by ID or 1-based index
179
+
180
+ Running `auth` without a subcommand defaults to `auth add` for backward compatibility.
181
+ - `check-usage`: Show your current GitHub Copilot usage and quota information directly in the terminal (no server required).
182
+ - `debug`: Display diagnostic information including version, runtime details, file paths, and authentication status. Useful for troubleshooting and support.
183
+
184
+ ## Command Line Options
185
+
186
+ ### Start Command Options
187
+
188
+ The following command line options are available for the `start` command:
189
+
190
+ | Option | Description | Default | Alias |
191
+ | -------------- | ----------------------------------------------------------------------------- | ---------- | ----- |
192
+ | --port | Port to listen on | 4141 | -p |
193
+ | --verbose | Enable verbose logging | false | -v |
194
+ | --account-type | Account type to use (individual, business, enterprise) | individual | -a |
195
+ | --manual | Enable manual request approval | false | none |
196
+ | --rate-limit | Rate limit in seconds between requests | none | -r |
197
+ | --wait | Wait instead of error when rate limit is hit | false | -w |
198
+ | --github-token | Provide GitHub token directly (must be generated using the `auth` subcommand) | none | -g |
199
+ | --claude-code | Generate a command to launch Claude Code with Copilot API config | false | -c |
200
+ | --show-token | Show GitHub and Copilot tokens on fetch and refresh | false | none |
201
+ | --proxy-env | Initialize proxy from environment variables | false | none |
202
+
203
+ ### Auth Command Options
204
+
205
+ The `auth` command has three subcommands for managing multiple accounts:
206
+
207
+ #### `auth add` - Add a new account
208
+
209
+ | Option | Description | Default | Alias |
210
+ | -------------- | ----------------------------------------------- | ---------- | ----- |
211
+ | --account-type | Account type (individual, business, enterprise) | individual | -a |
212
+ | --verbose | Enable verbose logging | false | -v |
213
+ | --show-token | Show GitHub token after auth | false | none |
214
+
215
+ #### `auth ls` - List registered accounts
216
+
217
+ | Option | Description | Default | Alias |
218
+ | ------------ | ------------------------------------------ | ------- | ----- |
219
+ | --show-quota | Show quota information (requires API call) | false | -q |
220
+ | --verbose | Enable verbose logging | false | -v |
221
+
222
+ #### `auth rm <target>` - Remove an account
223
+
224
+ | Option | Description | Default | Alias |
225
+ | --------- | ------------------------ | ------- | ----- |
226
+ | --force | Skip confirmation prompt | false | -f |
227
+ | --verbose | Enable verbose logging | false | -v |
228
+
229
+ The `<target>` can be either the account ID (GitHub username) or a 1-based index.
230
+
231
+ ### Debug Command Options
232
+
233
+ | Option | Description | Default | Alias |
234
+ | ------ | ------------------------- | ------- | ----- |
235
+ | --json | Output debug info as JSON | false | none |
236
+
237
+ ## Configuration (config.json)
238
+
239
+ - **Location:** `~/.local/share/copilot-api/config.json` (Linux/macOS) or `%USERPROFILE%\.local\share\copilot-api\config.json` (Windows).
240
+ - **Default shape:**
241
+ ```json
242
+ {
243
+ "extraPrompts": {
244
+ "gpt-5-mini": "<built-in exploration prompt>",
245
+ "gpt-5.1-codex-max": "<built-in exploration prompt>"
246
+ },
247
+ "smallModel": "gpt-5-mini",
248
+ "freeModelLoadBalancing": true,
249
+ "apiKey": "<your_api_key_here>",
250
+ "modelReasoningEfforts": {
251
+ "gpt-5-mini": "low"
252
+ },
253
+ "modelAliases": {
254
+ "fast": { "target": "gpt-5-mini", "allowOriginal": false },
255
+ "draft": { "target": "gpt-5.1-codex-max" }
256
+ },
257
+ "allowOriginalModelNamesForAliases": false,
258
+ "useFunctionApplyPatch": true,
259
+ "forceAgent": false,
260
+ "compactUseSmallModel": true
261
+ }
262
+ ```
263
+ - **extraPrompts:** Map of `model -> prompt` appended to the first system prompt when translating Anthropic-style requests to Copilot. Use this to inject guardrails or guidance per model. Missing default entries are auto-added without overwriting your custom prompts.
264
+ - **smallModel:** Fallback model used for tool-less warmup messages (e.g., Claude Code probe requests) to avoid spending premium requests; defaults to `gpt-5-mini`. If original names are blocked and this points to an aliased target, it resolves to the first alias.
265
+ - **freeModelLoadBalancing:** Enable round-robin routing for free-model requests across multiple accounts. Defaults to `true`. Set to `false` to route free-model requests sequentially (same ordering strategy as premium models).
266
+ - **apiKey (optional):** API key used to protect selected endpoints (see **API Key authentication** below). Prefer setting the `COPILOT_API_KEY` environment variable (takes precedence over `config.json`). The server does not generate an API key automatically — you must provide one. If no key is configured, protected endpoints remain publicly accessible (fail-open). **Do not commit secrets.**
267
+ - **modelReasoningEfforts:** Per-model `reasoning.effort` sent to the Copilot Responses API. Allowed values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. If a model isn’t listed, `high` is used by default.
268
+ - **modelAliases:** Map of `alias -> { target, allowOriginal? }` (legacy string values are still accepted). Alias keys are normalized (trim + lowercase) and must be non-empty; aliases cannot map to themselves (case-insensitive), and conflicting normalized aliases are rejected. `allowOriginal` overrides the global default per alias. If multiple aliases map to the same target, original names are allowed when any alias sets `allowOriginal: true` (allow-wins). Admin UI/API rejects blocked keys (`__proto__`, `constructor`, `prototype`). Aliases can be used in downstream requests.
269
+ - **allowOriginalModelNamesForAliases:** Global default for aliases that omit `allowOriginal`. When `false` (default), targets are blocked unless an alias explicitly allows them; when `true`, targets are allowed unless all aliases explicitly block them.
270
+ - **useFunctionApplyPatch:** When `true` (default), `POST /v1/responses` converts a `tools` entry with `{ "type": "custom", "name": "apply_patch" }` into an OpenAI-style `function` tool (with a parameter schema) for upstream compatibility. Set to `false` to leave custom tools untouched.
271
+ - **forceAgent:** When `true`, `POST /v1/responses` treats a request as agent-initiated if **any** input item has `role: "assistant"`. When `false` (default), only the **last** input item is checked.
272
+ - **compactUseSmallModel:** When `true`, detected "compact" requests (e.g., from Claude Code or opencode compact mode) will automatically use the configured `smallModel` to avoid consuming premium usage for short/background tasks. Defaults to `true`.
273
+
274
+ Edit this file to customize prompts or swap in your own fast model. If you edit it manually, restart the server (or call `GET /api/admin/config`) so the cached config is refreshed. Changes made through the Admin UI/API are validated, written to disk, and applied immediately; unknown keys are rejected.
275
+
276
+ ## API Endpoints
277
+
278
+ 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.
279
+
280
+ ### OpenAI Compatible Endpoints
281
+
282
+ These endpoints mimic the OpenAI API structure.
283
+
284
+ | Endpoint | Method | Description |
285
+ | --------------------------- | ------ | ---------------------------------------------------------------- |
286
+ | `POST /v1/responses` | `POST` | OpenAI Most advanced interface for generating model responses. |
287
+ | `POST /v1/chat/completions` | `POST` | Creates a model response for the given chat conversation. |
288
+ | `GET /v1/models` | `GET` | Lists the currently available models. |
289
+ | `POST /v1/embeddings` | `POST` | Creates an embedding vector representing the input text. |
290
+
291
+ ### Anthropic Compatible Endpoints
292
+
293
+ These endpoints are designed to be compatible with the Anthropic Messages API.
294
+
295
+ | Endpoint | Method | Description |
296
+ | -------------------------------- | ------ | ------------------------------------------------------------ |
297
+ | `POST /v1/messages` | `POST` | Creates a model response for a given conversation. |
298
+ | `POST /v1/messages/count_tokens` | `POST` | Calculates the number of tokens for a given set of messages. |
299
+
300
+ ### Usage Monitoring Endpoints
301
+
302
+ Endpoints for monitoring your Copilot usage and quotas across all accounts.
303
+
304
+ | Endpoint | Method | Description |
305
+ | -------------------- | ------ | ----------------------------------------------------------------------------- |
306
+ | `GET /usage` | `GET` | Get status of all registered accounts (ID, remaining quota, unlimited flag). |
307
+ | `GET /usage/:index` | `GET` | Get detailed Copilot usage for a specific account by index (0-based). |
308
+ | `GET /token` | `GET` | Get the current Copilot token being used by the API. |
309
+
310
+ > **Note on account indices**
311
+ > - `/usage/:index` is **0-based**.
312
+ > - If you start the server with `start --github-token ...`, a temporary account is included and shown as `"(temporary)"` in `GET /usage`. In that case, `index=0` refers to the temporary account and registered accounts start at `index=1`.
313
+ > - `auth rm <index>` uses a **1-based** index (as shown by `auth ls`).
314
+
315
+ ### API Key authentication (optional)
316
+
317
+ You can protect selected public endpoints by setting an API key:
318
+
319
+ - **Environment variable (preferred):** `COPILOT_API_KEY`
320
+ - **config.json:** `"apiKey": "<key>"` (used only when `COPILOT_API_KEY` is not set)
321
+
322
+ When a key is configured, requests to the following endpoints require authentication:
323
+ - OpenAI-compatible: `/v1/*`, `/chat/completions`, `/models`, `/embeddings`, `/responses`
324
+ - Usage/token: `/usage`, `/usage/*`, `/token`
325
+
326
+ Send the key using one of:
327
+ - `Authorization: Bearer <key>` (common for OpenAI clients)
328
+ - `x-api-key: <key>` (common for Anthropic clients)
329
+
330
+ If no key is configured, these endpoints are publicly accessible (fail-open).
331
+
332
+ ### Admin UI & Admin API
333
+
334
+ The server also exposes a built-in admin UI and API for inspecting account status and request history captured by the proxy.
335
+
336
+ | Endpoint | Method | Description |
337
+ | ----------------------------------- | ------ | -------------------------------------------------------------------- |
338
+ | `GET /admin` | `GET` | Built-in admin UI (single-page web app). |
339
+ | `GET /api/admin/meta` | `GET` | Admin DB metadata (db path, retention, etc.). |
340
+ | `GET /api/admin/accounts` | `GET` | List accounts with runtime status and (optional) aggregated stats. |
341
+ | `GET /api/admin/requests` | `GET` | Query request logs with filters and cursor pagination. |
342
+ | `GET /api/admin/requests/:requestId`| `GET` | Get a single request log entry by request ID. |
343
+
344
+ #### Authentication & access
345
+
346
+ - **Loopback access** is allowed by default when the hostname is `localhost`, `127.0.0.1`, or `::1`.
347
+ - **Remote access** is disabled unless you set `ADMIN_TOKEN` on the server.
348
+ - When `ADMIN_TOKEN` is set, send the token using one of:
349
+ - `x-admin-token: <token>`
350
+ - `Authorization: Bearer <token>`
351
+ - Tokens in URL query parameters are intentionally not supported.
352
+
353
+ #### Requests query (pagination & filters)
354
+
355
+ - `limit` defaults to 50 and is clamped to a max of 200.
356
+ - `cursor_id` is an integer cursor for pagination (use the `next_cursor_id` from the previous response).
357
+ - Filters: `account_id`, `upstream_model`, `client_model`, `upstream_endpoint`, `path`, `status`, `has_error`, `from_ms`, `to_ms`.
358
+ - Response fields: `items`, `next_cursor_id`, `has_more`.
359
+
360
+ ## Example Usage
361
+
362
+ Using with npx:
363
+
364
+ ```sh
365
+ # Basic usage with start command
366
+ npx @nick3/copilot-api@latest start
367
+
368
+ # Run on custom port with verbose logging
369
+ npx @nick3/copilot-api@latest start --port 8080 --verbose
370
+
371
+ # Use with a business plan GitHub account
372
+ npx @nick3/copilot-api@latest start --account-type business
373
+
374
+ # Use with an enterprise plan GitHub account
375
+ npx @nick3/copilot-api@latest start --account-type enterprise
376
+
377
+ # Enable manual approval for each request
378
+ npx @nick3/copilot-api@latest start --manual
379
+
380
+ # Set rate limit to 30 seconds between requests
381
+ npx @nick3/copilot-api@latest start --rate-limit 30
382
+
383
+ # Wait instead of error when rate limit is hit
384
+ npx @nick3/copilot-api@latest start --rate-limit 30 --wait
385
+
386
+ # Provide GitHub token directly
387
+ npx @nick3/copilot-api@latest start --github-token ghp_YOUR_TOKEN_HERE
388
+
389
+ # Run only the auth flow
390
+ npx @nick3/copilot-api@latest auth
391
+
392
+ # Run auth flow with verbose logging
393
+ npx @nick3/copilot-api@latest auth --verbose
394
+
395
+ # Add multiple accounts (each account is added in order)
396
+ npx @nick3/copilot-api@latest auth add
397
+ npx @nick3/copilot-api@latest auth add # add second account
398
+
399
+ # List all registered accounts
400
+ npx @nick3/copilot-api@latest auth ls
401
+
402
+ # List accounts with quota information
403
+ npx @nick3/copilot-api@latest auth ls -q
404
+
405
+ # Remove an account by index (1-based)
406
+ npx @nick3/copilot-api@latest auth rm 2
407
+
408
+ # Remove an account by ID (GitHub username)
409
+ npx @nick3/copilot-api@latest auth rm octocat
410
+
411
+ # Show your Copilot usage/quota in the terminal (no server needed)
412
+ npx @nick3/copilot-api@latest check-usage
413
+
414
+ # Display debug information for troubleshooting
415
+ npx @nick3/copilot-api@latest debug
416
+
417
+ # Display debug information in JSON format
418
+ npx @nick3/copilot-api@latest debug --json
419
+
420
+ # Initialize proxy from environment variables (HTTP_PROXY, HTTPS_PROXY, etc.)
421
+ npx @nick3/copilot-api@latest start --proxy-env
422
+ ```
423
+
424
+ ### Admin API examples
425
+
426
+ ```sh
427
+ # Loopback access (no token required)
428
+ curl "http://localhost:4141/api/admin/meta"
429
+
430
+ # Enable remote admin UI/API access (server-side)
431
+ # ADMIN_TOKEN=your_admin_token_here npx @nick3/copilot-api@latest start
432
+
433
+ # Remote access (token required)
434
+ curl -H "x-admin-token: your_admin_token_here" "http://localhost:4141/api/admin/accounts?include_stats=1"
435
+
436
+ # Request logs (filters + pagination)
437
+ curl "http://localhost:4141/api/admin/requests?limit=50&has_error=1"
438
+ # Use next_cursor_id from the response for pagination:
439
+ curl "http://localhost:4141/api/admin/requests?limit=50&cursor_id=<next_cursor_id>"
440
+
441
+ # Single request detail
442
+ curl "http://localhost:4141/api/admin/requests/<requestId>"
443
+ ```
444
+
445
+ ## Using the Usage Viewer
446
+
447
+ 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.
448
+
449
+ 1. Start the server. For example, using npx:
450
+ ```sh
451
+ npx @nick3/copilot-api@latest start
452
+ ```
453
+ 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:
454
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://localhost:4141/usage`
455
+ - If you use the `start.bat` script on Windows, this page will open automatically.
456
+
457
+ > **API Key note:** If you enable API key authentication for `/usage`, your client must send the API key header. If a client cannot set headers, use `curl` or another API client instead.
458
+
459
+ The dashboard provides a user-friendly interface to view your Copilot usage data:
460
+
461
+ - **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.
462
+ - **Fetch Data**: Click the "Fetch" button to load or refresh the usage data. The dashboard will automatically fetch data on load.
463
+ - **Usage Quotas**: View a summary of your usage quotas for different services like Chat and Completions, displayed with progress bars for a quick overview.
464
+ - **Detailed Information**: See the full JSON response from the API for a detailed breakdown of all available usage statistics.
465
+ - **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:
466
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://your-api-server/usage`
467
+
468
+ ## Using the Admin UI (/admin)
469
+
470
+ The proxy includes a built-in admin UI served from your running instance. It lets you inspect account status and request history captured by the proxy (models/endpoints, tokens/usage, timing, and error summaries).
471
+
472
+ 1. Start the server. For example, using npx:
473
+ ```sh
474
+ npx @nick3/copilot-api@latest start
475
+ ```
476
+ 2. Open the UI in your browser:
477
+ - `http://localhost:4141/admin` (replace the port if you changed it)
478
+
479
+ ### UI tips
480
+
481
+ - **Header controls (top-right)**
482
+ - **Motion**: `Magic` / `Subtle` / `Off` (auto-forced to `Off` when your OS has reduced motion enabled)
483
+ - **Theme**: `System` / `Light` / `Dark`
484
+ - **Admin token**: stored in `sessionStorage` (use the Token dialog to save/test it)
485
+ - **Navigation**
486
+ - **Accounts**: KPI overview (incl. error rate, tokens/request), plus filter + sort; click an account to jump into Requests with filters applied.
487
+ - **Requests**: Quick/Advanced filters, time range presets (15m/1h/6h/24h/7d) + custom date/time, cursor pagination.
488
+ - **Request detail**: Back button returns to Requests (preserving filters when navigated from the list); summary fields link back into Requests; JSON viewer supports search/highlight, expand/collapse, and Copy/Download.
489
+ - **Deep links**
490
+ - The admin UI uses hash routing, so sharable links look like: `http://localhost:4141/admin/#/requests?...`
491
+
492
+ ### Access control
493
+
494
+ - When accessing via `localhost` / `127.0.0.1` / `::1`, the admin API is available without a token.
495
+ - For non-loopback access (e.g. using a machine IP or hostname), you must enable remote access by setting `ADMIN_TOKEN` on the server and provide the token in requests.
496
+
497
+ The UI stores the token in `sessionStorage` and sends it as the `x-admin-token` header (it is never placed in the URL).
498
+
499
+ If you see:
500
+ - `403 forbidden`: the admin API is restricted to localhost unless `ADMIN_TOKEN` is set (or the request was blocked as cross-origin).
501
+ - `401 unauthorized`: `ADMIN_TOKEN` is set but the request did not include a valid token.
502
+
503
+ ### Data storage (admin.sqlite)
504
+
505
+ - Request history is stored in `admin.sqlite` under the app data directory:
506
+ - Linux/macOS: `~/.local/share/copilot-api/admin.sqlite`
507
+ - Windows: `%USERPROFILE%\.local\share\copilot-api\admin.sqlite`
508
+ - By default, the proxy keeps up to 14 days of logs and caps the DB at 200,000 rows (older entries are cleaned up automatically).
509
+ - For safety, the admin DB stores metadata only (no GitHub/Copilot tokens and no request/response content).
510
+
511
+ ## Using with Claude Code
512
+
513
+ 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.
514
+
515
+ There are two ways to configure Claude Code to use this proxy:
516
+
517
+ ### Interactive Setup with `--claude-code` flag
518
+
519
+ To get started, run the `start` command with the `--claude-code` flag:
520
+
521
+ ```sh
522
+ npx @nick3/copilot-api@latest start --claude-code
523
+ ```
524
+
525
+ 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.
526
+
527
+ Paste and run this command in a new terminal to launch Claude Code.
528
+
529
+ > **API Key note:** If you enabled API key authentication (via `COPILOT_API_KEY` or `config.json` `apiKey`), set `ANTHROPIC_AUTH_TOKEN` in the generated command to the same API key.
530
+
531
+ ### Manual Configuration with `settings.json`
532
+
533
+ 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.
534
+
535
+ Here is an example `.claude/settings.json` file:
536
+
537
+ > **API Key note:** If API key authentication is enabled, set `ANTHROPIC_AUTH_TOKEN` to your API key so Claude Code can send `x-api-key`. If not enabled, any value works.
538
+
539
+ ```json
540
+ {
541
+ "env": {
542
+ "ANTHROPIC_BASE_URL": "http://localhost:4141",
543
+ "ANTHROPIC_AUTH_TOKEN": "dummy",
544
+ "ANTHROPIC_MODEL": "gpt-5.2",
545
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "gpt-5.2",
546
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "gpt-5-mini",
547
+ "CLAUDE_CODE_SUBAGENT_MODEL": "gpt-5-mini",
548
+ "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1",
549
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
550
+ "BASH_MAX_TIMEOUT_MS": "600000",
551
+ "CLAUDE_CODE_ATTRIBUTION_HEADER": "0",
552
+ "CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION": "false"
553
+ },
554
+ "permissions": {
555
+ "deny": [
556
+ "WebSearch"
557
+ ]
558
+ }
559
+ }
560
+ ```
561
+
562
+ ### CLAUDE.md Recommended Content
563
+
564
+ Please include the following in `CLAUDE.md` (for Claude usage):
565
+
566
+ - Prohibited from directly asking questions to users, MUST use AskUserQuestion tool.
567
+ - Once you can confirm that the task is complete, MUST use AskUserQuestion tool to make user confirm. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
568
+
569
+ You can find more options here: [Claude Code settings](https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables)
570
+
571
+ 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)
572
+
573
+ ## Running from Source
574
+
575
+ The project can be run from source in several ways:
576
+
577
+ ### Development Mode
578
+
579
+ ```sh
580
+ bun run dev
581
+ ```
582
+
583
+ ### Production Mode
584
+
585
+ ```sh
586
+ bun run start
587
+ ```
588
+
589
+ ## Usage Tips
590
+
591
+ - To avoid hitting GitHub Copilot's rate limits, you can use the following flags:
592
+ - `--manual`: Enables manual approval for each request, giving you full control over when requests are sent.
593
+ - `--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.
594
+ - `--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.
595
+ - 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.
596
+ - **Multi-account request routing**: Add multiple GitHub Copilot accounts using `auth add`.
597
+ - **Premium models**: Accounts are tried in the order they were added. When an account's premium request quota (`remaining=0`) is exhausted (or insufficient for the selected model), the proxy automatically switches to the next eligible account.
598
+ - **Free models**: By default, requests are distributed round-robin across all eligible accounts (including the temporary account created via `start --github-token ...`). Set `freeModelLoadBalancing=false` in `config.json` to disable this and route free-model requests sequentially.
599
+ - **Model classification**: Based on Copilot model metadata (`billing.is_premium` / `billing.multiplier`). Missing billing info or `billing.is_premium !== true` is treated as free.