copilot-api-node20 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -277
- package/dist/get-user-BJ4s6iMX.js +1 -0
- package/dist/get-user-BT-kLu95.js +1 -0
- package/dist/main.js +1 -1637
- package/package.json +11 -3
- package/dist/main.js.map +0 -1
package/dist/main.js
CHANGED
|
@@ -1,1638 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { defineCommand, runMain } from "citty";
|
|
3
|
-
import consola from "consola";
|
|
4
|
-
import fs from "node:fs/promises";
|
|
5
|
-
import os from "node:os";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { EventEmitter } from "node:events";
|
|
8
|
-
import { randomUUID } from "node:crypto";
|
|
9
|
-
import clipboard from "clipboardy";
|
|
10
|
-
import process$1 from "node:process";
|
|
11
|
-
import { serve } from "srvx";
|
|
12
|
-
import invariant from "tiny-invariant";
|
|
13
|
-
import { execSync } from "node:child_process";
|
|
14
|
-
import { Hono } from "hono";
|
|
15
|
-
import { cors } from "hono/cors";
|
|
16
|
-
import { logger } from "hono/logger";
|
|
17
|
-
import { streamSSE } from "hono/streaming";
|
|
18
|
-
import { countTokens } from "gpt-tokenizer/model/gpt-4o";
|
|
19
|
-
import { events } from "fetch-event-stream";
|
|
20
|
-
import { request } from "undici";
|
|
21
|
-
|
|
22
|
-
//#region src/lib/paths.ts
|
|
23
|
-
const APP_DIR = path.join(os.homedir(), ".local", "share", "copilot-api");
|
|
24
|
-
const GITHUB_TOKEN_PATH = path.join(APP_DIR, "github_token");
|
|
25
|
-
const PATHS = {
|
|
26
|
-
APP_DIR,
|
|
27
|
-
GITHUB_TOKEN_PATH
|
|
28
|
-
};
|
|
29
|
-
async function ensurePaths() {
|
|
30
|
-
await fs.mkdir(PATHS.APP_DIR, { recursive: true });
|
|
31
|
-
await ensureFile(PATHS.GITHUB_TOKEN_PATH);
|
|
32
|
-
}
|
|
33
|
-
async function ensureFile(filePath) {
|
|
34
|
-
try {
|
|
35
|
-
await fs.access(filePath, fs.constants.W_OK);
|
|
36
|
-
} catch {
|
|
37
|
-
await fs.writeFile(filePath, "");
|
|
38
|
-
await fs.chmod(filePath, 384);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
//#endregion
|
|
43
|
-
//#region src/lib/state.ts
|
|
44
|
-
const state = {
|
|
45
|
-
accountType: "individual",
|
|
46
|
-
manualApprove: false,
|
|
47
|
-
rateLimitWait: false,
|
|
48
|
-
showToken: false,
|
|
49
|
-
connectivity: {
|
|
50
|
-
enabled: true,
|
|
51
|
-
probeEndpoints: [
|
|
52
|
-
"https://api.github.com",
|
|
53
|
-
"https://www.google.com",
|
|
54
|
-
"https://1.1.1.1"
|
|
55
|
-
],
|
|
56
|
-
fastProbeInterval: 5e3,
|
|
57
|
-
slowProbeInterval: 6e4,
|
|
58
|
-
timeoutMs: 5e3,
|
|
59
|
-
jitterMaxMs: 1e3,
|
|
60
|
-
connectionPooling: true,
|
|
61
|
-
dnsCache: true
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
//#endregion
|
|
66
|
-
//#region src/lib/connectivity.ts
|
|
67
|
-
var ConnectivityMonitor = class extends EventEmitter {
|
|
68
|
-
isOnline = true;
|
|
69
|
-
lastChecked = (/* @__PURE__ */ new Date()).toISOString();
|
|
70
|
-
consecutiveFailures = 0;
|
|
71
|
-
lastErrorType;
|
|
72
|
-
lastErrorMessage;
|
|
73
|
-
lastSuccessfulEndpoint;
|
|
74
|
-
endpointFailureStats = {};
|
|
75
|
-
checkInterval;
|
|
76
|
-
abortController;
|
|
77
|
-
start() {
|
|
78
|
-
if (!state.connectivity.enabled) {
|
|
79
|
-
consola.debug("Connectivity monitoring disabled");
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
consola.info("Starting connectivity monitor", {
|
|
83
|
-
probeEndpoints: state.connectivity.probeEndpoints,
|
|
84
|
-
fastInterval: state.connectivity.fastProbeInterval
|
|
85
|
-
});
|
|
86
|
-
this.scheduleNextCheck();
|
|
87
|
-
const cleanup = () => {
|
|
88
|
-
this.stop();
|
|
89
|
-
process.exit(0);
|
|
90
|
-
};
|
|
91
|
-
process.on("SIGINT", cleanup);
|
|
92
|
-
process.on("SIGTERM", cleanup);
|
|
93
|
-
}
|
|
94
|
-
stop() {
|
|
95
|
-
consola.debug("Stopping connectivity monitor");
|
|
96
|
-
if (this.checkInterval) {
|
|
97
|
-
clearTimeout(this.checkInterval);
|
|
98
|
-
this.checkInterval = void 0;
|
|
99
|
-
}
|
|
100
|
-
if (this.abortController) {
|
|
101
|
-
this.abortController.abort();
|
|
102
|
-
this.abortController = void 0;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
scheduleNextCheck() {
|
|
106
|
-
if (this.checkInterval) clearTimeout(this.checkInterval);
|
|
107
|
-
const baseInterval = this.isOnline ? state.connectivity.slowProbeInterval : state.connectivity.fastProbeInterval;
|
|
108
|
-
const jitter = Math.random() * state.connectivity.jitterMaxMs;
|
|
109
|
-
const interval = baseInterval + jitter;
|
|
110
|
-
this.checkInterval = setTimeout(() => {
|
|
111
|
-
this.performConnectivityCheck();
|
|
112
|
-
}, interval);
|
|
113
|
-
}
|
|
114
|
-
async performConnectivityCheck() {
|
|
115
|
-
this.abortController = new AbortController();
|
|
116
|
-
const timeoutId = setTimeout(() => this.abortController?.abort(), state.connectivity.timeoutMs);
|
|
117
|
-
try {
|
|
118
|
-
let success = false;
|
|
119
|
-
for (const endpoint of state.connectivity.probeEndpoints) try {
|
|
120
|
-
const response = await fetch(endpoint, {
|
|
121
|
-
method: "HEAD",
|
|
122
|
-
signal: this.abortController.signal,
|
|
123
|
-
headers: {
|
|
124
|
-
"User-Agent": "copilot-api-connectivity-monitor/1.0",
|
|
125
|
-
...state.connectivity.dnsCache && { "Cache-Control": "max-age=300" }
|
|
126
|
-
}
|
|
127
|
-
});
|
|
128
|
-
if (response.ok) {
|
|
129
|
-
success = true;
|
|
130
|
-
this.lastSuccessfulEndpoint = endpoint;
|
|
131
|
-
break;
|
|
132
|
-
}
|
|
133
|
-
} catch (error) {
|
|
134
|
-
this.endpointFailureStats[endpoint] = (this.endpointFailureStats[endpoint] || 0) + 1;
|
|
135
|
-
consola.debug(`Probe failed for ${endpoint}:`, error);
|
|
136
|
-
}
|
|
137
|
-
this.updateConnectivityState(success);
|
|
138
|
-
} catch (error) {
|
|
139
|
-
this.handleConnectivityError(error);
|
|
140
|
-
} finally {
|
|
141
|
-
clearTimeout(timeoutId);
|
|
142
|
-
this.scheduleNextCheck();
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
updateConnectivityState(isOnline) {
|
|
146
|
-
const wasOnline = this.isOnline;
|
|
147
|
-
this.isOnline = isOnline;
|
|
148
|
-
this.lastChecked = (/* @__PURE__ */ new Date()).toISOString();
|
|
149
|
-
if (isOnline) {
|
|
150
|
-
if (this.consecutiveFailures > 0) consola.info(`Connectivity restored after ${this.consecutiveFailures} failures`);
|
|
151
|
-
this.consecutiveFailures = 0;
|
|
152
|
-
this.lastErrorType = void 0;
|
|
153
|
-
this.lastErrorMessage = void 0;
|
|
154
|
-
if (!wasOnline) this.emit("online");
|
|
155
|
-
} else {
|
|
156
|
-
this.consecutiveFailures++;
|
|
157
|
-
if (wasOnline) {
|
|
158
|
-
consola.warn("Connectivity lost");
|
|
159
|
-
this.emit("offline");
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
handleConnectivityError(error) {
|
|
164
|
-
this.lastErrorType = error.name;
|
|
165
|
-
this.lastErrorMessage = error.message;
|
|
166
|
-
consola.error("Connectivity check failed:", error);
|
|
167
|
-
this.updateConnectivityState(false);
|
|
168
|
-
}
|
|
169
|
-
getConnectivityStats() {
|
|
170
|
-
return {
|
|
171
|
-
isOnline: this.isOnline,
|
|
172
|
-
lastChecked: this.lastChecked,
|
|
173
|
-
consecutiveFailures: this.consecutiveFailures,
|
|
174
|
-
lastErrorType: this.lastErrorType,
|
|
175
|
-
lastErrorMessage: this.lastErrorMessage
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
getPerformanceStats() {
|
|
179
|
-
const currentInterval = this.isOnline ? state.connectivity.slowProbeInterval : state.connectivity.fastProbeInterval;
|
|
180
|
-
const nextCheckEstimate = new Date(Date.now() + currentInterval + Math.random() * state.connectivity.jitterMaxMs).toISOString();
|
|
181
|
-
return {
|
|
182
|
-
currentInterval,
|
|
183
|
-
nextCheckEstimate,
|
|
184
|
-
lastSuccessfulEndpoint: this.lastSuccessfulEndpoint,
|
|
185
|
-
endpointFailureStats: { ...this.endpointFailureStats },
|
|
186
|
-
jitterEnabled: state.connectivity.jitterMaxMs > 0,
|
|
187
|
-
connectionPooling: state.connectivity.connectionPooling,
|
|
188
|
-
dnsCache: state.connectivity.dnsCache
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
};
|
|
192
|
-
const connectivityMonitor = new ConnectivityMonitor();
|
|
193
|
-
|
|
194
|
-
//#endregion
|
|
195
|
-
//#region src/lib/api-config.ts
|
|
196
|
-
const standardHeaders = () => ({
|
|
197
|
-
"content-type": "application/json",
|
|
198
|
-
accept: "application/json"
|
|
199
|
-
});
|
|
200
|
-
const COPILOT_VERSION = "0.32.2025093001";
|
|
201
|
-
const EDITOR_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`;
|
|
202
|
-
const USER_AGENT = `GitHubCopilotChat/${COPILOT_VERSION}`;
|
|
203
|
-
const API_VERSION = "2025-08-20";
|
|
204
|
-
const copilotBaseUrl = (state$1) => state$1.accountType === "individual" ? "https://api.githubcopilot.com" : `https://api.${state$1.accountType}.githubcopilot.com`;
|
|
205
|
-
const copilotHeaders = (state$1, vision = false) => {
|
|
206
|
-
const headers = {
|
|
207
|
-
Authorization: `Bearer ${state$1.copilotToken}`,
|
|
208
|
-
"content-type": standardHeaders()["content-type"],
|
|
209
|
-
"copilot-integration-id": "vscode-chat",
|
|
210
|
-
"editor-version": `vscode/${state$1.vsCodeVersion}`,
|
|
211
|
-
"editor-plugin-version": EDITOR_PLUGIN_VERSION,
|
|
212
|
-
"user-agent": USER_AGENT,
|
|
213
|
-
"openai-intent": "model-access",
|
|
214
|
-
"x-github-api-version": API_VERSION,
|
|
215
|
-
"x-interaction-type": "model-access",
|
|
216
|
-
"x-request-id": randomUUID(),
|
|
217
|
-
"x-vscode-user-agent-library-version": "electron-fetch"
|
|
218
|
-
};
|
|
219
|
-
if (vision) headers["copilot-vision-request"] = "true";
|
|
220
|
-
return headers;
|
|
221
|
-
};
|
|
222
|
-
const GITHUB_API_BASE_URL = "https://api.github.com";
|
|
223
|
-
const githubHeaders = (state$1) => ({
|
|
224
|
-
...standardHeaders(),
|
|
225
|
-
authorization: `token ${state$1.githubToken}`,
|
|
226
|
-
"editor-version": `vscode/${state$1.vsCodeVersion}`,
|
|
227
|
-
"editor-plugin-version": EDITOR_PLUGIN_VERSION,
|
|
228
|
-
"user-agent": USER_AGENT,
|
|
229
|
-
"x-github-api-version": API_VERSION,
|
|
230
|
-
"x-vscode-user-agent-library-version": "electron-fetch"
|
|
231
|
-
});
|
|
232
|
-
const GITHUB_BASE_URL = "https://github.com";
|
|
233
|
-
const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
234
|
-
const GITHUB_APP_SCOPES = ["read:user"].join(" ");
|
|
235
|
-
|
|
236
|
-
//#endregion
|
|
237
|
-
//#region src/lib/error.ts
|
|
238
|
-
var HTTPError = class extends Error {
|
|
239
|
-
response;
|
|
240
|
-
constructor(message, response) {
|
|
241
|
-
super(message);
|
|
242
|
-
this.response = response;
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
async function forwardError(c, error) {
|
|
246
|
-
consola.error("Error occurred:", error);
|
|
247
|
-
if (error instanceof HTTPError) {
|
|
248
|
-
const errorText = await error.response.text();
|
|
249
|
-
let errorJson;
|
|
250
|
-
try {
|
|
251
|
-
errorJson = JSON.parse(errorText);
|
|
252
|
-
} catch {
|
|
253
|
-
errorJson = errorText;
|
|
254
|
-
}
|
|
255
|
-
consola.error("HTTP error:", errorJson);
|
|
256
|
-
return c.json({ error: {
|
|
257
|
-
message: errorText,
|
|
258
|
-
type: "error"
|
|
259
|
-
} }, error.response.status);
|
|
260
|
-
}
|
|
261
|
-
return c.json({ error: {
|
|
262
|
-
message: error.message,
|
|
263
|
-
type: "error"
|
|
264
|
-
} }, 500);
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
//#endregion
|
|
268
|
-
//#region src/services/github/get-copilot-token.ts
|
|
269
|
-
const getCopilotToken = async () => {
|
|
270
|
-
const controller = new AbortController();
|
|
271
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
272
|
-
const timeout = setTimeout(() => {
|
|
273
|
-
controller.abort();
|
|
274
|
-
}, timeoutMs);
|
|
275
|
-
try {
|
|
276
|
-
const response = await fetch(`${GITHUB_API_BASE_URL}/copilot_internal/v2/token`, {
|
|
277
|
-
headers: githubHeaders(state),
|
|
278
|
-
signal: controller.signal
|
|
279
|
-
});
|
|
280
|
-
if (!response.ok) throw new HTTPError("Failed to get Copilot token", response);
|
|
281
|
-
return await response.json();
|
|
282
|
-
} finally {
|
|
283
|
-
clearTimeout(timeout);
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
|
|
287
|
-
//#endregion
|
|
288
|
-
//#region src/services/github/get-device-code.ts
|
|
289
|
-
async function getDeviceCode() {
|
|
290
|
-
const controller = new AbortController();
|
|
291
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
292
|
-
const timeout = setTimeout(() => {
|
|
293
|
-
controller.abort();
|
|
294
|
-
}, timeoutMs);
|
|
295
|
-
try {
|
|
296
|
-
const response = await fetch(`${GITHUB_BASE_URL}/login/device/code`, {
|
|
297
|
-
method: "POST",
|
|
298
|
-
headers: standardHeaders(),
|
|
299
|
-
body: JSON.stringify({
|
|
300
|
-
client_id: GITHUB_CLIENT_ID,
|
|
301
|
-
scope: GITHUB_APP_SCOPES
|
|
302
|
-
}),
|
|
303
|
-
signal: controller.signal
|
|
304
|
-
});
|
|
305
|
-
if (!response.ok) throw new HTTPError("Failed to get device code", response);
|
|
306
|
-
return await response.json();
|
|
307
|
-
} finally {
|
|
308
|
-
clearTimeout(timeout);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
//#endregion
|
|
313
|
-
//#region src/services/github/get-user.ts
|
|
314
|
-
async function getGitHubUser() {
|
|
315
|
-
const controller = new AbortController();
|
|
316
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
317
|
-
const timeout = setTimeout(() => {
|
|
318
|
-
controller.abort();
|
|
319
|
-
}, timeoutMs);
|
|
320
|
-
try {
|
|
321
|
-
const response = await fetch(`${GITHUB_API_BASE_URL}/user`, {
|
|
322
|
-
headers: {
|
|
323
|
-
authorization: `token ${state.githubToken}`,
|
|
324
|
-
...standardHeaders()
|
|
325
|
-
},
|
|
326
|
-
signal: controller.signal
|
|
327
|
-
});
|
|
328
|
-
if (!response.ok) throw new HTTPError("Failed to get GitHub user", response);
|
|
329
|
-
return await response.json();
|
|
330
|
-
} finally {
|
|
331
|
-
clearTimeout(timeout);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
//#endregion
|
|
336
|
-
//#region src/services/copilot/get-models.ts
|
|
337
|
-
const getModels = async () => {
|
|
338
|
-
const controller = new AbortController();
|
|
339
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
340
|
-
const timeout = setTimeout(() => {
|
|
341
|
-
controller.abort();
|
|
342
|
-
}, timeoutMs);
|
|
343
|
-
try {
|
|
344
|
-
const response = await fetch(`${copilotBaseUrl(state)}/models`, {
|
|
345
|
-
headers: copilotHeaders(state),
|
|
346
|
-
signal: controller.signal
|
|
347
|
-
});
|
|
348
|
-
if (!response.ok) throw new HTTPError("Failed to get models", response);
|
|
349
|
-
return await response.json();
|
|
350
|
-
} finally {
|
|
351
|
-
clearTimeout(timeout);
|
|
352
|
-
}
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
//#endregion
|
|
356
|
-
//#region src/services/get-vscode-version.ts
|
|
357
|
-
function getVSCodeVersion() {
|
|
358
|
-
return "1.105.0-insider";
|
|
359
|
-
}
|
|
360
|
-
getVSCodeVersion();
|
|
361
|
-
|
|
362
|
-
//#endregion
|
|
363
|
-
//#region src/lib/utils.ts
|
|
364
|
-
const sleep = (ms) => new Promise((resolve) => {
|
|
365
|
-
setTimeout(resolve, ms);
|
|
366
|
-
});
|
|
367
|
-
const isNullish = (value) => value === null || value === void 0;
|
|
368
|
-
async function cacheModels() {
|
|
369
|
-
const models = await getModels();
|
|
370
|
-
state.models = models;
|
|
371
|
-
}
|
|
372
|
-
const cacheVSCodeVersion = async () => {
|
|
373
|
-
const response = await getVSCodeVersion();
|
|
374
|
-
state.vsCodeVersion = response;
|
|
375
|
-
consola.info(`Using VSCode version: ${response}`);
|
|
376
|
-
};
|
|
377
|
-
|
|
378
|
-
//#endregion
|
|
379
|
-
//#region src/services/github/poll-access-token.ts
|
|
380
|
-
async function pollAccessToken(deviceCode) {
|
|
381
|
-
const sleepDuration = (deviceCode.interval + 1) * 1e3;
|
|
382
|
-
consola.debug(`Polling access token with interval of ${sleepDuration}ms`);
|
|
383
|
-
while (true) {
|
|
384
|
-
const controller = new AbortController();
|
|
385
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
386
|
-
const timeout = setTimeout(() => {
|
|
387
|
-
controller.abort();
|
|
388
|
-
}, timeoutMs);
|
|
389
|
-
try {
|
|
390
|
-
const response = await fetch(`${GITHUB_BASE_URL}/login/oauth/access_token`, {
|
|
391
|
-
method: "POST",
|
|
392
|
-
headers: standardHeaders(),
|
|
393
|
-
body: JSON.stringify({
|
|
394
|
-
client_id: GITHUB_CLIENT_ID,
|
|
395
|
-
device_code: deviceCode.device_code,
|
|
396
|
-
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
|
|
397
|
-
}),
|
|
398
|
-
signal: controller.signal
|
|
399
|
-
});
|
|
400
|
-
if (!response.ok) {
|
|
401
|
-
await sleep(sleepDuration);
|
|
402
|
-
consola.error("Failed to poll access token:", await response.text());
|
|
403
|
-
continue;
|
|
404
|
-
}
|
|
405
|
-
const json = await response.json();
|
|
406
|
-
consola.debug("Polling access token response:", json);
|
|
407
|
-
const { access_token } = json;
|
|
408
|
-
if (access_token) return access_token;
|
|
409
|
-
else await sleep(sleepDuration);
|
|
410
|
-
} catch (error) {
|
|
411
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
412
|
-
consola.error("Access token polling timed out");
|
|
413
|
-
await sleep(sleepDuration);
|
|
414
|
-
continue;
|
|
415
|
-
}
|
|
416
|
-
throw error;
|
|
417
|
-
} finally {
|
|
418
|
-
clearTimeout(timeout);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
//#endregion
|
|
424
|
-
//#region src/lib/token.ts
|
|
425
|
-
let tokenRefreshInterval;
|
|
426
|
-
let isRefreshPending = false;
|
|
427
|
-
let onlineHandler;
|
|
428
|
-
let offlineHandler;
|
|
429
|
-
function cleanupTokenManagement() {
|
|
430
|
-
consola.debug("Cleaning up token management");
|
|
431
|
-
if (tokenRefreshInterval) {
|
|
432
|
-
clearInterval(tokenRefreshInterval);
|
|
433
|
-
tokenRefreshInterval = void 0;
|
|
434
|
-
}
|
|
435
|
-
if (onlineHandler) {
|
|
436
|
-
connectivityMonitor.off("online", onlineHandler);
|
|
437
|
-
onlineHandler = void 0;
|
|
438
|
-
}
|
|
439
|
-
if (offlineHandler) {
|
|
440
|
-
connectivityMonitor.off("offline", offlineHandler);
|
|
441
|
-
offlineHandler = void 0;
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
const readGithubToken = () => fs.readFile(PATHS.GITHUB_TOKEN_PATH, "utf8");
|
|
445
|
-
const writeGithubToken = (token) => fs.writeFile(PATHS.GITHUB_TOKEN_PATH, token);
|
|
446
|
-
const setupCopilotToken = async () => {
|
|
447
|
-
const { token, refresh_in } = await getCopilotToken();
|
|
448
|
-
state.copilotToken = token;
|
|
449
|
-
consola.debug("GitHub Copilot Token fetched successfully!");
|
|
450
|
-
if (state.showToken) consola.info("Copilot token:", token);
|
|
451
|
-
const refreshInterval = (refresh_in - 60) * 1e3;
|
|
452
|
-
const refreshTokenWithRetry = async (maxRetries = 5, baseDelay = 1e3, reason = "scheduled") => {
|
|
453
|
-
if (isRefreshPending) {
|
|
454
|
-
consola.debug("Token refresh already in progress, skipping");
|
|
455
|
-
return;
|
|
456
|
-
}
|
|
457
|
-
isRefreshPending = true;
|
|
458
|
-
try {
|
|
459
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) try {
|
|
460
|
-
consola.debug(`Refreshing Copilot token (${reason}, attempt ${attempt}/${maxRetries})`);
|
|
461
|
-
const { token: token$1 } = await getCopilotToken();
|
|
462
|
-
state.copilotToken = token$1;
|
|
463
|
-
consola.debug("Copilot token refreshed successfully");
|
|
464
|
-
if (state.showToken) consola.info("Refreshed Copilot token:", token$1);
|
|
465
|
-
return;
|
|
466
|
-
} catch (error) {
|
|
467
|
-
const isLastAttempt = attempt === maxRetries;
|
|
468
|
-
consola.error(`Failed to refresh Copilot token (attempt ${attempt}/${maxRetries}):`, error);
|
|
469
|
-
if (isLastAttempt) {
|
|
470
|
-
consola.error("All token refresh attempts failed. Service may be unavailable until next scheduled refresh.");
|
|
471
|
-
return;
|
|
472
|
-
}
|
|
473
|
-
const delay = baseDelay * Math.pow(2, attempt - 1);
|
|
474
|
-
consola.debug(`Retrying token refresh in ${delay}ms...`);
|
|
475
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
476
|
-
}
|
|
477
|
-
} finally {
|
|
478
|
-
isRefreshPending = false;
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
tokenRefreshInterval = setInterval(() => {
|
|
482
|
-
refreshTokenWithRetry(5, 1e3, "scheduled").catch((error) => {
|
|
483
|
-
consola.error("Unexpected error in scheduled token refresh:", error);
|
|
484
|
-
});
|
|
485
|
-
}, refreshInterval);
|
|
486
|
-
connectivityMonitor.start();
|
|
487
|
-
onlineHandler = () => {
|
|
488
|
-
consola.debug("Network connectivity restored, attempting immediate token refresh");
|
|
489
|
-
refreshTokenWithRetry(3, 500, "network-restored").catch((error) => {
|
|
490
|
-
consola.error("Unexpected error in network-restored token refresh:", error);
|
|
491
|
-
});
|
|
492
|
-
};
|
|
493
|
-
offlineHandler = () => {
|
|
494
|
-
consola.debug("Network connectivity lost");
|
|
495
|
-
};
|
|
496
|
-
connectivityMonitor.on("online", onlineHandler);
|
|
497
|
-
connectivityMonitor.on("offline", offlineHandler);
|
|
498
|
-
};
|
|
499
|
-
async function setupGitHubToken(options) {
|
|
500
|
-
try {
|
|
501
|
-
const githubToken = await readGithubToken();
|
|
502
|
-
if (githubToken && !options?.force) {
|
|
503
|
-
state.githubToken = githubToken;
|
|
504
|
-
if (state.showToken) consola.info("GitHub token:", githubToken);
|
|
505
|
-
await logUser();
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
consola.info("Not logged in, getting new access token");
|
|
509
|
-
const response = await getDeviceCode();
|
|
510
|
-
consola.debug("Device code response:", response);
|
|
511
|
-
consola.info(`Please enter the code "${response.user_code}" in ${response.verification_uri}`);
|
|
512
|
-
const token = await pollAccessToken(response);
|
|
513
|
-
await writeGithubToken(token);
|
|
514
|
-
state.githubToken = token;
|
|
515
|
-
if (state.showToken) consola.info("GitHub token:", token);
|
|
516
|
-
await logUser();
|
|
517
|
-
} catch (error) {
|
|
518
|
-
if (error instanceof HTTPError) {
|
|
519
|
-
consola.error("Failed to get GitHub token:", await error.response.json());
|
|
520
|
-
throw error;
|
|
521
|
-
}
|
|
522
|
-
consola.error("Failed to get GitHub token:", error);
|
|
523
|
-
throw error;
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
async function logUser() {
|
|
527
|
-
const user = await getGitHubUser();
|
|
528
|
-
consola.info(`Logged in as ${user.login}`);
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
//#endregion
|
|
532
|
-
//#region src/auth.ts
|
|
533
|
-
async function runAuth(options) {
|
|
534
|
-
if (options.verbose) {
|
|
535
|
-
consola.level = 5;
|
|
536
|
-
consola.info("Verbose logging enabled");
|
|
537
|
-
}
|
|
538
|
-
state.showToken = options.showToken;
|
|
539
|
-
await ensurePaths();
|
|
540
|
-
await setupGitHubToken({ force: true });
|
|
541
|
-
consola.success("GitHub token written to", PATHS.GITHUB_TOKEN_PATH);
|
|
542
|
-
}
|
|
543
|
-
const auth = defineCommand({
|
|
544
|
-
meta: {
|
|
545
|
-
name: "auth",
|
|
546
|
-
description: "Run GitHub auth flow without running the server"
|
|
547
|
-
},
|
|
548
|
-
args: {
|
|
549
|
-
verbose: {
|
|
550
|
-
alias: "v",
|
|
551
|
-
type: "boolean",
|
|
552
|
-
default: false,
|
|
553
|
-
description: "Enable verbose logging"
|
|
554
|
-
},
|
|
555
|
-
"show-token": {
|
|
556
|
-
type: "boolean",
|
|
557
|
-
default: false,
|
|
558
|
-
description: "Show GitHub token on auth"
|
|
559
|
-
}
|
|
560
|
-
},
|
|
561
|
-
run({ args }) {
|
|
562
|
-
return runAuth({
|
|
563
|
-
verbose: args.verbose,
|
|
564
|
-
showToken: args["show-token"]
|
|
565
|
-
});
|
|
566
|
-
}
|
|
567
|
-
});
|
|
568
|
-
|
|
569
|
-
//#endregion
|
|
570
|
-
//#region src/services/github/get-copilot-usage.ts
|
|
571
|
-
const getCopilotUsage = async () => {
|
|
572
|
-
const controller = new AbortController();
|
|
573
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
574
|
-
const timeout = setTimeout(() => {
|
|
575
|
-
controller.abort();
|
|
576
|
-
}, timeoutMs);
|
|
577
|
-
try {
|
|
578
|
-
const response = await fetch(`${GITHUB_API_BASE_URL}/copilot_internal/user`, {
|
|
579
|
-
headers: githubHeaders(state),
|
|
580
|
-
signal: controller.signal
|
|
581
|
-
});
|
|
582
|
-
if (!response.ok) throw new HTTPError("Failed to get Copilot usage", response);
|
|
583
|
-
return await response.json();
|
|
584
|
-
} finally {
|
|
585
|
-
clearTimeout(timeout);
|
|
586
|
-
}
|
|
587
|
-
};
|
|
588
|
-
|
|
589
|
-
//#endregion
|
|
590
|
-
//#region src/check-usage.ts
|
|
591
|
-
const checkUsage = defineCommand({
|
|
592
|
-
meta: {
|
|
593
|
-
name: "check-usage",
|
|
594
|
-
description: "Show current GitHub Copilot usage/quota information"
|
|
595
|
-
},
|
|
596
|
-
async run() {
|
|
597
|
-
await ensurePaths();
|
|
598
|
-
await setupGitHubToken();
|
|
599
|
-
try {
|
|
600
|
-
const usage = await getCopilotUsage();
|
|
601
|
-
const premium = usage.quota_snapshots.premium_interactions;
|
|
602
|
-
const premiumTotal = premium.entitlement;
|
|
603
|
-
const premiumUsed = premiumTotal - premium.remaining;
|
|
604
|
-
const premiumPercentUsed = premiumTotal > 0 ? premiumUsed / premiumTotal * 100 : 0;
|
|
605
|
-
const premiumPercentRemaining = premium.percent_remaining;
|
|
606
|
-
function summarizeQuota(name, snap) {
|
|
607
|
-
if (!snap) return `${name}: N/A`;
|
|
608
|
-
const total = snap.entitlement;
|
|
609
|
-
const used = total - snap.remaining;
|
|
610
|
-
const percentUsed = total > 0 ? used / total * 100 : 0;
|
|
611
|
-
const percentRemaining = snap.percent_remaining;
|
|
612
|
-
return `${name}: ${used}/${total} used (${percentUsed.toFixed(1)}% used, ${percentRemaining.toFixed(1)}% remaining)`;
|
|
613
|
-
}
|
|
614
|
-
const premiumLine = `Premium: ${premiumUsed}/${premiumTotal} used (${premiumPercentUsed.toFixed(1)}% used, ${premiumPercentRemaining.toFixed(1)}% remaining)`;
|
|
615
|
-
const chatLine = summarizeQuota("Chat", usage.quota_snapshots.chat);
|
|
616
|
-
const completionsLine = summarizeQuota("Completions", usage.quota_snapshots.completions);
|
|
617
|
-
consola.box(`Copilot Usage (plan: ${usage.copilot_plan})\nQuota resets: ${usage.quota_reset_date}\n\nQuotas:\n ${premiumLine}\n ${chatLine}\n ${completionsLine}`);
|
|
618
|
-
} catch (err) {
|
|
619
|
-
consola.error("Failed to fetch Copilot usage:", err);
|
|
620
|
-
process.exit(1);
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
});
|
|
624
|
-
|
|
625
|
-
//#endregion
|
|
626
|
-
//#region src/debug.ts
|
|
627
|
-
async function getPackageVersion() {
|
|
628
|
-
try {
|
|
629
|
-
const packageJsonPath = new URL("../package.json", import.meta.url).pathname;
|
|
630
|
-
const packageJson = JSON.parse(await fs.readFile(packageJsonPath));
|
|
631
|
-
return packageJson.version;
|
|
632
|
-
} catch {
|
|
633
|
-
return "unknown";
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
function getRuntimeInfo() {
|
|
637
|
-
const isBun = typeof Bun !== "undefined";
|
|
638
|
-
return {
|
|
639
|
-
name: isBun ? "bun" : "node",
|
|
640
|
-
version: isBun ? Bun.version : process.version.slice(1),
|
|
641
|
-
platform: os.platform(),
|
|
642
|
-
arch: os.arch()
|
|
643
|
-
};
|
|
644
|
-
}
|
|
645
|
-
async function checkTokenExists() {
|
|
646
|
-
try {
|
|
647
|
-
const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH);
|
|
648
|
-
if (!stats.isFile()) return false;
|
|
649
|
-
const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, "utf8");
|
|
650
|
-
return content.trim().length > 0;
|
|
651
|
-
} catch {
|
|
652
|
-
return false;
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
async function getDebugInfo() {
|
|
656
|
-
const [version, tokenExists] = await Promise.all([getPackageVersion(), checkTokenExists()]);
|
|
657
|
-
return {
|
|
658
|
-
version,
|
|
659
|
-
runtime: getRuntimeInfo(),
|
|
660
|
-
paths: {
|
|
661
|
-
APP_DIR: PATHS.APP_DIR,
|
|
662
|
-
GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH
|
|
663
|
-
},
|
|
664
|
-
tokenExists
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
function printDebugInfoPlain(info) {
|
|
668
|
-
consola.info(`copilot-api debug
|
|
669
|
-
|
|
670
|
-
Version: ${info.version}
|
|
671
|
-
Runtime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})
|
|
672
|
-
|
|
673
|
-
Paths:
|
|
674
|
-
- APP_DIR: ${info.paths.APP_DIR}
|
|
675
|
-
- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}
|
|
676
|
-
|
|
677
|
-
Token exists: ${info.tokenExists ? "Yes" : "No"}`);
|
|
678
|
-
}
|
|
679
|
-
function printDebugInfoJson(info) {
|
|
680
|
-
console.log(JSON.stringify(info, null, 2));
|
|
681
|
-
}
|
|
682
|
-
async function runDebug(options) {
|
|
683
|
-
const debugInfo = await getDebugInfo();
|
|
684
|
-
if (options.json) printDebugInfoJson(debugInfo);
|
|
685
|
-
else printDebugInfoPlain(debugInfo);
|
|
686
|
-
}
|
|
687
|
-
const debug = defineCommand({
|
|
688
|
-
meta: {
|
|
689
|
-
name: "debug",
|
|
690
|
-
description: "Print debug information about the application"
|
|
691
|
-
},
|
|
692
|
-
args: { json: {
|
|
693
|
-
type: "boolean",
|
|
694
|
-
default: false,
|
|
695
|
-
description: "Output debug information as JSON"
|
|
696
|
-
} },
|
|
697
|
-
run({ args }) {
|
|
698
|
-
return runDebug({ json: args.json });
|
|
699
|
-
}
|
|
700
|
-
});
|
|
701
|
-
|
|
702
|
-
//#endregion
|
|
703
|
-
//#region src/lib/shell.ts
|
|
704
|
-
function getShell() {
|
|
705
|
-
const { platform, ppid, env } = process$1;
|
|
706
|
-
if (platform === "win32") {
|
|
707
|
-
try {
|
|
708
|
-
const command = `wmic process get ParentProcessId,Name | findstr "${ppid}"`;
|
|
709
|
-
const parentProcess = execSync(command, { stdio: "pipe" }).toString();
|
|
710
|
-
if (parentProcess.toLowerCase().includes("powershell.exe")) return "powershell";
|
|
711
|
-
} catch {
|
|
712
|
-
return "cmd";
|
|
713
|
-
}
|
|
714
|
-
return "cmd";
|
|
715
|
-
} else {
|
|
716
|
-
const shellPath = env.SHELL;
|
|
717
|
-
if (shellPath) {
|
|
718
|
-
if (shellPath.endsWith("zsh")) return "zsh";
|
|
719
|
-
if (shellPath.endsWith("fish")) return "fish";
|
|
720
|
-
if (shellPath.endsWith("bash")) return "bash";
|
|
721
|
-
}
|
|
722
|
-
return "sh";
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
/**
|
|
726
|
-
* Generates a copy-pasteable script to set multiple environment variables
|
|
727
|
-
* and run a subsequent command.
|
|
728
|
-
* @param {EnvVars} envVars - An object of environment variables to set.
|
|
729
|
-
* @param {string} commandToRun - The command to run after setting the variables.
|
|
730
|
-
* @returns {string} The formatted script string.
|
|
731
|
-
*/
|
|
732
|
-
function generateEnvScript(envVars, commandToRun = "") {
|
|
733
|
-
const shell = getShell();
|
|
734
|
-
const filteredEnvVars = Object.entries(envVars).filter(([, value]) => value !== void 0);
|
|
735
|
-
let commandBlock;
|
|
736
|
-
switch (shell) {
|
|
737
|
-
case "powershell":
|
|
738
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `$env:${key} = ${value}`).join("; ");
|
|
739
|
-
break;
|
|
740
|
-
case "cmd":
|
|
741
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `set ${key}=${value}`).join(" & ");
|
|
742
|
-
break;
|
|
743
|
-
case "fish":
|
|
744
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `set -gx ${key} ${value}`).join("; ");
|
|
745
|
-
break;
|
|
746
|
-
default: {
|
|
747
|
-
const assignments = filteredEnvVars.map(([key, value]) => `${key}=${value}`).join(" ");
|
|
748
|
-
commandBlock = filteredEnvVars.length > 0 ? `export ${assignments}` : "";
|
|
749
|
-
break;
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
if (commandBlock && commandToRun) {
|
|
753
|
-
const separator = shell === "cmd" ? " & " : " && ";
|
|
754
|
-
return `${commandBlock}${separator}${commandToRun}`;
|
|
755
|
-
}
|
|
756
|
-
return commandBlock || commandToRun;
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
//#endregion
|
|
760
|
-
//#region src/lib/approval.ts
|
|
761
|
-
const awaitApproval = async () => {
|
|
762
|
-
const response = await consola.prompt(`Accept incoming request?`, { type: "confirm" });
|
|
763
|
-
if (!response) throw new HTTPError("Request rejected", Response.json({ message: "Request rejected" }, { status: 403 }));
|
|
764
|
-
};
|
|
765
|
-
|
|
766
|
-
//#endregion
|
|
767
|
-
//#region src/lib/rate-limit.ts
|
|
768
|
-
async function checkRateLimit(state$1) {
|
|
769
|
-
if (state$1.rateLimitSeconds === void 0) return;
|
|
770
|
-
const now = Date.now();
|
|
771
|
-
if (!state$1.lastRequestTimestamp) {
|
|
772
|
-
state$1.lastRequestTimestamp = now;
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
const elapsedSeconds = (now - state$1.lastRequestTimestamp) / 1e3;
|
|
776
|
-
if (elapsedSeconds > state$1.rateLimitSeconds) {
|
|
777
|
-
state$1.lastRequestTimestamp = now;
|
|
778
|
-
return;
|
|
779
|
-
}
|
|
780
|
-
const waitTimeSeconds = Math.ceil(state$1.rateLimitSeconds - elapsedSeconds);
|
|
781
|
-
if (!state$1.rateLimitWait) {
|
|
782
|
-
consola.warn(`Rate limit exceeded. Need to wait ${waitTimeSeconds} more seconds.`);
|
|
783
|
-
throw new HTTPError("Rate limit exceeded", Response.json({ message: "Rate limit exceeded" }, { status: 429 }));
|
|
784
|
-
}
|
|
785
|
-
const waitTimeMs = waitTimeSeconds * 1e3;
|
|
786
|
-
consola.warn(`Rate limit reached. Waiting ${waitTimeSeconds} seconds before proceeding...`);
|
|
787
|
-
await sleep(waitTimeMs);
|
|
788
|
-
state$1.lastRequestTimestamp = now;
|
|
789
|
-
consola.info("Rate limit wait completed, proceeding with request");
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
//#endregion
|
|
793
|
-
//#region src/lib/tokenizer.ts
|
|
794
|
-
const getTokenCount = (messages) => {
|
|
795
|
-
const simplifiedMessages = messages.map((message) => {
|
|
796
|
-
let content = "";
|
|
797
|
-
if (typeof message.content === "string") content = message.content;
|
|
798
|
-
else if (Array.isArray(message.content)) content = message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
799
|
-
return {
|
|
800
|
-
...message,
|
|
801
|
-
content
|
|
802
|
-
};
|
|
803
|
-
});
|
|
804
|
-
let inputMessages = simplifiedMessages.filter((message) => {
|
|
805
|
-
return message.role !== "tool";
|
|
806
|
-
});
|
|
807
|
-
let outputMessages = [];
|
|
808
|
-
const lastMessage = simplifiedMessages.at(-1);
|
|
809
|
-
if (lastMessage?.role === "assistant") {
|
|
810
|
-
inputMessages = simplifiedMessages.slice(0, -1);
|
|
811
|
-
outputMessages = [lastMessage];
|
|
812
|
-
}
|
|
813
|
-
const inputTokens = countTokens(inputMessages);
|
|
814
|
-
const outputTokens = countTokens(outputMessages);
|
|
815
|
-
return {
|
|
816
|
-
input: inputTokens,
|
|
817
|
-
output: outputTokens
|
|
818
|
-
};
|
|
819
|
-
};
|
|
820
|
-
|
|
821
|
-
//#endregion
|
|
822
|
-
//#region src/lib/sanitize.ts
|
|
823
|
-
/**
|
|
824
|
-
* Sanitizes JSON payloads by removing ANSI escape sequences and invisible Unicode characters
|
|
825
|
-
* that can cause GitHub Copilot API to return 400 Bad Request errors.
|
|
826
|
-
*/
|
|
827
|
-
/**
|
|
828
|
-
* Removes ANSI escape sequences and problematic Unicode characters from a string
|
|
829
|
-
*/
|
|
830
|
-
function sanitizeString(str) {
|
|
831
|
-
return str.replaceAll(/\x1b\[[0-9;]*[a-z]/gi, "").replaceAll(/\x1b\[[0-9;]*m/g, "").replaceAll(/\x1b\[[\d;]*[HfA-DsuJKmhlp]/g, "").replaceAll(/[\x00-\x08\v\f\x0E-\x1F\x7F]/g, "").replaceAll(/[\u200B-\u200D\uFEFF]/g, "").replaceAll(/[\u2060-\u2064]/g, "").replaceAll(/[\u206A-\u206F]/g, "").replaceAll(/[\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/g, "").replaceAll(/[\uFFF0-\uFFFF]/g, "");
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* Recursively sanitizes all string values in an object or array
|
|
835
|
-
*/
|
|
836
|
-
function sanitizePayload(payload) {
|
|
837
|
-
if (typeof payload === "string") return sanitizeString(payload);
|
|
838
|
-
if (Array.isArray(payload)) return payload.map((item) => sanitizePayload(item));
|
|
839
|
-
if (payload && typeof payload === "object") {
|
|
840
|
-
const sanitized = {};
|
|
841
|
-
for (const [key, value] of Object.entries(payload)) sanitized[key] = sanitizePayload(value);
|
|
842
|
-
return sanitized;
|
|
843
|
-
}
|
|
844
|
-
return payload;
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
//#endregion
|
|
848
|
-
//#region src/services/copilot/create-chat-completions.ts
|
|
849
|
-
const createChatCompletions = async (payload) => {
|
|
850
|
-
if (!state.copilotToken) throw new Error("Copilot token not found");
|
|
851
|
-
const sanitizedPayload = sanitizePayload(payload);
|
|
852
|
-
const enableVision = sanitizedPayload.messages.some((x) => typeof x.content !== "string" && x.content?.some((x$1) => x$1.type === "image_url"));
|
|
853
|
-
const isAgentCall = sanitizedPayload.messages.some((msg) => ["assistant", "tool"].includes(msg.role));
|
|
854
|
-
const headers = {
|
|
855
|
-
...copilotHeaders(state, enableVision),
|
|
856
|
-
"X-Initiator": isAgentCall ? "agent" : "user"
|
|
857
|
-
};
|
|
858
|
-
const controller = new AbortController();
|
|
859
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
860
|
-
const timeout = setTimeout(() => {
|
|
861
|
-
controller.abort();
|
|
862
|
-
}, timeoutMs);
|
|
863
|
-
try {
|
|
864
|
-
const { statusCode, headers: responseHeaders, body } = await request(`${copilotBaseUrl(state)}/chat/completions`, {
|
|
865
|
-
method: "POST",
|
|
866
|
-
headers,
|
|
867
|
-
body: JSON.stringify(sanitizedPayload),
|
|
868
|
-
signal: controller.signal,
|
|
869
|
-
headersTimeout: timeoutMs,
|
|
870
|
-
bodyTimeout: timeoutMs * 3,
|
|
871
|
-
connectTimeout: timeoutMs
|
|
872
|
-
});
|
|
873
|
-
const response = new Response(body, {
|
|
874
|
-
status: statusCode,
|
|
875
|
-
headers: responseHeaders
|
|
876
|
-
});
|
|
877
|
-
if (!response.ok) {
|
|
878
|
-
consola.error("Failed to create chat completions", response);
|
|
879
|
-
throw new HTTPError("Failed to create chat completions", response);
|
|
880
|
-
}
|
|
881
|
-
if (sanitizedPayload.stream) return events(response);
|
|
882
|
-
return await response.json();
|
|
883
|
-
} finally {
|
|
884
|
-
clearTimeout(timeout);
|
|
885
|
-
}
|
|
886
|
-
};
|
|
887
|
-
|
|
888
|
-
//#endregion
|
|
889
|
-
//#region src/routes/chat-completions/handler.ts
|
|
890
|
-
async function handleCompletion$1(c) {
|
|
891
|
-
await checkRateLimit(state);
|
|
892
|
-
let payload = await c.req.json();
|
|
893
|
-
consola.debug("Request payload:", JSON.stringify(payload).slice(-400));
|
|
894
|
-
consola.info("Current token count:", getTokenCount(payload.messages));
|
|
895
|
-
if (state.manualApprove) await awaitApproval();
|
|
896
|
-
if (isNullish(payload.max_tokens)) {
|
|
897
|
-
const selectedModel = state.models?.data.find((model) => model.id === payload.model);
|
|
898
|
-
payload = {
|
|
899
|
-
...payload,
|
|
900
|
-
max_tokens: selectedModel?.capabilities.limits.max_output_tokens
|
|
901
|
-
};
|
|
902
|
-
consola.debug("Set max_tokens to:", JSON.stringify(payload.max_tokens));
|
|
903
|
-
}
|
|
904
|
-
const response = await createChatCompletions(payload);
|
|
905
|
-
if (isNonStreaming$1(response)) {
|
|
906
|
-
consola.debug("Non-streaming response:", JSON.stringify(response));
|
|
907
|
-
return c.json(response);
|
|
908
|
-
}
|
|
909
|
-
consola.debug("Streaming response");
|
|
910
|
-
return streamSSE(c, async (stream) => {
|
|
911
|
-
for await (const chunk of response) {
|
|
912
|
-
consola.debug("Streaming chunk:", JSON.stringify(chunk));
|
|
913
|
-
await stream.writeSSE(chunk);
|
|
914
|
-
}
|
|
915
|
-
});
|
|
916
|
-
}
|
|
917
|
-
const isNonStreaming$1 = (response) => Object.hasOwn(response, "choices");
|
|
918
|
-
|
|
919
|
-
//#endregion
|
|
920
|
-
//#region src/routes/chat-completions/route.ts
|
|
921
|
-
const completionRoutes = new Hono();
|
|
922
|
-
completionRoutes.post("/", async (c) => {
|
|
923
|
-
try {
|
|
924
|
-
return await handleCompletion$1(c);
|
|
925
|
-
} catch (error) {
|
|
926
|
-
return await forwardError(c, error);
|
|
927
|
-
}
|
|
928
|
-
});
|
|
929
|
-
|
|
930
|
-
//#endregion
|
|
931
|
-
//#region src/services/copilot/create-embeddings.ts
|
|
932
|
-
const createEmbeddings = async (payload) => {
|
|
933
|
-
if (!state.copilotToken) throw new Error("Copilot token not found");
|
|
934
|
-
const controller = new AbortController();
|
|
935
|
-
const timeoutMs = state.timeoutMs ?? 12e4;
|
|
936
|
-
const timeout = setTimeout(() => {
|
|
937
|
-
controller.abort();
|
|
938
|
-
}, timeoutMs);
|
|
939
|
-
try {
|
|
940
|
-
const response = await fetch(`${copilotBaseUrl(state)}/embeddings`, {
|
|
941
|
-
method: "POST",
|
|
942
|
-
headers: copilotHeaders(state),
|
|
943
|
-
body: JSON.stringify(payload),
|
|
944
|
-
signal: controller.signal
|
|
945
|
-
});
|
|
946
|
-
if (!response.ok) throw new HTTPError("Failed to create embeddings", response);
|
|
947
|
-
return await response.json();
|
|
948
|
-
} finally {
|
|
949
|
-
clearTimeout(timeout);
|
|
950
|
-
}
|
|
951
|
-
};
|
|
952
|
-
|
|
953
|
-
//#endregion
|
|
954
|
-
//#region src/routes/embeddings/route.ts
|
|
955
|
-
const embeddingRoutes = new Hono();
|
|
956
|
-
embeddingRoutes.post("/", async (c) => {
|
|
957
|
-
try {
|
|
958
|
-
const paylod = await c.req.json();
|
|
959
|
-
const response = await createEmbeddings(paylod);
|
|
960
|
-
return c.json(response);
|
|
961
|
-
} catch (error) {
|
|
962
|
-
return await forwardError(c, error);
|
|
963
|
-
}
|
|
964
|
-
});
|
|
965
|
-
|
|
966
|
-
//#endregion
|
|
967
|
-
//#region src/routes/messages/utils.ts
|
|
968
|
-
function mapOpenAIStopReasonToAnthropic(finishReason) {
|
|
969
|
-
if (finishReason === null) return null;
|
|
970
|
-
const stopReasonMap = {
|
|
971
|
-
stop: "end_turn",
|
|
972
|
-
length: "max_tokens",
|
|
973
|
-
tool_calls: "tool_use",
|
|
974
|
-
content_filter: "end_turn"
|
|
975
|
-
};
|
|
976
|
-
return stopReasonMap[finishReason];
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
//#endregion
|
|
980
|
-
//#region src/routes/messages/non-stream-translation.ts
|
|
981
|
-
function translateToOpenAI(payload) {
|
|
982
|
-
return {
|
|
983
|
-
model: translateModelName(payload.model),
|
|
984
|
-
messages: translateAnthropicMessagesToOpenAI(payload.messages, payload.system),
|
|
985
|
-
max_tokens: payload.max_tokens,
|
|
986
|
-
stop: payload.stop_sequences,
|
|
987
|
-
stream: payload.stream,
|
|
988
|
-
temperature: payload.temperature,
|
|
989
|
-
top_p: payload.top_p,
|
|
990
|
-
user: payload.metadata?.user_id,
|
|
991
|
-
tools: translateAnthropicToolsToOpenAI(payload.tools),
|
|
992
|
-
tool_choice: translateAnthropicToolChoiceToOpenAI(payload.tool_choice)
|
|
993
|
-
};
|
|
994
|
-
}
|
|
995
|
-
function translateModelName(model) {
|
|
996
|
-
if (model.startsWith("claude-sonnet-4-")) return model.replace(/^claude-sonnet-4-.*/, "claude-sonnet-4");
|
|
997
|
-
else if (model.startsWith("claude-opus-")) return model.replace(/^claude-opus-4-.*/, "claude-opus-4");
|
|
998
|
-
return model;
|
|
999
|
-
}
|
|
1000
|
-
function translateAnthropicMessagesToOpenAI(anthropicMessages, system) {
|
|
1001
|
-
const systemMessages = handleSystemPrompt(system);
|
|
1002
|
-
const otherMessages = anthropicMessages.flatMap((message) => message.role === "user" ? handleUserMessage(message) : handleAssistantMessage(message));
|
|
1003
|
-
return [...systemMessages, ...otherMessages];
|
|
1004
|
-
}
|
|
1005
|
-
function handleSystemPrompt(system) {
|
|
1006
|
-
if (!system) return [];
|
|
1007
|
-
if (typeof system === "string") return [{
|
|
1008
|
-
role: "system",
|
|
1009
|
-
content: system
|
|
1010
|
-
}];
|
|
1011
|
-
else {
|
|
1012
|
-
const systemText = system.map((block) => block.text).join("\n\n");
|
|
1013
|
-
return [{
|
|
1014
|
-
role: "system",
|
|
1015
|
-
content: systemText
|
|
1016
|
-
}];
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
function handleUserMessage(message) {
|
|
1020
|
-
const newMessages = [];
|
|
1021
|
-
if (Array.isArray(message.content)) {
|
|
1022
|
-
const toolResultBlocks = message.content.filter((block) => block.type === "tool_result");
|
|
1023
|
-
const otherBlocks = message.content.filter((block) => block.type !== "tool_result");
|
|
1024
|
-
for (const block of toolResultBlocks) newMessages.push({
|
|
1025
|
-
role: "tool",
|
|
1026
|
-
tool_call_id: block.tool_use_id,
|
|
1027
|
-
content: mapContent(block.content)
|
|
1028
|
-
});
|
|
1029
|
-
if (otherBlocks.length > 0) newMessages.push({
|
|
1030
|
-
role: "user",
|
|
1031
|
-
content: mapContent(otherBlocks)
|
|
1032
|
-
});
|
|
1033
|
-
} else newMessages.push({
|
|
1034
|
-
role: "user",
|
|
1035
|
-
content: mapContent(message.content)
|
|
1036
|
-
});
|
|
1037
|
-
return newMessages;
|
|
1038
|
-
}
|
|
1039
|
-
function handleAssistantMessage(message) {
|
|
1040
|
-
if (!Array.isArray(message.content)) return [{
|
|
1041
|
-
role: "assistant",
|
|
1042
|
-
content: mapContent(message.content)
|
|
1043
|
-
}];
|
|
1044
|
-
const toolUseBlocks = message.content.filter((block) => block.type === "tool_use");
|
|
1045
|
-
const textBlocks = message.content.filter((block) => block.type === "text");
|
|
1046
|
-
const thinkingBlocks = message.content.filter((block) => block.type === "thinking");
|
|
1047
|
-
const allTextContent = [...textBlocks.map((b) => b.text), ...thinkingBlocks.map((b) => b.thinking)].join("\n\n");
|
|
1048
|
-
return toolUseBlocks.length > 0 ? [{
|
|
1049
|
-
role: "assistant",
|
|
1050
|
-
content: allTextContent || null,
|
|
1051
|
-
tool_calls: toolUseBlocks.map((toolUse) => ({
|
|
1052
|
-
id: toolUse.id,
|
|
1053
|
-
type: "function",
|
|
1054
|
-
function: {
|
|
1055
|
-
name: toolUse.name,
|
|
1056
|
-
arguments: JSON.stringify(toolUse.input)
|
|
1057
|
-
}
|
|
1058
|
-
}))
|
|
1059
|
-
}] : [{
|
|
1060
|
-
role: "assistant",
|
|
1061
|
-
content: mapContent(message.content)
|
|
1062
|
-
}];
|
|
1063
|
-
}
|
|
1064
|
-
function mapContent(content) {
|
|
1065
|
-
if (typeof content === "string") return content;
|
|
1066
|
-
if (!Array.isArray(content)) return null;
|
|
1067
|
-
const hasImage = content.some((block) => block.type === "image");
|
|
1068
|
-
if (!hasImage) return content.filter((block) => block.type === "text" || block.type === "thinking").map((block) => block.type === "text" ? block.text : block.thinking).join("\n\n");
|
|
1069
|
-
const contentParts = [];
|
|
1070
|
-
for (const block of content) switch (block.type) {
|
|
1071
|
-
case "text":
|
|
1072
|
-
contentParts.push({
|
|
1073
|
-
type: "text",
|
|
1074
|
-
text: block.text
|
|
1075
|
-
});
|
|
1076
|
-
break;
|
|
1077
|
-
case "thinking":
|
|
1078
|
-
contentParts.push({
|
|
1079
|
-
type: "text",
|
|
1080
|
-
text: block.thinking
|
|
1081
|
-
});
|
|
1082
|
-
break;
|
|
1083
|
-
case "image":
|
|
1084
|
-
contentParts.push({
|
|
1085
|
-
type: "image_url",
|
|
1086
|
-
image_url: { url: `data:${block.source.media_type};base64,${block.source.data}` }
|
|
1087
|
-
});
|
|
1088
|
-
break;
|
|
1089
|
-
}
|
|
1090
|
-
return contentParts;
|
|
1091
|
-
}
|
|
1092
|
-
function translateAnthropicToolsToOpenAI(anthropicTools) {
|
|
1093
|
-
if (!anthropicTools) return void 0;
|
|
1094
|
-
return anthropicTools.map((tool) => ({
|
|
1095
|
-
type: "function",
|
|
1096
|
-
function: {
|
|
1097
|
-
name: tool.name,
|
|
1098
|
-
description: tool.description,
|
|
1099
|
-
parameters: tool.input_schema
|
|
1100
|
-
}
|
|
1101
|
-
}));
|
|
1102
|
-
}
|
|
1103
|
-
function translateAnthropicToolChoiceToOpenAI(anthropicToolChoice) {
|
|
1104
|
-
if (!anthropicToolChoice) return void 0;
|
|
1105
|
-
switch (anthropicToolChoice.type) {
|
|
1106
|
-
case "auto": return "auto";
|
|
1107
|
-
case "any": return "required";
|
|
1108
|
-
case "tool":
|
|
1109
|
-
if (anthropicToolChoice.name) return {
|
|
1110
|
-
type: "function",
|
|
1111
|
-
function: { name: anthropicToolChoice.name }
|
|
1112
|
-
};
|
|
1113
|
-
return void 0;
|
|
1114
|
-
case "none": return "none";
|
|
1115
|
-
default: return void 0;
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
function translateToAnthropic(response) {
|
|
1119
|
-
const allTextBlocks = [];
|
|
1120
|
-
const allToolUseBlocks = [];
|
|
1121
|
-
let stopReason = null;
|
|
1122
|
-
stopReason = response.choices[0]?.finish_reason ?? stopReason;
|
|
1123
|
-
for (const choice of response.choices) {
|
|
1124
|
-
const textBlocks = getAnthropicTextBlocks(choice.message.content);
|
|
1125
|
-
const toolUseBlocks = getAnthropicToolUseBlocks(choice.message.tool_calls);
|
|
1126
|
-
allTextBlocks.push(...textBlocks);
|
|
1127
|
-
allToolUseBlocks.push(...toolUseBlocks);
|
|
1128
|
-
if (choice.finish_reason === "tool_calls" || stopReason === "stop") stopReason = choice.finish_reason;
|
|
1129
|
-
}
|
|
1130
|
-
return {
|
|
1131
|
-
id: response.id,
|
|
1132
|
-
type: "message",
|
|
1133
|
-
role: "assistant",
|
|
1134
|
-
model: response.model,
|
|
1135
|
-
content: [...allTextBlocks, ...allToolUseBlocks],
|
|
1136
|
-
stop_reason: mapOpenAIStopReasonToAnthropic(stopReason),
|
|
1137
|
-
stop_sequence: null,
|
|
1138
|
-
usage: {
|
|
1139
|
-
input_tokens: response.usage?.prompt_tokens ?? 0,
|
|
1140
|
-
output_tokens: response.usage?.completion_tokens ?? 0
|
|
1141
|
-
}
|
|
1142
|
-
};
|
|
1143
|
-
}
|
|
1144
|
-
function getAnthropicTextBlocks(messageContent) {
|
|
1145
|
-
if (typeof messageContent === "string") return [{
|
|
1146
|
-
type: "text",
|
|
1147
|
-
text: messageContent
|
|
1148
|
-
}];
|
|
1149
|
-
if (Array.isArray(messageContent)) return messageContent.filter((part) => part.type === "text").map((part) => ({
|
|
1150
|
-
type: "text",
|
|
1151
|
-
text: part.text
|
|
1152
|
-
}));
|
|
1153
|
-
return [];
|
|
1154
|
-
}
|
|
1155
|
-
function getAnthropicToolUseBlocks(toolCalls) {
|
|
1156
|
-
if (!toolCalls) return [];
|
|
1157
|
-
return toolCalls.map((toolCall) => ({
|
|
1158
|
-
type: "tool_use",
|
|
1159
|
-
id: toolCall.id,
|
|
1160
|
-
name: toolCall.function.name,
|
|
1161
|
-
input: JSON.parse(toolCall.function.arguments)
|
|
1162
|
-
}));
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
//#endregion
|
|
1166
|
-
//#region src/routes/messages/stream-translation.ts
|
|
1167
|
-
function isToolBlockOpen(state$1) {
|
|
1168
|
-
if (!state$1.contentBlockOpen) return false;
|
|
1169
|
-
return Object.values(state$1.toolCalls).some((tc) => tc.anthropicBlockIndex === state$1.contentBlockIndex);
|
|
1170
|
-
}
|
|
1171
|
-
function translateChunkToAnthropicEvents(chunk, state$1) {
|
|
1172
|
-
const events$1 = [];
|
|
1173
|
-
if (chunk.choices.length === 0) return events$1;
|
|
1174
|
-
const choice = chunk.choices[0];
|
|
1175
|
-
const { delta } = choice;
|
|
1176
|
-
if (!state$1.messageStartSent) {
|
|
1177
|
-
events$1.push({
|
|
1178
|
-
type: "message_start",
|
|
1179
|
-
message: {
|
|
1180
|
-
id: chunk.id,
|
|
1181
|
-
type: "message",
|
|
1182
|
-
role: "assistant",
|
|
1183
|
-
content: [],
|
|
1184
|
-
model: chunk.model,
|
|
1185
|
-
stop_reason: null,
|
|
1186
|
-
stop_sequence: null,
|
|
1187
|
-
usage: {
|
|
1188
|
-
input_tokens: chunk.usage?.prompt_tokens ?? 0,
|
|
1189
|
-
output_tokens: 0
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
});
|
|
1193
|
-
state$1.messageStartSent = true;
|
|
1194
|
-
}
|
|
1195
|
-
if (delta.content) {
|
|
1196
|
-
if (isToolBlockOpen(state$1)) {
|
|
1197
|
-
events$1.push({
|
|
1198
|
-
type: "content_block_stop",
|
|
1199
|
-
index: state$1.contentBlockIndex
|
|
1200
|
-
});
|
|
1201
|
-
state$1.contentBlockIndex++;
|
|
1202
|
-
state$1.contentBlockOpen = false;
|
|
1203
|
-
}
|
|
1204
|
-
if (!state$1.contentBlockOpen) {
|
|
1205
|
-
events$1.push({
|
|
1206
|
-
type: "content_block_start",
|
|
1207
|
-
index: state$1.contentBlockIndex,
|
|
1208
|
-
content_block: {
|
|
1209
|
-
type: "text",
|
|
1210
|
-
text: ""
|
|
1211
|
-
}
|
|
1212
|
-
});
|
|
1213
|
-
state$1.contentBlockOpen = true;
|
|
1214
|
-
}
|
|
1215
|
-
events$1.push({
|
|
1216
|
-
type: "content_block_delta",
|
|
1217
|
-
index: state$1.contentBlockIndex,
|
|
1218
|
-
delta: {
|
|
1219
|
-
type: "text_delta",
|
|
1220
|
-
text: delta.content
|
|
1221
|
-
}
|
|
1222
|
-
});
|
|
1223
|
-
}
|
|
1224
|
-
if (delta.tool_calls) for (const toolCall of delta.tool_calls) {
|
|
1225
|
-
if (toolCall.id && toolCall.function?.name) {
|
|
1226
|
-
if (state$1.contentBlockOpen) {
|
|
1227
|
-
events$1.push({
|
|
1228
|
-
type: "content_block_stop",
|
|
1229
|
-
index: state$1.contentBlockIndex
|
|
1230
|
-
});
|
|
1231
|
-
state$1.contentBlockIndex++;
|
|
1232
|
-
state$1.contentBlockOpen = false;
|
|
1233
|
-
}
|
|
1234
|
-
const anthropicBlockIndex = state$1.contentBlockIndex;
|
|
1235
|
-
state$1.toolCalls[toolCall.index] = {
|
|
1236
|
-
id: toolCall.id,
|
|
1237
|
-
name: toolCall.function.name,
|
|
1238
|
-
anthropicBlockIndex
|
|
1239
|
-
};
|
|
1240
|
-
events$1.push({
|
|
1241
|
-
type: "content_block_start",
|
|
1242
|
-
index: anthropicBlockIndex,
|
|
1243
|
-
content_block: {
|
|
1244
|
-
type: "tool_use",
|
|
1245
|
-
id: toolCall.id,
|
|
1246
|
-
name: toolCall.function.name,
|
|
1247
|
-
input: {}
|
|
1248
|
-
}
|
|
1249
|
-
});
|
|
1250
|
-
state$1.contentBlockOpen = true;
|
|
1251
|
-
}
|
|
1252
|
-
if (toolCall.function?.arguments) {
|
|
1253
|
-
const toolCallInfo = state$1.toolCalls[toolCall.index];
|
|
1254
|
-
if (toolCallInfo) events$1.push({
|
|
1255
|
-
type: "content_block_delta",
|
|
1256
|
-
index: toolCallInfo.anthropicBlockIndex,
|
|
1257
|
-
delta: {
|
|
1258
|
-
type: "input_json_delta",
|
|
1259
|
-
partial_json: toolCall.function.arguments
|
|
1260
|
-
}
|
|
1261
|
-
});
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
if (choice.finish_reason) {
|
|
1265
|
-
if (state$1.contentBlockOpen) {
|
|
1266
|
-
events$1.push({
|
|
1267
|
-
type: "content_block_stop",
|
|
1268
|
-
index: state$1.contentBlockIndex
|
|
1269
|
-
});
|
|
1270
|
-
state$1.contentBlockOpen = false;
|
|
1271
|
-
}
|
|
1272
|
-
events$1.push({
|
|
1273
|
-
type: "message_delta",
|
|
1274
|
-
delta: {
|
|
1275
|
-
stop_reason: mapOpenAIStopReasonToAnthropic(choice.finish_reason),
|
|
1276
|
-
stop_sequence: null
|
|
1277
|
-
},
|
|
1278
|
-
usage: {
|
|
1279
|
-
input_tokens: chunk.usage?.prompt_tokens ?? 0,
|
|
1280
|
-
output_tokens: chunk.usage?.completion_tokens ?? 0,
|
|
1281
|
-
...chunk.usage?.prompt_tokens_details?.cached_tokens !== void 0 && { cache_read_input_tokens: chunk.usage.prompt_tokens_details.cached_tokens }
|
|
1282
|
-
}
|
|
1283
|
-
}, { type: "message_stop" });
|
|
1284
|
-
}
|
|
1285
|
-
return events$1;
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
//#endregion
|
|
1289
|
-
//#region src/routes/messages/handler.ts
|
|
1290
|
-
async function handleCompletion(c) {
|
|
1291
|
-
await checkRateLimit(state);
|
|
1292
|
-
const anthropicPayload = await c.req.json();
|
|
1293
|
-
consola.debug("Anthropic request payload:", JSON.stringify(anthropicPayload));
|
|
1294
|
-
const openAIPayload = translateToOpenAI(anthropicPayload);
|
|
1295
|
-
consola.debug("Translated OpenAI request payload:", JSON.stringify(openAIPayload));
|
|
1296
|
-
if (state.manualApprove) await awaitApproval();
|
|
1297
|
-
const response = await createChatCompletions(openAIPayload);
|
|
1298
|
-
if (isNonStreaming(response)) {
|
|
1299
|
-
consola.debug("Non-streaming response from Copilot:", JSON.stringify(response).slice(-400));
|
|
1300
|
-
const anthropicResponse = translateToAnthropic(response);
|
|
1301
|
-
consola.debug("Translated Anthropic response:", JSON.stringify(anthropicResponse));
|
|
1302
|
-
return c.json(anthropicResponse);
|
|
1303
|
-
}
|
|
1304
|
-
consola.debug("Streaming response from Copilot");
|
|
1305
|
-
return streamSSE(c, async (stream) => {
|
|
1306
|
-
const streamState = {
|
|
1307
|
-
messageStartSent: false,
|
|
1308
|
-
contentBlockIndex: 0,
|
|
1309
|
-
contentBlockOpen: false,
|
|
1310
|
-
toolCalls: {}
|
|
1311
|
-
};
|
|
1312
|
-
for await (const rawEvent of response) {
|
|
1313
|
-
consola.debug("Copilot raw stream event:", JSON.stringify(rawEvent));
|
|
1314
|
-
if (rawEvent.data === "[DONE]") break;
|
|
1315
|
-
if (!rawEvent.data) continue;
|
|
1316
|
-
const chunk = JSON.parse(rawEvent.data);
|
|
1317
|
-
const events$1 = translateChunkToAnthropicEvents(chunk, streamState);
|
|
1318
|
-
for (const event of events$1) {
|
|
1319
|
-
consola.debug("Translated Anthropic event:", JSON.stringify(event));
|
|
1320
|
-
await stream.writeSSE({
|
|
1321
|
-
event: event.type,
|
|
1322
|
-
data: JSON.stringify(event)
|
|
1323
|
-
});
|
|
1324
|
-
}
|
|
1325
|
-
}
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
const isNonStreaming = (response) => Object.hasOwn(response, "choices");
|
|
1329
|
-
|
|
1330
|
-
//#endregion
|
|
1331
|
-
//#region src/routes/messages/route.ts
|
|
1332
|
-
const messageRoutes = new Hono();
|
|
1333
|
-
messageRoutes.post("/", async (c) => {
|
|
1334
|
-
try {
|
|
1335
|
-
return await handleCompletion(c);
|
|
1336
|
-
} catch (error) {
|
|
1337
|
-
return await forwardError(c, error);
|
|
1338
|
-
}
|
|
1339
|
-
});
|
|
1340
|
-
|
|
1341
|
-
//#endregion
|
|
1342
|
-
//#region src/routes/models/route.ts
|
|
1343
|
-
const modelRoutes = new Hono();
|
|
1344
|
-
modelRoutes.get("/", async (c) => {
|
|
1345
|
-
try {
|
|
1346
|
-
if (!state.models) await cacheModels();
|
|
1347
|
-
const models = state.models?.data.map((model) => ({
|
|
1348
|
-
id: model.id,
|
|
1349
|
-
object: "model",
|
|
1350
|
-
type: "model",
|
|
1351
|
-
created: 0,
|
|
1352
|
-
created_at: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
1353
|
-
owned_by: model.vendor,
|
|
1354
|
-
display_name: model.name
|
|
1355
|
-
}));
|
|
1356
|
-
return c.json({
|
|
1357
|
-
object: "list",
|
|
1358
|
-
data: models,
|
|
1359
|
-
has_more: false
|
|
1360
|
-
});
|
|
1361
|
-
} catch (error) {
|
|
1362
|
-
return await forwardError(c, error);
|
|
1363
|
-
}
|
|
1364
|
-
});
|
|
1365
|
-
|
|
1366
|
-
//#endregion
|
|
1367
|
-
//#region src/routes/token/route.ts
|
|
1368
|
-
const tokenRoute = new Hono();
|
|
1369
|
-
tokenRoute.get("/", (c) => {
|
|
1370
|
-
try {
|
|
1371
|
-
return c.json({ token: state.copilotToken });
|
|
1372
|
-
} catch (error) {
|
|
1373
|
-
console.error("Error fetching token:", error);
|
|
1374
|
-
return c.json({
|
|
1375
|
-
error: "Failed to fetch token",
|
|
1376
|
-
token: null
|
|
1377
|
-
}, 500);
|
|
1378
|
-
}
|
|
1379
|
-
});
|
|
1380
|
-
|
|
1381
|
-
//#endregion
|
|
1382
|
-
//#region src/routes/usage/route.ts
|
|
1383
|
-
const usageRoute = new Hono();
|
|
1384
|
-
usageRoute.get("/", async (c) => {
|
|
1385
|
-
try {
|
|
1386
|
-
const usage = await getCopilotUsage();
|
|
1387
|
-
return c.json(usage);
|
|
1388
|
-
} catch (error) {
|
|
1389
|
-
console.error("Error fetching Copilot usage:", error);
|
|
1390
|
-
return c.json({ error: "Failed to fetch Copilot usage" }, 500);
|
|
1391
|
-
}
|
|
1392
|
-
});
|
|
1393
|
-
|
|
1394
|
-
//#endregion
|
|
1395
|
-
//#region src/server.ts
|
|
1396
|
-
const server = new Hono();
|
|
1397
|
-
server.use(logger());
|
|
1398
|
-
server.use(cors());
|
|
1399
|
-
server.get("/", (c) => c.text("Server running"));
|
|
1400
|
-
server.route("/chat/completions", completionRoutes);
|
|
1401
|
-
server.route("/models", modelRoutes);
|
|
1402
|
-
server.route("/embeddings", embeddingRoutes);
|
|
1403
|
-
server.route("/usage", usageRoute);
|
|
1404
|
-
server.route("/token", tokenRoute);
|
|
1405
|
-
server.route("/v1/chat/completions", completionRoutes);
|
|
1406
|
-
server.route("/v1/models", modelRoutes);
|
|
1407
|
-
server.route("/v1/embeddings", embeddingRoutes);
|
|
1408
|
-
server.route("/v1/messages", messageRoutes);
|
|
1409
|
-
server.post("/v1/messages/count_tokens", (c) => c.json({ input_tokens: 1 }));
|
|
1410
|
-
|
|
1411
|
-
//#endregion
|
|
1412
|
-
//#region src/start.ts
|
|
1413
|
-
const cleanupFunctions = [];
|
|
1414
|
-
function setupGracefulShutdown() {
|
|
1415
|
-
const cleanup = async () => {
|
|
1416
|
-
consola.info("Gracefully shutting down...");
|
|
1417
|
-
for (const cleanupFn of cleanupFunctions) try {
|
|
1418
|
-
await cleanupFn();
|
|
1419
|
-
} catch (error) {
|
|
1420
|
-
consola.error("Error during cleanup:", error);
|
|
1421
|
-
}
|
|
1422
|
-
consola.info("Shutdown complete");
|
|
1423
|
-
process$1.exit(0);
|
|
1424
|
-
};
|
|
1425
|
-
process$1.on("SIGINT", cleanup);
|
|
1426
|
-
process$1.on("SIGTERM", cleanup);
|
|
1427
|
-
process$1.on("uncaughtException", (error) => {
|
|
1428
|
-
consola.error("Uncaught exception:", error);
|
|
1429
|
-
cleanup().finally(() => process$1.exit(1));
|
|
1430
|
-
});
|
|
1431
|
-
process$1.on("unhandledRejection", (reason, promise) => {
|
|
1432
|
-
consola.error("Unhandled promise rejection at:", promise, "reason:", reason);
|
|
1433
|
-
cleanup().finally(() => process$1.exit(1));
|
|
1434
|
-
});
|
|
1435
|
-
}
|
|
1436
|
-
async function runServer(options) {
|
|
1437
|
-
setupGracefulShutdown();
|
|
1438
|
-
cleanupFunctions.push(() => {
|
|
1439
|
-
consola.debug("Cleaning up connectivity monitor");
|
|
1440
|
-
connectivityMonitor.stop();
|
|
1441
|
-
}, () => {
|
|
1442
|
-
consola.debug("Cleaning up token management");
|
|
1443
|
-
cleanupTokenManagement();
|
|
1444
|
-
});
|
|
1445
|
-
if (options.verbose) {
|
|
1446
|
-
consola.level = 5;
|
|
1447
|
-
consola.info("Verbose logging enabled");
|
|
1448
|
-
}
|
|
1449
|
-
state.accountType = options.accountType;
|
|
1450
|
-
if (options.accountType !== "individual") consola.info(`Using ${options.accountType} plan GitHub account`);
|
|
1451
|
-
state.manualApprove = options.manual;
|
|
1452
|
-
state.rateLimitSeconds = options.rateLimit;
|
|
1453
|
-
state.rateLimitWait = options.rateLimitWait;
|
|
1454
|
-
state.showToken = options.showToken;
|
|
1455
|
-
state.timeoutMs = options.timeout;
|
|
1456
|
-
state.connectivity.enabled = !options.disableConnectivityMonitoring;
|
|
1457
|
-
await ensurePaths();
|
|
1458
|
-
await cacheVSCodeVersion();
|
|
1459
|
-
if (options.githubToken) {
|
|
1460
|
-
state.githubToken = options.githubToken;
|
|
1461
|
-
consola.info("Using provided GitHub token");
|
|
1462
|
-
} else await setupGitHubToken();
|
|
1463
|
-
await setupCopilotToken();
|
|
1464
|
-
await cacheModels();
|
|
1465
|
-
consola.info(`Available models: \n${state.models?.data.map((model) => `- ${model.id}`).join("\n")}`);
|
|
1466
|
-
const serverUrl = `http://localhost:${options.port}`;
|
|
1467
|
-
if (options.claudeCode) {
|
|
1468
|
-
invariant(state.models, "Models should be loaded by now");
|
|
1469
|
-
let selectedModel;
|
|
1470
|
-
let selectedSmallModel;
|
|
1471
|
-
if (options.model && options.smallModel) {
|
|
1472
|
-
const availableModelIds = state.models.data.map((model) => model.id);
|
|
1473
|
-
if (!availableModelIds.includes(options.model)) {
|
|
1474
|
-
consola.error(`Invalid model: ${options.model}`);
|
|
1475
|
-
consola.info(`Available models: \n${availableModelIds.join("\n")}`);
|
|
1476
|
-
process$1.exit(1);
|
|
1477
|
-
}
|
|
1478
|
-
if (!availableModelIds.includes(options.smallModel)) {
|
|
1479
|
-
consola.error(`Invalid small model: ${options.smallModel}`);
|
|
1480
|
-
consola.info(`Available models: \n${availableModelIds.join("\n")}`);
|
|
1481
|
-
process$1.exit(1);
|
|
1482
|
-
}
|
|
1483
|
-
selectedModel = options.model;
|
|
1484
|
-
selectedSmallModel = options.smallModel;
|
|
1485
|
-
consola.info(`Using model: ${selectedModel}`);
|
|
1486
|
-
consola.info(`Using small model: ${selectedSmallModel}`);
|
|
1487
|
-
} else if (options.model || options.smallModel) {
|
|
1488
|
-
consola.error("Both --model and --small-model must be specified when using command-line model selection");
|
|
1489
|
-
process$1.exit(1);
|
|
1490
|
-
} else {
|
|
1491
|
-
selectedModel = await consola.prompt("Select a model to use with Claude Code", {
|
|
1492
|
-
type: "select",
|
|
1493
|
-
options: state.models.data.map((model) => model.id)
|
|
1494
|
-
});
|
|
1495
|
-
selectedSmallModel = await consola.prompt("Select a small model to use with Claude Code", {
|
|
1496
|
-
type: "select",
|
|
1497
|
-
options: state.models.data.map((model) => model.id)
|
|
1498
|
-
});
|
|
1499
|
-
}
|
|
1500
|
-
const command = generateEnvScript({
|
|
1501
|
-
ANTHROPIC_BASE_URL: serverUrl,
|
|
1502
|
-
ANTHROPIC_AUTH_TOKEN: "dummy",
|
|
1503
|
-
ANTHROPIC_MODEL: selectedModel,
|
|
1504
|
-
ANTHROPIC_SMALL_FAST_MODEL: selectedSmallModel
|
|
1505
|
-
}, "claude");
|
|
1506
|
-
try {
|
|
1507
|
-
clipboard.writeSync(command);
|
|
1508
|
-
consola.success("Copied Claude Code command to clipboard!");
|
|
1509
|
-
} catch {
|
|
1510
|
-
consola.warn("Failed to copy to clipboard. Here is the Claude Code command:");
|
|
1511
|
-
consola.log(command);
|
|
1512
|
-
}
|
|
1513
|
-
}
|
|
1514
|
-
consola.box(`🌐 Usage Viewer: https://ericc-ch.github.io/copilot-api?endpoint=${serverUrl}/usage`);
|
|
1515
|
-
serve({
|
|
1516
|
-
fetch: server.fetch,
|
|
1517
|
-
port: options.port
|
|
1518
|
-
});
|
|
1519
|
-
}
|
|
1520
|
-
const start = defineCommand({
|
|
1521
|
-
meta: {
|
|
1522
|
-
name: "start",
|
|
1523
|
-
description: "Start the Copilot API server"
|
|
1524
|
-
},
|
|
1525
|
-
args: {
|
|
1526
|
-
port: {
|
|
1527
|
-
alias: "p",
|
|
1528
|
-
type: "string",
|
|
1529
|
-
default: "4141",
|
|
1530
|
-
description: "Port to listen on"
|
|
1531
|
-
},
|
|
1532
|
-
verbose: {
|
|
1533
|
-
alias: "v",
|
|
1534
|
-
type: "boolean",
|
|
1535
|
-
default: false,
|
|
1536
|
-
description: "Enable verbose logging"
|
|
1537
|
-
},
|
|
1538
|
-
"account-type": {
|
|
1539
|
-
alias: "a",
|
|
1540
|
-
type: "string",
|
|
1541
|
-
default: "individual",
|
|
1542
|
-
description: "Account type to use (individual, business, enterprise)"
|
|
1543
|
-
},
|
|
1544
|
-
manual: {
|
|
1545
|
-
type: "boolean",
|
|
1546
|
-
default: false,
|
|
1547
|
-
description: "Enable manual request approval"
|
|
1548
|
-
},
|
|
1549
|
-
"rate-limit": {
|
|
1550
|
-
alias: "r",
|
|
1551
|
-
type: "string",
|
|
1552
|
-
description: "Rate limit in seconds between requests"
|
|
1553
|
-
},
|
|
1554
|
-
wait: {
|
|
1555
|
-
alias: "w",
|
|
1556
|
-
type: "boolean",
|
|
1557
|
-
default: false,
|
|
1558
|
-
description: "Wait instead of error when rate limit is hit. Has no effect if rate limit is not set"
|
|
1559
|
-
},
|
|
1560
|
-
"github-token": {
|
|
1561
|
-
alias: "g",
|
|
1562
|
-
type: "string",
|
|
1563
|
-
description: "Provide GitHub token directly (must be generated using the `auth` subcommand)"
|
|
1564
|
-
},
|
|
1565
|
-
"claude-code": {
|
|
1566
|
-
alias: "c",
|
|
1567
|
-
type: "boolean",
|
|
1568
|
-
default: false,
|
|
1569
|
-
description: "Generate a command to launch Claude Code with Copilot API config"
|
|
1570
|
-
},
|
|
1571
|
-
model: {
|
|
1572
|
-
alias: "m",
|
|
1573
|
-
type: "string",
|
|
1574
|
-
description: "Model to use with Claude Code (requires --claude-code)"
|
|
1575
|
-
},
|
|
1576
|
-
"small-model": {
|
|
1577
|
-
alias: "s",
|
|
1578
|
-
type: "string",
|
|
1579
|
-
description: "Small/fast model to use with Claude Code (requires --claude-code)"
|
|
1580
|
-
},
|
|
1581
|
-
"show-token": {
|
|
1582
|
-
type: "boolean",
|
|
1583
|
-
default: false,
|
|
1584
|
-
description: "Show GitHub and Copilot tokens on fetch and refresh"
|
|
1585
|
-
},
|
|
1586
|
-
timeout: {
|
|
1587
|
-
alias: "t",
|
|
1588
|
-
type: "string",
|
|
1589
|
-
description: "API timeout in milliseconds (default: 120000)"
|
|
1590
|
-
},
|
|
1591
|
-
"disable-connectivity-monitoring": {
|
|
1592
|
-
type: "boolean",
|
|
1593
|
-
default: false,
|
|
1594
|
-
description: "Disable automatic network connectivity monitoring for token refresh"
|
|
1595
|
-
}
|
|
1596
|
-
},
|
|
1597
|
-
run({ args }) {
|
|
1598
|
-
const rateLimitRaw = args["rate-limit"];
|
|
1599
|
-
const rateLimit = rateLimitRaw === void 0 ? void 0 : Number.parseInt(rateLimitRaw, 10);
|
|
1600
|
-
const timeoutRaw = args.timeout;
|
|
1601
|
-
const timeout = timeoutRaw === void 0 ? 12e4 : Number.parseInt(timeoutRaw, 10);
|
|
1602
|
-
return runServer({
|
|
1603
|
-
port: Number.parseInt(args.port, 10),
|
|
1604
|
-
verbose: args.verbose,
|
|
1605
|
-
accountType: args["account-type"],
|
|
1606
|
-
manual: args.manual,
|
|
1607
|
-
rateLimit,
|
|
1608
|
-
rateLimitWait: args.wait,
|
|
1609
|
-
githubToken: args["github-token"],
|
|
1610
|
-
claudeCode: args["claude-code"],
|
|
1611
|
-
model: args.model,
|
|
1612
|
-
smallModel: args["small-model"],
|
|
1613
|
-
showToken: args["show-token"],
|
|
1614
|
-
timeout,
|
|
1615
|
-
disableConnectivityMonitoring: args["disable-connectivity-monitoring"]
|
|
1616
|
-
});
|
|
1617
|
-
}
|
|
1618
|
-
});
|
|
1619
|
-
|
|
1620
|
-
//#endregion
|
|
1621
|
-
//#region src/main.ts
|
|
1622
|
-
const main = defineCommand({
|
|
1623
|
-
meta: {
|
|
1624
|
-
name: "copilot-api",
|
|
1625
|
-
description: "A wrapper around GitHub Copilot API to make it OpenAI compatible, making it usable for other tools."
|
|
1626
|
-
},
|
|
1627
|
-
subCommands: {
|
|
1628
|
-
auth,
|
|
1629
|
-
start,
|
|
1630
|
-
"check-usage": checkUsage,
|
|
1631
|
-
debug
|
|
1632
|
-
}
|
|
1633
|
-
});
|
|
1634
|
-
await runMain(main);
|
|
1635
|
-
|
|
1636
|
-
//#endregion
|
|
1637
|
-
export { };
|
|
1638
|
-
//# sourceMappingURL=main.js.map
|
|
2
|
+
import{CompletionLogger as S,GITHUB_API_BASE_URL as G,GITHUB_APP_SCOPES as de,GITHUB_BASE_URL as R,GITHUB_CLIENT_ID as L,HTTPError as y,PATHS as w,copilotBaseUrl as E,copilotHeaders as P,ensurePaths as j,forwardError as I,getGitHubUser as pe,githubHeaders as J,initializeVSCodeIdentifiers as me,standardHeaders as W,state as s}from"./get-user-BJ4s6iMX.js";import{defineCommand as T,runMain as fe}from"citty";import i from"consola";import C from"node:fs/promises";import K from"node:os";import he from"clipboardy";import g from"node:process";import{serve as ge}from"srvx";import ye from"tiny-invariant";import{execSync as we}from"node:child_process";import{Hono as k}from"hono";import{cors as ke}from"hono/cors";import{streamSSE as V}from"hono/streaming";import{events as be}from"fetch-event-stream";import{request as _e}from"undici";var ve=class extends EventTarget{isOnline=!0;lastChecked=new Date().toISOString();consecutiveFailures=0;lastErrorType;lastErrorMessage;lastSuccessfulEndpoint;endpointFailureStats={};checkInterval;abortController;on(e,t){return this.addEventListener(e,t),this}off(e,t){return this.removeEventListener(e,t),this}start(){if(!s.connectivity.enabled){i.debug("Network monitoring disabled");return}i.info("Starting network monitor",{probeEndpoints:s.connectivity.probeEndpoints,fastInterval:s.connectivity.fastProbeInterval}),this.scheduleNextCheck();let e=()=>{this.stop(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}stop(){i.debug("Stopping connectivity monitor"),this.checkInterval&&=(clearTimeout(this.checkInterval),void 0),this.abortController&&=(this.abortController.abort(),void 0)}scheduleNextCheck(){this.checkInterval&&clearTimeout(this.checkInterval);let e=this.isOnline?s.connectivity.slowProbeInterval:s.connectivity.fastProbeInterval,t=Math.random()*s.connectivity.jitterMaxMs,o=e+t;this.checkInterval=setTimeout(()=>{this.performConnectivityCheck().catch(n=>{i.error("Connectivity check failed:",n)})},o)}async performConnectivityCheck(){this.abortController=new AbortController;let e=setTimeout(()=>this.abortController?.abort(),s.connectivity.timeoutMs);try{let t=!1;for(let o of s.connectivity.probeEndpoints)try{if((await fetch(o,{method:"HEAD",signal:this.abortController.signal,headers:{"\u0055\u0073\u0065\u0072\u002d\u0041\u0067\u0065\u006e\u0074":"service-api-connectivity-monitor/1.0",...s.connectivity.dnsCache&&{"Cache-Control":"max-age=300"}}})).ok){t=!0,this.lastSuccessfulEndpoint=o;break}}catch(n){this.endpointFailureStats[o]=(this.endpointFailureStats[o]||0)+1,i.debug(`Probe failed for ${o}:`,n)}this.updateConnectivityState(t)}catch(t){this.handleConnectivityError(t)}finally{clearTimeout(e),this.scheduleNextCheck()}}updateConnectivityState(e){let t=this.isOnline;this.isOnline=e,this.lastChecked=new Date().toISOString(),e?(this.consecutiveFailures>0&&i.info(`Connectivity restored after ${this.consecutiveFailures} failures`),this.consecutiveFailures=0,this.lastErrorType=void 0,this.lastErrorMessage=void 0,t||this.dispatchEvent(new CustomEvent("online"))):(this.consecutiveFailures++,t&&(i.warn("Network lost"),this.dispatchEvent(new CustomEvent("offline"))))}handleConnectivityError(e){this.lastErrorType=e.name,this.lastErrorMessage=e.message,i.error("Connectivity check failed:",e),this.updateConnectivityState(!1)}getConnectivityStats(){return{isOnline:this.isOnline,lastChecked:this.lastChecked,consecutiveFailures:this.consecutiveFailures,lastErrorType:this.lastErrorType,lastErrorMessage:this.lastErrorMessage}}getPerformanceStats(){let e=this.isOnline?s.connectivity.slowProbeInterval:s.connectivity.fastProbeInterval,t=new Date(Date.now()+e+Math.random()*s.connectivity.jitterMaxMs).toISOString();return{currentInterval:e,nextCheckEstimate:t,lastSuccessfulEndpoint:this.lastSuccessfulEndpoint,endpointFailureStats:{...this.endpointFailureStats},jitterEnabled:s.connectivity.jitterMaxMs>0,connectionPooling:s.connectivity.connectionPooling,dnsCache:s.connectivity.dnsCache}}};const v=new ve,z=async()=>{let e=new AbortController,t=s.timeoutMs??12e4,o=setTimeout(()=>{e.abort()},t);try{let n=await fetch(`${G}/\u0063\u006f\u0070\u0069\u006c\u006f\u0074_internal/v2/token`,{headers:J(s),signal:e.signal});if(!n.ok)throw new y("\u0046\u0061\u0069\u006c\u0065\u0064\u0020\u0074\u006f\u0020\u0067\u0065\u0074\u0020\u0043\u006f\u0070\u0069\u006c\u006f\u0074\u0020\u0074\u006f\u006b\u0065\u006e",n);return await n.json()}finally{clearTimeout(o)}};async function Te(){let e=new AbortController,t=s.timeoutMs??12e4,o=setTimeout(()=>{e.abort()},t);try{let n=await fetch(`${R}/login/device/code`,{method:"POST",headers:W(),body:JSON.stringify({client_id:L,scope:de}),signal:e.signal});if(!n.ok)throw new y("Failed to get device code",n);return await n.json()}finally{clearTimeout(o)}}const Ce=async()=>{let e=new AbortController,t=s.timeoutMs??12e4,o=setTimeout(()=>{e.abort()},t);try{let n=await fetch(`${E(s)}/models`,{headers:P(s),signal:e.signal});if(!n.ok)throw new y("Failed to get models",n);return await n.json()}finally{clearTimeout(o)}};function Q(){return"1.105.0-insider"}Q();const A=e=>new Promise(t=>{setTimeout(t,e)}),xe=e=>e==null;async function X(){let e=await Ce();s.models=e}const Se=()=>{let e=Q();s.vsCodeVersion=e,i.info(`Using VSCode version:${e}`)};async function Ie(e){let t=(e.interval+1)*1e3;for(i.debug(`Polling access token with interval of ${t}ms`);;){let o=new AbortController,n=s.timeoutMs??12e4,r=setTimeout(()=>{o.abort()},n);try{let a=await fetch(`${R}/login/oauth/access_token`,{method:"POST",headers:W(),body:JSON.stringify({client_id:L,device_code:e.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:o.signal});if(!a.ok){await A(t),i.error("Failed to poll access token:",await a.text());continue}let l=await a.json();i.debug("Polling access token response:",l);let{access_token:c}=l;if(c)return c;await A(t)}catch(a){if(a instanceof Error&&a.name==="AbortError"){i.error("Access token polling timed out"),await A(t);continue}throw a}finally{clearTimeout(r)}}}let N,H=!1,$,O;function Ae(){i.debug("Cleaning up token management"),N&&=(clearInterval(N),void 0),$&&=(v.off("online",$),void 0),O&&=(v.off("offline",O),void 0)}const $e=()=>C.readFile(w.GITHUB_TOKEN_PATH,"utf8"),Oe=e=>C.writeFile(w.GITHUB_TOKEN_PATH,e),Ee=async()=>{let{token:e,refresh_in:t}=await z();s.copilotToken=e,i.debug("GitHub Copilot Token fetched successfully!"),s.showToken&&i.info("Copilot token:",e);let o=(t-60)*1e3,n=async(r=5,a=1e3,l="scheduled")=>{if(H){i.debug("Service refresh already in progress,skipping");return}H=!0;try{for(let c=1;c<=r;c++)try{i.debug(`Refreshing Copilot token (${l},attempt ${c}/${r})`);let{token:u}=await z();s.copilotToken=u,i.debug("Copilot token refreshed successfully"),s.showToken&&i.info("Refreshed Copilot token:",u);return}catch(u){let f=c===r;if(i.error(`Failed to refresh Copilot token (attempt ${c}/${r}):`,u),f){i.error("All token refresh attempts failed. Service may be unavailable until next scheduled refresh.");return}let d=a*2**(c-1);i.debug(`Retrying token refresh in ${d}ms...`),await new Promise(p=>setTimeout(p,d))}}finally{H=!1}};N=setInterval(()=>{n(5,1e3,"scheduled").catch(r=>{i.error("Unexpected error in scheduled token refresh:",r)})},o),v.start(),$=()=>{i.debug("Network status restored,attempting immediate token refresh"),n(3,500,"network-restored").catch(r=>{i.error("Unexpected error in network-restored token refresh:",r)})},O=()=>{i.debug("Network status lost")},v.on("online",$),v.on("offline",O)};async function q(e){try{let t=await $e();if(t&&!e?.force){s.githubToken=t,s.showToken&&i.info("GitHub token:",t),await Y();return}i.info("Authentication required");let o=await Te();i.debug("Device code response:",o),i.info(`Please enter the code "${o.user_code}" in ${o.verification_uri}`);let n=await Ie(o);await Oe(n),s.githubToken=n,s.showToken&&i.info("GitHub token:",n),await Y()}catch(t){throw t instanceof y?(i.error("Failed to get GitHub token:",await t.response.json()),t):(i.error("Failed to get GitHub token:",t),t)}}async function Y(){let e=await pe();i.info(`Logged in as ${e.login}`)}async function Pe(e){e.verbose&&(i.level=5,i.info("Verbose logging enabled")),s.showToken=e.showToken,await j(),await q({force:!0}),i.success("GitHub token written to",w.GITHUB_TOKEN_PATH)}const je=T({meta:{name:"auth",description:"Run GitHub auth flow without running the server"},args:{verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"show-token":{type:"boolean",default:!1,description:"Show GitHub token on auth"}},run({args:e}){return Pe({verbose:e.verbose,showToken:e["show-token"]})}}),Z=async()=>{let e=new AbortController,t=s.timeoutMs??12e4,o=setTimeout(()=>{e.abort()},t);try{let n=await fetch(`${G}/\u0063\u006f\u0070\u0069\u006c\u006f\u0074_internal/user`,{headers:J(s),signal:e.signal});if(!n.ok)throw new y("Failed to get Copilot usage",n);return await n.json()}finally{clearTimeout(o)}},Ne=T({meta:{name:"check-usage",description:"Show current GitHub Copilot usage/quota information"},async run(){await j(),await q();try{let c=function(p,_){if(!_)return`${p}:N/A`;let h=_.entitlement,M=h-_.remaining,ce=h>0?M/h*100:0,ue=_.percent_remaining;return`${p}:${M}/${h} used (${ce.toFixed(1)}% used,${ue.toFixed(1)}% remaining)`};var e=c;let t=await Z(),o=t.quota_snapshots.premium_interactions,n=o.entitlement,r=n-o.remaining,a=n>0?r/n*100:0,l=o.percent_remaining,u=`Premium:${r}/${n} used (${a.toFixed(1)}% used,${l.toFixed(1)}% remaining)`,f=c("Chat",t.quota_snapshots.chat),d=c("Completions",t.quota_snapshots.completions);i.box(`Copilot Usage (plan:${t.copilot_plan})Quota resets:${t.quota_reset_date}Quotas:${u} ${f} ${d}`)}catch(t){i.error("Failed to fetch Copilot usage:",t),process.exit(1)}}});async function He(){try{let e=new URL("../package.json",import.meta.url).pathname,t=await C.readFile(e);return JSON.parse(t.toString()).version}catch{return"unknown"}}function qe(){let e=typeof Bun<"u";return{name:e?"bun":"node",version:e?Bun.version:process.version.slice(1),platform:K.platform(),arch:K.arch()}}async function Fe(){try{return(await C.stat(w.GITHUB_TOKEN_PATH)).isFile()?(await C.readFile(w.GITHUB_TOKEN_PATH,"utf8")).trim().length>0:!1}catch{return!1}}async function De(){let[e,t]=await Promise.all([He(),Fe()]);return{version:e,runtime:qe(),paths:{APP_DIR:w.APP_DIR,GITHUB_TOKEN_PATH:w.GITHUB_TOKEN_PATH},tokenExists:t}}function Ue(e){i.info(`copilot-api debugVersion:${e.version}Runtime:${e.runtime.name} ${e.runtime.version} (${e.runtime.platform} ${e.runtime.arch})Paths:- APP_DIR:${e.paths.APP_DIR}- GITHUB_TOKEN_PATH:${e.paths.GITHUB_TOKEN_PATH}Token exists:${e.tokenExists?"Yes":"No"}`)}function Be(e){console.log(JSON.stringify(e,null,2))}async function Me(e){let t=await De();e.json?Be(t):Ue(t)}const Ge=T({meta:{name:"debug",description:"Print debug information about the application"},args:{json:{type:"boolean",default:!1,description:"Output debug information as JSON"}},run({args:e}){return Me({json:e.json})}});function Re(){let{platform:e,ppid:t,env:o}=g;if(e==="win32"){try{let n=`wmic process get ParentProcessId,Name | findstr "${t}"`;if(we(n,{stdio:"pipe"}).toString().toLowerCase().includes("powershell.exe"))return"powershell"}catch{return"cmd"}return"cmd"}else{let n=o.SHELL;if(n){if(n.endsWith("zsh"))return"zsh";if(n.endsWith("fish"))return"fish";if(n.endsWith("bash"))return"bash"}return"sh"}}function Le(e,t=""){let o=Re(),n=Object.entries(e).filter(([,a])=>a!==void 0),r;switch(o){case"powershell":r=n.map(([a,l])=>`$env:${a} =${l}`).join(";");break;case"cmd":r=n.map(([a,l])=>`set ${a}=${l}`).join(" & ");break;case"fish":r=n.map(([a,l])=>`set -gx ${a} ${l}`).join(";");break;default:{let a=n.map(([l,c])=>`${l}=${c}`).join(" ");r=n.length>0?`export ${a}`:"";break}}return r&&t?`${r}${o==="cmd"?" & ":" && "}${t}`:r||t}function Je(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function We(){return async(e,t)=>{let o=Date.now(),n=Je();e.set("requestId",n),e.header("x-request-id",n),S.registerCompletion(n,e,o),await t(),e.get("requestData")?.tokenUsage&&S.executeCompletion(n)}}const ee=async()=>{if(!await i.prompt("Accept incoming request?",{type:"confirm"}))throw new y("Request rejected",Response.json({message:"Request rejected"},{status:403}))},te={input:3e-6,output:15e-6};function b(e){let t=e.prompt_tokens||0,o=e.completion_tokens||0,n=e.total_tokens||t+o,r=t*te.input+o*te.output;return{inputTokens:t,outputTokens:o,totalTokens:n,estimatedCost:r,cachedTokens:e.prompt_tokens_details?.cached_tokens,acceptedPredictionTokens:e.completion_tokens_details?.accepted_prediction_tokens,rejectedPredictionTokens:e.completion_tokens_details?.rejected_prediction_tokens}}async function ne(e){if(e.rateLimitSeconds===void 0)return;let t=Date.now();if(!e.lastRequestTimestamp){e.lastRequestTimestamp=t;return}let o=(t-e.lastRequestTimestamp)/1e3;if(o>e.rateLimitSeconds){e.lastRequestTimestamp=t;return}let n=Math.ceil(e.rateLimitSeconds-o);if(!e.rateLimitWait)throw i.warn(`Rate limit exceeded. Need to wait ${n} more seconds.`),new y("Rate limit exceeded",Response.json({message:"Rate limit exceeded"},{status:429}));let r=n*1e3;i.warn(`Rate limit reached. Waiting ${n} seconds before proceeding...`),await A(r),e.lastRequestTimestamp=t,i.info("Rate limit wait completed,proceeding with request")}function Ke(e){let t=e,o=String.fromCodePoint(27),n=t.split(o);if(n.length>1){t=n[0];for(let r=1;r<n.length;r++){let a=n[r],l=a.match(/^\[[0-9;]*[a-z]/i);t+=l?a.slice(l[0].length):o+a}}return t.replaceAll(/[\u200B-\u200D\uFEFF]/g,"").replaceAll(/[\u2060-\u2064]/g,"").replaceAll(/[\u206A-\u206F]/g,"").replaceAll(/[\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/g,"").replaceAll(/[\uFFF0-\uFFFF]/g,"").replaceAll(/[\x00-\x08\v\f\x0E-\x1F]/g,"")}function F(e){if(typeof e=="string")return Ke(e);if(Array.isArray(e))return e.map(o=>F(o));if(e&&typeof e=="object"){let t={};for(let[o,n]of Object.entries(e))t[o]=F(n);return t}return e}const oe=async e=>{if(!s.copilotToken)throw Error("\u0043\u006f\u0070\u0069\u006c\u006f\u0074\u0020\u0074\u006f\u006b\u0065\u006e\u0020\u006e\u006f\u0074\u0020\u0066\u006f\u0075\u006e\u0064");let t=F(e),o=t.messages.some(u=>typeof u.content!="string"&&u.content?.some(f=>f.type==="image_url")),n=t.messages.some(u=>["assistant","tool"].includes(u.role)),r={...P(s,o),"X-Initiator":n?"agent":"user"},a=new AbortController,l=s.timeoutMs??12e4,c=setTimeout(()=>{a.abort()},l);try{let{statusCode:u,headers:f,body:d}=await _e(`${E(s)}/\u0063\u0068\u0061\u0074\u002f\u0063\u006f\u006d\u0070\u006c\u0065\u0074\u0069\u006f\u006e\u0073`,{method:"POST",headers:r,body:JSON.stringify(t),signal:a.signal,headersTimeout:l,bodyTimeout:l*3}),p=new Response(d,{status:u,headers:f});if(!p.ok)throw new y("Failed to create chat completions",p);return t.stream?be(p):await p.json()}finally{clearTimeout(c)}};async function Ve(e){await ne(s);let t=await e.req.json();if(i.debug("Request data:",JSON.stringify(t).slice(-400)),e.set("requestData",{model:t.model}),s.manualApprove&&await ee(),xe(t.max_tokens)){let a=s.models?.data.find(l=>l.id===t.model);t={...t,max_tokens:a?.capabilities.limits.max_output_tokens},i.debug("Set max_tokens to:",JSON.stringify(t.max_tokens))}let o=performance.now(),n=await oe(t),r=performance.now()-o;if(ze(n)){let a=e.get("requestData")||{};return n.usage&&(a.tokenUsage=b(n.usage)),a.copilotDuration=r,e.set("requestData",a),i.debug("Response data:",JSON.stringify(n)),e.json(n)}return V(e,async a=>{let l=null;for await(let u of n){let f=u;if(u.data&&u.data!=="[DONE]")try{let d=JSON.parse(u.data);if(d.usage){l=d.usage;let p=e.get("requestData")||{};p.tokenUsage=b(l),p.copilotDuration=r,e.set("requestData",p)}if(d.usage?.prompt_tokens_details?.cached_tokens!==void 0){let p={...d,usage:{...d.usage,prompt_tokens_details:void 0}};f={...u,data:JSON.stringify(p)}}}catch{}await a.writeSSE(f)}if(l){let u=e.get("requestData")||{};u.tokenUsage||(u.tokenUsage=b(l),u.copilotDuration=r,e.set("requestData",u))}let c=e.get("requestId");c&&S.executeCompletion(c)})}const ze=e=>Object.hasOwn(e,"choices"),D=new k;D.post("/",async e=>{try{return await Ve(e)}catch(t){return await I(e,t)}});const Qe=async e=>{if(!s.copilotToken)throw Error("\u0043\u006f\u0070\u0069\u006c\u006f\u0074\u0020\u0074\u006f\u006b\u0065\u006e\u0020\u006e\u006f\u0074\u0020\u0066\u006f\u0075\u006e\u0064");let t=new AbortController,o=s.timeoutMs??12e4,n=setTimeout(()=>{t.abort()},o);try{let r=await fetch(`${E(s)}/embeddings`,{method:"POST",headers:P(s),body:JSON.stringify(e),signal:t.signal});if(!r.ok)throw new y("Failed to create embeddings",r);return await r.json()}finally{clearTimeout(n)}},U=new k;U.post("/",async e=>{try{let t=await e.req.json();e.set("requestData",{model:t.model});let o=performance.now(),n=await Qe(t),r=performance.now()-o,a=e.get("requestData")||{};return a.tokenUsage=b(n.usage),a.copilotDuration=r,e.set("requestData",a),e.json(n)}catch(t){return await I(e,t)}});function ie(e){return e===null?null:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"end_turn"}[e]}function Xe(e){return{model:Ye(e.model),messages:Ze(e.messages,e.system),max_tokens:e.max_tokens,stop:e.stop_sequences,stream:e.stream,temperature:e.temperature,top_p:e.top_p,user:e.metadata?.user_id,tools:ot(e.tools),tool_choice:it(e.tool_choice)}}function Ye(e){return e.startsWith("claude-sonnet-4-")?e.replace(/^claude-sonnet-4-.*/,"claude-sonnet-4"):e.startsWith("claude-opus-")?e.replace(/^claude-opus-4-.*/,"claude-opus-4"):e}function Ze(e,t){let o=et(t),n=e.flatMap(r=>r.role==="user"?tt(r):nt(r));return[...o,...n]}function et(e){return e?typeof e=="string"?[{role:"system",content:e}]:[{role:"system",content:e.map(o=>o.text).join(``)}]:[]}function tt(e){let t=[];if(Array.isArray(e.content)){let o=e.content.filter(r=>r.type==="tool_result"),n=e.content.filter(r=>r.type!=="tool_result");for(let r of o)t.push({role:"tool",tool_call_id:r.tool_use_id,content:x(r.content)});n.length>0&&t.push({role:"user",content:x(n)})}else t.push({role:"user",content:x(e.content)});return t}function nt(e){if(!Array.isArray(e.content))return[{role:"assistant",content:x(e.content)}];let t=e.content.filter(a=>a.type==="tool_use"),o=e.content.filter(a=>a.type==="text"),n=e.content.filter(a=>a.type==="thinking"),r=[...o.map(a=>a.text),...n.map(a=>a.thinking)].join(``);return t.length>0?[{role:"assistant",content:r||null,tool_calls:t.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}}))}]:[{role:"assistant",content:x(e.content)}]}function x(e){if(typeof e=="string")return e;if(!Array.isArray(e))return null;if(!e.some(n=>n.type==="image"))return e.filter(n=>n.type==="text"||n.type==="thinking").map(n=>n.type==="text"?n.text:n.thinking).join(``);let o=[];for(let n of e)switch(n.type){case"text":o.push({type:"text",text:n.text});break;case"thinking":o.push({type:"text",text:n.thinking});break;case"image":o.push({type:"image_url",image_url:{url:`data:${n.source.media_type};base64,${n.source.data}`}});break}return o}function ot(e){if(e)return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.input_schema}}))}function it(e){if(e)switch(e.type){case"auto":return"auto";case"any":return"required";case"tool":return e.name?{type:"function",function:{name:e.name}}:void 0;case"none":return"none";default:return}}function at(e){let t=[],o=[],n=null;n=e.choices[0]?.finish_reason??n;for(let r of e.choices){let a=rt(r.message.content),l=st(r.message.tool_calls);t.push(...a),o.push(...l),(r.finish_reason==="tool_calls"||n==="stop")&&(n=r.finish_reason)}return{id:e.id,type:"message",role:"assistant",model:e.model,content:[...t,...o],stop_reason:ie(n),stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}}}function rt(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>({type:"text",text:t.text})):[]}function st(e){return e?e.map(t=>({type:"tool_use",id:t.id,name:t.function.name,input:JSON.parse(t.function.arguments)})):[]}function lt(e){return e.contentBlockOpen?Object.values(e.toolCalls).some(t=>t.anthropicBlockIndex===e.contentBlockIndex):!1}function ct(e,t){let o=[];if(e.choices.length===0)return o;let n=e.choices[0],{delta:r}=n;if(t.messageStartSent||=(o.push({type:"message_start",message:{id:e.id,type:"message",role:"assistant",content:[],model:e.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:0}}}),!0),r.content&&(lt(t)&&(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,t.contentBlockOpen=!1),t.contentBlockOpen||=(o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),!0),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:r.content}})),r.tool_calls)for(let a of r.tool_calls){if(a.id&&a.function?.name){t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,!1);let l=t.contentBlockIndex;t.toolCalls[a.index]={id:a.id,name:a.function.name,anthropicBlockIndex:l},o.push({type:"content_block_start",index:l,content_block:{type:"tool_use",id:a.id,name:a.function.name,input:{}}}),t.contentBlockOpen=!0}if(a.function?.arguments){let l=t.toolCalls[a.index];l&&o.push({type:"content_block_delta",index:l.anthropicBlockIndex,delta:{type:"input_json_delta",partial_json:a.function.arguments}})}}return n.finish_reason&&(t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),!1),o.push({type:"message_delta",delta:{stop_reason:ie(n.finish_reason),stop_sequence:null},usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}},{type:"message_stop"})),o}async function ut(e){await ne(s);let t=await e.req.json();i.debug("API request payload:",JSON.stringify(t));let o=Xe(t);i.debug("Processed API request payload:",JSON.stringify(o)),e.set("requestData",{model:o.model});let n=performance.now();s.manualApprove&&await ee();let r=await oe(o),a=performance.now()-n;if(dt(r)){let l=e.get("requestData")||{};r.usage&&(l.tokenUsage=b(r.usage)),l.copilotDuration=a,e.set("requestData",l),i.debug("Non-streaming response from Copilot:",JSON.stringify(r).slice(-400));let c=at(r);return i.debug("Processed API response:",JSON.stringify(c)),e.json(c)}return i.debug("Streaming response from service"),V(e,async l=>{let c=null,u={messageStartSent:!1,contentBlockIndex:0,contentBlockOpen:!1,toolCalls:{}};for await(let d of r){if(i.debug("Copilot raw stream event:",JSON.stringify(d)),d.data==="[DONE]")break;if(!d.data)continue;let p=JSON.parse(d.data);if(p.usage){c=p.usage;let h=e.get("requestData")||{};h.tokenUsage=b(c),h.copilotDuration=a,e.set("requestData",h)}let _=ct(p,u);for(let h of _)i.debug("Processed API event:",JSON.stringify(h)),await l.writeSSE({event:h.type,data:JSON.stringify(h)})}if(c){let d=e.get("requestData")||{};d.tokenUsage||(d.tokenUsage=b(c),d.copilotDuration=a,e.set("requestData",d))}let f=e.get("requestId");f&&S.executeCompletion(f)})}const dt=e=>Object.hasOwn(e,"choices"),ae=new k;ae.post("/",async e=>{try{return await ut(e)}catch(t){return await I(e,t)}});const B=new k;B.get("/",async e=>{try{s.models||await X();let t=s.models?.data.map(o=>({id:o.id,object:"model",type:"model",created:0,created_at:new Date(0).toISOString(),owned_by:o.vendor,display_name:o.name,context_length:o.capabilities.limits?.max_context_window_tokens}));return e.json({object:"list",data:t,has_more:!1})}catch(t){return await I(e,t)}});const re=new k;re.get("/",e=>{try{return e.json({token:s.copilotToken})}catch(t){return console.error("Error fetching token:",t),e.json({error:"Failed to fetch token",token:null},500)}});const se=new k;se.get("/",async e=>{try{let t=await Z();return e.json(t)}catch(t){return console.error("Error fetching Copilot usage:",t),e.json({error:"Failed to fetch Copilot usage"},500)}});const m=new k;m.use(We()),m.use(ke()),m.get("/",e=>e.text("Server running")),m.route("/chat/completions",D),m.route("\u002f\u006d\u006f\u0064\u0065\u006c\u0073",B),m.route("\u002f\u0065\u006d\u0062\u0065\u0064\u0064\u0069\u006e\u0067\u0073",U),m.route("/usage",se),m.route("/token",re),m.route("\u002f\u0076\u0031\u002f\u0063\u0068\u0061\u0074\u002f\u0063\u006f\u006d\u0070\u006c\u0065\u0074\u0069\u006f\u006e\u0073",D),m.route("\u002f\u0076\u0031\u002f\u006d\u006f\u0064\u0065\u006c\u0073",B),m.route("\u002f\u0076\u0031\u002f\u0065\u006d\u0062\u0065\u0064\u0064\u0069\u006e\u0067\u0073",U),m.route("\u002f\u0076\u0031\u002f\u006d\u0065\u0073\u0073\u0061\u0067\u0065\u0073",ae),m.post("/v1/messages/count_tokens",e=>e.json({input_tokens:1}));const le=[];function pt(){let e=async()=>{i.info("Gracefully shutting down...");for(let t of le)try{await t()}catch(o){i.error("Error during cleanup:",o)}i.info("Shutdown complete"),g.exit(0)};g.on("SIGINT",e),g.on("SIGTERM",e),g.on("uncaughtException",t=>{i.error("Uncaught exception:",t),e().finally(()=>g.exit(1))}),g.on("unhandledRejection",(t,o)=>{i.error("Unhandled promise rejection at:",o,"reason:",t),e().finally(()=>g.exit(1))})}async function mt(e,t){if(!e.claudeCode)return;ye(s.models,"Models should be loaded by now");let o,n;if(e.model&&e.smallModel){let a=s.models.data.map(l=>l.id);a.includes(e.model)||(i.error(`Invalid model:${e.model}`),i.info(`Available models:${a.join(``)}`),g.exit(1)),a.includes(e.smallModel)||(i.error(`Invalid small model:${e.smallModel}`),i.info(`Available models:${a.join(``)}`),g.exit(1)),o=e.model,n=e.smallModel,i.info(`Using model:${o}`),i.info(`Using small model:${n}`)}else e.model||e.smallModel?(i.error("Both --model and --small-model must be specified when using command-line model selection"),g.exit(1)):(o=await i.prompt("Select a model to use with Claude Code",{type:"select",options:s.models.data.map(a=>a.id)}),n=await i.prompt("Select a small model to use with Claude Code",{type:"select",options:s.models.data.map(a=>a.id)}));let r=Le({ANTHROPIC_BASE_URL:t,ANTHROPIC_AUTH_TOKEN:"dummy",ANTHROPIC_MODEL:o,ANTHROPIC_SMALL_FAST_MODEL:n},"claude");try{he.writeSync(r),i.success("Copied Claude Code command to clipboard!")}catch{i.warn("Failed to copy to clipboard. Here is the Claude Code command:"),i.log(r)}}async function ft(e){pt(),le.push(()=>{i.debug("Cleaning up connectivity monitor"),v.stop()},()=>{i.debug("Cleaning up token management"),Ae()}),e.verbose&&(i.level=5,i.info("Verbose logging enabled")),s.accountType=e.accountType,e.accountType!=="individual"&&i.info(`Using ${e.accountType} plan GitHub account`),s.manualApprove=e.manual,s.rateLimitSeconds=e.rateLimit,s.rateLimitWait=e.rateLimitWait,s.showToken=e.showToken,s.timeoutMs=e.timeout,s.connectivity.enabled=!e.disableConnectivityMonitoring,await j(),Se(),e.githubToken?(s.githubToken=e.githubToken,i.info("Using provided auth token")):await q();try{let{getGitHubUser:o}=await import("./get-user-BT-kLu95.js"),n=await o();await me(s,n.login)}catch(o){i.error("Failed to get GitHub user info for machine ID generation:",o),i.error("Cannot proceed without GitHub user information"),g.exit(1)}await Ee(),await X(),i.info("Available services:");for(let o of s.models?.data??[]){let n=o.capabilities.limits?.max_context_window_tokens,r=n?` (${n.toLocaleString()} tokens)`:"";i.info(`- ${o.id}${r}`)}let t=`http://localhost:${e.port}`;await mt(e,t),i.box(`\u{1F310} Usage Viewer:https://ericc-ch.\u0067\u0069\u0074\u0068\u0075\u0062.io/copilot-api?endpoint=${t}/usage`),ge({fetch:m.fetch,port:e.port})}const ht=T({meta:{name:"start",description:"Start the Copilot API server"},args:{port:{alias:"p",type:"string",default:"4141",description:"Port to listen on"},verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"account-type":{alias:"a",type:"string",default:"individual",description:"Account type to use (individual,business,enterprise)"},manual:{type:"boolean",default:!1,description:"Enable manual request approval"},"rate-limit":{alias:"r",type:"string",description:"Rate limit in seconds between requests"},wait:{alias:"w",type:"boolean",default:!1,description:"Wait instead of error when rate limit is hit. Has no effect if rate limit is not set"},"\u0067\u0069\u0074\u0068\u0075\u0062\u002d\u0074\u006f\u006b\u0065\u006e":{alias:"g",type:"string",description:"Provide GitHub token directly (must be generated using the `auth` subcommand)"},"claude-code":{alias:"c",type:"boolean",default:!1,description:"Generate a command to launch Claude Code with Copilot API config"},model:{alias:"m",type:"string",description:"Model to use with Claude Code (requires --claude-code)"},"small-model":{alias:"s",type:"string",description:"Small/fast model to use with Claude Code (requires --claude-code)"},"show-token":{type:"boolean",default:!1,description:"Show GitHub and Copilot tokens on fetch and refresh"},timeout:{alias:"t",type:"string",description:"API timeout in milliseconds (default:120000)"},"disable-connectivity-monitoring":{type:"boolean",default:!1,description:"Disable automatic network connectivity monitoring for token refresh"}},run({args:e}){let t=e["rate-limit"],o=t===void 0?void 0:Number.parseInt(t,10),n=e.timeout,r=n===void 0?12e4:Number.parseInt(n,10);return ft({port:Number.parseInt(e.port,10),verbose:e.verbose,accountType:e["account-type"],manual:e.manual,rateLimit:o,rateLimitWait:e.wait,githubToken:e["\u0067\u0069\u0074\u0068\u0075\u0062\u002d\u0074\u006f\u006b\u0065\u006e"],claudeCode:e["claude-code"],model:e.model,smallModel:e["small-model"],showToken:e["show-token"],timeout:r,disableConnectivityMonitoring:e["disable-connectivity-monitoring"]})}}),gt=T({meta:{name:"\u0063\u006f\u0070\u0069\u006c\u006f\u0074\u002d\u0061\u0070\u0069",description:"A wrapper around GitHub Copilot API to make it OpenAI compatible,making it usable for other tools."},subCommands:{auth:je,start:ht,"check-usage":Ne,debug:Ge}});await fe(gt);
|