xiaodcs-copilot-api 2.1.0-recovery.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +839 -0
- package/README.zh-CN.md +888 -0
- package/dist/auth-BB3ETAFy.js +2 -0
- package/dist/auth-KY033tLZ.js +355 -0
- package/dist/config-RMZKaZqy.js +456 -0
- package/dist/debug-kE2HCJrP.js +90 -0
- package/dist/electron-fetch-DPhDE6JE.js +20 -0
- package/dist/main.js +43 -0
- package/dist/mcp-BG6fpi6q.js +35 -0
- package/dist/models-Du754vZc.js +88 -0
- package/dist/server-J_CROZdx.js +10893 -0
- package/dist/start-DQZDepT-.js +523 -0
- package/dist/tls-BmWaOfKV.js +14 -0
- package/dist/token--3EQGrXj.js +1503 -0
- package/dist/tool-search-Ds1vbmGG.js +114 -0
- package/package.json +94 -0
- package/pages/index.html +2113 -0
|
@@ -0,0 +1,1503 @@
|
|
|
1
|
+
import { A as isResponsesApiWebSocketEnabled, M as PATHS, c as setProviderConfig, n as getRawProviderConfig } from "./config-RMZKaZqy.js";
|
|
2
|
+
import consola from "consola";
|
|
3
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
4
|
+
import fs, { readFile } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { createServer } from "node:http";
|
|
7
|
+
import { events } from "fetch-event-stream";
|
|
8
|
+
import { getProxyForUrl } from "proxy-from-env";
|
|
9
|
+
import { WebSocket } from "undici";
|
|
10
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
12
|
+
import { exec } from "node:child_process";
|
|
13
|
+
//#region src/lib/error.ts
|
|
14
|
+
var HTTPError = class extends Error {
|
|
15
|
+
response;
|
|
16
|
+
constructor(message, response) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.response = response;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
async function forwardError(c, error) {
|
|
22
|
+
consola.error("Error occurred:", error);
|
|
23
|
+
if (error instanceof HTTPError) {
|
|
24
|
+
if (error.response.status === 429) for (const [name, value] of error.response.headers) {
|
|
25
|
+
const lowerName = name.toLowerCase();
|
|
26
|
+
if (lowerName === "retry-after" || lowerName.startsWith("x-")) c.header(name, value);
|
|
27
|
+
}
|
|
28
|
+
const errorText = await error.response.text();
|
|
29
|
+
let errorJson;
|
|
30
|
+
try {
|
|
31
|
+
errorJson = JSON.parse(errorText);
|
|
32
|
+
} catch {
|
|
33
|
+
errorJson = errorText;
|
|
34
|
+
}
|
|
35
|
+
consola.error("HTTP error:", errorJson);
|
|
36
|
+
return c.json({ error: {
|
|
37
|
+
message: errorText,
|
|
38
|
+
type: "error"
|
|
39
|
+
} }, error.response.status);
|
|
40
|
+
}
|
|
41
|
+
return c.json({ error: {
|
|
42
|
+
message: error.message,
|
|
43
|
+
type: "error"
|
|
44
|
+
} }, 500);
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/lib/state.ts
|
|
48
|
+
const state = {
|
|
49
|
+
accountType: "individual",
|
|
50
|
+
showToken: false,
|
|
51
|
+
verbose: false,
|
|
52
|
+
vsCodeDeviceId: randomUUID()
|
|
53
|
+
};
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/services/responses-websocket.ts
|
|
56
|
+
const DEFAULT_WEBSOCKET_IDLE_TIMEOUT_MS = 6e4;
|
|
57
|
+
const websocketPool = /* @__PURE__ */ new Map();
|
|
58
|
+
const websocketActiveRequests = /* @__PURE__ */ new Map();
|
|
59
|
+
const createWebSocketUrl = (url) => {
|
|
60
|
+
const websocketUrl = new URL(url);
|
|
61
|
+
if (websocketUrl.protocol === "https:") websocketUrl.protocol = "wss:";
|
|
62
|
+
else if (websocketUrl.protocol === "http:") websocketUrl.protocol = "ws:";
|
|
63
|
+
return websocketUrl.toString();
|
|
64
|
+
};
|
|
65
|
+
const createPooledWebSocketStream = (request, options) => runPooledWebSocketRequest(request, options);
|
|
66
|
+
const runPooledWebSocketRequest = async function* (request, options) {
|
|
67
|
+
const { entry, pooled } = getPooledWebSocketRequestTarget(request, options);
|
|
68
|
+
const release = acquirePooledWebSocketEntry(request.poolKey, entry, pooled, options);
|
|
69
|
+
try {
|
|
70
|
+
const websocket = await getReadyPooledWebSocket(request.poolKey, entry, pooled, options);
|
|
71
|
+
websocket.send(JSON.stringify(request.payload));
|
|
72
|
+
for await (const data of createWebSocketMessageStream(websocket, options)) {
|
|
73
|
+
const chunk = options.createChunk(data);
|
|
74
|
+
yield chunk;
|
|
75
|
+
if (options.isTerminalChunk(chunk)) return;
|
|
76
|
+
}
|
|
77
|
+
removePooledWebSocketEntry(request.poolKey, entry);
|
|
78
|
+
throw new Error(options.terminalChunkMissingMessage);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
removePooledWebSocketEntry(request.poolKey, entry);
|
|
81
|
+
throw toError(error);
|
|
82
|
+
} finally {
|
|
83
|
+
release();
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const getPooledWebSocketRequestTarget = (request, options) => {
|
|
87
|
+
if (getPooledWebSocketActiveRequestCount(request.poolKey) > 0) return {
|
|
88
|
+
entry: createPooledWebSocketEntry(request, options),
|
|
89
|
+
pooled: false
|
|
90
|
+
};
|
|
91
|
+
const existing = websocketPool.get(request.poolKey);
|
|
92
|
+
if (existing && !existing.closed) {
|
|
93
|
+
consola.debug("websocket from pool");
|
|
94
|
+
clearPooledWebSocketIdleTimer(existing);
|
|
95
|
+
return {
|
|
96
|
+
entry: existing,
|
|
97
|
+
pooled: true
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const entry = createPooledWebSocketEntry(request, options);
|
|
101
|
+
websocketPool.set(request.poolKey, entry);
|
|
102
|
+
return {
|
|
103
|
+
entry,
|
|
104
|
+
pooled: true
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
const createPooledWebSocketEntry = (request, options) => {
|
|
108
|
+
const entry = {
|
|
109
|
+
closed: false,
|
|
110
|
+
idleTimer: null,
|
|
111
|
+
requestCount: 0,
|
|
112
|
+
websocketPromise: openWebSocket({
|
|
113
|
+
headers: request.headers,
|
|
114
|
+
openErrorMessage: options.openErrorMessage,
|
|
115
|
+
url: request.url
|
|
116
|
+
})
|
|
117
|
+
};
|
|
118
|
+
entry.websocketPromise.then((websocket) => {
|
|
119
|
+
websocket.addEventListener("close", () => {
|
|
120
|
+
removePooledWebSocketEntry(request.poolKey, entry);
|
|
121
|
+
});
|
|
122
|
+
websocket.addEventListener("error", () => {
|
|
123
|
+
removePooledWebSocketEntry(request.poolKey, entry);
|
|
124
|
+
});
|
|
125
|
+
}).catch(() => {
|
|
126
|
+
removePooledWebSocketEntry(request.poolKey, entry);
|
|
127
|
+
});
|
|
128
|
+
return entry;
|
|
129
|
+
};
|
|
130
|
+
const acquirePooledWebSocketEntry = (poolKey, entry, pooled, options) => {
|
|
131
|
+
clearPooledWebSocketIdleTimer(entry);
|
|
132
|
+
incrementPooledWebSocketActiveRequestCount(poolKey);
|
|
133
|
+
entry.requestCount += 1;
|
|
134
|
+
let released = false;
|
|
135
|
+
return () => {
|
|
136
|
+
if (released) return;
|
|
137
|
+
released = true;
|
|
138
|
+
entry.requestCount -= 1;
|
|
139
|
+
decrementPooledWebSocketActiveRequestCount(poolKey);
|
|
140
|
+
if (entry.closed || entry.requestCount > 0) return;
|
|
141
|
+
if (pooled && websocketPool.get(poolKey) === entry) {
|
|
142
|
+
schedulePooledWebSocketIdleClose(poolKey, entry, options);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
removePooledWebSocketEntry(poolKey, entry);
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
const getReadyPooledWebSocket = async (poolKey, entry, pooled, options) => {
|
|
149
|
+
const unavailableErrorMessage = options?.unavailableErrorMessage ?? "Websocket connection became unavailable before the request started";
|
|
150
|
+
if (entry.closed) throw new Error(unavailableErrorMessage);
|
|
151
|
+
const websocket = await entry.websocketPromise;
|
|
152
|
+
if (entry.closed || pooled && websocketPool.get(poolKey) !== entry) throw new Error(unavailableErrorMessage);
|
|
153
|
+
if (websocket.readyState !== WebSocket.OPEN) {
|
|
154
|
+
removePooledWebSocketEntry(poolKey, entry);
|
|
155
|
+
throw new Error(unavailableErrorMessage);
|
|
156
|
+
}
|
|
157
|
+
return websocket;
|
|
158
|
+
};
|
|
159
|
+
const schedulePooledWebSocketIdleClose = (poolKey, entry, options) => {
|
|
160
|
+
clearPooledWebSocketIdleTimer(entry);
|
|
161
|
+
entry.idleTimer = setTimeout(() => {
|
|
162
|
+
removePooledWebSocketEntry(poolKey, entry);
|
|
163
|
+
}, options.idleTimeoutMs ?? DEFAULT_WEBSOCKET_IDLE_TIMEOUT_MS);
|
|
164
|
+
unrefTimer(entry.idleTimer);
|
|
165
|
+
};
|
|
166
|
+
const clearPooledWebSocketIdleTimer = (entry) => {
|
|
167
|
+
if (entry.idleTimer) {
|
|
168
|
+
clearTimeout(entry.idleTimer);
|
|
169
|
+
entry.idleTimer = null;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const getPooledWebSocketActiveRequestCount = (poolKey) => websocketActiveRequests.get(poolKey) ?? 0;
|
|
173
|
+
const incrementPooledWebSocketActiveRequestCount = (poolKey) => {
|
|
174
|
+
websocketActiveRequests.set(poolKey, getPooledWebSocketActiveRequestCount(poolKey) + 1);
|
|
175
|
+
};
|
|
176
|
+
const decrementPooledWebSocketActiveRequestCount = (poolKey) => {
|
|
177
|
+
const nextCount = getPooledWebSocketActiveRequestCount(poolKey) - 1;
|
|
178
|
+
if (nextCount <= 0) {
|
|
179
|
+
websocketActiveRequests.delete(poolKey);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
websocketActiveRequests.set(poolKey, nextCount);
|
|
183
|
+
};
|
|
184
|
+
const removePooledWebSocketEntry = (poolKey, entry) => {
|
|
185
|
+
if (websocketPool.get(poolKey) === entry) websocketPool.delete(poolKey);
|
|
186
|
+
if (entry.closed) return;
|
|
187
|
+
entry.closed = true;
|
|
188
|
+
clearPooledWebSocketIdleTimer(entry);
|
|
189
|
+
entry.websocketPromise.then(closeWebSocket).catch(() => {});
|
|
190
|
+
};
|
|
191
|
+
const unrefTimer = (timer) => {
|
|
192
|
+
if (typeof timer === "object" && "unref" in timer && typeof timer.unref === "function") timer.unref();
|
|
193
|
+
};
|
|
194
|
+
const createWebSocketError = (message, event) => {
|
|
195
|
+
const reason = event?.error ?? event?.message;
|
|
196
|
+
if (reason === void 0 || reason === "") return new Error(message);
|
|
197
|
+
const cause = toError(reason);
|
|
198
|
+
return new Error(`${message}: ${cause.message}`, { cause });
|
|
199
|
+
};
|
|
200
|
+
const openWebSocket = async ({ headers, openErrorMessage, url }) => await new Promise((resolve, reject) => {
|
|
201
|
+
const proxy = typeof Bun === "undefined" ? void 0 : getProxyUrl(url);
|
|
202
|
+
const websocket = new WebSocket(url, {
|
|
203
|
+
headers,
|
|
204
|
+
...proxy ? { proxy } : {}
|
|
205
|
+
});
|
|
206
|
+
const cleanup = () => {
|
|
207
|
+
websocket.removeEventListener("open", onOpen);
|
|
208
|
+
websocket.removeEventListener("error", onError);
|
|
209
|
+
};
|
|
210
|
+
const onOpen = () => {
|
|
211
|
+
cleanup();
|
|
212
|
+
resolve(websocket);
|
|
213
|
+
};
|
|
214
|
+
const onError = (event) => {
|
|
215
|
+
cleanup();
|
|
216
|
+
reject(createWebSocketError(openErrorMessage, event));
|
|
217
|
+
};
|
|
218
|
+
websocket.addEventListener("open", onOpen);
|
|
219
|
+
websocket.addEventListener("error", onError);
|
|
220
|
+
});
|
|
221
|
+
const createWebSocketMessageStream = async function* (websocket, options) {
|
|
222
|
+
const queue = [];
|
|
223
|
+
let closed = false;
|
|
224
|
+
let error = null;
|
|
225
|
+
let notify = null;
|
|
226
|
+
const wake = () => {
|
|
227
|
+
notify?.();
|
|
228
|
+
notify = null;
|
|
229
|
+
};
|
|
230
|
+
const onMessage = (event) => {
|
|
231
|
+
queue.push(normalizeWebSocketMessageData(event.data));
|
|
232
|
+
wake();
|
|
233
|
+
};
|
|
234
|
+
const onClose = () => {
|
|
235
|
+
consola.debug("WebSocket closed");
|
|
236
|
+
closed = true;
|
|
237
|
+
wake();
|
|
238
|
+
};
|
|
239
|
+
const onError = (event) => {
|
|
240
|
+
consola.error("WebSocket error:", event, event.error);
|
|
241
|
+
error = createWebSocketError(options.streamErrorMessage, event);
|
|
242
|
+
wake();
|
|
243
|
+
};
|
|
244
|
+
websocket.addEventListener("message", onMessage);
|
|
245
|
+
websocket.addEventListener("close", onClose);
|
|
246
|
+
websocket.addEventListener("error", onError);
|
|
247
|
+
try {
|
|
248
|
+
while (true) {
|
|
249
|
+
const item = queue.shift();
|
|
250
|
+
if (item) {
|
|
251
|
+
yield await item;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (error) throw toError(error);
|
|
255
|
+
if (closed) break;
|
|
256
|
+
await new Promise((resolve) => {
|
|
257
|
+
notify = resolve;
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
} finally {
|
|
261
|
+
websocket.removeEventListener("message", onMessage);
|
|
262
|
+
websocket.removeEventListener("close", onClose);
|
|
263
|
+
websocket.removeEventListener("error", onError);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const normalizeWebSocketMessageData = async (data) => {
|
|
267
|
+
if (typeof data === "string") return data;
|
|
268
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
269
|
+
if (ArrayBuffer.isView(data)) {
|
|
270
|
+
const view = data;
|
|
271
|
+
return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
|
|
272
|
+
}
|
|
273
|
+
if (isTextReadable(data)) return await data.text();
|
|
274
|
+
return String(data);
|
|
275
|
+
};
|
|
276
|
+
const isTextReadable = (value) => {
|
|
277
|
+
if (!value || typeof value !== "object" || !("text" in value)) return false;
|
|
278
|
+
return typeof value.text === "function";
|
|
279
|
+
};
|
|
280
|
+
const toError = (value) => {
|
|
281
|
+
if (value instanceof Error) return value;
|
|
282
|
+
return new Error(String(value));
|
|
283
|
+
};
|
|
284
|
+
const closeWebSocket = (websocket) => {
|
|
285
|
+
if (websocket.readyState === WebSocket.CONNECTING || websocket.readyState === WebSocket.OPEN) websocket.close();
|
|
286
|
+
};
|
|
287
|
+
const getProxyUrl = (url) => {
|
|
288
|
+
return getProxyForUrl(url.replace(/^wss:/, "https:").replace(/^ws:/, "http:"));
|
|
289
|
+
};
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/services/responses-websocket-helpers.ts
|
|
292
|
+
const encodePoolKeyPart = (value) => encodeURIComponent(value);
|
|
293
|
+
const getErrorMessage = (error) => {
|
|
294
|
+
if (error instanceof Error && error.message) return error.message;
|
|
295
|
+
return String(error);
|
|
296
|
+
};
|
|
297
|
+
const createResponsesErrorServerSentEventChunk = (message) => {
|
|
298
|
+
const errorEvent = {
|
|
299
|
+
code: null,
|
|
300
|
+
message,
|
|
301
|
+
param: null,
|
|
302
|
+
sequence_number: 0,
|
|
303
|
+
type: "error"
|
|
304
|
+
};
|
|
305
|
+
return {
|
|
306
|
+
event: errorEvent.type,
|
|
307
|
+
data: JSON.stringify(errorEvent)
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
const isTerminalResponsesStreamChunk = (chunk) => {
|
|
311
|
+
if (!chunk.data || chunk.data === "[DONE]") return false;
|
|
312
|
+
try {
|
|
313
|
+
const parsed = JSON.parse(chunk.data);
|
|
314
|
+
return parsed.type === "response.completed" || parsed.type === "response.failed" || parsed.type === "response.incomplete" || parsed.type === "error";
|
|
315
|
+
} catch {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const createResponsesSafeStream = async function* (source) {
|
|
320
|
+
try {
|
|
321
|
+
yield* source;
|
|
322
|
+
} catch (error) {
|
|
323
|
+
yield createResponsesErrorServerSentEventChunk(getErrorMessage(error));
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
//#endregion
|
|
327
|
+
//#region src/lib/request-context.ts
|
|
328
|
+
const TRACE_ID_MAX_LENGTH = 64;
|
|
329
|
+
const TRACE_ID_PATTERN = /^\w[\w.-]*$/;
|
|
330
|
+
const asyncLocalStorage = new AsyncLocalStorage();
|
|
331
|
+
const requestContext = {
|
|
332
|
+
getStore: () => asyncLocalStorage.getStore(),
|
|
333
|
+
run: (context, callback) => asyncLocalStorage.run(context, callback)
|
|
334
|
+
};
|
|
335
|
+
function generateTraceId() {
|
|
336
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
337
|
+
}
|
|
338
|
+
function resolveTraceId(traceId) {
|
|
339
|
+
const candidate = traceId?.trim();
|
|
340
|
+
if (!candidate || candidate.length > TRACE_ID_MAX_LENGTH || !TRACE_ID_PATTERN.test(candidate)) return generateTraceId();
|
|
341
|
+
return candidate;
|
|
342
|
+
}
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/services/codex/create-responses.ts
|
|
345
|
+
const CODEX_API_BASE_URL = "https://chatgpt.com/backend-api";
|
|
346
|
+
const STRIPPED_CODEX_REQUEST_HEADERS = new Set([
|
|
347
|
+
"accept-encoding",
|
|
348
|
+
"authorization",
|
|
349
|
+
"cdn-loop",
|
|
350
|
+
"connection",
|
|
351
|
+
"content-length",
|
|
352
|
+
"host",
|
|
353
|
+
"keep-alive",
|
|
354
|
+
"proxy-authenticate",
|
|
355
|
+
"proxy-authorization",
|
|
356
|
+
"te",
|
|
357
|
+
"trailer",
|
|
358
|
+
"transfer-encoding",
|
|
359
|
+
"true-client-ip",
|
|
360
|
+
"upgrade",
|
|
361
|
+
"x-api-key",
|
|
362
|
+
"x-forwarded-for",
|
|
363
|
+
"x-forwarded-proto"
|
|
364
|
+
]);
|
|
365
|
+
const STRIPPED_CODEX_WEBSOCKET_HEADERS = new Set(["accept", "content-type"]);
|
|
366
|
+
const shouldForwardCodexRequestHeader = (headerName) => {
|
|
367
|
+
const headerNameLower = headerName.toLowerCase();
|
|
368
|
+
return !STRIPPED_CODEX_REQUEST_HEADERS.has(headerNameLower) && !headerNameLower.includes("trace") && !headerNameLower.startsWith("cf-");
|
|
369
|
+
};
|
|
370
|
+
const buildForwardedCodexRequestHeaders = (requestHeaders) => {
|
|
371
|
+
const headers = new Headers();
|
|
372
|
+
for (const [headerName, headerValue] of requestHeaders) if (shouldForwardCodexRequestHeader(headerName)) headers.set(headerName, headerValue);
|
|
373
|
+
return headers;
|
|
374
|
+
};
|
|
375
|
+
const setDefaultCodexHeader = (headers, headerName, headerValue) => {
|
|
376
|
+
if (!headers.has(headerName)) headers.set(headerName, headerValue);
|
|
377
|
+
};
|
|
378
|
+
const applyOpencodeCodexHeaders = (headers) => {
|
|
379
|
+
if (!headers.get("user-agent")?.startsWith("opencode")) return;
|
|
380
|
+
headers.set("originator", "opencode");
|
|
381
|
+
const sessionId = requestContext.getStore()?.sessionAffinity;
|
|
382
|
+
if (sessionId) headers.set("session-id", sessionId);
|
|
383
|
+
};
|
|
384
|
+
const requireCodexAuthContext = () => {
|
|
385
|
+
const accessToken = state.codexAccessToken;
|
|
386
|
+
const accountId = state.codexAccountId;
|
|
387
|
+
if (!accessToken) throw new Error("Codex access token is not loaded");
|
|
388
|
+
if (!accountId) throw new Error("Codex account id is not loaded");
|
|
389
|
+
return {
|
|
390
|
+
accessToken,
|
|
391
|
+
accountId
|
|
392
|
+
};
|
|
393
|
+
};
|
|
394
|
+
function resolveCodexResponsesUrl(baseUrl = CODEX_API_BASE_URL) {
|
|
395
|
+
const normalized = baseUrl.trim().replace(/\/+$/, "");
|
|
396
|
+
if (!normalized) return `${CODEX_API_BASE_URL}/codex/responses`;
|
|
397
|
+
if (normalized.endsWith("/codex/responses")) return normalized;
|
|
398
|
+
if (normalized.endsWith("/codex")) return `${normalized}/responses`;
|
|
399
|
+
return `${normalized}/codex/responses`;
|
|
400
|
+
}
|
|
401
|
+
function buildCodexResponsesHeaders(requestHeaders, options = {}) {
|
|
402
|
+
const headers = buildCodexRequestHeaders(requestHeaders);
|
|
403
|
+
setDefaultCodexHeader(headers, "accept", options.stream ? "text/event-stream" : "application/json");
|
|
404
|
+
setDefaultCodexHeader(headers, "content-type", "application/json");
|
|
405
|
+
return headers;
|
|
406
|
+
}
|
|
407
|
+
function buildCodexRequestHeaders(requestHeaders) {
|
|
408
|
+
const { accessToken, accountId } = requireCodexAuthContext();
|
|
409
|
+
const headers = buildForwardedCodexRequestHeaders(requestHeaders);
|
|
410
|
+
headers.set("authorization", `Bearer ${accessToken}`);
|
|
411
|
+
headers.set("chatgpt-account-id", accountId);
|
|
412
|
+
setDefaultCodexHeader(headers, "originator", "copilot-api");
|
|
413
|
+
setDefaultCodexHeader(headers, "user-agent", "copilot-api");
|
|
414
|
+
applyOpencodeCodexHeaders(headers);
|
|
415
|
+
return headers;
|
|
416
|
+
}
|
|
417
|
+
function resolveCodexResponsesTransport(transport) {
|
|
418
|
+
return transport ?? (isResponsesApiWebSocketEnabled() ? "websocket" : "http");
|
|
419
|
+
}
|
|
420
|
+
function buildCodexResponsesWebSocketHeaders(requestHeaders) {
|
|
421
|
+
const headers = buildCodexResponsesHeaders(requestHeaders);
|
|
422
|
+
setDefaultCodexHeader(headers, "openai-beta", "responses_websockets=2026-02-06");
|
|
423
|
+
for (const headerName of STRIPPED_CODEX_WEBSOCKET_HEADERS) headers.delete(headerName);
|
|
424
|
+
return Object.fromEntries(headers);
|
|
425
|
+
}
|
|
426
|
+
function buildCodexResponsesWebSocketPayload(payload) {
|
|
427
|
+
const websocketPayload = {
|
|
428
|
+
type: "response.create",
|
|
429
|
+
...normalizeCodexResponsesPayload(payload)
|
|
430
|
+
};
|
|
431
|
+
delete websocketPayload.stream;
|
|
432
|
+
return websocketPayload;
|
|
433
|
+
}
|
|
434
|
+
function buildCodexResponsesWebSocketUrl(baseUrl = CODEX_API_BASE_URL) {
|
|
435
|
+
return createWebSocketUrl(resolveCodexResponsesUrl(baseUrl));
|
|
436
|
+
}
|
|
437
|
+
function prepareCodexResponsesWebSocketRequest(payload, requestHeaders, baseUrl = CODEX_API_BASE_URL) {
|
|
438
|
+
const headers = buildCodexResponsesWebSocketHeaders(requestHeaders);
|
|
439
|
+
return {
|
|
440
|
+
headers,
|
|
441
|
+
payload: buildCodexResponsesWebSocketPayload(payload),
|
|
442
|
+
poolKey: buildCodexResponsesWebSocketPoolKey(payload, headers, baseUrl),
|
|
443
|
+
url: buildCodexResponsesWebSocketUrl(baseUrl)
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async function forwardCodexResponses(payload, requestHeaders, baseUrl = CODEX_API_BASE_URL, options = {}) {
|
|
447
|
+
consola.log(`<-- model: ${payload.model}`);
|
|
448
|
+
const transport = resolveCodexResponsesTransport(options.transport);
|
|
449
|
+
if (payload.stream && transport === "websocket") return forwardCodexResponsesOverWebSocket(payload, requestHeaders, baseUrl);
|
|
450
|
+
const normalizedPayload = normalizeCodexResponsesPayload(payload);
|
|
451
|
+
const response = await fetch(resolveCodexResponsesUrl(baseUrl), {
|
|
452
|
+
method: "POST",
|
|
453
|
+
headers: buildCodexResponsesHeaders(requestHeaders, { stream: normalizedPayload.stream }),
|
|
454
|
+
body: JSON.stringify(normalizedPayload)
|
|
455
|
+
});
|
|
456
|
+
if (!response.ok) throw new HTTPError("Failed to create codex responses", response);
|
|
457
|
+
if (normalizedPayload.stream) return events(response);
|
|
458
|
+
return await response.json();
|
|
459
|
+
}
|
|
460
|
+
const normalizeCodexResponsesPayload = (payload) => {
|
|
461
|
+
const normalizedPayload = {
|
|
462
|
+
...payload,
|
|
463
|
+
store: false
|
|
464
|
+
};
|
|
465
|
+
delete normalizedPayload.temperature;
|
|
466
|
+
delete normalizedPayload.top_p;
|
|
467
|
+
delete normalizedPayload.max_output_tokens;
|
|
468
|
+
delete normalizedPayload.metadata;
|
|
469
|
+
if (typeof normalizedPayload.instructions === "string" && normalizedPayload.instructions.trim().length > 0 || !Array.isArray(normalizedPayload.input)) return normalizedPayload;
|
|
470
|
+
const instructions = [];
|
|
471
|
+
let messageCount = 0;
|
|
472
|
+
const remainingInput = normalizedPayload.input.filter((inputItem) => {
|
|
473
|
+
const message = getResponseInputMessage(inputItem);
|
|
474
|
+
if (!message) return true;
|
|
475
|
+
messageCount += 1;
|
|
476
|
+
if (message.role !== "system" || messageCount > 3) return true;
|
|
477
|
+
const systemPrompt = getTextContent(message.content);
|
|
478
|
+
if (systemPrompt === void 0) return true;
|
|
479
|
+
if (systemPrompt.trim().length > 0) instructions.push(systemPrompt);
|
|
480
|
+
return false;
|
|
481
|
+
});
|
|
482
|
+
if (remainingInput.length === normalizedPayload.input.length) return normalizedPayload;
|
|
483
|
+
if (instructions.length > 0) normalizedPayload.instructions = instructions.join("\n\n");
|
|
484
|
+
if (remainingInput.length > 0) normalizedPayload.input = remainingInput;
|
|
485
|
+
else delete normalizedPayload.input;
|
|
486
|
+
return normalizedPayload;
|
|
487
|
+
};
|
|
488
|
+
const getResponseInputMessage = (inputItem) => {
|
|
489
|
+
if (typeof inputItem !== "object" || inputItem === null) return;
|
|
490
|
+
const { role, type } = inputItem;
|
|
491
|
+
if (typeof role !== "string" || type !== void 0 && type !== "message") return;
|
|
492
|
+
return inputItem;
|
|
493
|
+
};
|
|
494
|
+
const getTextContent = (content) => {
|
|
495
|
+
if (typeof content === "string") return content;
|
|
496
|
+
if (content === void 0) return "";
|
|
497
|
+
if (!Array.isArray(content)) return;
|
|
498
|
+
const textBlocks = [];
|
|
499
|
+
for (const contentBlock of content) {
|
|
500
|
+
const text = getTextBlock(contentBlock);
|
|
501
|
+
if (text === void 0) return;
|
|
502
|
+
if (text.length > 0) textBlocks.push(text);
|
|
503
|
+
}
|
|
504
|
+
return textBlocks.join("\n\n");
|
|
505
|
+
};
|
|
506
|
+
const getTextBlock = (contentBlock) => {
|
|
507
|
+
if (typeof contentBlock !== "object" || contentBlock === null) return;
|
|
508
|
+
const { text, type } = contentBlock;
|
|
509
|
+
if (type !== void 0 && type !== "input_text" && type !== "output_text") return;
|
|
510
|
+
return typeof text === "string" ? text : void 0;
|
|
511
|
+
};
|
|
512
|
+
const buildCodexResponsesWebSocketPoolKey = (payload, headers, baseUrl) => {
|
|
513
|
+
const authFingerprint = createHash("sha256").update(`${state.codexAccessToken ?? "missing-token"}:${state.codexAccountId ?? "missing-account"}`).digest("hex").slice(0, 16);
|
|
514
|
+
const headerFingerprint = createHash("sha256").update(JSON.stringify(Object.entries(headers).filter(([headerName]) => !headerName.toLowerCase().includes("trace")).sort(([left], [right]) => left.localeCompare(right)))).digest("hex").slice(0, 16);
|
|
515
|
+
return [
|
|
516
|
+
"codex",
|
|
517
|
+
resolveCodexResponsesUrl(baseUrl),
|
|
518
|
+
payload.model,
|
|
519
|
+
authFingerprint,
|
|
520
|
+
headerFingerprint
|
|
521
|
+
].map(encodePoolKeyPart).join("|");
|
|
522
|
+
};
|
|
523
|
+
const forwardCodexResponsesOverWebSocket = (payload, requestHeaders, baseUrl) => {
|
|
524
|
+
return createCodexResponsesWebSocketStream(prepareCodexResponsesWebSocketRequest(payload, requestHeaders, baseUrl));
|
|
525
|
+
};
|
|
526
|
+
const createCodexResponsesWebSocketStream = (request) => createResponsesSafeStream(createPooledWebSocketStream(request, {
|
|
527
|
+
createChunk: createCodexResponsesWebSocketStreamChunk,
|
|
528
|
+
isTerminalChunk: isTerminalResponsesStreamChunk,
|
|
529
|
+
openErrorMessage: "Failed to create codex responses websocket",
|
|
530
|
+
streamErrorMessage: "Codex responses websocket stream error",
|
|
531
|
+
terminalChunkMissingMessage: "Codex responses websocket ended without a terminal response"
|
|
532
|
+
}));
|
|
533
|
+
const createCodexResponsesWebSocketStreamChunk = (data) => {
|
|
534
|
+
if (data === "[DONE]") return { data };
|
|
535
|
+
try {
|
|
536
|
+
const parsed = JSON.parse(data);
|
|
537
|
+
if (parsed.type === "error" && parsed.error) {
|
|
538
|
+
consola.warn("Codex responses websocket stream error:", parsed.error);
|
|
539
|
+
parsed.message = parsed.error.message;
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
event: typeof parsed.type === "string" ? parsed.type : void 0,
|
|
543
|
+
data: JSON.stringify(parsed),
|
|
544
|
+
id: typeof parsed.id === "string" ? parsed.id : void 0
|
|
545
|
+
};
|
|
546
|
+
} catch {
|
|
547
|
+
return { data };
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region src/lib/oauth/codex.ts
|
|
552
|
+
const CALLBACK_HOST = "127.0.0.1";
|
|
553
|
+
const CALLBACK_PORT = 1455;
|
|
554
|
+
const CALLBACK_PATH = "/auth/callback";
|
|
555
|
+
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
556
|
+
const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
|
|
557
|
+
const TOKEN_URL = "https://auth.openai.com/oauth/token";
|
|
558
|
+
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
|
|
559
|
+
const SCOPE = "openid profile email offline_access";
|
|
560
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
561
|
+
const REFRESH_BUFFER_MS = 6e4;
|
|
562
|
+
const CALLBACK_TIMEOUT_MS = 45e3;
|
|
563
|
+
function base64UrlEncode(bytes) {
|
|
564
|
+
return Buffer.from(bytes).toString("base64url");
|
|
565
|
+
}
|
|
566
|
+
async function generatePkce() {
|
|
567
|
+
const verifierBytes = new Uint8Array(32);
|
|
568
|
+
crypto.getRandomValues(verifierBytes);
|
|
569
|
+
const verifier = base64UrlEncode(verifierBytes);
|
|
570
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
571
|
+
return {
|
|
572
|
+
verifier,
|
|
573
|
+
challenge: base64UrlEncode(new Uint8Array(hashBuffer))
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function createState() {
|
|
577
|
+
return randomBytes(16).toString("hex");
|
|
578
|
+
}
|
|
579
|
+
function parseAuthorizationInput(input) {
|
|
580
|
+
const value = input.trim();
|
|
581
|
+
if (!value) return {};
|
|
582
|
+
try {
|
|
583
|
+
const url = new URL(value);
|
|
584
|
+
return {
|
|
585
|
+
code: url.searchParams.get("code") ?? void 0,
|
|
586
|
+
state: url.searchParams.get("state") ?? void 0
|
|
587
|
+
};
|
|
588
|
+
} catch {}
|
|
589
|
+
if (value.includes("#")) {
|
|
590
|
+
const [code, state] = value.split("#", 2);
|
|
591
|
+
return {
|
|
592
|
+
code,
|
|
593
|
+
state
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
if (value.includes("code=")) {
|
|
597
|
+
const params = new URLSearchParams(value);
|
|
598
|
+
return {
|
|
599
|
+
code: params.get("code") ?? void 0,
|
|
600
|
+
state: params.get("state") ?? void 0
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
return { code: value };
|
|
604
|
+
}
|
|
605
|
+
function decodeJwt(accessToken) {
|
|
606
|
+
try {
|
|
607
|
+
const payload = accessToken.split(".")[1];
|
|
608
|
+
if (!payload) return null;
|
|
609
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
610
|
+
} catch {
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function getAccountId(accessToken) {
|
|
615
|
+
const payload = decodeJwt(accessToken);
|
|
616
|
+
if (!payload) return null;
|
|
617
|
+
const authPayload = payload[JWT_CLAIM_PATH];
|
|
618
|
+
if (!authPayload || typeof authPayload !== "object") return null;
|
|
619
|
+
const accountId = authPayload.chatgpt_account_id;
|
|
620
|
+
return typeof accountId === "string" && accountId ? accountId : null;
|
|
621
|
+
}
|
|
622
|
+
function renderOAuthPage(options) {
|
|
623
|
+
return `<!doctype html>
|
|
624
|
+
<html lang="en">
|
|
625
|
+
<head>
|
|
626
|
+
<meta charset="utf-8" />
|
|
627
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
628
|
+
<title>${escapeHtml(options.title)}</title>
|
|
629
|
+
<style>
|
|
630
|
+
body {
|
|
631
|
+
margin: 0;
|
|
632
|
+
min-height: 100vh;
|
|
633
|
+
display: flex;
|
|
634
|
+
align-items: center;
|
|
635
|
+
justify-content: center;
|
|
636
|
+
padding: 24px;
|
|
637
|
+
background: #09090b;
|
|
638
|
+
color: #fafafa;
|
|
639
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
640
|
+
text-align: center;
|
|
641
|
+
}
|
|
642
|
+
main {
|
|
643
|
+
max-width: 560px;
|
|
644
|
+
}
|
|
645
|
+
h1 {
|
|
646
|
+
margin: 0 0 12px;
|
|
647
|
+
font-size: 28px;
|
|
648
|
+
line-height: 1.15;
|
|
649
|
+
}
|
|
650
|
+
p {
|
|
651
|
+
margin: 0;
|
|
652
|
+
color: #a1a1aa;
|
|
653
|
+
line-height: 1.6;
|
|
654
|
+
}
|
|
655
|
+
</style>
|
|
656
|
+
</head>
|
|
657
|
+
<body>
|
|
658
|
+
<main>
|
|
659
|
+
<h1>${escapeHtml(options.heading)}</h1>
|
|
660
|
+
<p>${escapeHtml(options.message)}</p>
|
|
661
|
+
</main>
|
|
662
|
+
</body>
|
|
663
|
+
</html>`;
|
|
664
|
+
}
|
|
665
|
+
function escapeHtml(value) {
|
|
666
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
667
|
+
}
|
|
668
|
+
function renderOAuthSuccessPage(message) {
|
|
669
|
+
return renderOAuthPage({
|
|
670
|
+
title: "Authentication successful",
|
|
671
|
+
heading: "Authentication successful",
|
|
672
|
+
message
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
function renderOAuthErrorPage(message) {
|
|
676
|
+
return renderOAuthPage({
|
|
677
|
+
title: "Authentication failed",
|
|
678
|
+
heading: "Authentication failed",
|
|
679
|
+
message
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
async function exchangeAuthorizationCode(code, verifier) {
|
|
683
|
+
const response = await fetch(TOKEN_URL, {
|
|
684
|
+
method: "POST",
|
|
685
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
686
|
+
body: new URLSearchParams({
|
|
687
|
+
grant_type: "authorization_code",
|
|
688
|
+
client_id: CLIENT_ID,
|
|
689
|
+
code,
|
|
690
|
+
code_verifier: verifier,
|
|
691
|
+
redirect_uri: REDIRECT_URI
|
|
692
|
+
})
|
|
693
|
+
});
|
|
694
|
+
if (!response.ok) {
|
|
695
|
+
const details = await response.text().catch(() => "");
|
|
696
|
+
throw new Error(`Codex token exchange failed (${response.status}): ${details || response.statusText}`);
|
|
697
|
+
}
|
|
698
|
+
const payload = await response.json();
|
|
699
|
+
if (typeof payload.access_token !== "string" || typeof payload.refresh_token !== "string" || typeof payload.expires_in !== "number") throw new TypeError(`Codex token exchange response missing fields: ${JSON.stringify(payload)}`);
|
|
700
|
+
return {
|
|
701
|
+
accessToken: payload.access_token,
|
|
702
|
+
refreshToken: payload.refresh_token,
|
|
703
|
+
expiresAt: Date.now() + payload.expires_in * 1e3
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
async function refreshAccessToken(refreshToken) {
|
|
707
|
+
const response = await fetch(TOKEN_URL, {
|
|
708
|
+
method: "POST",
|
|
709
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
710
|
+
body: new URLSearchParams({
|
|
711
|
+
grant_type: "refresh_token",
|
|
712
|
+
refresh_token: refreshToken,
|
|
713
|
+
client_id: CLIENT_ID
|
|
714
|
+
})
|
|
715
|
+
});
|
|
716
|
+
if (!response.ok) {
|
|
717
|
+
const details = await response.text().catch(() => "");
|
|
718
|
+
throw new Error(`Codex token refresh failed (${response.status}): ${details || response.statusText}`);
|
|
719
|
+
}
|
|
720
|
+
const payload = await response.json();
|
|
721
|
+
if (typeof payload.access_token !== "string" || typeof payload.refresh_token !== "string" || typeof payload.expires_in !== "number") throw new TypeError(`Codex token refresh response missing fields: ${JSON.stringify(payload)}`);
|
|
722
|
+
return {
|
|
723
|
+
accessToken: payload.access_token,
|
|
724
|
+
refreshToken: payload.refresh_token,
|
|
725
|
+
expiresAt: Date.now() + payload.expires_in * 1e3
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
async function createAuthorizationFlow() {
|
|
729
|
+
const { verifier, challenge } = await generatePkce();
|
|
730
|
+
const state = createState();
|
|
731
|
+
const url = new URL(AUTHORIZE_URL);
|
|
732
|
+
url.searchParams.set("response_type", "code");
|
|
733
|
+
url.searchParams.set("client_id", CLIENT_ID);
|
|
734
|
+
url.searchParams.set("redirect_uri", REDIRECT_URI);
|
|
735
|
+
url.searchParams.set("scope", SCOPE);
|
|
736
|
+
url.searchParams.set("code_challenge", challenge);
|
|
737
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
738
|
+
url.searchParams.set("state", state);
|
|
739
|
+
url.searchParams.set("id_token_add_organizations", "true");
|
|
740
|
+
url.searchParams.set("codex_cli_simplified_flow", "true");
|
|
741
|
+
url.searchParams.set("originator", "copilot-api");
|
|
742
|
+
return {
|
|
743
|
+
verifier,
|
|
744
|
+
state,
|
|
745
|
+
url: url.toString()
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
async function waitForAuthorizationCode(state) {
|
|
749
|
+
let resolveCode;
|
|
750
|
+
const waitForCode = new Promise((resolve) => {
|
|
751
|
+
resolveCode = resolve;
|
|
752
|
+
});
|
|
753
|
+
const server = createServer((request, response) => {
|
|
754
|
+
try {
|
|
755
|
+
const url = new URL(request.url || "", "http://localhost");
|
|
756
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
757
|
+
response.statusCode = 404;
|
|
758
|
+
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
759
|
+
response.end(renderOAuthErrorPage("Callback route not found."));
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (url.searchParams.get("state") !== state) {
|
|
763
|
+
response.statusCode = 400;
|
|
764
|
+
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
765
|
+
response.end(renderOAuthErrorPage("State mismatch."));
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
const code = url.searchParams.get("code");
|
|
769
|
+
if (!code) {
|
|
770
|
+
response.statusCode = 400;
|
|
771
|
+
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
772
|
+
response.end(renderOAuthErrorPage("Missing authorization code."));
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
response.statusCode = 200;
|
|
776
|
+
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
777
|
+
response.end(renderOAuthSuccessPage("OpenAI Codex authentication completed. You can close this window."));
|
|
778
|
+
resolveCode?.(code);
|
|
779
|
+
} catch {
|
|
780
|
+
response.statusCode = 500;
|
|
781
|
+
response.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
782
|
+
response.end(renderOAuthErrorPage("Internal error while processing OAuth callback."));
|
|
783
|
+
}
|
|
784
|
+
});
|
|
785
|
+
try {
|
|
786
|
+
await new Promise((resolve, reject) => {
|
|
787
|
+
server.once("error", reject);
|
|
788
|
+
server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
|
|
789
|
+
server.off("error", reject);
|
|
790
|
+
resolve();
|
|
791
|
+
});
|
|
792
|
+
});
|
|
793
|
+
} catch {
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
try {
|
|
797
|
+
const timeout = new Promise((resolve) => {
|
|
798
|
+
setTimeout(() => resolve(null), CALLBACK_TIMEOUT_MS);
|
|
799
|
+
});
|
|
800
|
+
return await Promise.race([waitForCode, timeout]);
|
|
801
|
+
} finally {
|
|
802
|
+
await new Promise((resolve, reject) => {
|
|
803
|
+
server.close((error) => {
|
|
804
|
+
if (error) {
|
|
805
|
+
reject(error);
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
resolve();
|
|
809
|
+
});
|
|
810
|
+
}).catch(() => void 0);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
async function loginCodex(options) {
|
|
814
|
+
const { verifier, state, url } = await createAuthorizationFlow();
|
|
815
|
+
options.onAuth({
|
|
816
|
+
url,
|
|
817
|
+
instructions: "Please complete the login in the browser. If the browser does not automatically redirect, please paste the callback URL or code back to the terminal."
|
|
818
|
+
});
|
|
819
|
+
options.onProgress?.("Waiting for Codex OAuth callback");
|
|
820
|
+
let code = await waitForAuthorizationCode(state);
|
|
821
|
+
if (!code) {
|
|
822
|
+
const parsed = parseAuthorizationInput(await options.onPrompt("Paste the authorization code or full redirect URL:"));
|
|
823
|
+
if (parsed.state && parsed.state !== state) throw new Error("Codex OAuth state mismatch");
|
|
824
|
+
code = parsed.code ?? null;
|
|
825
|
+
}
|
|
826
|
+
if (!code) throw new Error("Missing Codex authorization code");
|
|
827
|
+
const tokenResult = await exchangeAuthorizationCode(code, verifier);
|
|
828
|
+
const accountId = getAccountId(tokenResult.accessToken);
|
|
829
|
+
if (!accountId) throw new Error("Failed to extract Codex account id from access token");
|
|
830
|
+
return {
|
|
831
|
+
accessToken: tokenResult.accessToken,
|
|
832
|
+
refreshToken: tokenResult.refreshToken,
|
|
833
|
+
expiresAt: tokenResult.expiresAt,
|
|
834
|
+
accountId
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
async function refreshCodexCredentials(credentials) {
|
|
838
|
+
const tokenResult = await refreshAccessToken(credentials.refreshToken);
|
|
839
|
+
const accountId = getAccountId(tokenResult.accessToken);
|
|
840
|
+
if (!accountId) throw new Error("Failed to extract Codex account id from access token");
|
|
841
|
+
return {
|
|
842
|
+
accessToken: tokenResult.accessToken,
|
|
843
|
+
refreshToken: tokenResult.refreshToken,
|
|
844
|
+
expiresAt: tokenResult.expiresAt,
|
|
845
|
+
accountId
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
function isCodexCredentialsExpired(credentials, now = Date.now()) {
|
|
849
|
+
return credentials.expiresAt <= now + REFRESH_BUFFER_MS;
|
|
850
|
+
}
|
|
851
|
+
const compactSystemPromptStarts = ["You are a helpful AI assistant tasked with summarizing conversations", "You are an anchored context summarization assistant for coding sessions."];
|
|
852
|
+
const compactTextOnlyGuard = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.";
|
|
853
|
+
const compactSummaryPromptStart = "Your task is to create a detailed summary of the conversation so far";
|
|
854
|
+
const compactAutoContinuePromptStarts = [
|
|
855
|
+
"This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.",
|
|
856
|
+
"Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.",
|
|
857
|
+
"The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context."
|
|
858
|
+
];
|
|
859
|
+
const compactMessageSections = ["Pending Tasks:", "Current Work:"];
|
|
860
|
+
//#endregion
|
|
861
|
+
//#region src/lib/opencode.ts
|
|
862
|
+
const execAsync = (command) => {
|
|
863
|
+
return new Promise((resolve, reject) => {
|
|
864
|
+
exec(command, (error, stdout) => {
|
|
865
|
+
if (error) {
|
|
866
|
+
reject(error);
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
resolve(stdout);
|
|
870
|
+
});
|
|
871
|
+
});
|
|
872
|
+
};
|
|
873
|
+
let opencodeVersionCache;
|
|
874
|
+
const getGlobalNpmRoot = async () => {
|
|
875
|
+
return (await execAsync("npm root -g")).trim();
|
|
876
|
+
};
|
|
877
|
+
async function resolveOpencodeVersion() {
|
|
878
|
+
try {
|
|
879
|
+
const npmRootPath = await getGlobalNpmRoot();
|
|
880
|
+
const packageJson = await readFile(path.join(npmRootPath, "opencode-ai", "package.json"), "utf8");
|
|
881
|
+
const { version } = JSON.parse(packageJson);
|
|
882
|
+
opencodeVersionCache = version;
|
|
883
|
+
} catch (error) {
|
|
884
|
+
consola.warn(`Failed to resolve opencode version`, error);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
const initOpencodeVersion = () => {
|
|
888
|
+
if (process.env.COPILOT_API_OAUTH_APP?.trim() !== "opencode") return Promise.resolve();
|
|
889
|
+
return resolveOpencodeVersion();
|
|
890
|
+
};
|
|
891
|
+
const getCachedOpencodeVersion = () => {
|
|
892
|
+
return opencodeVersionCache;
|
|
893
|
+
};
|
|
894
|
+
//#endregion
|
|
895
|
+
//#region src/lib/api-config.ts
|
|
896
|
+
const isOpencodeOauthApp = () => {
|
|
897
|
+
return process.env.COPILOT_API_OAUTH_APP?.trim() === "opencode";
|
|
898
|
+
};
|
|
899
|
+
const normalizeDomain = (input) => {
|
|
900
|
+
return input.trim().replace(/^https?:\/\//u, "").replace(/\/+$/u, "");
|
|
901
|
+
};
|
|
902
|
+
const getEnterpriseDomain = () => {
|
|
903
|
+
const raw = (process.env.COPILOT_API_ENTERPRISE_URL ?? "").trim();
|
|
904
|
+
if (!raw) return null;
|
|
905
|
+
return normalizeDomain(raw) || null;
|
|
906
|
+
};
|
|
907
|
+
const getGitHubBaseUrl = () => {
|
|
908
|
+
const resolvedDomain = getEnterpriseDomain();
|
|
909
|
+
return resolvedDomain ? `https://${resolvedDomain}` : GITHUB_BASE_URL;
|
|
910
|
+
};
|
|
911
|
+
const getGitHubApiBaseUrl = () => {
|
|
912
|
+
const resolvedDomain = getEnterpriseDomain();
|
|
913
|
+
return resolvedDomain ? `https://api.${resolvedDomain}` : GITHUB_API_BASE_URL;
|
|
914
|
+
};
|
|
915
|
+
const getOpencodeOauthHeaders = () => {
|
|
916
|
+
return {
|
|
917
|
+
Accept: "application/json",
|
|
918
|
+
"Content-Type": "application/json",
|
|
919
|
+
"User-Agent": getOpencodeVersion()
|
|
920
|
+
};
|
|
921
|
+
};
|
|
922
|
+
const getOpencodeLLMHeaders = () => {
|
|
923
|
+
return {
|
|
924
|
+
Accept: "application/json",
|
|
925
|
+
"Content-Type": "application/json",
|
|
926
|
+
"User-Agent": OPENCODE_LLM_USER_AGENT
|
|
927
|
+
};
|
|
928
|
+
};
|
|
929
|
+
const normalizeOpencodeUserAgent = (userAgent) => {
|
|
930
|
+
const candidate = userAgent.trim();
|
|
931
|
+
const opencodeProduct = candidate.match(/^opencode\/[^\s,]+/u)?.[0];
|
|
932
|
+
if (!opencodeProduct || candidate.includes(`, ${opencodeProduct}`)) return candidate;
|
|
933
|
+
return `${candidate}, ${opencodeProduct}`;
|
|
934
|
+
};
|
|
935
|
+
const getOauthUrls = () => {
|
|
936
|
+
const githubBaseUrl = getGitHubBaseUrl();
|
|
937
|
+
return {
|
|
938
|
+
deviceCodeUrl: `${githubBaseUrl}/login/device/code`,
|
|
939
|
+
accessTokenUrl: `${githubBaseUrl}/login/oauth/access_token`
|
|
940
|
+
};
|
|
941
|
+
};
|
|
942
|
+
const getOauthAppConfig = () => {
|
|
943
|
+
if (isOpencodeOauthApp()) return {
|
|
944
|
+
clientId: OPENCODE_GITHUB_CLIENT_ID,
|
|
945
|
+
headers: getOpencodeOauthHeaders(),
|
|
946
|
+
scope: GITHUB_APP_SCOPES
|
|
947
|
+
};
|
|
948
|
+
return {
|
|
949
|
+
clientId: GITHUB_CLIENT_ID,
|
|
950
|
+
headers: standardHeaders(),
|
|
951
|
+
scope: GITHUB_APP_SCOPES
|
|
952
|
+
};
|
|
953
|
+
};
|
|
954
|
+
const prepareForCompact = (headers, compactType) => {
|
|
955
|
+
if (compactType) {
|
|
956
|
+
headers["x-initiator"] = "agent";
|
|
957
|
+
if (!isOpencodeOauthApp() && compactType === 1) {
|
|
958
|
+
headers["x-interaction-type"] = "conversation-compaction";
|
|
959
|
+
headers["openai-intent"] = "conversation-agent";
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
const prepareInteractionHeaders = (sessionId, isSubagent, headers) => {
|
|
964
|
+
const sendInteractionHeaders = !isOpencodeOauthApp();
|
|
965
|
+
if (isSubagent) {
|
|
966
|
+
headers["x-initiator"] = "agent";
|
|
967
|
+
if (sendInteractionHeaders) headers["x-interaction-type"] = "conversation-subagent";
|
|
968
|
+
}
|
|
969
|
+
if (sessionId && sendInteractionHeaders) headers["x-interaction-id"] = sessionId;
|
|
970
|
+
};
|
|
971
|
+
const standardHeaders = () => ({
|
|
972
|
+
"content-type": "application/json",
|
|
973
|
+
accept: "application/json"
|
|
974
|
+
});
|
|
975
|
+
const getOpencodeVersion = () => {
|
|
976
|
+
const version = getCachedOpencodeVersion();
|
|
977
|
+
if (version) return "opencode/" + version;
|
|
978
|
+
return OPENCODE_VERSION;
|
|
979
|
+
};
|
|
980
|
+
const OPENCODE_VERSION = "opencode/1.14.29";
|
|
981
|
+
const OPENCODE_LLM_USER_AGENT = "opencode/1.14.29 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.13, opencode/1.14.29";
|
|
982
|
+
const COPILOT_VERSION = "0.58.0";
|
|
983
|
+
const EDITOR_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`;
|
|
984
|
+
const USER_AGENT = `GitHubCopilotChat/${COPILOT_VERSION}`;
|
|
985
|
+
const CLAUDE_AGENT_USER_AGENT = "vscode_claude_code/2.1.112 (external, sdk-ts, agent-sdk/0.2.112)";
|
|
986
|
+
const EDITOR_WEBSOCKET_PLUGIN_VERSION = `copilot-chat/${COPILOT_VERSION}`;
|
|
987
|
+
const API_VERSION = "2026-06-01";
|
|
988
|
+
const WEBSOCKET_API_VERSION = API_VERSION;
|
|
989
|
+
const copilotBaseUrl = (state) => {
|
|
990
|
+
const enterpriseDomain = getEnterpriseDomain();
|
|
991
|
+
if (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;
|
|
992
|
+
if (isOpencodeOauthApp()) return "https://api.githubcopilot.com";
|
|
993
|
+
if (state.copilotApiUrl) return state.copilotApiUrl;
|
|
994
|
+
return state.accountType === "individual" ? "https://api.githubcopilot.com" : `https://api.${state.accountType}.githubcopilot.com`;
|
|
995
|
+
};
|
|
996
|
+
const prepareMessageProxyHeaders = (headers) => {
|
|
997
|
+
if (isOpencodeOauthApp()) return;
|
|
998
|
+
const requestIdValue = randomUUID();
|
|
999
|
+
headers["x-agent-task-id"] = requestIdValue;
|
|
1000
|
+
headers["x-request-id"] = requestIdValue;
|
|
1001
|
+
headers["x-interaction-type"] = "messages-proxy";
|
|
1002
|
+
headers["openai-intent"] = "messages-proxy";
|
|
1003
|
+
headers["user-agent"] = CLAUDE_AGENT_USER_AGENT;
|
|
1004
|
+
delete headers["copilot-integration-id"];
|
|
1005
|
+
};
|
|
1006
|
+
const copilotModelsHeaders = (state) => {
|
|
1007
|
+
if (isOpencodeOauthApp()) return {
|
|
1008
|
+
Authorization: `Bearer ${state.copilotToken}`,
|
|
1009
|
+
"User-Agent": getOpencodeVersion()
|
|
1010
|
+
};
|
|
1011
|
+
const headers = githubCopilotHeaders(state);
|
|
1012
|
+
headers["x-interaction-type"] = "model-access";
|
|
1013
|
+
headers["openai-intent"] = "model-access";
|
|
1014
|
+
delete headers["x-interaction-id"];
|
|
1015
|
+
delete headers["content-type"];
|
|
1016
|
+
return headers;
|
|
1017
|
+
};
|
|
1018
|
+
const copilotHeaders = (state, requestId, vision = false) => {
|
|
1019
|
+
if (isOpencodeOauthApp()) {
|
|
1020
|
+
const headers = {
|
|
1021
|
+
Authorization: `Bearer ${state.copilotToken}`,
|
|
1022
|
+
...getOpencodeLLMHeaders(),
|
|
1023
|
+
"Openai-Intent": "conversation-edits"
|
|
1024
|
+
};
|
|
1025
|
+
const store = requestContext.getStore();
|
|
1026
|
+
const userAgent = store?.userAgent.trim();
|
|
1027
|
+
if (userAgent?.startsWith("opencode/")) headers["User-Agent"] = normalizeOpencodeUserAgent(userAgent);
|
|
1028
|
+
if (store?.sessionAffinity) headers["x-session-affinity"] = store.sessionAffinity;
|
|
1029
|
+
if (store?.parentSessionId) headers["x-parent-session-id"] = store.parentSessionId;
|
|
1030
|
+
if (vision) headers["Copilot-Vision-Request"] = "true";
|
|
1031
|
+
return headers;
|
|
1032
|
+
}
|
|
1033
|
+
return githubCopilotHeaders(state, requestId, vision);
|
|
1034
|
+
};
|
|
1035
|
+
const copilotWebSocketHeaders = (preparedHeaders) => {
|
|
1036
|
+
if (isOpencodeOauthApp()) return omitHeader(preparedHeaders, "x-initiator");
|
|
1037
|
+
const requestId = getPreparedHeader(preparedHeaders, "x-request-id") ?? randomUUID();
|
|
1038
|
+
const source = createHeaderResolver(preparedHeaders);
|
|
1039
|
+
const headers = {
|
|
1040
|
+
Authorization: source("authorization"),
|
|
1041
|
+
"X-Request-Id": requestId,
|
|
1042
|
+
"OpenAI-Intent": source("openai-intent", "conversation-agent"),
|
|
1043
|
+
"X-GitHub-Api-Version": source("x-github-api-version", WEBSOCKET_API_VERSION),
|
|
1044
|
+
"X-Interaction-Id": source("x-interaction-id", requestId),
|
|
1045
|
+
"X-Interaction-Type": source("x-interaction-type", "conversation-agent"),
|
|
1046
|
+
"X-Agent-Task-Id": source("x-agent-task-id", requestId)
|
|
1047
|
+
};
|
|
1048
|
+
setPreparedHeader(headers, "VScode-SessionId", preparedHeaders, "vscode-sessionid");
|
|
1049
|
+
setPreparedHeader(headers, "VScode-MachineId", preparedHeaders, "vscode-machineid");
|
|
1050
|
+
Object.assign(headers, {
|
|
1051
|
+
"Editor-Device-Id": source("editor-device-id"),
|
|
1052
|
+
"Editor-Plugin-Version": source("editor-plugin-version", EDITOR_WEBSOCKET_PLUGIN_VERSION),
|
|
1053
|
+
"Editor-Version": source("editor-version"),
|
|
1054
|
+
"Copilot-Integration-Id": source("copilot-integration-id", "vscode-chat")
|
|
1055
|
+
});
|
|
1056
|
+
setPreparedHeader(headers, "Copilot-Vision-Request", preparedHeaders, "copilot-vision-request");
|
|
1057
|
+
headers["user-agent"] = "node";
|
|
1058
|
+
return headers;
|
|
1059
|
+
};
|
|
1060
|
+
const createHeaderResolver = (headers) => (headerName, fallback = "") => getPreparedHeader(headers, headerName) ?? fallback;
|
|
1061
|
+
const getPreparedHeader = (headers, headerName) => {
|
|
1062
|
+
const normalizedHeaderName = headerName.toLowerCase();
|
|
1063
|
+
return Object.entries(headers).find(([key]) => key.toLowerCase() === normalizedHeaderName)?.[1];
|
|
1064
|
+
};
|
|
1065
|
+
const setPreparedHeader = (target, targetHeaderName, source, sourceHeaderName) => {
|
|
1066
|
+
const value = getPreparedHeader(source, sourceHeaderName);
|
|
1067
|
+
if (value) target[targetHeaderName] = value;
|
|
1068
|
+
};
|
|
1069
|
+
const omitHeader = (headers, headerName) => {
|
|
1070
|
+
const normalizedHeaderName = headerName.toLowerCase();
|
|
1071
|
+
return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== normalizedHeaderName));
|
|
1072
|
+
};
|
|
1073
|
+
const githubCopilotHeaders = (state, requestId, vision = false) => {
|
|
1074
|
+
const requestIdValue = requestId ?? randomUUID();
|
|
1075
|
+
const headers = {
|
|
1076
|
+
Authorization: `Bearer ${state.copilotToken}`,
|
|
1077
|
+
"content-type": standardHeaders()["content-type"],
|
|
1078
|
+
"copilot-integration-id": "vscode-chat",
|
|
1079
|
+
"editor-device-id": state.vsCodeDeviceId,
|
|
1080
|
+
"editor-version": `vscode/${state.vsCodeVersion}`,
|
|
1081
|
+
"editor-plugin-version": EDITOR_PLUGIN_VERSION,
|
|
1082
|
+
"user-agent": USER_AGENT,
|
|
1083
|
+
"openai-intent": "conversation-agent",
|
|
1084
|
+
"x-github-api-version": API_VERSION,
|
|
1085
|
+
"x-request-id": requestIdValue,
|
|
1086
|
+
"x-vscode-user-agent-library-version": "electron-fetch",
|
|
1087
|
+
"x-agent-task-id": requestIdValue,
|
|
1088
|
+
"x-interaction-type": "conversation-agent"
|
|
1089
|
+
};
|
|
1090
|
+
if (vision) headers["copilot-vision-request"] = "true";
|
|
1091
|
+
if (state.macMachineId) headers["vscode-machineid"] = state.macMachineId;
|
|
1092
|
+
if (state.vsCodeSessionId) headers["vscode-sessionid"] = state.vsCodeSessionId;
|
|
1093
|
+
return headers;
|
|
1094
|
+
};
|
|
1095
|
+
const GITHUB_API_BASE_URL = "https://api.github.com";
|
|
1096
|
+
const githubHeaders = (state) => {
|
|
1097
|
+
if (isOpencodeOauthApp()) return {
|
|
1098
|
+
Authorization: `Bearer ${state.githubToken}`,
|
|
1099
|
+
...getOpencodeOauthHeaders()
|
|
1100
|
+
};
|
|
1101
|
+
return {
|
|
1102
|
+
authorization: `token ${state.githubToken}`,
|
|
1103
|
+
"user-agent": USER_AGENT,
|
|
1104
|
+
"x-github-api-version": "2025-04-01",
|
|
1105
|
+
"x-vscode-user-agent-library-version": "electron-fetch"
|
|
1106
|
+
};
|
|
1107
|
+
};
|
|
1108
|
+
const GITHUB_BASE_URL = "https://github.com";
|
|
1109
|
+
const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
1110
|
+
const GITHUB_APP_SCOPES = ["read:user"].join(" ");
|
|
1111
|
+
const OPENCODE_GITHUB_CLIENT_ID = "Ov23li8tweQw6odWQebz";
|
|
1112
|
+
//#endregion
|
|
1113
|
+
//#region src/lib/credential-store.ts
|
|
1114
|
+
function isNodeError(error) {
|
|
1115
|
+
return error instanceof Error && "code" in error;
|
|
1116
|
+
}
|
|
1117
|
+
async function readOptionalFile(filePath) {
|
|
1118
|
+
try {
|
|
1119
|
+
return await fs.readFile(filePath, "utf8");
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
if (isNodeError(error) && error.code === "ENOENT") return null;
|
|
1122
|
+
throw error;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
async function writeProtectedFile(filePath, content) {
|
|
1126
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
1127
|
+
await fs.writeFile(filePath, content, "utf8");
|
|
1128
|
+
try {
|
|
1129
|
+
await fs.chmod(filePath, 384);
|
|
1130
|
+
} catch {
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
function normalizeCodexCredentials(credentials) {
|
|
1135
|
+
if (!credentials || typeof credentials !== "object") return null;
|
|
1136
|
+
const candidate = credentials;
|
|
1137
|
+
if (typeof candidate.accessToken !== "string" || typeof candidate.refreshToken !== "string" || typeof candidate.expiresAt !== "number" || typeof candidate.accountId !== "string") return null;
|
|
1138
|
+
return {
|
|
1139
|
+
accessToken: candidate.accessToken,
|
|
1140
|
+
refreshToken: candidate.refreshToken,
|
|
1141
|
+
expiresAt: candidate.expiresAt,
|
|
1142
|
+
accountId: candidate.accountId
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
async function readGitHubToken() {
|
|
1146
|
+
return (await readOptionalFile(PATHS.GITHUB_TOKEN_PATH))?.trim() || null;
|
|
1147
|
+
}
|
|
1148
|
+
async function writeGitHubToken(token) {
|
|
1149
|
+
await writeProtectedFile(PATHS.GITHUB_TOKEN_PATH, token.trim());
|
|
1150
|
+
}
|
|
1151
|
+
async function readCodexCredentials() {
|
|
1152
|
+
const raw = await readOptionalFile(PATHS.CODEX_CREDENTIAL_PATH);
|
|
1153
|
+
if (!raw?.trim()) return null;
|
|
1154
|
+
let parsed;
|
|
1155
|
+
try {
|
|
1156
|
+
parsed = JSON.parse(raw);
|
|
1157
|
+
} catch (error) {
|
|
1158
|
+
throw new Error(`Codex credentials file is not valid JSON: ${PATHS.CODEX_CREDENTIAL_PATH}`, { cause: error });
|
|
1159
|
+
}
|
|
1160
|
+
const credentials = normalizeCodexCredentials(parsed);
|
|
1161
|
+
if (!credentials) throw new Error(`Codex credentials file is missing required fields: ${PATHS.CODEX_CREDENTIAL_PATH}`);
|
|
1162
|
+
return credentials;
|
|
1163
|
+
}
|
|
1164
|
+
async function writeCodexCredentials(credentials) {
|
|
1165
|
+
await writeProtectedFile(PATHS.CODEX_CREDENTIAL_PATH, `${JSON.stringify(credentials, null, 2)}\n`);
|
|
1166
|
+
}
|
|
1167
|
+
//#endregion
|
|
1168
|
+
//#region src/services/github/get-copilot-token.ts
|
|
1169
|
+
const getCopilotToken = async () => {
|
|
1170
|
+
const response = await fetch(`${getGitHubApiBaseUrl()}/copilot_internal/v2/token`, { headers: githubHeaders(state) });
|
|
1171
|
+
if (!response.ok) {
|
|
1172
|
+
const errorText = await response.clone().text();
|
|
1173
|
+
consola.error("Failed to get Copilot token response body", errorText);
|
|
1174
|
+
throw new HTTPError("Failed to get Copilot token", response);
|
|
1175
|
+
}
|
|
1176
|
+
return await response.json();
|
|
1177
|
+
};
|
|
1178
|
+
//#endregion
|
|
1179
|
+
//#region src/services/github/get-copilot-usage.ts
|
|
1180
|
+
const getCopilotUsage = async (githubToken) => {
|
|
1181
|
+
const resolvedGithubToken = githubToken ?? state.githubToken;
|
|
1182
|
+
if (!resolvedGithubToken) return null;
|
|
1183
|
+
const authState = {
|
|
1184
|
+
...state,
|
|
1185
|
+
githubToken: resolvedGithubToken
|
|
1186
|
+
};
|
|
1187
|
+
const response = await fetch(`${getGitHubApiBaseUrl()}/copilot_internal/user`, { headers: githubHeaders(authState) });
|
|
1188
|
+
if (!response.ok) {
|
|
1189
|
+
const errorText = await response.clone().text();
|
|
1190
|
+
consola.error("Failed to get Copilot user response body", errorText);
|
|
1191
|
+
throw new HTTPError("Failed to get Copilot usage", response);
|
|
1192
|
+
}
|
|
1193
|
+
return await response.json();
|
|
1194
|
+
};
|
|
1195
|
+
//#endregion
|
|
1196
|
+
//#region src/services/github/get-device-code.ts
|
|
1197
|
+
async function getDeviceCode() {
|
|
1198
|
+
const { clientId, headers, scope } = getOauthAppConfig();
|
|
1199
|
+
const { deviceCodeUrl } = getOauthUrls();
|
|
1200
|
+
const response = await fetch(deviceCodeUrl, {
|
|
1201
|
+
method: "POST",
|
|
1202
|
+
headers,
|
|
1203
|
+
body: JSON.stringify({
|
|
1204
|
+
client_id: clientId,
|
|
1205
|
+
scope
|
|
1206
|
+
})
|
|
1207
|
+
});
|
|
1208
|
+
if (!response.ok) throw new HTTPError("Failed to get device code", response);
|
|
1209
|
+
return await response.json();
|
|
1210
|
+
}
|
|
1211
|
+
//#endregion
|
|
1212
|
+
//#region src/lib/utils.ts
|
|
1213
|
+
const sleep = (ms) => new Promise((resolve) => {
|
|
1214
|
+
setTimeout(resolve, ms);
|
|
1215
|
+
});
|
|
1216
|
+
const isNullish = (value) => value === null || value === void 0;
|
|
1217
|
+
const isAsyncIterable = (value) => Boolean(value) && typeof value[Symbol.asyncIterator] === "function";
|
|
1218
|
+
const isResponsesStream = (value) => isAsyncIterable(value);
|
|
1219
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
1220
|
+
const getUserIdJsonField = (userIdPayload, field) => {
|
|
1221
|
+
const value = userIdPayload?.[field];
|
|
1222
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1223
|
+
};
|
|
1224
|
+
const parseJsonUserId = (userId) => {
|
|
1225
|
+
try {
|
|
1226
|
+
const parsed = JSON.parse(userId);
|
|
1227
|
+
return isRecord(parsed) ? parsed : null;
|
|
1228
|
+
} catch {
|
|
1229
|
+
return null;
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
const parseUserIdMetadata = (userId) => {
|
|
1233
|
+
if (!userId || typeof userId !== "string") return {
|
|
1234
|
+
safetyIdentifier: null,
|
|
1235
|
+
sessionId: null
|
|
1236
|
+
};
|
|
1237
|
+
const legacySafetyIdentifier = userId.match(/user_([^_]+)_account/)?.[1] ?? null;
|
|
1238
|
+
const legacySessionId = userId.match(/_session_(.+)$/)?.[1] ?? null;
|
|
1239
|
+
const parsedUserId = legacySafetyIdentifier && legacySessionId ? null : parseJsonUserId(userId);
|
|
1240
|
+
return {
|
|
1241
|
+
safetyIdentifier: legacySafetyIdentifier ?? getUserIdJsonField(parsedUserId, "device_id") ?? getUserIdJsonField(parsedUserId, "account_uuid"),
|
|
1242
|
+
sessionId: legacySessionId ?? getUserIdJsonField(parsedUserId, "session_id")
|
|
1243
|
+
};
|
|
1244
|
+
};
|
|
1245
|
+
const findLastUserContent = (messages) => {
|
|
1246
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1247
|
+
const msg = messages[i];
|
|
1248
|
+
if (msg.role === "user" && msg.content) {
|
|
1249
|
+
if (typeof msg.content === "string") return msg.content;
|
|
1250
|
+
else if (Array.isArray(msg.content)) {
|
|
1251
|
+
const array = msg.content.filter((n) => n.type !== "tool_result").map((n) => ({
|
|
1252
|
+
...n,
|
|
1253
|
+
cache_control: void 0
|
|
1254
|
+
}));
|
|
1255
|
+
if (array.length > 0) return JSON.stringify(array);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
return null;
|
|
1260
|
+
};
|
|
1261
|
+
const generateRequestIdFromPayload = (payload, sessionId) => {
|
|
1262
|
+
const messages = payload.messages;
|
|
1263
|
+
if (messages) {
|
|
1264
|
+
const lastUserContent = typeof messages === "string" ? messages : findLastUserContent(messages);
|
|
1265
|
+
if (lastUserContent) return getUUID((sessionId ?? "") + (state.macMachineId ?? "") + lastUserContent);
|
|
1266
|
+
}
|
|
1267
|
+
return randomUUID();
|
|
1268
|
+
};
|
|
1269
|
+
const getRootSessionId = (anthropicPayload, c) => {
|
|
1270
|
+
const userId = anthropicPayload.metadata?.user_id;
|
|
1271
|
+
const sessionId = userId ? parseUserIdMetadata(userId).sessionId || void 0 : c.req.header("x-session-id");
|
|
1272
|
+
return sessionId ? getUUID(sessionId) : sessionId;
|
|
1273
|
+
};
|
|
1274
|
+
const getUUID = (content) => {
|
|
1275
|
+
const uuidBytes = createHash("sha256").update(content).digest().subarray(0, 16);
|
|
1276
|
+
uuidBytes[6] = uuidBytes[6] & 15 | 64;
|
|
1277
|
+
uuidBytes[8] = uuidBytes[8] & 63 | 128;
|
|
1278
|
+
const uuidHex = uuidBytes.toString("hex");
|
|
1279
|
+
return `${uuidHex.slice(0, 8)}-${uuidHex.slice(8, 12)}-${uuidHex.slice(12, 16)}-${uuidHex.slice(16, 20)}-${uuidHex.slice(20)}`;
|
|
1280
|
+
};
|
|
1281
|
+
//#endregion
|
|
1282
|
+
//#region src/services/github/poll-access-token.ts
|
|
1283
|
+
async function pollAccessToken(deviceCode) {
|
|
1284
|
+
const { clientId, headers } = getOauthAppConfig();
|
|
1285
|
+
const { accessTokenUrl } = getOauthUrls();
|
|
1286
|
+
const sleepDuration = (deviceCode.interval + 1) * 1e3;
|
|
1287
|
+
consola.debug(`Polling access token with interval of ${sleepDuration}ms`);
|
|
1288
|
+
while (true) {
|
|
1289
|
+
const response = await fetch(accessTokenUrl, {
|
|
1290
|
+
method: "POST",
|
|
1291
|
+
headers,
|
|
1292
|
+
body: JSON.stringify({
|
|
1293
|
+
client_id: clientId,
|
|
1294
|
+
device_code: deviceCode.device_code,
|
|
1295
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
|
|
1296
|
+
})
|
|
1297
|
+
});
|
|
1298
|
+
if (!response.ok) {
|
|
1299
|
+
await sleep(sleepDuration);
|
|
1300
|
+
consola.error("Failed to poll access token:", await response.text());
|
|
1301
|
+
continue;
|
|
1302
|
+
}
|
|
1303
|
+
const json = await response.json();
|
|
1304
|
+
consola.debug("Polling access token response:", json);
|
|
1305
|
+
const { access_token } = json;
|
|
1306
|
+
if (access_token) return access_token;
|
|
1307
|
+
else await sleep(sleepDuration);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
//#endregion
|
|
1311
|
+
//#region src/lib/token.ts
|
|
1312
|
+
let copilotRefreshLoopController = null;
|
|
1313
|
+
let codexRefreshLoopController = null;
|
|
1314
|
+
const stopCopilotRefreshLoop = () => {
|
|
1315
|
+
if (!copilotRefreshLoopController) return;
|
|
1316
|
+
copilotRefreshLoopController.abort();
|
|
1317
|
+
copilotRefreshLoopController = null;
|
|
1318
|
+
};
|
|
1319
|
+
const stopCodexRefreshLoop = () => {
|
|
1320
|
+
if (!codexRefreshLoopController) return;
|
|
1321
|
+
codexRefreshLoopController.abort();
|
|
1322
|
+
codexRefreshLoopController = null;
|
|
1323
|
+
};
|
|
1324
|
+
function applyCodexCredentials(credentials) {
|
|
1325
|
+
state.codexAccessToken = credentials.accessToken;
|
|
1326
|
+
state.codexRefreshToken = credentials.refreshToken;
|
|
1327
|
+
state.codexExpiresAt = credentials.expiresAt;
|
|
1328
|
+
state.codexAccountId = credentials.accountId;
|
|
1329
|
+
consola.debug("Codex credentials loaded successfully");
|
|
1330
|
+
if (state.showToken) consola.info("Codex access token:", credentials.accessToken);
|
|
1331
|
+
}
|
|
1332
|
+
function getLoadedCodexCredentials() {
|
|
1333
|
+
if (!state.codexAccessToken || !state.codexRefreshToken || !state.codexExpiresAt || !state.codexAccountId) return null;
|
|
1334
|
+
return {
|
|
1335
|
+
accessToken: state.codexAccessToken,
|
|
1336
|
+
refreshToken: state.codexRefreshToken,
|
|
1337
|
+
expiresAt: state.codexExpiresAt,
|
|
1338
|
+
accountId: state.codexAccountId
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
function syncCodexProviderConfig(options) {
|
|
1342
|
+
const existingProviderConfig = getRawProviderConfig("codex") ?? {};
|
|
1343
|
+
setProviderConfig("codex", {
|
|
1344
|
+
...existingProviderConfig,
|
|
1345
|
+
type: "openai-responses",
|
|
1346
|
+
enabled: options?.enabled ?? existingProviderConfig.enabled,
|
|
1347
|
+
baseUrl: CODEX_API_BASE_URL,
|
|
1348
|
+
authType: "oauth2",
|
|
1349
|
+
pricingCurrency: "USD"
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
async function persistCodexCredentials(credentials, options) {
|
|
1353
|
+
await writeCodexCredentials(credentials);
|
|
1354
|
+
syncCodexProviderConfig({ enabled: options?.enableProvider ? true : void 0 });
|
|
1355
|
+
applyCodexCredentials(credentials);
|
|
1356
|
+
}
|
|
1357
|
+
const setupCopilotToken = async () => {
|
|
1358
|
+
if (isOpencodeOauthApp()) {
|
|
1359
|
+
if (!state.githubToken) throw new Error(`opencode token not found`);
|
|
1360
|
+
state.copilotToken = state.githubToken;
|
|
1361
|
+
consola.debug("GitHub Copilot token set from opencode auth token");
|
|
1362
|
+
if (state.showToken) consola.info("Copilot token:", state.copilotToken);
|
|
1363
|
+
stopCopilotRefreshLoop();
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
const { token, refresh_in } = await getCopilotToken();
|
|
1367
|
+
state.copilotToken = token;
|
|
1368
|
+
consola.debug("GitHub Copilot Token fetched successfully!");
|
|
1369
|
+
if (state.showToken) consola.info("Copilot token:", token);
|
|
1370
|
+
stopCopilotRefreshLoop();
|
|
1371
|
+
const controller = new AbortController();
|
|
1372
|
+
copilotRefreshLoopController = controller;
|
|
1373
|
+
runCopilotRefreshLoop(refresh_in, controller.signal).catch(() => {
|
|
1374
|
+
consola.warn("Copilot token refresh loop stopped");
|
|
1375
|
+
}).finally(() => {
|
|
1376
|
+
if (copilotRefreshLoopController === controller) copilotRefreshLoopController = null;
|
|
1377
|
+
});
|
|
1378
|
+
};
|
|
1379
|
+
const setupCodexToken = async () => {
|
|
1380
|
+
const loadedCredentials = getLoadedCodexCredentials();
|
|
1381
|
+
if (loadedCredentials && !isCodexCredentialsExpired(loadedCredentials)) {
|
|
1382
|
+
if (codexRefreshLoopController) return;
|
|
1383
|
+
applyCodexCredentials(loadedCredentials);
|
|
1384
|
+
}
|
|
1385
|
+
const credentials = loadedCredentials ?? await readCodexCredentials();
|
|
1386
|
+
if (!credentials) throw new Error(`Codex credentials not found. Run \`copilot-api auth login --provider codex\` first.`);
|
|
1387
|
+
syncCodexProviderConfig();
|
|
1388
|
+
let nextCredentials = credentials;
|
|
1389
|
+
if (isCodexCredentialsExpired(credentials)) {
|
|
1390
|
+
consola.debug("Refreshing expired Codex credentials");
|
|
1391
|
+
nextCredentials = await refreshCodexCredentials(credentials);
|
|
1392
|
+
await persistCodexCredentials(nextCredentials);
|
|
1393
|
+
}
|
|
1394
|
+
applyCodexCredentials(nextCredentials);
|
|
1395
|
+
stopCodexRefreshLoop();
|
|
1396
|
+
const controller = new AbortController();
|
|
1397
|
+
codexRefreshLoopController = controller;
|
|
1398
|
+
runCodexRefreshLoop(controller.signal).catch(() => {
|
|
1399
|
+
consola.warn("Codex token refresh loop stopped");
|
|
1400
|
+
}).finally(() => {
|
|
1401
|
+
if (codexRefreshLoopController === controller) codexRefreshLoopController = null;
|
|
1402
|
+
});
|
|
1403
|
+
};
|
|
1404
|
+
const REFRESH_POLL_INTERVAL_MS = 15e3;
|
|
1405
|
+
const EARLY_REFRESH_BUFFER_MS = 6e4;
|
|
1406
|
+
const RETRY_REFRESH_DELAY_MS = 15e3;
|
|
1407
|
+
const MAX_RETRY_REFRESH_DELAY_MS = 6e5;
|
|
1408
|
+
const RETRY_REFRESH_JITTER_MS = 15e3;
|
|
1409
|
+
const MIN_REFRESH_DELAY_MS = 1e3;
|
|
1410
|
+
const getRefreshDeadlineMs = (refreshIn, nowMs = Date.now()) => nowMs + Math.max(refreshIn * 1e3 - EARLY_REFRESH_BUFFER_MS, MIN_REFRESH_DELAY_MS);
|
|
1411
|
+
const getRefreshPollDelayMs = (refreshAtMs, nowMs = Date.now()) => Math.min(Math.max(refreshAtMs - nowMs, 0), REFRESH_POLL_INTERVAL_MS);
|
|
1412
|
+
const runCopilotRefreshLoop = async (refreshIn, signal) => {
|
|
1413
|
+
let refreshAtMs = getRefreshDeadlineMs(refreshIn);
|
|
1414
|
+
let retryDelayMs = RETRY_REFRESH_DELAY_MS;
|
|
1415
|
+
while (!signal.aborted) {
|
|
1416
|
+
const nextDelayMs = getRefreshPollDelayMs(refreshAtMs);
|
|
1417
|
+
if (nextDelayMs > 0) {
|
|
1418
|
+
await setTimeout$1(nextDelayMs, void 0, { signal });
|
|
1419
|
+
continue;
|
|
1420
|
+
}
|
|
1421
|
+
consola.debug("Refreshing Copilot token");
|
|
1422
|
+
try {
|
|
1423
|
+
const { token, refresh_in } = await getCopilotToken();
|
|
1424
|
+
state.copilotToken = token;
|
|
1425
|
+
refreshAtMs = getRefreshDeadlineMs(refresh_in);
|
|
1426
|
+
retryDelayMs = RETRY_REFRESH_DELAY_MS;
|
|
1427
|
+
consola.debug("Copilot token refreshed");
|
|
1428
|
+
if (state.showToken) consola.info("Refreshed Copilot token:", token);
|
|
1429
|
+
} catch (error) {
|
|
1430
|
+
consola.error("Failed to refresh Copilot token:", error);
|
|
1431
|
+
const delayMs = Math.min(retryDelayMs + Math.floor(Math.random() * RETRY_REFRESH_JITTER_MS), MAX_RETRY_REFRESH_DELAY_MS);
|
|
1432
|
+
refreshAtMs = Date.now() + delayMs;
|
|
1433
|
+
retryDelayMs = Math.min(retryDelayMs * 2, MAX_RETRY_REFRESH_DELAY_MS);
|
|
1434
|
+
consola.warn(`Retrying Copilot token refresh in ${Math.round(delayMs / 1e3)}s`);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
const runCodexRefreshLoop = async (signal) => {
|
|
1439
|
+
let refreshAtMs = Math.max((state.codexExpiresAt ?? Date.now()) - EARLY_REFRESH_BUFFER_MS, Date.now());
|
|
1440
|
+
while (!signal.aborted) {
|
|
1441
|
+
const expiresAt = state.codexExpiresAt;
|
|
1442
|
+
const refreshToken = state.codexRefreshToken;
|
|
1443
|
+
if (!expiresAt || !refreshToken) return;
|
|
1444
|
+
const nextDelayMs = getRefreshPollDelayMs(refreshAtMs);
|
|
1445
|
+
if (nextDelayMs > 0) {
|
|
1446
|
+
await setTimeout$1(nextDelayMs, void 0, { signal });
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
1449
|
+
consola.debug("Refreshing Codex credentials");
|
|
1450
|
+
try {
|
|
1451
|
+
const credentials = await refreshCodexCredentials({
|
|
1452
|
+
accessToken: state.codexAccessToken ?? "",
|
|
1453
|
+
refreshToken,
|
|
1454
|
+
expiresAt,
|
|
1455
|
+
accountId: state.codexAccountId ?? ""
|
|
1456
|
+
});
|
|
1457
|
+
await persistCodexCredentials(credentials);
|
|
1458
|
+
refreshAtMs = Math.max(credentials.expiresAt - EARLY_REFRESH_BUFFER_MS, Date.now());
|
|
1459
|
+
consola.debug("Codex credentials refreshed");
|
|
1460
|
+
} catch (error) {
|
|
1461
|
+
consola.error("Failed to refresh Codex credentials:", error);
|
|
1462
|
+
refreshAtMs = Date.now() + RETRY_REFRESH_DELAY_MS;
|
|
1463
|
+
consola.warn(`Retrying Codex token refresh in ${RETRY_REFRESH_DELAY_MS / 1e3}s`);
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
};
|
|
1467
|
+
async function setupGitHubToken(options) {
|
|
1468
|
+
try {
|
|
1469
|
+
const githubToken = await readGitHubToken();
|
|
1470
|
+
if (githubToken && !options?.force) {
|
|
1471
|
+
state.githubToken = githubToken;
|
|
1472
|
+
if (state.showToken) consola.info("GitHub token:", githubToken);
|
|
1473
|
+
await logUser();
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
consola.info("Not logged in, getting new access token");
|
|
1477
|
+
const response = await getDeviceCode();
|
|
1478
|
+
consola.debug("Device code response:", response);
|
|
1479
|
+
consola.info(`Please enter the code "${response.user_code}" in ${response.verification_uri}`);
|
|
1480
|
+
const token = await pollAccessToken(response);
|
|
1481
|
+
await writeGitHubToken(token);
|
|
1482
|
+
state.githubToken = token;
|
|
1483
|
+
if (state.showToken) consola.info("GitHub token:", token);
|
|
1484
|
+
await logUser();
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
if (error instanceof HTTPError) {
|
|
1487
|
+
consola.error("Failed to get GitHub token:", await error.response.json());
|
|
1488
|
+
throw error;
|
|
1489
|
+
}
|
|
1490
|
+
consola.error("Failed to get GitHub token:", error);
|
|
1491
|
+
throw error;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
async function logUser() {
|
|
1495
|
+
const copilotUser = await getCopilotUsage();
|
|
1496
|
+
if (!copilotUser) throw new Error("GitHub token not found");
|
|
1497
|
+
state.userName = copilotUser.login;
|
|
1498
|
+
consola.info(`Logged in as ${copilotUser.login}`);
|
|
1499
|
+
state.copilotApiUrl = copilotUser.endpoints.api;
|
|
1500
|
+
state.tokenBasedBilling = copilotUser.token_based_billing;
|
|
1501
|
+
}
|
|
1502
|
+
//#endregion
|
|
1503
|
+
export { buildCodexRequestHeaders as A, state as B, compactAutoContinuePromptStarts as C, compactTextOnlyGuard as D, compactSystemPromptStarts as E, createResponsesSafeStream as F, forwardError as H, encodePoolKeyPart as I, isTerminalResponsesStreamChunk as L, generateTraceId as M, requestContext as N, loginCodex as O, resolveTraceId as P, createPooledWebSocketStream as R, initOpencodeVersion as S, compactSummaryPromptStart as T, HTTPError as V, copilotModelsHeaders as _, setupGitHubToken as a, prepareInteractionHeaders as b, getUUID as c, isResponsesStream as d, parseUserIdMetadata as f, copilotHeaders as g, copilotBaseUrl as h, setupCopilotToken as i, forwardCodexResponses as j, CODEX_API_BASE_URL as k, isAsyncIterable as l, readGitHubToken as m, persistCodexCredentials as n, generateRequestIdFromPayload as o, getCopilotUsage as p, setupCodexToken as r, getRootSessionId as s, logUser as t, isNullish as u, copilotWebSocketHeaders as v, compactMessageSections as w, prepareMessageProxyHeaders as x, prepareForCompact as y, createWebSocketUrl as z };
|