copilot-api-plus 1.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.
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,360 @@
1
+ # Copilot API Plus
2
+
3
+ > **Fork of [ericc-ch/copilot-api](https://github.com/ericc-ch/copilot-api)** with bug fixes and improvements.
4
+
5
+ > [!WARNING]
6
+ > 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.
7
+
8
+ > [!WARNING]
9
+ > **GitHub Security Notice:**
10
+ > Excessive automated or scripted use of Copilot (including rapid or bulk requests, such as via automated tools) may trigger GitHub's abuse-detection systems.
11
+ > You may receive a warning from GitHub Security, and further anomalous activity could result in temporary suspension of your Copilot access.
12
+ >
13
+ > GitHub prohibits use of their servers for excessive automated bulk activity or any activity that places undue burden on their infrastructure.
14
+ >
15
+ > Please review:
16
+ >
17
+ > - [GitHub Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies/github-acceptable-use-policies#4-spam-and-inauthentic-activity-on-github)
18
+ > - [GitHub Copilot Terms](https://docs.github.com/site-policy/github-terms/github-terms-for-additional-products-and-features#github-copilot)
19
+ >
20
+ > Use this proxy responsibly to avoid account restrictions.
21
+
22
+ ---
23
+
24
+ ## What's Different from Original?
25
+
26
+ This fork includes the following bug fixes and improvements:
27
+
28
+ - ✅ **Auto Re-authentication**: Automatically detects invalid/expired GitHub tokens and re-authenticates
29
+ - ✅ **Logout Command**: New `logout` command to clear stored tokens and switch accounts
30
+ - ✅ **Better Error Handling**: Token refresh failures no longer crash the server
31
+ - ✅ **OAuth Timeout**: Device code polling now has proper timeout handling
32
+ - ✅ **Token Validation**: Validates provided GitHub tokens before use
33
+ - ✅ **API Key Auth**: API key authentication middleware is now properly enabled
34
+
35
+ ---
36
+
37
+ ## Project Overview
38
+
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).
40
+
41
+ ## Features
42
+
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
+ ## Prerequisites
53
+
54
+ - Bun (>= 1.2.x)
55
+ - GitHub account with Copilot subscription (individual, business, or enterprise)
56
+
57
+ ## Installation
58
+
59
+ To install dependencies, run:
60
+
61
+ ```sh
62
+ bun install
63
+ ```
64
+
65
+ ## Using with Docker
66
+
67
+ Build image
68
+
69
+ ```sh
70
+ docker build -t copilot-api-plus .
71
+ ```
72
+
73
+ Run the container
74
+
75
+ ```sh
76
+ # Create a directory on your host to persist the GitHub token and related data
77
+ mkdir -p ./copilot-data
78
+
79
+ # Run the container with a bind mount to persist the token
80
+ # This ensures your authentication survives container restarts
81
+
82
+ docker run -p 4141:4141 -v $(pwd)/copilot-data:/root/.local/share/copilot-api-plus copilot-api-plus
83
+ ```
84
+
85
+ > **Note:**
86
+ > The GitHub token and related data will be stored in `copilot-data` on your host. This is mapped to `/root/.local/share/copilot-api-plus` inside the container, ensuring persistence across restarts.
87
+
88
+ ### Docker with Environment Variables
89
+
90
+ You can pass the GitHub token directly to the container using environment variables:
91
+
92
+ ```sh
93
+ # Build with GitHub token
94
+ docker build --build-arg GH_TOKEN=your_github_token_here -t copilot-api-plus .
95
+
96
+ # Run with GitHub token
97
+ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api-plus
98
+
99
+ # Run with additional options
100
+ docker run -p 4141:4141 -e GH_TOKEN=your_token copilot-api-plus start --verbose --port 4141
101
+ ```
102
+
103
+ ### Docker Compose Example
104
+
105
+ ```yaml
106
+ version: "3.8"
107
+ services:
108
+ copilot-api-plus:
109
+ build: .
110
+ ports:
111
+ - "4141:4141"
112
+ environment:
113
+ - GH_TOKEN=your_github_token_here
114
+ restart: unless-stopped
115
+ ```
116
+
117
+ The Docker image includes:
118
+
119
+ - Multi-stage build for optimized image size
120
+ - Non-root user for enhanced security
121
+ - Health check for container monitoring
122
+ - Pinned base image version for reproducible builds
123
+
124
+ ## Using with npx
125
+
126
+ You can run the project directly using npx:
127
+
128
+ ```sh
129
+ npx copilot-api-plus@latest start
130
+ ```
131
+
132
+ With options:
133
+
134
+ ```sh
135
+ npx copilot-api-plus@latest start --port 8080
136
+ ```
137
+
138
+ For authentication only:
139
+
140
+ ```sh
141
+ npx copilot-api-plus@latest auth
142
+ ```
143
+
144
+ ## Command Structure
145
+
146
+ Copilot API Plus uses a subcommand structure with these main commands:
147
+
148
+ - `start`: Start the Copilot API server. This command will also handle authentication if needed.
149
+ - `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.
150
+ - `check-usage`: Show your current GitHub Copilot usage and quota information directly in the terminal (no server required).
151
+ - `debug`: Display diagnostic information including version, runtime details, file paths, and authentication status. Useful for troubleshooting and support.
152
+ - `logout`: Clear stored GitHub token and logout. Use this to switch accounts or re-authenticate.
153
+
154
+ ## Command Line Options
155
+
156
+ ### Start Command Options
157
+
158
+ The following command line options are available for the `start` command:
159
+
160
+ | Option | Description | Default | Alias |
161
+ | -------------- | ----------------------------------------------------------------------------- | ---------- | ----- |
162
+ | --port | Port to listen on | 4141 | -p |
163
+ | --verbose | Enable verbose logging | false | -v |
164
+ | --account-type | Account type to use (individual, business, enterprise) | individual | -a |
165
+ | --manual | Enable manual request approval | false | none |
166
+ | --rate-limit | Rate limit in seconds between requests | none | -r |
167
+ | --wait | Wait instead of error when rate limit is hit | false | -w |
168
+ | --github-token | Provide GitHub token directly (must be generated using the `auth` subcommand) | none | -g |
169
+ | --claude-code | Generate a command to launch Claude Code with Copilot API config | false | -c |
170
+ | --show-token | Show GitHub and Copilot tokens on fetch and refresh | false | none |
171
+ | --proxy-env | Initialize proxy from environment variables | false | none |
172
+
173
+ ### Auth Command Options
174
+
175
+ | Option | Description | Default | Alias |
176
+ | ------------ | ------------------------- | ------- | ----- |
177
+ | --verbose | Enable verbose logging | false | -v |
178
+ | --show-token | Show GitHub token on auth | false | none |
179
+
180
+ ### Debug Command Options
181
+
182
+ | Option | Description | Default | Alias |
183
+ | ------ | ------------------------- | ------- | ----- |
184
+ | --json | Output debug info as JSON | false | none |
185
+
186
+ ## API Endpoints
187
+
188
+ 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.
189
+
190
+ ### OpenAI Compatible Endpoints
191
+
192
+ These endpoints mimic the OpenAI API structure.
193
+
194
+ | Endpoint | Method | Description |
195
+ | --------------------------- | ------ | --------------------------------------------------------- |
196
+ | `POST /v1/chat/completions` | `POST` | Creates a model response for the given chat conversation. |
197
+ | `GET /v1/models` | `GET` | Lists the currently available models. |
198
+ | `POST /v1/embeddings` | `POST` | Creates an embedding vector representing the input text. |
199
+
200
+ ### Anthropic Compatible Endpoints
201
+
202
+ These endpoints are designed to be compatible with the Anthropic Messages API.
203
+
204
+ | Endpoint | Method | Description |
205
+ | -------------------------------- | ------ | ------------------------------------------------------------ |
206
+ | `POST /v1/messages` | `POST` | Creates a model response for a given conversation. |
207
+ | `POST /v1/messages/count_tokens` | `POST` | Calculates the number of tokens for a given set of messages. |
208
+
209
+ ### Usage Monitoring Endpoints
210
+
211
+ New endpoints for monitoring your Copilot usage and quotas.
212
+
213
+ | Endpoint | Method | Description |
214
+ | ------------ | ------ | ------------------------------------------------------------ |
215
+ | `GET /usage` | `GET` | Get detailed Copilot usage statistics and quota information. |
216
+ | `GET /token` | `GET` | Get the current Copilot token being used by the API. |
217
+
218
+ ## Example Usage
219
+
220
+ Using with npx:
221
+
222
+ ```sh
223
+ # Basic usage with start command
224
+ npx copilot-api-plus@latest start
225
+
226
+ # Run on custom port with verbose logging
227
+ npx copilot-api-plus@latest start --port 8080 --verbose
228
+
229
+ # Use with a business plan GitHub account
230
+ npx copilot-api-plus@latest start --account-type business
231
+
232
+ # Use with an enterprise plan GitHub account
233
+ npx copilot-api-plus@latest start --account-type enterprise
234
+
235
+ # Enable manual approval for each request
236
+ npx copilot-api-plus@latest start --manual
237
+
238
+ # Set rate limit to 30 seconds between requests
239
+ npx copilot-api-plus@latest start --rate-limit 30
240
+
241
+ # Wait instead of error when rate limit is hit
242
+ npx copilot-api-plus@latest start --rate-limit 30 --wait
243
+
244
+ # Provide GitHub token directly
245
+ npx copilot-api-plus@latest start --github-token ghp_YOUR_TOKEN_HERE
246
+
247
+ # Run only the auth flow
248
+ npx copilot-api-plus@latest auth
249
+
250
+ # Run auth flow with verbose logging
251
+ npx copilot-api-plus@latest auth --verbose
252
+
253
+ # Show your Copilot usage/quota in the terminal (no server needed)
254
+ npx copilot-api-plus@latest check-usage
255
+
256
+ # Display debug information for troubleshooting
257
+ npx copilot-api-plus@latest debug
258
+
259
+ # Display debug information in JSON format
260
+ npx copilot-api-plus@latest debug --json
261
+
262
+ # Logout and clear stored tokens (to switch accounts)
263
+ npx copilot-api-plus@latest logout
264
+
265
+ # Initialize proxy from environment variables (HTTP_PROXY, HTTPS_PROXY, etc.)
266
+ npx copilot-api-plus@latest start --proxy-env
267
+ ```
268
+
269
+ ## Using the Usage Viewer
270
+
271
+ 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.
272
+
273
+ 1. Start the server. For example, using npx:
274
+ ```sh
275
+ npx copilot-api@latest start
276
+ ```
277
+ 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:
278
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://localhost:4141/usage`
279
+ - If you use the `start.bat` script on Windows, this page will open automatically.
280
+
281
+ The dashboard provides a user-friendly interface to view your Copilot usage data:
282
+
283
+ - **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.
284
+ - **Fetch Data**: Click the "Fetch" button to load or refresh the usage data. The dashboard will automatically fetch data on load.
285
+ - **Usage Quotas**: View a summary of your usage quotas for different services like Chat and Completions, displayed with progress bars for a quick overview.
286
+ - **Detailed Information**: See the full JSON response from the API for a detailed breakdown of all available usage statistics.
287
+ - **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:
288
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://your-api-server/usage`
289
+
290
+ ## Using with Claude Code
291
+
292
+ 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.
293
+
294
+ There are two ways to configure Claude Code to use this proxy:
295
+
296
+ ### Interactive Setup with `--claude-code` flag
297
+
298
+ To get started, run the `start` command with the `--claude-code` flag:
299
+
300
+ ```sh
301
+ npx copilot-api@latest start --claude-code
302
+ ```
303
+
304
+ 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.
305
+
306
+ Paste and run this command in a new terminal to launch Claude Code.
307
+
308
+ ### Manual Configuration with `settings.json`
309
+
310
+ 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.
311
+
312
+ Here is an example `.claude/settings.json` file:
313
+
314
+ ```json
315
+ {
316
+ "env": {
317
+ "ANTHROPIC_BASE_URL": "http://localhost:4141",
318
+ "ANTHROPIC_AUTH_TOKEN": "dummy",
319
+ "ANTHROPIC_MODEL": "gpt-4.1",
320
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "gpt-4.1",
321
+ "ANTHROPIC_SMALL_FAST_MODEL": "gpt-4.1",
322
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "gpt-4.1",
323
+ "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1",
324
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
325
+ },
326
+ "permissions": {
327
+ "deny": [
328
+ "WebSearch"
329
+ ]
330
+ }
331
+ }
332
+ ```
333
+
334
+ You can find more options here: [Claude Code settings](https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables)
335
+
336
+ 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)
337
+
338
+ ## Running from Source
339
+
340
+ The project can be run from source in several ways:
341
+
342
+ ### Development Mode
343
+
344
+ ```sh
345
+ bun run dev
346
+ ```
347
+
348
+ ### Production Mode
349
+
350
+ ```sh
351
+ bun run start
352
+ ```
353
+
354
+ ## Usage Tips
355
+
356
+ - To avoid hitting GitHub Copilot's rate limits, you can use the following flags:
357
+ - `--manual`: Enables manual approval for each request, giving you full control over when requests are sent.
358
+ - `--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.
359
+ - `--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.
360
+ - 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.
@@ -0,0 +1,3 @@
1
+ import { HTTPError, forwardError } from "./error-Cmeg4mmB.js";
2
+
3
+ export { HTTPError };
@@ -0,0 +1,35 @@
1
+ import consola from "consola";
2
+
3
+ //#region src/lib/error.ts
4
+ var HTTPError = class extends Error {
5
+ response;
6
+ constructor(message, response) {
7
+ super(message);
8
+ this.response = response;
9
+ }
10
+ };
11
+ async function forwardError(c, error) {
12
+ consola.error("Error occurred:", error);
13
+ if (error instanceof HTTPError) {
14
+ const errorText = await error.response.text();
15
+ let errorJson;
16
+ try {
17
+ errorJson = JSON.parse(errorText);
18
+ } catch {
19
+ errorJson = errorText;
20
+ }
21
+ consola.error("HTTP error:", errorJson);
22
+ return c.json({ error: {
23
+ message: errorText,
24
+ type: "error"
25
+ } }, error.response.status);
26
+ }
27
+ return c.json({ error: {
28
+ message: error.message,
29
+ type: "error"
30
+ } }, 500);
31
+ }
32
+
33
+ //#endregion
34
+ export { HTTPError, forwardError };
35
+ //# sourceMappingURL=error-Cmeg4mmB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-Cmeg4mmB.js","names":["errorJson: unknown"],"sources":["../src/lib/error.ts"],"sourcesContent":["import type { Context } from \"hono\"\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\"\n\nimport consola from \"consola\"\n\nexport class HTTPError extends Error {\n response: Response\n\n constructor(message: string, response: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport async function forwardError(c: Context, error: unknown) {\n consola.error(\"Error occurred:\", error)\n\n if (error instanceof HTTPError) {\n const errorText = await error.response.text()\n let errorJson: unknown\n try {\n errorJson = JSON.parse(errorText)\n } catch {\n errorJson = errorText\n }\n consola.error(\"HTTP error:\", errorJson)\n return c.json(\n {\n error: {\n message: errorText,\n type: \"error\",\n },\n },\n error.response.status as ContentfulStatusCode,\n )\n }\n\n return c.json(\n {\n error: {\n message: (error as Error).message,\n type: \"error\",\n },\n },\n 500,\n )\n}\n"],"mappings":";;;AAKA,IAAa,YAAb,cAA+B,MAAM;CACnC;CAEA,YAAY,SAAiB,UAAoB;AAC/C,QAAM,QAAQ;AACd,OAAK,WAAW;;;AAIpB,eAAsB,aAAa,GAAY,OAAgB;AAC7D,SAAQ,MAAM,mBAAmB,MAAM;AAEvC,KAAI,iBAAiB,WAAW;EAC9B,MAAM,YAAY,MAAM,MAAM,SAAS,MAAM;EAC7C,IAAIA;AACJ,MAAI;AACF,eAAY,KAAK,MAAM,UAAU;UAC3B;AACN,eAAY;;AAEd,UAAQ,MAAM,eAAe,UAAU;AACvC,SAAO,EAAE,KACP,EACE,OAAO;GACL,SAAS;GACT,MAAM;GACP,EACF,EACD,MAAM,SAAS,OAChB;;AAGH,QAAO,EAAE,KACP,EACE,OAAO;EACL,SAAU,MAAgB;EAC1B,MAAM;EACP,EACF,EACD,IACD"}
@@ -0,0 +1,4 @@
1
+ import { getGitHubUser } from "./get-user-DalX7epg.js";
2
+ import "./error-Cmeg4mmB.js";
3
+
4
+ export { getGitHubUser };
@@ -0,0 +1,66 @@
1
+ import { HTTPError } from "./error-Cmeg4mmB.js";
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ //#region src/lib/state.ts
5
+ const state = {
6
+ accountType: "individual",
7
+ manualApprove: false,
8
+ rateLimitWait: false,
9
+ showToken: false
10
+ };
11
+
12
+ //#endregion
13
+ //#region src/lib/api-config.ts
14
+ const standardHeaders = () => ({
15
+ "content-type": "application/json",
16
+ accept: "application/json"
17
+ });
18
+ const COPILOT_VERSION = "0.26.7";
19
+ const EDITOR_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`;
20
+ const USER_AGENT = `GitHubCopilotChat/${COPILOT_VERSION}`;
21
+ const API_VERSION = "2025-04-01";
22
+ const copilotBaseUrl = (state$1) => state$1.accountType === "individual" ? "https://api.githubcopilot.com" : `https://api.${state$1.accountType}.githubcopilot.com`;
23
+ const copilotHeaders = (state$1, vision = false) => {
24
+ const headers = {
25
+ Authorization: `Bearer ${state$1.copilotToken}`,
26
+ "content-type": standardHeaders()["content-type"],
27
+ "copilot-integration-id": "vscode-chat",
28
+ "editor-version": `vscode/${state$1.vsCodeVersion}`,
29
+ "editor-plugin-version": EDITOR_PLUGIN_VERSION,
30
+ "user-agent": USER_AGENT,
31
+ "openai-intent": "conversation-panel",
32
+ "x-github-api-version": API_VERSION,
33
+ "x-request-id": randomUUID(),
34
+ "x-vscode-user-agent-library-version": "electron-fetch"
35
+ };
36
+ if (vision) headers["copilot-vision-request"] = "true";
37
+ return headers;
38
+ };
39
+ const GITHUB_API_BASE_URL = "https://api.github.com";
40
+ const githubHeaders = (state$1) => ({
41
+ ...standardHeaders(),
42
+ authorization: `token ${state$1.githubToken}`,
43
+ "editor-version": `vscode/${state$1.vsCodeVersion}`,
44
+ "editor-plugin-version": EDITOR_PLUGIN_VERSION,
45
+ "user-agent": USER_AGENT,
46
+ "x-github-api-version": API_VERSION,
47
+ "x-vscode-user-agent-library-version": "electron-fetch"
48
+ });
49
+ const GITHUB_BASE_URL = "https://github.com";
50
+ const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
51
+ const GITHUB_APP_SCOPES = ["read:user"].join(" ");
52
+
53
+ //#endregion
54
+ //#region src/services/github/get-user.ts
55
+ async function getGitHubUser() {
56
+ const response = await fetch(`${GITHUB_API_BASE_URL}/user`, { headers: {
57
+ authorization: `token ${state.githubToken}`,
58
+ ...standardHeaders()
59
+ } });
60
+ if (!response.ok) throw new HTTPError("Failed to get GitHub user", response);
61
+ return await response.json();
62
+ }
63
+
64
+ //#endregion
65
+ export { GITHUB_API_BASE_URL, GITHUB_APP_SCOPES, GITHUB_BASE_URL, GITHUB_CLIENT_ID, copilotBaseUrl, copilotHeaders, getGitHubUser, githubHeaders, standardHeaders, state };
66
+ //# sourceMappingURL=get-user-DalX7epg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-user-DalX7epg.js","names":["state: State","state","headers: Record<string, string>"],"sources":["../src/lib/state.ts","../src/lib/api-config.ts","../src/services/github/get-user.ts"],"sourcesContent":["import type { ModelsResponse } from \"~/services/copilot/get-models\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n\n accountType: string\n models?: ModelsResponse\n vsCodeVersion?: string\n\n manualApprove: boolean\n rateLimitWait: boolean\n showToken: boolean\n\n // Rate limiting configuration\n rateLimitSeconds?: number\n lastRequestTimestamp?: number\n\n // API key authentication\n apiKeys?: Array<string>\n}\n\nexport const state: State = {\n accountType: \"individual\",\n manualApprove: false,\n rateLimitWait: false,\n showToken: false,\n}\n","import { randomUUID } from \"node:crypto\"\n\nimport type { State } from \"./state\"\n\nexport const standardHeaders = () => ({\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n})\n\nconst COPILOT_VERSION = \"0.26.7\"\nconst EDITOR_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`\nconst USER_AGENT = `GitHubCopilotChat/${COPILOT_VERSION}`\n\nconst API_VERSION = \"2025-04-01\"\n\nexport const copilotBaseUrl = (state: State) =>\n state.accountType === \"individual\" ?\n \"https://api.githubcopilot.com\"\n : `https://api.${state.accountType}.githubcopilot.com`\nexport const copilotHeaders = (state: State, vision: boolean = false) => {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${state.copilotToken}`,\n \"content-type\": standardHeaders()[\"content-type\"],\n \"copilot-integration-id\": \"vscode-chat\",\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": EDITOR_PLUGIN_VERSION,\n \"user-agent\": USER_AGENT,\n \"openai-intent\": \"conversation-panel\",\n \"x-github-api-version\": API_VERSION,\n \"x-request-id\": randomUUID(),\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n }\n\n if (vision) headers[\"copilot-vision-request\"] = \"true\"\n\n return headers\n}\n\nexport const GITHUB_API_BASE_URL = \"https://api.github.com\"\nexport const githubHeaders = (state: State) => ({\n ...standardHeaders(),\n authorization: `token ${state.githubToken}`,\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": EDITOR_PLUGIN_VERSION,\n \"user-agent\": USER_AGENT,\n \"x-github-api-version\": API_VERSION,\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n})\n\nexport const GITHUB_BASE_URL = \"https://github.com\"\nexport const GITHUB_CLIENT_ID = \"Iv1.b507a08c87ecfe98\"\nexport const GITHUB_APP_SCOPES = [\"read:user\"].join(\" \")\n","import { GITHUB_API_BASE_URL, standardHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\n\nexport async function getGitHubUser() {\n const response = await fetch(`${GITHUB_API_BASE_URL}/user`, {\n headers: {\n authorization: `token ${state.githubToken}`,\n ...standardHeaders(),\n },\n })\n\n if (!response.ok) throw new HTTPError(\"Failed to get GitHub user\", response)\n\n return (await response.json()) as GithubUserResponse\n}\n\n// Trimmed for the sake of simplicity\ninterface GithubUserResponse {\n login: string\n}\n"],"mappings":";;;;AAsBA,MAAaA,QAAe;CAC1B,aAAa;CACb,eAAe;CACf,eAAe;CACf,WAAW;CACZ;;;;ACvBD,MAAa,yBAAyB;CACpC,gBAAgB;CAChB,QAAQ;CACT;AAED,MAAM,kBAAkB;AACxB,MAAM,wBAAwB,gBAAgB;AAC9C,MAAM,aAAa,qBAAqB;AAExC,MAAM,cAAc;AAEpB,MAAa,kBAAkB,YAC7BC,QAAM,gBAAgB,eACpB,kCACA,eAAeA,QAAM,YAAY;AACrC,MAAa,kBAAkB,SAAc,SAAkB,UAAU;CACvE,MAAMC,UAAkC;EACtC,eAAe,UAAUD,QAAM;EAC/B,gBAAgB,iBAAiB,CAAC;EAClC,0BAA0B;EAC1B,kBAAkB,UAAUA,QAAM;EAClC,yBAAyB;EACzB,cAAc;EACd,iBAAiB;EACjB,wBAAwB;EACxB,gBAAgB,YAAY;EAC5B,uCAAuC;EACxC;AAED,KAAI,OAAQ,SAAQ,4BAA4B;AAEhD,QAAO;;AAGT,MAAa,sBAAsB;AACnC,MAAa,iBAAiB,aAAkB;CAC9C,GAAG,iBAAiB;CACpB,eAAe,SAASA,QAAM;CAC9B,kBAAkB,UAAUA,QAAM;CAClC,yBAAyB;CACzB,cAAc;CACd,wBAAwB;CACxB,uCAAuC;CACxC;AAED,MAAa,kBAAkB;AAC/B,MAAa,mBAAmB;AAChC,MAAa,oBAAoB,CAAC,YAAY,CAAC,KAAK,IAAI;;;;AC/CxD,eAAsB,gBAAgB;CACpC,MAAM,WAAW,MAAM,MAAM,GAAG,oBAAoB,QAAQ,EAC1D,SAAS;EACP,eAAe,SAAS,MAAM;EAC9B,GAAG,iBAAiB;EACrB,EACF,CAAC;AAEF,KAAI,CAAC,SAAS,GAAI,OAAM,IAAI,UAAU,6BAA6B,SAAS;AAE5E,QAAQ,MAAM,SAAS,MAAM"}