@jeffreycao/copilot-api 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,381 @@
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/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
+ - **Rate Limit Control**: Manage API usage with rate-limiting options (`--rate-limit`) and a waiting mechanism (`--wait`) to prevent errors from rapid requests.
38
+ - **Manual Request Approval**: Manually approve or deny each API request for fine-grained control over usage (`--manual`).
39
+ - **Token Visibility**: Option to display GitHub and Copilot tokens during authentication and refresh for debugging (`--show-token`).
40
+ - **Flexible Authentication**: Authenticate interactively or provide a GitHub token directly, suitable for CI/CD environments.
41
+ - **Support for Different Account Types**: Works with individual, business, and enterprise GitHub Copilot plans.
42
+
43
+ ## Demo
44
+
45
+ https://github.com/user-attachments/assets/7654b383-669d-4eb9-b23c-06d7aefee8c5
46
+
47
+ ## Prerequisites
48
+
49
+ - Bun (>= 1.2.x)
50
+ - GitHub account with Copilot subscription (individual, business, or enterprise)
51
+
52
+ ## Installation
53
+
54
+ To install dependencies, run:
55
+
56
+ ```sh
57
+ bun install
58
+ ```
59
+
60
+ ## Using with Docker
61
+
62
+ Build image
63
+
64
+ ```sh
65
+ docker build -t copilot-api .
66
+ ```
67
+
68
+ Run the container
69
+
70
+ ```sh
71
+ # Create a directory on your host to persist the GitHub token and related data
72
+ mkdir -p ./copilot-data
73
+
74
+ # Run the container with a bind mount to persist the token
75
+ # This ensures your authentication survives container restarts
76
+
77
+ docker run -p 4141:4141 -v $(pwd)/copilot-data:/root/.local/share/copilot-api copilot-api
78
+ ```
79
+
80
+ > **Note:**
81
+ > 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.
82
+
83
+ ### Docker with Environment Variables
84
+
85
+ You can pass the GitHub token directly to the container using environment variables:
86
+
87
+ ```sh
88
+ # Build with GitHub token
89
+ docker build --build-arg GH_TOKEN=your_github_token_here -t copilot-api .
90
+
91
+ # Run with GitHub token
92
+ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api
93
+
94
+ # Run with additional options
95
+ docker run -p 4141:4141 -e GH_TOKEN=your_token copilot-api start --verbose --port 4141
96
+ ```
97
+
98
+ ### Docker Compose Example
99
+
100
+ ```yaml
101
+ version: "3.8"
102
+ services:
103
+ copilot-api:
104
+ build: .
105
+ ports:
106
+ - "4141:4141"
107
+ environment:
108
+ - GH_TOKEN=your_github_token_here
109
+ restart: unless-stopped
110
+ ```
111
+
112
+ The Docker image includes:
113
+
114
+ - Multi-stage build for optimized image size
115
+ - Non-root user for enhanced security
116
+ - Health check for container monitoring
117
+ - Pinned base image version for reproducible builds
118
+
119
+ ## Using with npx
120
+
121
+ You can run the project directly using npx:
122
+
123
+ ```sh
124
+ npx copilot-api@latest start
125
+ ```
126
+
127
+ With options:
128
+
129
+ ```sh
130
+ npx copilot-api@latest start --port 8080
131
+ ```
132
+
133
+ For authentication only:
134
+
135
+ ```sh
136
+ npx copilot-api@latest auth
137
+ ```
138
+
139
+ ## Command Structure
140
+
141
+ Copilot API now uses a subcommand structure with these main commands:
142
+
143
+ - `start`: Start the Copilot API server. This command will also handle authentication if needed.
144
+ - `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.
145
+ - `check-usage`: Show your current GitHub Copilot usage and quota information directly in the terminal (no server required).
146
+ - `debug`: Display diagnostic information including version, runtime details, file paths, and authentication status. Useful for troubleshooting and support.
147
+
148
+ ## Command Line Options
149
+
150
+ ### Start Command Options
151
+
152
+ The following command line options are available for the `start` command:
153
+
154
+ | Option | Description | Default | Alias |
155
+ | -------------- | ----------------------------------------------------------------------------- | ---------- | ----- |
156
+ | --port | Port to listen on | 4141 | -p |
157
+ | --verbose | Enable verbose logging | false | -v |
158
+ | --account-type | Account type to use (individual, business, enterprise) | individual | -a |
159
+ | --manual | Enable manual request approval | false | none |
160
+ | --rate-limit | Rate limit in seconds between requests | none | -r |
161
+ | --wait | Wait instead of error when rate limit is hit | false | -w |
162
+ | --github-token | Provide GitHub token directly (must be generated using the `auth` subcommand) | none | -g |
163
+ | --claude-code | Generate a command to launch Claude Code with Copilot API config | false | -c |
164
+ | --show-token | Show GitHub and Copilot tokens on fetch and refresh | false | none |
165
+ | --proxy-env | Initialize proxy from environment variables | false | none |
166
+
167
+ ### Auth Command Options
168
+
169
+ | Option | Description | Default | Alias |
170
+ | ------------ | ------------------------- | ------- | ----- |
171
+ | --verbose | Enable verbose logging | false | -v |
172
+ | --show-token | Show GitHub token on auth | false | none |
173
+
174
+ ### Debug Command Options
175
+
176
+ | Option | Description | Default | Alias |
177
+ | ------ | ------------------------- | ------- | ----- |
178
+ | --json | Output debug info as JSON | false | none |
179
+
180
+ ## Configuration (config.json)
181
+
182
+ - **Location:** `~/.local/share/copilot-api/config.json` (Linux/macOS) or `%USERPROFILE%\.local\share\copilot-api\config.json` (Windows).
183
+ - **Default shape:**
184
+ ```json
185
+ {
186
+ "extraPrompts": {
187
+ "gpt-5-mini": "<built-in exploration prompt>",
188
+ "gpt-5.1-codex-max": "<built-in exploration prompt>"
189
+ },
190
+ "smallModel": "gpt-5-mini",
191
+ "modelReasoningEfforts": {
192
+ "gpt-5-mini": "low"
193
+ }
194
+ }
195
+ ```
196
+ - **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.
197
+ - **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`.
198
+ - **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.
199
+
200
+ Edit this file to customize prompts or swap in your own fast model. Restart the server (or rerun the command) after changes so the cached config is refreshed.
201
+
202
+ ## API Endpoints
203
+
204
+ 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.
205
+
206
+ ### OpenAI Compatible Endpoints
207
+
208
+ These endpoints mimic the OpenAI API structure.
209
+
210
+ | Endpoint | Method | Description |
211
+ | --------------------------- | ------ | ---------------------------------------------------------------- |
212
+ | `POST /v1/responses` | `POST` | OpenAI Most advanced interface for generating model responses. |
213
+ | `POST /v1/chat/completions` | `POST` | Creates a model response for the given chat conversation. |
214
+ | `GET /v1/models` | `GET` | Lists the currently available models. |
215
+ | `POST /v1/embeddings` | `POST` | Creates an embedding vector representing the input text. |
216
+
217
+ ### Anthropic Compatible Endpoints
218
+
219
+ These endpoints are designed to be compatible with the Anthropic Messages API.
220
+
221
+ | Endpoint | Method | Description |
222
+ | -------------------------------- | ------ | ------------------------------------------------------------ |
223
+ | `POST /v1/messages` | `POST` | Creates a model response for a given conversation. |
224
+ | `POST /v1/messages/count_tokens` | `POST` | Calculates the number of tokens for a given set of messages. |
225
+
226
+ ### Usage Monitoring Endpoints
227
+
228
+ New endpoints for monitoring your Copilot usage and quotas.
229
+
230
+ | Endpoint | Method | Description |
231
+ | ------------ | ------ | ------------------------------------------------------------ |
232
+ | `GET /usage` | `GET` | Get detailed Copilot usage statistics and quota information. |
233
+ | `GET /token` | `GET` | Get the current Copilot token being used by the API. |
234
+
235
+ ## Example Usage
236
+
237
+ Using with npx:
238
+
239
+ ```sh
240
+ # Basic usage with start command
241
+ npx copilot-api@latest start
242
+
243
+ # Run on custom port with verbose logging
244
+ npx copilot-api@latest start --port 8080 --verbose
245
+
246
+ # Use with a business plan GitHub account
247
+ npx copilot-api@latest start --account-type business
248
+
249
+ # Use with an enterprise plan GitHub account
250
+ npx copilot-api@latest start --account-type enterprise
251
+
252
+ # Enable manual approval for each request
253
+ npx copilot-api@latest start --manual
254
+
255
+ # Set rate limit to 30 seconds between requests
256
+ npx copilot-api@latest start --rate-limit 30
257
+
258
+ # Wait instead of error when rate limit is hit
259
+ npx copilot-api@latest start --rate-limit 30 --wait
260
+
261
+ # Provide GitHub token directly
262
+ npx copilot-api@latest start --github-token ghp_YOUR_TOKEN_HERE
263
+
264
+ # Run only the auth flow
265
+ npx copilot-api@latest auth
266
+
267
+ # Run auth flow with verbose logging
268
+ npx copilot-api@latest auth --verbose
269
+
270
+ # Show your Copilot usage/quota in the terminal (no server needed)
271
+ npx copilot-api@latest check-usage
272
+
273
+ # Display debug information for troubleshooting
274
+ npx copilot-api@latest debug
275
+
276
+ # Display debug information in JSON format
277
+ npx copilot-api@latest debug --json
278
+
279
+ # Initialize proxy from environment variables (HTTP_PROXY, HTTPS_PROXY, etc.)
280
+ npx copilot-api@latest start --proxy-env
281
+ ```
282
+
283
+ ## Using the Usage Viewer
284
+
285
+ 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.
286
+
287
+ 1. Start the server. For example, using npx:
288
+ ```sh
289
+ npx copilot-api@latest start
290
+ ```
291
+ 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:
292
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://localhost:4141/usage`
293
+ - If you use the `start.bat` script on Windows, this page will open automatically.
294
+
295
+ The dashboard provides a user-friendly interface to view your Copilot usage data:
296
+
297
+ - **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.
298
+ - **Fetch Data**: Click the "Fetch" button to load or refresh the usage data. The dashboard will automatically fetch data on load.
299
+ - **Usage Quotas**: View a summary of your usage quotas for different services like Chat and Completions, displayed with progress bars for a quick overview.
300
+ - **Detailed Information**: See the full JSON response from the API for a detailed breakdown of all available usage statistics.
301
+ - **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:
302
+ `https://ericc-ch.github.io/copilot-api?endpoint=http://your-api-server/usage`
303
+
304
+ ## Using with Claude Code
305
+
306
+ 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.
307
+
308
+ There are two ways to configure Claude Code to use this proxy:
309
+
310
+ ### Interactive Setup with `--claude-code` flag
311
+
312
+ To get started, run the `start` command with the `--claude-code` flag:
313
+
314
+ ```sh
315
+ npx copilot-api@latest start --claude-code
316
+ ```
317
+
318
+ 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.
319
+
320
+ Paste and run this command in a new terminal to launch Claude Code.
321
+
322
+ ### Manual Configuration with `settings.json`
323
+
324
+ 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.
325
+
326
+ Here is an example `.claude/settings.json` file:
327
+
328
+ ```json
329
+ {
330
+ "env": {
331
+ "ANTHROPIC_BASE_URL": "http://localhost:4141",
332
+ "ANTHROPIC_AUTH_TOKEN": "dummy",
333
+ "ANTHROPIC_MODEL": "gpt-4.1",
334
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "gpt-4.1",
335
+ "ANTHROPIC_SMALL_FAST_MODEL": "gpt-4.1",
336
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "gpt-4.1",
337
+ "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1",
338
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
339
+ },
340
+ "permissions": {
341
+ "deny": [
342
+ "WebSearch"
343
+ ]
344
+ }
345
+ }
346
+ ```
347
+
348
+ You can find more options here: [Claude Code settings](https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables)
349
+
350
+ 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)
351
+
352
+ ## Running from Source
353
+
354
+ The project can be run from source in several ways:
355
+
356
+ ### Development Mode
357
+
358
+ ```sh
359
+ bun run dev
360
+ ```
361
+
362
+ ### Production Mode
363
+
364
+ ```sh
365
+ bun run start
366
+ ```
367
+
368
+ ## Usage Tips
369
+
370
+ - To avoid hitting GitHub Copilot's rate limits, you can use the following flags:
371
+ - `--manual`: Enables manual approval for each request, giving you full control over when requests are sent.
372
+ - `--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.
373
+ - `--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.
374
+ - 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.
375
+
376
+ ### CLAUDE.md Recommended Content
377
+
378
+ Please include the following in `CLAUDE.md` (for Claude usage):
379
+
380
+ - Prohibited from directly asking questions to users, MUST use AskUserQuestion tool.
381
+ - 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.
@@ -0,0 +1,258 @@
1
+ import consola from "consola";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import fs$1 from "node:fs";
7
+
8
+ //#region src/lib/paths.ts
9
+ const APP_DIR = path.join(os.homedir(), ".local", "share", "copilot-api");
10
+ const GITHUB_TOKEN_PATH = path.join(APP_DIR, "github_token");
11
+ const CONFIG_PATH = path.join(APP_DIR, "config.json");
12
+ const PATHS = {
13
+ APP_DIR,
14
+ GITHUB_TOKEN_PATH,
15
+ CONFIG_PATH
16
+ };
17
+ async function ensurePaths() {
18
+ await fs.mkdir(PATHS.APP_DIR, { recursive: true });
19
+ await ensureFile(PATHS.GITHUB_TOKEN_PATH);
20
+ await ensureFile(PATHS.CONFIG_PATH);
21
+ }
22
+ async function ensureFile(filePath) {
23
+ try {
24
+ await fs.access(filePath, fs.constants.W_OK);
25
+ } catch {
26
+ await fs.writeFile(filePath, "");
27
+ await fs.chmod(filePath, 384);
28
+ }
29
+ }
30
+
31
+ //#endregion
32
+ //#region src/lib/state.ts
33
+ const state = {
34
+ accountType: "individual",
35
+ manualApprove: false,
36
+ rateLimitWait: false,
37
+ showToken: false,
38
+ verbose: false
39
+ };
40
+
41
+ //#endregion
42
+ //#region src/lib/api-config.ts
43
+ const standardHeaders = () => ({
44
+ "content-type": "application/json",
45
+ accept: "application/json"
46
+ });
47
+ const COPILOT_VERSION = "0.35.0";
48
+ const EDITOR_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`;
49
+ const USER_AGENT = `GitHubCopilotChat/${COPILOT_VERSION}`;
50
+ const API_VERSION = "2025-10-01";
51
+ const copilotBaseUrl = (state$1) => state$1.accountType === "individual" ? "https://api.githubcopilot.com" : `https://api.${state$1.accountType}.githubcopilot.com`;
52
+ const copilotHeaders = (state$1, vision = false) => {
53
+ const headers = {
54
+ Authorization: `Bearer ${state$1.copilotToken}`,
55
+ "content-type": standardHeaders()["content-type"],
56
+ "copilot-integration-id": "vscode-chat",
57
+ "editor-version": `vscode/${state$1.vsCodeVersion}`,
58
+ "editor-plugin-version": EDITOR_PLUGIN_VERSION,
59
+ "user-agent": USER_AGENT,
60
+ "openai-intent": "conversation-agent",
61
+ "x-github-api-version": API_VERSION,
62
+ "x-request-id": randomUUID(),
63
+ "x-vscode-user-agent-library-version": "electron-fetch"
64
+ };
65
+ if (vision) headers["copilot-vision-request"] = "true";
66
+ return headers;
67
+ };
68
+ const GITHUB_API_BASE_URL = "https://api.github.com";
69
+ const githubHeaders = (state$1) => ({
70
+ ...standardHeaders(),
71
+ authorization: `token ${state$1.githubToken}`,
72
+ "editor-version": `vscode/${state$1.vsCodeVersion}`,
73
+ "editor-plugin-version": EDITOR_PLUGIN_VERSION,
74
+ "user-agent": USER_AGENT,
75
+ "x-github-api-version": API_VERSION,
76
+ "x-vscode-user-agent-library-version": "electron-fetch"
77
+ });
78
+ const GITHUB_BASE_URL = "https://github.com";
79
+ const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
80
+ const GITHUB_APP_SCOPES = ["read:user"].join(" ");
81
+
82
+ //#endregion
83
+ //#region src/lib/error.ts
84
+ var HTTPError = class extends Error {
85
+ response;
86
+ constructor(message, response) {
87
+ super(message);
88
+ this.response = response;
89
+ }
90
+ };
91
+ async function forwardError(c, error) {
92
+ consola.error("Error occurred:", error);
93
+ if (error instanceof HTTPError) {
94
+ const errorText = await error.response.text();
95
+ let errorJson;
96
+ try {
97
+ errorJson = JSON.parse(errorText);
98
+ } catch {
99
+ errorJson = errorText;
100
+ }
101
+ consola.error("HTTP error:", errorJson);
102
+ return c.json({ error: {
103
+ message: errorText,
104
+ type: "error"
105
+ } }, error.response.status);
106
+ }
107
+ return c.json({ error: {
108
+ message: error.message,
109
+ type: "error"
110
+ } }, 500);
111
+ }
112
+
113
+ //#endregion
114
+ //#region src/services/copilot/get-models.ts
115
+ const getModels = async () => {
116
+ const response = await fetch(`${copilotBaseUrl(state)}/models`, { headers: copilotHeaders(state) });
117
+ if (!response.ok) throw new HTTPError("Failed to get models", response);
118
+ return await response.json();
119
+ };
120
+
121
+ //#endregion
122
+ //#region src/services/get-vscode-version.ts
123
+ const FALLBACK = "1.107.0";
124
+ async function getVSCodeVersion() {
125
+ const controller = new AbortController();
126
+ const timeout = setTimeout(() => {
127
+ controller.abort();
128
+ }, 5e3);
129
+ try {
130
+ const match = (await (await fetch("https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=visual-studio-code-bin", { signal: controller.signal })).text()).match(/pkgver=([0-9.]+)/);
131
+ if (match) return match[1];
132
+ return FALLBACK;
133
+ } catch {
134
+ return FALLBACK;
135
+ } finally {
136
+ clearTimeout(timeout);
137
+ }
138
+ }
139
+ await getVSCodeVersion();
140
+
141
+ //#endregion
142
+ //#region src/lib/utils.ts
143
+ const sleep = (ms) => new Promise((resolve) => {
144
+ setTimeout(resolve, ms);
145
+ });
146
+ const isNullish = (value) => value === null || value === void 0;
147
+ async function cacheModels() {
148
+ state.models = await getModels();
149
+ }
150
+ const cacheVSCodeVersion = async () => {
151
+ const response = await getVSCodeVersion();
152
+ state.vsCodeVersion = response;
153
+ consola.info(`Using VSCode version: ${response}`);
154
+ };
155
+
156
+ //#endregion
157
+ //#region src/services/github/get-copilot-usage.ts
158
+ const getCopilotUsage = async () => {
159
+ const response = await fetch(`${GITHUB_API_BASE_URL}/copilot_internal/user`, { headers: githubHeaders(state) });
160
+ if (!response.ok) throw new HTTPError("Failed to get Copilot usage", response);
161
+ return await response.json();
162
+ };
163
+
164
+ //#endregion
165
+ //#region src/lib/config.ts
166
+ const gpt5ExplorationPrompt = `## Exploration and reading files
167
+ - **Think first.** Before any tool call, decide ALL files/resources you will need.
168
+ - **Batch everything.** If you need multiple files (even from different places), read them together.
169
+ - **multi_tool_use.parallel** Use multi_tool_use.parallel to parallelize tool calls and only this.
170
+ - **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
171
+ - **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.`;
172
+ const defaultConfig = {
173
+ extraPrompts: {
174
+ "gpt-5-mini": gpt5ExplorationPrompt,
175
+ "gpt-5.1-codex-max": gpt5ExplorationPrompt
176
+ },
177
+ smallModel: "gpt-5-mini",
178
+ modelReasoningEfforts: { "gpt-5-mini": "low" },
179
+ useFunctionApplyPatch: true,
180
+ compactUseSmallModel: true
181
+ };
182
+ let cachedConfig = null;
183
+ function ensureConfigFile() {
184
+ try {
185
+ fs$1.accessSync(PATHS.CONFIG_PATH, fs$1.constants.R_OK | fs$1.constants.W_OK);
186
+ } catch {
187
+ fs$1.mkdirSync(PATHS.APP_DIR, { recursive: true });
188
+ fs$1.writeFileSync(PATHS.CONFIG_PATH, `${JSON.stringify(defaultConfig, null, 2)}\n`, "utf8");
189
+ try {
190
+ fs$1.chmodSync(PATHS.CONFIG_PATH, 384);
191
+ } catch {
192
+ return;
193
+ }
194
+ }
195
+ }
196
+ function readConfigFromDisk() {
197
+ ensureConfigFile();
198
+ try {
199
+ const raw = fs$1.readFileSync(PATHS.CONFIG_PATH, "utf8");
200
+ if (!raw.trim()) {
201
+ fs$1.writeFileSync(PATHS.CONFIG_PATH, `${JSON.stringify(defaultConfig, null, 2)}\n`, "utf8");
202
+ return defaultConfig;
203
+ }
204
+ return JSON.parse(raw);
205
+ } catch (error) {
206
+ consola.error("Failed to read config file, using default config", error);
207
+ return defaultConfig;
208
+ }
209
+ }
210
+ function mergeDefaultExtraPrompts(config) {
211
+ const extraPrompts = config.extraPrompts ?? {};
212
+ const defaultExtraPrompts = defaultConfig.extraPrompts ?? {};
213
+ if (Object.keys(defaultExtraPrompts).filter((model) => !Object.hasOwn(extraPrompts, model)).length === 0) return {
214
+ mergedConfig: config,
215
+ changed: false
216
+ };
217
+ return {
218
+ mergedConfig: {
219
+ ...config,
220
+ extraPrompts: {
221
+ ...defaultExtraPrompts,
222
+ ...extraPrompts
223
+ }
224
+ },
225
+ changed: true
226
+ };
227
+ }
228
+ function mergeConfigWithDefaults() {
229
+ const config = readConfigFromDisk();
230
+ const { mergedConfig, changed } = mergeDefaultExtraPrompts(config);
231
+ if (changed) try {
232
+ fs$1.writeFileSync(PATHS.CONFIG_PATH, `${JSON.stringify(mergedConfig, null, 2)}\n`, "utf8");
233
+ } catch (writeError) {
234
+ consola.warn("Failed to write merged extraPrompts to config file", writeError);
235
+ }
236
+ cachedConfig = mergedConfig;
237
+ return mergedConfig;
238
+ }
239
+ function getConfig() {
240
+ cachedConfig ??= readConfigFromDisk();
241
+ return cachedConfig;
242
+ }
243
+ function getExtraPromptForModel(model) {
244
+ return getConfig().extraPrompts?.[model] ?? "";
245
+ }
246
+ function getSmallModel() {
247
+ return getConfig().smallModel ?? "gpt-5-mini";
248
+ }
249
+ function getReasoningEffortForModel(model) {
250
+ return getConfig().modelReasoningEfforts?.[model] ?? "high";
251
+ }
252
+ function shouldCompactUseSmallModel() {
253
+ return getConfig().compactUseSmallModel ?? true;
254
+ }
255
+
256
+ //#endregion
257
+ export { GITHUB_API_BASE_URL, GITHUB_APP_SCOPES, GITHUB_BASE_URL, GITHUB_CLIENT_ID, HTTPError, PATHS, cacheModels, cacheVSCodeVersion, copilotBaseUrl, copilotHeaders, ensurePaths, forwardError, getConfig, getCopilotUsage, getExtraPromptForModel, getReasoningEffortForModel, getSmallModel, githubHeaders, isNullish, mergeConfigWithDefaults, shouldCompactUseSmallModel, sleep, standardHeaders, state };
258
+ //# sourceMappingURL=config-BKsHEU7z.js.map