@jeffreycao/copilot-api 2.7.37 → 2.7.39
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/dist/{auth-Bamibni8.js → auth-DBOz2FcU.js} +9 -12
- package/dist/{auth-Bamibni8.js.map → auth-DBOz2FcU.js.map} +1 -1
- package/dist/auth-IiEbOqcu.js +1 -0
- package/dist/{config-D8pUyhJp.js → config-BqSuE5h5.js} +7 -22
- package/dist/config-BqSuE5h5.js.map +1 -0
- package/dist/{config-store-CYG9aCTL.js → config-store-BsluQttR.js} +7 -13
- package/dist/{config-store-CYG9aCTL.js.map → config-store-BsluQttR.js.map} +1 -1
- package/dist/{copilot-runtime-VVi3SKsW.js → copilot-runtime-0CujVONa.js} +11 -19
- package/dist/{copilot-runtime-VVi3SKsW.js.map → copilot-runtime-0CujVONa.js.map} +1 -1
- package/dist/{debug-BXvLeaet.js → debug-RUUyusA_.js} +4 -5
- package/dist/{debug-BXvLeaet.js.map → debug-RUUyusA_.js.map} +1 -1
- package/dist/{electron-fetch-DsMaRX6v.js → electron-fetch-ByE9Ctv0.js} +2 -3
- package/dist/{electron-fetch-DsMaRX6v.js.map → electron-fetch-ByE9Ctv0.js.map} +1 -1
- package/dist/{fast-path-BwgQKZBk.js → fast-path-B53kz5S1.js} +1 -2
- package/dist/{fast-path-BwgQKZBk.js.map → fast-path-B53kz5S1.js.map} +1 -1
- package/dist/main.js +9 -10
- package/dist/{mcp-Dd_hxxuG.js → mcp-DJE9135Q.js} +3 -4
- package/dist/{mcp-Dd_hxxuG.js.map → mcp-DJE9135Q.js.map} +1 -1
- package/dist/mcp-server-DPadDLWn.js +1 -0
- package/dist/{mcp-server-CTGaok8g.js → mcp-server-DvGD6L9t.js} +3 -4
- package/dist/{mcp-server-CTGaok8g.js.map → mcp-server-DvGD6L9t.js.map} +1 -1
- package/dist/{provider-C6wFZzeY.js → provider-BMPS2mij.js} +3 -4
- package/dist/{provider-C6wFZzeY.js.map → provider-BMPS2mij.js.map} +1 -1
- package/dist/{provider-management-B9lCOTka.js → provider-management-vyEQj9RR.js} +3 -4
- package/dist/{provider-management-B9lCOTka.js.map → provider-management-vyEQj9RR.js.map} +1 -1
- package/dist/{server-Z3SfnFdc.js → server-Jvc5DYJV.js} +104 -201
- package/dist/{server-Z3SfnFdc.js.map → server-Jvc5DYJV.js.map} +1 -1
- package/dist/{start-BEda1BbC.js → start-BQBvYKD-.js} +13 -18
- package/dist/{start-BEda1BbC.js.map → start-BQBvYKD-.js.map} +1 -1
- package/dist/{tls-uiriilgk.js → tls-cISpkgFD.js} +2 -3
- package/dist/{tls-uiriilgk.js.map → tls-cISpkgFD.js.map} +1 -1
- package/dist/{token-DW6rW7yB.js → token-_1CBLbqH.js} +23 -43
- package/dist/{token-DW6rW7yB.js.map → token-_1CBLbqH.js.map} +1 -1
- package/dist/{tool-search-CcvaqM03.js → tool-search-DzipwtCX.js} +2 -3
- package/dist/{tool-search-CcvaqM03.js.map → tool-search-DzipwtCX.js.map} +1 -1
- package/package.json +6 -6
- package/dist/auth-Dg8DFYd2.js +0 -2
- package/dist/config-D8pUyhJp.js.map +0 -1
- package/dist/mcp-server-CEfcUYiN.js +0 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { C as ensurePaths, D as state, E as isGitHubCopilotEnabled, S as PATHS, _ as mergeConfigWithDefaults } from "./config-store-
|
|
2
|
-
import { b as startModelsDevCache, i as listEnabledProviders } from "./config-
|
|
3
|
-
import { A as initOpencodeVersion, G as GITHUB_TOKEN_ENV, K as readGitHubToken, R as getConfiguredApiKeys, q as readGitHubTokenFromEnv, z as getMissingApiKeysMessage } from "./token-
|
|
4
|
-
import { o as runProviderSetup } from "./auth-
|
|
5
|
-
import { i as registerProcessCleanup, r as EventBus, t as setupCopilotRuntime } from "./copilot-runtime-
|
|
1
|
+
import { C as ensurePaths, D as state, E as isGitHubCopilotEnabled, S as PATHS, _ as mergeConfigWithDefaults } from "./config-store-BsluQttR.js";
|
|
2
|
+
import { b as startModelsDevCache, i as listEnabledProviders } from "./config-BqSuE5h5.js";
|
|
3
|
+
import { A as initOpencodeVersion, G as GITHUB_TOKEN_ENV, K as readGitHubToken, R as getConfiguredApiKeys, q as readGitHubTokenFromEnv, z as getMissingApiKeysMessage } from "./token-_1CBLbqH.js";
|
|
4
|
+
import { o as runProviderSetup } from "./auth-DBOz2FcU.js";
|
|
5
|
+
import { i as registerProcessCleanup, r as EventBus, t as setupCopilotRuntime } from "./copilot-runtime-0CujVONa.js";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
import consola from "consola";
|
|
8
8
|
import { resolve } from "node:path";
|
|
@@ -11,7 +11,7 @@ import { Agent, ProxyAgent, setGlobalDispatcher } from "undici";
|
|
|
11
11
|
import { pathToFileURL } from "node:url";
|
|
12
12
|
import { serve } from "srvx";
|
|
13
13
|
import { isIP } from "node:net";
|
|
14
|
-
|
|
14
|
+
// src/lib/proxy.ts
|
|
15
15
|
let proxyEnvDispatcher;
|
|
16
16
|
function initProxyFromEnv() {
|
|
17
17
|
try {
|
|
@@ -60,8 +60,7 @@ function initProxyFromEnv() {
|
|
|
60
60
|
consola.debug("Proxy setup skipped:", err);
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
|
-
|
|
64
|
-
//#region src/lib/server-host-shared.ts
|
|
63
|
+
// src/lib/server-host-shared.ts
|
|
65
64
|
const INVALID_HOST_CHARACTERS = /[\s/?#]/;
|
|
66
65
|
const NORMALIZED_WILDCARD_HOSTS = /* @__PURE__ */ new Set(["0.0.0.0", "::"]);
|
|
67
66
|
function stripIpv6Brackets(hostname) {
|
|
@@ -76,8 +75,7 @@ function normalizeHostnameBase(hostname) {
|
|
|
76
75
|
function isWildcardHostname(hostname) {
|
|
77
76
|
return NORMALIZED_WILDCARD_HOSTS.has(stripIpv6Brackets(hostname.trim()));
|
|
78
77
|
}
|
|
79
|
-
|
|
80
|
-
//#region src/lib/server-host.ts
|
|
78
|
+
// src/lib/server-host.ts
|
|
81
79
|
const DEFAULT_SERVER_HOST = "127.0.0.1";
|
|
82
80
|
function isLoopbackIpv4(hostname) {
|
|
83
81
|
return isIP(hostname) === 4 && hostname.split(".", 1)[0] === "127";
|
|
@@ -119,8 +117,7 @@ function resolveClientHostname(hostname) {
|
|
|
119
117
|
function formatServerUrl(hostname, port) {
|
|
120
118
|
return `http://${isIP(hostname) === 6 ? `[${hostname.replace("%", "%25")}]` : hostname}:${port}`;
|
|
121
119
|
}
|
|
122
|
-
|
|
123
|
-
//#region src/lib/gateway-plugins.ts
|
|
120
|
+
// src/lib/gateway-plugins.ts
|
|
124
121
|
const MAX_PENDING_EVENTS = 1024;
|
|
125
122
|
var GatewayPlugins = class {
|
|
126
123
|
bus = new EventBus();
|
|
@@ -241,8 +238,7 @@ async function loadGatewayPlugins(setting, options) {
|
|
|
241
238
|
}
|
|
242
239
|
return plugins;
|
|
243
240
|
}
|
|
244
|
-
|
|
245
|
-
//#region src/start.ts
|
|
241
|
+
// src/start.ts
|
|
246
242
|
async function resolveGitHubToken(cliToken) {
|
|
247
243
|
if (cliToken) return {
|
|
248
244
|
token: cliToken,
|
|
@@ -283,7 +279,7 @@ async function setupProviderMode() {
|
|
|
283
279
|
consola.info(`Configured providers: ${providersAfterSetup.join(", ")}`);
|
|
284
280
|
}
|
|
285
281
|
async function runServer(options) {
|
|
286
|
-
(await import("./tls-
|
|
282
|
+
(await import("./tls-cISpkgFD.js")).enableSystemCACompat();
|
|
287
283
|
consola.options.throttle = 0;
|
|
288
284
|
mergeConfigWithDefaults();
|
|
289
285
|
const configuredApiKeys = getConfiguredApiKeys();
|
|
@@ -305,7 +301,7 @@ async function runServer(options) {
|
|
|
305
301
|
if (resolvedGitHubToken && isGitHubCopilotEnabled()) await setupCopilotMode(resolvedGitHubToken.token, resolvedGitHubToken.source);
|
|
306
302
|
else await setupProviderMode();
|
|
307
303
|
consola.box(`🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`);
|
|
308
|
-
const { createServer } = await import("./server-
|
|
304
|
+
const { createServer } = await import("./server-Jvc5DYJV.js");
|
|
309
305
|
const plugins = await loadGatewayPlugins(process.env.COPILOT_API_PLUGINS, {
|
|
310
306
|
port: options.port,
|
|
311
307
|
baseDir: PATHS.APP_DIR
|
|
@@ -373,7 +369,6 @@ const start = defineCommand({
|
|
|
373
369
|
});
|
|
374
370
|
}
|
|
375
371
|
});
|
|
376
|
-
//#endregion
|
|
377
372
|
export { start };
|
|
378
373
|
|
|
379
|
-
//# sourceMappingURL=start-
|
|
374
|
+
//# sourceMappingURL=start-BQBvYKD-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-BEda1BbC.js","names":["get"],"sources":["../src/lib/proxy.ts","../src/lib/server-host-shared.ts","../src/lib/server-host.ts","../src/lib/gateway-plugins.ts","../src/start.ts"],"sourcesContent":["import consola from \"consola\"\nimport { getProxyForUrl } from \"proxy-from-env\"\nimport { Agent, ProxyAgent, setGlobalDispatcher, type Dispatcher } from \"undici\"\n\nlet proxyEnvDispatcher: Dispatcher | undefined\n\nexport function getProxyEnvDispatcher(): Dispatcher | undefined {\n return proxyEnvDispatcher\n}\n\nexport function initProxyFromEnv(): void {\n try {\n const direct = new Agent()\n const proxies = new Map<string, ProxyAgent>()\n\n // We only need a minimal dispatcher that implements `dispatch` at runtime.\n // Typing the object as `Dispatcher` forces TypeScript to require many\n // additional methods. Instead, keep a plain object and cast when passing\n // to `setGlobalDispatcher`.\n const dispatcher = {\n dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandler,\n ) {\n try {\n const origin =\n typeof options.origin === \"string\" ?\n new URL(options.origin)\n : (options.origin as URL)\n const get = getProxyForUrl as unknown as (\n u: string,\n ) => string | undefined\n const raw = get(origin.toString())\n const proxyUrl = raw && raw.length > 0 ? raw : undefined\n if (!proxyUrl) {\n consola.debug(`HTTP proxy bypass: ${origin.hostname}`)\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n let agent = proxies.get(proxyUrl)\n if (!agent) {\n agent = new ProxyAgent(proxyUrl)\n proxies.set(proxyUrl, agent)\n }\n let label = proxyUrl\n try {\n const u = new URL(proxyUrl)\n label = `${u.protocol}//${u.host}`\n } catch {\n /* noop */\n }\n consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`)\n return (agent as unknown as Dispatcher).dispatch(options, handler)\n } catch {\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n },\n close() {\n return direct.close()\n },\n destroy() {\n return direct.destroy()\n },\n }\n\n proxyEnvDispatcher = dispatcher as unknown as Dispatcher\n\n if (typeof Bun !== \"undefined\") {\n consola.debug(\"WebSocket proxy configured from environment (per-URL)\")\n return\n }\n\n setGlobalDispatcher(proxyEnvDispatcher)\n consola.debug(\"HTTP proxy configured from environment (per-URL)\")\n } catch (err) {\n consola.debug(\"Proxy setup skipped:\", err)\n }\n}\n","// Pure hostname helpers shared by the gateway server (Node) and the desktop\n// app (including the renderer bundle). This module must stay free of\n// `node:*` imports because the renderer cannot use `node:net`; all\n// address-family checks live in `server-host.ts`.\nexport const INVALID_HOST_CHARACTERS = /[\\s/?#]/\n\n// Bind hosts that listen on every interface, in normalized form (no\n// brackets, so \"[::]\" is covered via `stripIpv6Brackets`).\nexport const NORMALIZED_WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\"])\n\nexport function stripIpv6Brackets(hostname: string): string {\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n return hostname.slice(1, -1)\n }\n return hostname\n}\n\nexport function normalizeHostnameBase(hostname: string): string {\n const normalized = stripIpv6Brackets(hostname.trim())\n if (!normalized || INVALID_HOST_CHARACTERS.test(normalized)) {\n throw new Error(`Invalid server host: ${JSON.stringify(hostname)}`)\n }\n return normalized\n}\n\nexport function isWildcardHostname(hostname: string): boolean {\n return NORMALIZED_WILDCARD_HOSTS.has(stripIpv6Brackets(hostname.trim()))\n}\n","import { isIP } from \"node:net\"\n\nimport { isWildcardHostname, normalizeHostnameBase } from \"./server-host-shared\"\n\nexport const DEFAULT_SERVER_HOST = \"127.0.0.1\"\n\n// Listen failures that mean the hostname itself cannot be bound, as opposed\n// to the port being occupied (EADDRINUSE) or forbidden (EACCES). ENOTFOUND\n// covers unresolvable names such as typos, EADDRNOTAVAIL covers valid IPs\n// that are not assigned to this machine.\nconst INVALID_BIND_ERROR_CODES = new Set([\n \"ENOTFOUND\",\n \"EADDRNOTAVAIL\",\n \"EINVAL\",\n \"EAFNOSUPPORT\",\n \"ENXIO\",\n])\n\nexport function isInvalidBindErrorCode(code?: string): boolean {\n return !!code && INVALID_BIND_ERROR_CODES.has(code)\n}\n\nexport interface ServerBinding {\n hostname: string\n clientHostname: string\n networkExposed: boolean\n}\n\nfunction isLoopbackIpv4(hostname: string): boolean {\n return isIP(hostname) === 4 && hostname.split(\".\", 1)[0] === \"127\"\n}\n\nfunction isLoopbackMappedIpv4(hostname: string): boolean {\n try {\n const canonicalHostname = new URL(`http://[${hostname}]/`).hostname.slice(\n 1,\n -1,\n )\n const mappedIpv4 = canonicalHostname.match(\n /^::ffff:([\\da-f]{1,4}):[\\da-f]{1,4}$/,\n )\n if (!mappedIpv4) {\n return false\n }\n\n return (Number.parseInt(mappedIpv4[1], 16) & 0xff00) === 0x7f00\n } catch {\n return false\n }\n}\n\nexport function normalizeServerHostname(hostname: string): string {\n return normalizeHostnameBase(hostname)\n}\n\nexport function isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeServerHostname(hostname).toLowerCase()\n if (normalized === \"localhost\" || normalized === \"localhost.\") {\n return true\n }\n if (isLoopbackIpv4(normalized)) {\n return true\n }\n if (isIP(normalized) !== 6) {\n return false\n }\n\n if (normalized === \"::1\" || normalized === \"0:0:0:0:0:0:0:1\") {\n return true\n }\n\n return isLoopbackMappedIpv4(normalized)\n}\n\nexport function resolveServerBinding(\n hostname: string,\n hasApiKeys: boolean,\n): ServerBinding {\n const normalizedHostname = normalizeServerHostname(hostname)\n const networkExposed = !isLoopbackHostname(normalizedHostname)\n\n if (networkExposed && !hasApiKeys) {\n throw new Error(\n `Refusing to listen on non-loopback host ${JSON.stringify(normalizedHostname)} without gateway API keys. Run \\`npx @jeffreycao/copilot-api@latest auth keys --add <key>\\` first, or use \\`--host ${DEFAULT_SERVER_HOST}\\`.`,\n )\n }\n\n return {\n hostname: normalizedHostname,\n clientHostname: resolveClientHostname(normalizedHostname),\n networkExposed,\n }\n}\n\nexport function resolveClientHostname(hostname: string): string {\n const normalizedHostname = normalizeServerHostname(hostname)\n // Wildcard binds listen on every interface, which clients cannot dial\n // directly (0.0.0.0 is not a routable destination).\n return isWildcardHostname(normalizedHostname) ? DEFAULT_SERVER_HOST : (\n normalizedHostname.toLowerCase()\n )\n}\n\nexport function resolveClientHostnameOrDefault(\n hostname: string | null | undefined,\n): string {\n const normalizedHostname = hostname?.trim()\n return normalizedHostname ?\n resolveClientHostname(normalizedHostname)\n : DEFAULT_SERVER_HOST\n}\n\nexport function formatServerUrl(hostname: string, port: number): string {\n const urlHostname =\n isIP(hostname) === 6 ? `[${hostname.replace(\"%\", \"%25\")}]` : hostname\n return `http://${urlHostname}:${port}`\n}\n","import consola from \"consola\"\nimport { resolve } from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\n\nimport { EventBus } from \"./event-bus\"\nimport type {\n GatewayPluginApi,\n GatewayPluginEvents,\n GatewayPluginSetup,\n} from \"./types/gateway-plugins\"\nexport type {\n GatewayPluginApi,\n GatewayPluginEvents,\n GatewayPluginSetup,\n PluginRequest,\n} from \"./types/gateway-plugins\"\n\nconst MAX_PENDING_EVENTS = 1024\n\ninterface PluginState {\n name: string\n pending: number\n overflowReported: boolean\n tail: Promise<void>\n unsubscribe: Array<() => void>\n cleanup?: () => void | Promise<void>\n}\n\n// Each plugin has a bounded, ordered queue. Requests never await plugin I/O.\nexport class GatewayPlugins {\n private readonly bus = new EventBus<GatewayPluginEvents>()\n private readonly plugins: Array<PluginState> = []\n private subscriptions = 0\n private closing: Promise<void> | undefined\n\n private readonly port: number\n\n constructor(port: number) {\n this.port = port\n }\n\n get enabled(): boolean {\n return this.subscriptions > 0\n }\n\n async register(name: string, setup: GatewayPluginSetup): Promise<void> {\n if (this.closing) throw new Error(\"Gateway plugins are closing\")\n const plugin: PluginState = {\n name,\n pending: 0,\n overflowReported: false,\n tail: Promise.resolve(),\n unsubscribe: [],\n }\n const api: GatewayPluginApi = Object.freeze({\n version: 1 as const,\n server: Object.freeze({ pid: process.pid, port: this.port }),\n on: <Name extends keyof GatewayPluginEvents>(\n event: Name,\n handler: (\n value: Readonly<GatewayPluginEvents[Name]>,\n ) => void | Promise<void>,\n ) => {\n if (this.closing) throw new Error(\"Gateway plugins are closing\")\n const off = this.bus.subscribe(event, (value) => {\n if (plugin.pending >= MAX_PENDING_EVENTS) {\n if (!plugin.overflowReported) {\n plugin.overflowReported = true\n consola.warn(\n `Plugin '${name}' event queue is full; dropping events`,\n )\n }\n return\n }\n plugin.pending++\n plugin.tail = plugin.tail.then(async () => {\n try {\n await handler(value)\n } catch (error) {\n consola.warn(`Plugin '${name}' hook failed`, error)\n } finally {\n plugin.pending--\n if (!plugin.pending) plugin.overflowReported = false\n }\n })\n })\n this.subscriptions++\n let active = true\n const unsubscribe = () => {\n if (!active) return\n active = false\n off()\n this.subscriptions--\n }\n plugin.unsubscribe.push(unsubscribe)\n return unsubscribe\n },\n log: (message: string) => consola.info(`[plugin:${name}] ${message}`),\n })\n try {\n const cleanup = await setup(api)\n if (typeof cleanup === \"function\") plugin.cleanup = cleanup\n this.plugins.push(plugin)\n } catch (error) {\n for (const off of plugin.unsubscribe) off()\n throw error\n }\n }\n\n publish<Name extends keyof GatewayPluginEvents>(\n name: Name,\n event: GatewayPluginEvents[Name],\n ): void {\n if (this.enabled) {\n const snapshot = { ...event }\n Object.freeze(snapshot)\n this.bus.publish<Name>(name, snapshot)\n }\n }\n\n async flush(): Promise<void> {\n await Promise.all(this.plugins.map((plugin) => plugin.tail))\n }\n\n close(timeoutMs = 2000): Promise<void> {\n if (this.closing) return this.closing\n for (const plugin of this.plugins) {\n for (const off of plugin.unsubscribe) off()\n }\n let timer: ReturnType<typeof setTimeout>\n const shutdown = Promise.all(\n this.plugins.map(async (plugin) => {\n await plugin.tail\n try {\n await plugin.cleanup?.()\n } catch (error) {\n consola.warn(`Plugin '${plugin.name}' cleanup failed`, error)\n }\n }),\n )\n const timeout = new Promise<void>((resolveTimeout) => {\n timer = setTimeout(resolveTimeout, timeoutMs)\n })\n this.closing = Promise.race([shutdown, timeout]).then(() => {\n clearTimeout(timer)\n })\n return this.closing\n }\n}\n\nexport async function loadGatewayPlugins(\n setting: string | undefined,\n options: { port: number; baseDir: string },\n): Promise<GatewayPlugins | undefined> {\n if (!setting?.trim()) return undefined\n const paths: unknown = JSON.parse(setting)\n if (\n !Array.isArray(paths)\n || !paths.every((path: unknown) => typeof path === \"string\" && path.trim())\n ) {\n throw new Error(\n \"COPILOT_API_PLUGINS must be a JSON array of local module paths\",\n )\n }\n const plugins = new GatewayPlugins(options.port)\n for (const path of new Set(paths as Array<string>)) {\n const url = pathToFileURL(resolve(options.baseDir, path)).href\n try {\n const module: unknown = await import(url)\n if (\n !module\n || typeof module !== \"object\"\n || !(\"default\" in module)\n || typeof module.default !== \"function\"\n ) {\n throw new Error(\"Plugin must default-export a setup function\")\n }\n await plugins.register(path, module.default as GatewayPluginSetup)\n } catch (error) {\n consola.warn(`Failed to load gateway plugin '${path}'`, error)\n }\n }\n return plugins\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport { serve, type ServerHandler } from \"srvx\"\n\nimport { runProviderSetup } from \"./auth\"\nimport { isGitHubCopilotEnabled } from \"./lib/github-copilot-provider\"\nimport { listEnabledProviders, mergeConfigWithDefaults } from \"./lib/config\"\nimport { setupCopilotRuntime } from \"~/lib/copilot-runtime\"\nimport {\n GITHUB_TOKEN_ENV,\n readGitHubToken,\n readGitHubTokenFromEnv,\n} from \"./lib/credential-store\"\nimport { startModelsDevCache } from \"./lib/models-dev-cache\"\nimport { initOpencodeVersion } from \"./lib/opencode\"\nimport { ensurePaths, PATHS } from \"./lib/paths\"\nimport { initProxyFromEnv } from \"./lib/proxy\"\nimport {\n getConfiguredApiKeys,\n getMissingApiKeysMessage,\n} from \"./lib/request-auth\"\nimport {\n DEFAULT_SERVER_HOST,\n formatServerUrl,\n resolveServerBinding,\n} from \"./lib/server-host\"\nimport { state } from \"./lib/state\"\nimport { loadGatewayPlugins } from \"./lib/gateway-plugins\"\nimport { registerProcessCleanup } from \"./lib/process-cleanup\"\n\ninterface RunServerOptions {\n host: string\n port: number\n verbose: boolean\n githubToken?: string\n showToken: boolean\n proxyEnv: boolean\n}\n\ntype GitHubTokenSource = \"cli\" | \"env\" | \"file\"\n\n// The environment is preferred over the token file so the token never has to\n// travel through the process list; --github-token stays first for callers that\n// opt in explicitly.\nasync function resolveGitHubToken(\n cliToken: string | undefined,\n): Promise<{ token: string; source: GitHubTokenSource } | null> {\n if (cliToken) return { token: cliToken, source: \"cli\" }\n\n const envToken = readGitHubTokenFromEnv()\n if (envToken) return { token: envToken, source: \"env\" }\n\n const fileToken = await readGitHubToken()\n if (fileToken) return { token: fileToken, source: \"file\" }\n\n return null\n}\n\nasync function setupCopilotMode(\n githubToken: string,\n source: GitHubTokenSource,\n): Promise<void> {\n state.githubTokenSource = source\n consola.info(\n source === \"cli\" ? \"Using provided GitHub token\"\n : source === \"env\" ?\n `Using GitHub token from the ${GITHUB_TOKEN_ENV} environment variable`\n : \"Using GitHub token from local file\",\n )\n\n await setupCopilotRuntime(githubToken)\n}\n\nasync function setupProviderMode(): Promise<void> {\n const enabledProviders = listEnabledProviders()\n\n if (enabledProviders.length > 0) {\n consola.info(`Using enabled providers: ${enabledProviders.join(\", \")}`)\n return\n }\n\n if (!isGitHubCopilotEnabled()) {\n throw new Error(\n \"No enabled providers found. Enable GitHub Copilot with `copilot-api provider enable github-copilot`, or enable another configured provider.\",\n )\n }\n\n consola.info(\"No enabled providers found. Setting one up...\")\n await runProviderSetup()\n\n if (state.githubToken && isGitHubCopilotEnabled()) {\n // The setup flow persisted the token with the credential store.\n await setupCopilotMode(state.githubToken, \"file\")\n return\n }\n\n const providersAfterSetup = listEnabledProviders()\n if (providersAfterSetup.length === 0) {\n throw new Error(\n \"Failed to configure any provider. Run `copilot-api auth login` to set one up.\",\n )\n }\n consola.info(`Configured providers: ${providersAfterSetup.join(\", \")}`)\n}\n\nexport async function runServer(options: RunServerOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n consola.options.throttle = 0\n\n mergeConfigWithDefaults()\n\n const configuredApiKeys = getConfiguredApiKeys()\n const binding = resolveServerBinding(\n options.host,\n configuredApiKeys.length > 0,\n )\n\n const missingApiKeysMessage = getMissingApiKeysMessage()\n if (missingApiKeysMessage) {\n consola.info(missingApiKeysMessage)\n }\n\n await initOpencodeVersion()\n\n if (options.proxyEnv) {\n initProxyFromEnv()\n }\n\n state.verbose = options.verbose\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n await startModelsDevCache()\n\n const serverUrl = formatServerUrl(binding.clientHostname, options.port)\n\n const resolvedGitHubToken =\n isGitHubCopilotEnabled() ?\n await resolveGitHubToken(options.githubToken)\n : null\n if (resolvedGitHubToken && isGitHubCopilotEnabled()) {\n await setupCopilotMode(\n resolvedGitHubToken.token,\n resolvedGitHubToken.source,\n )\n } else {\n await setupProviderMode()\n }\n\n consola.box(\n `🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`,\n )\n\n const { createServer } = await import(\"./server\")\n const plugins = await loadGatewayPlugins(process.env.COPILOT_API_PLUGINS, {\n port: options.port,\n baseDir: PATHS.APP_DIR,\n })\n if (plugins) registerProcessCleanup(() => plugins.close())\n const server = createServer({\n networkExposed: binding.networkExposed,\n port: options.port,\n plugins,\n })\n\n serve({\n fetch: server.fetch as ServerHandler,\n hostname: binding.hostname,\n port: options.port,\n bun: {\n idleTimeout: 0,\n },\n })\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the Copilot API server\",\n },\n args: {\n host: {\n type: \"string\",\n default: process.env.HOST?.trim() || DEFAULT_SERVER_HOST,\n description: \"Host to listen on\",\n },\n port: {\n alias: \"p\",\n type: \"string\",\n default: \"4141\",\n description: \"Port to listen on\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"github-token\": {\n alias: \"g\",\n type: \"string\",\n description:\n \"Provide GitHub token directly (must be generated using the `auth` subcommand)\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub and Copilot tokens on fetch and refresh\",\n },\n \"proxy-env\": {\n type: \"boolean\",\n default: false,\n description: \"Initialize proxy from environment variables\",\n },\n },\n run({ args }) {\n return runServer({\n host: args.host,\n port: Number.parseInt(args.port, 10),\n verbose: args.verbose,\n githubToken: args[\"github-token\"],\n showToken: args[\"show-token\"],\n proxyEnv: args[\"proxy-env\"],\n })\n },\n})\n"],"mappings":";;;;;;;;;;;;;;AAIA,IAAI;AAMJ,SAAgB,mBAAyB;CACvC,IAAI;EACF,MAAM,SAAS,IAAI,MAAM;EACzB,MAAM,0BAAU,IAAI,IAAwB;EAmD5C,qBAAqB;GA5CnB,SACE,SACA,SACA;IACA,IAAI;KACF,MAAM,SACJ,OAAO,QAAQ,WAAW,WACxB,IAAI,IAAI,QAAQ,MAAM,IACrB,QAAQ;KAIb,MAAM,MAAMA,eAAI,OAAO,SAAS,CAAC;KACjC,MAAM,WAAW,OAAO,IAAI,SAAS,IAAI,MAAM,KAAA;KAC/C,IAAI,CAAC,UAAU;MACb,QAAQ,MAAM,sBAAsB,OAAO,UAAU;MACrD,OAAQ,OAAiC,SAAS,SAAS,OAAO;KACpE;KACA,IAAI,QAAQ,QAAQ,IAAI,QAAQ;KAChC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;CACF,CAAC;CAED,MAAM;EACJ,OAAO,OAAO;EACd,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,KAAK,EACH,aAAa,EACf;CACF,CAAC;AACH;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,MAAM;GACJ,MAAM;GACN,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAA;GAChC,aAAa;EACf;EACA,MAAM;GACJ,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,aACE;EACJ;EACA,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,aAAa;GACX,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,UAAU;GACf,MAAM,KAAK;GACX,MAAM,OAAO,SAAS,KAAK,MAAM,EAAE;GACnC,SAAS,KAAK;GACd,aAAa,KAAK;GAClB,WAAW,KAAK;GAChB,UAAU,KAAK;EACjB,CAAC;CACH;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"start-BQBvYKD-.js","names":["get"],"sources":["../src/lib/proxy.ts","../src/lib/server-host-shared.ts","../src/lib/server-host.ts","../src/lib/gateway-plugins.ts","../src/start.ts"],"sourcesContent":["import consola from \"consola\"\nimport { getProxyForUrl } from \"proxy-from-env\"\nimport { Agent, ProxyAgent, setGlobalDispatcher, type Dispatcher } from \"undici\"\n\nlet proxyEnvDispatcher: Dispatcher | undefined\n\nexport function getProxyEnvDispatcher(): Dispatcher | undefined {\n return proxyEnvDispatcher\n}\n\nexport function initProxyFromEnv(): void {\n try {\n const direct = new Agent()\n const proxies = new Map<string, ProxyAgent>()\n\n // We only need a minimal dispatcher that implements `dispatch` at runtime.\n // Typing the object as `Dispatcher` forces TypeScript to require many\n // additional methods. Instead, keep a plain object and cast when passing\n // to `setGlobalDispatcher`.\n const dispatcher = {\n dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandler,\n ) {\n try {\n const origin =\n typeof options.origin === \"string\" ?\n new URL(options.origin)\n : (options.origin as URL)\n const get = getProxyForUrl as unknown as (\n u: string,\n ) => string | undefined\n const raw = get(origin.toString())\n const proxyUrl = raw && raw.length > 0 ? raw : undefined\n if (!proxyUrl) {\n consola.debug(`HTTP proxy bypass: ${origin.hostname}`)\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n let agent = proxies.get(proxyUrl)\n if (!agent) {\n agent = new ProxyAgent(proxyUrl)\n proxies.set(proxyUrl, agent)\n }\n let label = proxyUrl\n try {\n const u = new URL(proxyUrl)\n label = `${u.protocol}//${u.host}`\n } catch {\n /* noop */\n }\n consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`)\n return (agent as unknown as Dispatcher).dispatch(options, handler)\n } catch {\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n },\n close() {\n return direct.close()\n },\n destroy() {\n return direct.destroy()\n },\n }\n\n proxyEnvDispatcher = dispatcher as unknown as Dispatcher\n\n if (typeof Bun !== \"undefined\") {\n consola.debug(\"WebSocket proxy configured from environment (per-URL)\")\n return\n }\n\n setGlobalDispatcher(proxyEnvDispatcher)\n consola.debug(\"HTTP proxy configured from environment (per-URL)\")\n } catch (err) {\n consola.debug(\"Proxy setup skipped:\", err)\n }\n}\n","// Pure hostname helpers shared by the gateway server (Node) and the desktop\n// app (including the renderer bundle). This module must stay free of\n// `node:*` imports because the renderer cannot use `node:net`; all\n// address-family checks live in `server-host.ts`.\nexport const INVALID_HOST_CHARACTERS = /[\\s/?#]/\n\n// Bind hosts that listen on every interface, in normalized form (no\n// brackets, so \"[::]\" is covered via `stripIpv6Brackets`).\nexport const NORMALIZED_WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\"])\n\nexport function stripIpv6Brackets(hostname: string): string {\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n return hostname.slice(1, -1)\n }\n return hostname\n}\n\nexport function normalizeHostnameBase(hostname: string): string {\n const normalized = stripIpv6Brackets(hostname.trim())\n if (!normalized || INVALID_HOST_CHARACTERS.test(normalized)) {\n throw new Error(`Invalid server host: ${JSON.stringify(hostname)}`)\n }\n return normalized\n}\n\nexport function isWildcardHostname(hostname: string): boolean {\n return NORMALIZED_WILDCARD_HOSTS.has(stripIpv6Brackets(hostname.trim()))\n}\n","import { isIP } from \"node:net\"\n\nimport { isWildcardHostname, normalizeHostnameBase } from \"./server-host-shared\"\n\nexport const DEFAULT_SERVER_HOST = \"127.0.0.1\"\n\n// Listen failures that mean the hostname itself cannot be bound, as opposed\n// to the port being occupied (EADDRINUSE) or forbidden (EACCES). ENOTFOUND\n// covers unresolvable names such as typos, EADDRNOTAVAIL covers valid IPs\n// that are not assigned to this machine.\nconst INVALID_BIND_ERROR_CODES = new Set([\n \"ENOTFOUND\",\n \"EADDRNOTAVAIL\",\n \"EINVAL\",\n \"EAFNOSUPPORT\",\n \"ENXIO\",\n])\n\nexport function isInvalidBindErrorCode(code?: string): boolean {\n return !!code && INVALID_BIND_ERROR_CODES.has(code)\n}\n\nexport interface ServerBinding {\n hostname: string\n clientHostname: string\n networkExposed: boolean\n}\n\nfunction isLoopbackIpv4(hostname: string): boolean {\n return isIP(hostname) === 4 && hostname.split(\".\", 1)[0] === \"127\"\n}\n\nfunction isLoopbackMappedIpv4(hostname: string): boolean {\n try {\n const canonicalHostname = new URL(`http://[${hostname}]/`).hostname.slice(\n 1,\n -1,\n )\n const mappedIpv4 = canonicalHostname.match(\n /^::ffff:([\\da-f]{1,4}):[\\da-f]{1,4}$/,\n )\n if (!mappedIpv4) {\n return false\n }\n\n return (Number.parseInt(mappedIpv4[1], 16) & 0xff00) === 0x7f00\n } catch {\n return false\n }\n}\n\nexport function normalizeServerHostname(hostname: string): string {\n return normalizeHostnameBase(hostname)\n}\n\nexport function isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeServerHostname(hostname).toLowerCase()\n if (normalized === \"localhost\" || normalized === \"localhost.\") {\n return true\n }\n if (isLoopbackIpv4(normalized)) {\n return true\n }\n if (isIP(normalized) !== 6) {\n return false\n }\n\n if (normalized === \"::1\" || normalized === \"0:0:0:0:0:0:0:1\") {\n return true\n }\n\n return isLoopbackMappedIpv4(normalized)\n}\n\nexport function resolveServerBinding(\n hostname: string,\n hasApiKeys: boolean,\n): ServerBinding {\n const normalizedHostname = normalizeServerHostname(hostname)\n const networkExposed = !isLoopbackHostname(normalizedHostname)\n\n if (networkExposed && !hasApiKeys) {\n throw new Error(\n `Refusing to listen on non-loopback host ${JSON.stringify(normalizedHostname)} without gateway API keys. Run \\`npx @jeffreycao/copilot-api@latest auth keys --add <key>\\` first, or use \\`--host ${DEFAULT_SERVER_HOST}\\`.`,\n )\n }\n\n return {\n hostname: normalizedHostname,\n clientHostname: resolveClientHostname(normalizedHostname),\n networkExposed,\n }\n}\n\nexport function resolveClientHostname(hostname: string): string {\n const normalizedHostname = normalizeServerHostname(hostname)\n // Wildcard binds listen on every interface, which clients cannot dial\n // directly (0.0.0.0 is not a routable destination).\n return isWildcardHostname(normalizedHostname) ? DEFAULT_SERVER_HOST : (\n normalizedHostname.toLowerCase()\n )\n}\n\nexport function resolveClientHostnameOrDefault(\n hostname: string | null | undefined,\n): string {\n const normalizedHostname = hostname?.trim()\n return normalizedHostname ?\n resolveClientHostname(normalizedHostname)\n : DEFAULT_SERVER_HOST\n}\n\nexport function formatServerUrl(hostname: string, port: number): string {\n const urlHostname =\n isIP(hostname) === 6 ? `[${hostname.replace(\"%\", \"%25\")}]` : hostname\n return `http://${urlHostname}:${port}`\n}\n","import consola from \"consola\"\nimport { resolve } from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\n\nimport { EventBus } from \"./event-bus\"\nimport type {\n GatewayPluginApi,\n GatewayPluginEvents,\n GatewayPluginSetup,\n} from \"./types/gateway-plugins\"\nexport type {\n GatewayPluginApi,\n GatewayPluginEvents,\n GatewayPluginSetup,\n PluginRequest,\n} from \"./types/gateway-plugins\"\n\nconst MAX_PENDING_EVENTS = 1024\n\ninterface PluginState {\n name: string\n pending: number\n overflowReported: boolean\n tail: Promise<void>\n unsubscribe: Array<() => void>\n cleanup?: () => void | Promise<void>\n}\n\n// Each plugin has a bounded, ordered queue. Requests never await plugin I/O.\nexport class GatewayPlugins {\n private readonly bus = new EventBus<GatewayPluginEvents>()\n private readonly plugins: Array<PluginState> = []\n private subscriptions = 0\n private closing: Promise<void> | undefined\n\n private readonly port: number\n\n constructor(port: number) {\n this.port = port\n }\n\n get enabled(): boolean {\n return this.subscriptions > 0\n }\n\n async register(name: string, setup: GatewayPluginSetup): Promise<void> {\n if (this.closing) throw new Error(\"Gateway plugins are closing\")\n const plugin: PluginState = {\n name,\n pending: 0,\n overflowReported: false,\n tail: Promise.resolve(),\n unsubscribe: [],\n }\n const api: GatewayPluginApi = Object.freeze({\n version: 1 as const,\n server: Object.freeze({ pid: process.pid, port: this.port }),\n on: <Name extends keyof GatewayPluginEvents>(\n event: Name,\n handler: (\n value: Readonly<GatewayPluginEvents[Name]>,\n ) => void | Promise<void>,\n ) => {\n if (this.closing) throw new Error(\"Gateway plugins are closing\")\n const off = this.bus.subscribe(event, (value) => {\n if (plugin.pending >= MAX_PENDING_EVENTS) {\n if (!plugin.overflowReported) {\n plugin.overflowReported = true\n consola.warn(\n `Plugin '${name}' event queue is full; dropping events`,\n )\n }\n return\n }\n plugin.pending++\n plugin.tail = plugin.tail.then(async () => {\n try {\n await handler(value)\n } catch (error) {\n consola.warn(`Plugin '${name}' hook failed`, error)\n } finally {\n plugin.pending--\n if (!plugin.pending) plugin.overflowReported = false\n }\n })\n })\n this.subscriptions++\n let active = true\n const unsubscribe = () => {\n if (!active) return\n active = false\n off()\n this.subscriptions--\n }\n plugin.unsubscribe.push(unsubscribe)\n return unsubscribe\n },\n log: (message: string) => consola.info(`[plugin:${name}] ${message}`),\n })\n try {\n const cleanup = await setup(api)\n if (typeof cleanup === \"function\") plugin.cleanup = cleanup\n this.plugins.push(plugin)\n } catch (error) {\n for (const off of plugin.unsubscribe) off()\n throw error\n }\n }\n\n publish<Name extends keyof GatewayPluginEvents>(\n name: Name,\n event: GatewayPluginEvents[Name],\n ): void {\n if (this.enabled) {\n const snapshot = { ...event }\n Object.freeze(snapshot)\n this.bus.publish<Name>(name, snapshot)\n }\n }\n\n async flush(): Promise<void> {\n await Promise.all(this.plugins.map((plugin) => plugin.tail))\n }\n\n close(timeoutMs = 2000): Promise<void> {\n if (this.closing) return this.closing\n for (const plugin of this.plugins) {\n for (const off of plugin.unsubscribe) off()\n }\n let timer: ReturnType<typeof setTimeout>\n const shutdown = Promise.all(\n this.plugins.map(async (plugin) => {\n await plugin.tail\n try {\n await plugin.cleanup?.()\n } catch (error) {\n consola.warn(`Plugin '${plugin.name}' cleanup failed`, error)\n }\n }),\n )\n const timeout = new Promise<void>((resolveTimeout) => {\n timer = setTimeout(resolveTimeout, timeoutMs)\n })\n this.closing = Promise.race([shutdown, timeout]).then(() => {\n clearTimeout(timer)\n })\n return this.closing\n }\n}\n\nexport async function loadGatewayPlugins(\n setting: string | undefined,\n options: { port: number; baseDir: string },\n): Promise<GatewayPlugins | undefined> {\n if (!setting?.trim()) return undefined\n const paths: unknown = JSON.parse(setting)\n if (\n !Array.isArray(paths)\n || !paths.every((path: unknown) => typeof path === \"string\" && path.trim())\n ) {\n throw new Error(\n \"COPILOT_API_PLUGINS must be a JSON array of local module paths\",\n )\n }\n const plugins = new GatewayPlugins(options.port)\n for (const path of new Set(paths as Array<string>)) {\n const url = pathToFileURL(resolve(options.baseDir, path)).href\n try {\n const module: unknown = await import(url)\n if (\n !module\n || typeof module !== \"object\"\n || !(\"default\" in module)\n || typeof module.default !== \"function\"\n ) {\n throw new Error(\"Plugin must default-export a setup function\")\n }\n await plugins.register(path, module.default as GatewayPluginSetup)\n } catch (error) {\n consola.warn(`Failed to load gateway plugin '${path}'`, error)\n }\n }\n return plugins\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport { serve, type ServerHandler } from \"srvx\"\n\nimport { runProviderSetup } from \"./auth\"\nimport { isGitHubCopilotEnabled } from \"./lib/github-copilot-provider\"\nimport { listEnabledProviders, mergeConfigWithDefaults } from \"./lib/config\"\nimport { setupCopilotRuntime } from \"~/lib/copilot-runtime\"\nimport {\n GITHUB_TOKEN_ENV,\n readGitHubToken,\n readGitHubTokenFromEnv,\n} from \"./lib/credential-store\"\nimport { startModelsDevCache } from \"./lib/models-dev-cache\"\nimport { initOpencodeVersion } from \"./lib/opencode\"\nimport { ensurePaths, PATHS } from \"./lib/paths\"\nimport { initProxyFromEnv } from \"./lib/proxy\"\nimport {\n getConfiguredApiKeys,\n getMissingApiKeysMessage,\n} from \"./lib/request-auth\"\nimport {\n DEFAULT_SERVER_HOST,\n formatServerUrl,\n resolveServerBinding,\n} from \"./lib/server-host\"\nimport { state } from \"./lib/state\"\nimport { loadGatewayPlugins } from \"./lib/gateway-plugins\"\nimport { registerProcessCleanup } from \"./lib/process-cleanup\"\n\ninterface RunServerOptions {\n host: string\n port: number\n verbose: boolean\n githubToken?: string\n showToken: boolean\n proxyEnv: boolean\n}\n\ntype GitHubTokenSource = \"cli\" | \"env\" | \"file\"\n\n// The environment is preferred over the token file so the token never has to\n// travel through the process list; --github-token stays first for callers that\n// opt in explicitly.\nasync function resolveGitHubToken(\n cliToken: string | undefined,\n): Promise<{ token: string; source: GitHubTokenSource } | null> {\n if (cliToken) return { token: cliToken, source: \"cli\" }\n\n const envToken = readGitHubTokenFromEnv()\n if (envToken) return { token: envToken, source: \"env\" }\n\n const fileToken = await readGitHubToken()\n if (fileToken) return { token: fileToken, source: \"file\" }\n\n return null\n}\n\nasync function setupCopilotMode(\n githubToken: string,\n source: GitHubTokenSource,\n): Promise<void> {\n state.githubTokenSource = source\n consola.info(\n source === \"cli\" ? \"Using provided GitHub token\"\n : source === \"env\" ?\n `Using GitHub token from the ${GITHUB_TOKEN_ENV} environment variable`\n : \"Using GitHub token from local file\",\n )\n\n await setupCopilotRuntime(githubToken)\n}\n\nasync function setupProviderMode(): Promise<void> {\n const enabledProviders = listEnabledProviders()\n\n if (enabledProviders.length > 0) {\n consola.info(`Using enabled providers: ${enabledProviders.join(\", \")}`)\n return\n }\n\n if (!isGitHubCopilotEnabled()) {\n throw new Error(\n \"No enabled providers found. Enable GitHub Copilot with `copilot-api provider enable github-copilot`, or enable another configured provider.\",\n )\n }\n\n consola.info(\"No enabled providers found. Setting one up...\")\n await runProviderSetup()\n\n if (state.githubToken && isGitHubCopilotEnabled()) {\n // The setup flow persisted the token with the credential store.\n await setupCopilotMode(state.githubToken, \"file\")\n return\n }\n\n const providersAfterSetup = listEnabledProviders()\n if (providersAfterSetup.length === 0) {\n throw new Error(\n \"Failed to configure any provider. Run `copilot-api auth login` to set one up.\",\n )\n }\n consola.info(`Configured providers: ${providersAfterSetup.join(\", \")}`)\n}\n\nexport async function runServer(options: RunServerOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n consola.options.throttle = 0\n\n mergeConfigWithDefaults()\n\n const configuredApiKeys = getConfiguredApiKeys()\n const binding = resolveServerBinding(\n options.host,\n configuredApiKeys.length > 0,\n )\n\n const missingApiKeysMessage = getMissingApiKeysMessage()\n if (missingApiKeysMessage) {\n consola.info(missingApiKeysMessage)\n }\n\n await initOpencodeVersion()\n\n if (options.proxyEnv) {\n initProxyFromEnv()\n }\n\n state.verbose = options.verbose\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n await startModelsDevCache()\n\n const serverUrl = formatServerUrl(binding.clientHostname, options.port)\n\n const resolvedGitHubToken =\n isGitHubCopilotEnabled() ?\n await resolveGitHubToken(options.githubToken)\n : null\n if (resolvedGitHubToken && isGitHubCopilotEnabled()) {\n await setupCopilotMode(\n resolvedGitHubToken.token,\n resolvedGitHubToken.source,\n )\n } else {\n await setupProviderMode()\n }\n\n consola.box(\n `🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`,\n )\n\n const { createServer } = await import(\"./server\")\n const plugins = await loadGatewayPlugins(process.env.COPILOT_API_PLUGINS, {\n port: options.port,\n baseDir: PATHS.APP_DIR,\n })\n if (plugins) registerProcessCleanup(() => plugins.close())\n const server = createServer({\n networkExposed: binding.networkExposed,\n port: options.port,\n plugins,\n })\n\n serve({\n fetch: server.fetch as ServerHandler,\n hostname: binding.hostname,\n port: options.port,\n bun: {\n idleTimeout: 0,\n },\n })\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the Copilot API server\",\n },\n args: {\n host: {\n type: \"string\",\n default: process.env.HOST?.trim() || DEFAULT_SERVER_HOST,\n description: \"Host to listen on\",\n },\n port: {\n alias: \"p\",\n type: \"string\",\n default: \"4141\",\n description: \"Port to listen on\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"github-token\": {\n alias: \"g\",\n type: \"string\",\n description:\n \"Provide GitHub token directly (must be generated using the `auth` subcommand)\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub and Copilot tokens on fetch and refresh\",\n },\n \"proxy-env\": {\n type: \"boolean\",\n default: false,\n description: \"Initialize proxy from environment variables\",\n },\n },\n run({ args }) {\n return runServer({\n host: args.host,\n port: Number.parseInt(args.port, 10),\n verbose: args.verbose,\n githubToken: args[\"github-token\"],\n showToken: args[\"show-token\"],\n proxyEnv: args[\"proxy-env\"],\n })\n },\n})\n"],"mappings":";;;;;;;;;;;;;;AAIA,IAAI;AAMJ,SAAgB,mBAAyB;CACvC,IAAI;EACF,MAAM,SAAS,IAAI,MAAM;EACzB,MAAM,0BAAU,IAAI,IAAwB;EAmD5C,qBAAqB;GA5CnB,SACE,SACA,S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oB,MACtB;MAEA,MAAM,kBAAkB;CAG1B,QAAQ,IACN,wBAAwB,UAAU,yBAAyB,UAAU,OACvE;CAEA,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,UAAU,MAAM,mBAAmB,QAAQ,IAAI,qBAAqB;EACxE,MAAM,QAAQ;EACd,SAAS,MAAM;CACjB,CAAC;CACD,IAAI,SAAS,6BAA6B,QAAQ,MAAM,CAAC;CACzD,MAAM,SAAS,aAAa;EAC1B,gBAAgB,QAAQ;EACxB,MAAM,QAAQ;EACd;CACF,CAAC;CAED,MAAM;EACJ,OAAO,OAAO;EACd,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,KAAK,EACH,aAAa,EACf;CACF,CAAC;AACH;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,MAAM;GACJ,MAAM;GACN,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAA;GAChC,aAAa;EACf;EACA,MAAM;GACJ,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,aACE;EACJ;EACA,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,aAAa;GACX,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,UAAU;GACf,MAAM,KAAK;GACX,MAAM,OAAO,SAAS,KAAK,MAAM,EAAE;GACnC,SAAS,KAAK;GACd,aAAa,KAAK;GAClB,WAAW,KAAK;GAChB,UAAU,KAAK;EACjB,CAAC;CACH;AACF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import consola from "consola";
|
|
2
2
|
import tls from "node:tls";
|
|
3
|
-
|
|
3
|
+
// src/lib/tls.ts
|
|
4
4
|
function enableSystemCACompat() {
|
|
5
5
|
if (!(typeof Bun !== "undefined")) try {
|
|
6
6
|
const defaultCerts = tls.getCACertificates("default");
|
|
@@ -10,7 +10,6 @@ function enableSystemCACompat() {
|
|
|
10
10
|
consola.log("[tls] system ca not available");
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
//#endregion
|
|
14
13
|
export { enableSystemCACompat };
|
|
15
14
|
|
|
16
|
-
//# sourceMappingURL=tls-
|
|
15
|
+
//# sourceMappingURL=tls-cISpkgFD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tls-
|
|
1
|
+
{"version":3,"file":"tls-cISpkgFD.js","names":[],"sources":["../src/lib/tls.ts"],"sourcesContent":["import consola from \"consola\"\nimport tls from \"node:tls\"\n\nexport function enableSystemCACompat() {\n const isBun = typeof Bun !== \"undefined\"\n if (!isBun) {\n try {\n const defaultCerts = tls.getCACertificates(\"default\")\n const systemCerts = tls.getCACertificates(\"system\")\n tls.setDefaultCACertificates([...defaultCerts, ...systemCerts])\n } catch {\n consola.log(\"[tls] system ca not available\")\n }\n }\n}\n"],"mappings":";;;AAGA,SAAgB,uBAAuB;CAErC,IAAI,EADU,OAAO,QAAQ,cAE3B,IAAI;EACF,MAAM,eAAe,IAAI,kBAAkB,SAAS;EACpD,MAAM,cAAc,IAAI,kBAAkB,QAAQ;EAClD,IAAI,yBAAyB,CAAC,GAAG,cAAc,GAAG,WAAW,CAAC;CAChE,QAAQ;EACN,QAAQ,IAAI,+BAA+B;CAC7C;AAEJ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as UpstreamStreamInactivityTimeoutError, D as state, M as writeFileAtomically, O as HTTPError, S as PATHS, T as assertGitHubCopilotEnabled, c as getConfig, d as getUpstreamTransportConfig, g as isResponsesApiWebSocketEnabled, k as UpstreamHeadersTimeoutError, v as readEditableConfigFromDisk } from "./config-store-
|
|
2
|
-
import { c as setProviderConfig, n as getRawProviderConfig } from "./config-
|
|
1
|
+
import { A as UpstreamStreamInactivityTimeoutError, D as state, M as writeFileAtomically, O as HTTPError, S as PATHS, T as assertGitHubCopilotEnabled, c as getConfig, d as getUpstreamTransportConfig, g as isResponsesApiWebSocketEnabled, k as UpstreamHeadersTimeoutError, v as readEditableConfigFromDisk } from "./config-store-BsluQttR.js";
|
|
2
|
+
import { c as setProviderConfig, n as getRawProviderConfig } from "./config-BqSuE5h5.js";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
5
5
|
import path from "node:path";
|
|
@@ -12,15 +12,14 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
12
12
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
13
13
|
import { z } from "zod";
|
|
14
14
|
import { exec } from "node:child_process";
|
|
15
|
-
|
|
15
|
+
// src/lib/internal-headers.ts
|
|
16
16
|
const FULL_MODEL_CATALOG_HEADER = "x-full-model-catalog";
|
|
17
17
|
function stripInternalRequestHeaders(headers) {
|
|
18
18
|
const forwarded = new Headers(headers);
|
|
19
19
|
forwarded.delete(FULL_MODEL_CATALOG_HEADER);
|
|
20
20
|
return forwarded;
|
|
21
21
|
}
|
|
22
|
-
|
|
23
|
-
//#region src/services/responses-websocket.ts
|
|
22
|
+
// src/services/responses-websocket.ts
|
|
24
23
|
const websocketPool = /* @__PURE__ */ new Map();
|
|
25
24
|
const websocketActiveRequests = /* @__PURE__ */ new Map();
|
|
26
25
|
var ResponsesWebSocketOpenTimeoutError = class extends Error {
|
|
@@ -438,8 +437,7 @@ const getProxyUrl = (url) => getProxyForUrl(url.replace(/^wss:/u, "https:").repl
|
|
|
438
437
|
const unrefTimer = (timer) => {
|
|
439
438
|
if (typeof timer === "object" && "unref" in timer && typeof timer.unref === "function") timer.unref();
|
|
440
439
|
};
|
|
441
|
-
|
|
442
|
-
//#region src/services/responses-websocket-helpers.ts
|
|
440
|
+
// src/services/responses-websocket-helpers.ts
|
|
443
441
|
const encodePoolKeyPart = (value) => encodeURIComponent(value);
|
|
444
442
|
const getErrorMessage = (error) => {
|
|
445
443
|
if (error instanceof Error && error.message) return error.message;
|
|
@@ -478,8 +476,7 @@ const createResponsesSafeStream = async function* (source, options = {}) {
|
|
|
478
476
|
}
|
|
479
477
|
};
|
|
480
478
|
const isAbortError = (error) => error instanceof Error && error.name === "AbortError";
|
|
481
|
-
|
|
482
|
-
//#region src/services/responses-http.ts
|
|
479
|
+
// src/services/responses-http.ts
|
|
483
480
|
const createResponsesHttpEventStream = async function* (response) {
|
|
484
481
|
const responseBody = response.body;
|
|
485
482
|
if (!responseBody) return;
|
|
@@ -507,8 +504,7 @@ const createResponsesHttpEventStream = async function* (response) {
|
|
|
507
504
|
}
|
|
508
505
|
}
|
|
509
506
|
};
|
|
510
|
-
|
|
511
|
-
//#region src/services/upstream-http.ts
|
|
507
|
+
// src/services/upstream-http.ts
|
|
512
508
|
async function fetchUpstreamWithLifecycle(input, init, options) {
|
|
513
509
|
options.clientSignal?.throwIfAborted();
|
|
514
510
|
const lifecycle = createRequestLifecycle(options);
|
|
@@ -645,8 +641,7 @@ const toError = (value) => {
|
|
|
645
641
|
if (value instanceof Error) return value;
|
|
646
642
|
return new Error(String(value));
|
|
647
643
|
};
|
|
648
|
-
|
|
649
|
-
//#region src/lib/request-context.ts
|
|
644
|
+
// src/lib/request-context.ts
|
|
650
645
|
const TRACE_ID_MAX_LENGTH = 64;
|
|
651
646
|
const TRACE_ID_PATTERN = /^\w[\w.-]*$/;
|
|
652
647
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
@@ -665,8 +660,7 @@ function resolveTraceId(traceId) {
|
|
|
665
660
|
if (!candidate || candidate.length > TRACE_ID_MAX_LENGTH || !TRACE_ID_PATTERN.test(candidate)) return generateTraceId();
|
|
666
661
|
return candidate;
|
|
667
662
|
}
|
|
668
|
-
|
|
669
|
-
//#region src/services/codex/create-responses.ts
|
|
663
|
+
// src/services/codex/create-responses.ts
|
|
670
664
|
const CODEX_API_BASE_URL = "https://chatgpt.com/backend-api";
|
|
671
665
|
const CODEX_RESPONSE_METADATA_EVENT = "codex.response.metadata";
|
|
672
666
|
const RESPONSE_CREATED_EVENT = "response.created";
|
|
@@ -972,8 +966,7 @@ function shouldIncludeHeader(headerName) {
|
|
|
972
966
|
const header = headerName.toLowerCase();
|
|
973
967
|
return !header.includes("trace") && !header.startsWith("x-codex-turn");
|
|
974
968
|
}
|
|
975
|
-
|
|
976
|
-
//#region src/lib/oauth/codex.ts
|
|
969
|
+
// src/lib/oauth/codex.ts
|
|
977
970
|
const CALLBACK_HOST = "127.0.0.1";
|
|
978
971
|
const CALLBACK_PORT = 1455;
|
|
979
972
|
const CALLBACK_PATH = "/auth/callback";
|
|
@@ -1315,8 +1308,7 @@ async function refreshCodexCredentials(credentials, options = {}) {
|
|
|
1315
1308
|
function isCodexCredentialsExpired(credentials, now = Date.now()) {
|
|
1316
1309
|
return credentials.expiresAt <= now + REFRESH_BUFFER_MS$1;
|
|
1317
1310
|
}
|
|
1318
|
-
|
|
1319
|
-
//#region src/lib/oauth/xai.ts
|
|
1311
|
+
// src/lib/oauth/xai.ts
|
|
1320
1312
|
const XAI_API_BASE_URL = "https://cli-chat-proxy.grok.com";
|
|
1321
1313
|
const CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
1322
1314
|
const ISSUER = "https://auth.x.ai/oauth2";
|
|
@@ -1786,8 +1778,7 @@ const readCodexCredentialStore = codexCredentialStore.readStore;
|
|
|
1786
1778
|
codexCredentialStore.readCredentials;
|
|
1787
1779
|
const writeCodexCredentials = codexCredentialStore.writeCredentials;
|
|
1788
1780
|
codexCredentialStore.removeCredentials;
|
|
1789
|
-
|
|
1790
|
-
//#region src/lib/oauth-accounts.ts
|
|
1781
|
+
// src/lib/oauth-accounts.ts
|
|
1791
1782
|
function createOAuthAccountManager(options) {
|
|
1792
1783
|
const store = createOAuthCredentialStore(options.label, options.credentialPath);
|
|
1793
1784
|
const withMutationLock = (operation) => withCredentialFileLock(`${options.credentialPath()}.accounts`, operation);
|
|
@@ -1829,8 +1820,7 @@ function createOAuthAccountManager(options) {
|
|
|
1829
1820
|
})
|
|
1830
1821
|
};
|
|
1831
1822
|
}
|
|
1832
|
-
|
|
1833
|
-
//#region src/lib/xai-token.ts
|
|
1823
|
+
// src/lib/xai-token.ts
|
|
1834
1824
|
function syncXaiProviderConfig(accountId, enable = false) {
|
|
1835
1825
|
const { apiKey: _apiKey, modelsDevProviderId: _catalog, ...existing } = readEditableConfigFromDisk().providers?.xai ?? {};
|
|
1836
1826
|
setProviderConfig("xai", {
|
|
@@ -1888,8 +1878,7 @@ async function getXaiAccessToken() {
|
|
|
1888
1878
|
refreshInFlight.set(key, refresh);
|
|
1889
1879
|
return await refresh;
|
|
1890
1880
|
}
|
|
1891
|
-
|
|
1892
|
-
//#region src/lib/request-auth.ts
|
|
1881
|
+
// src/lib/request-auth.ts
|
|
1893
1882
|
function normalizeApiKeys(apiKeys) {
|
|
1894
1883
|
if (!Array.isArray(apiKeys)) {
|
|
1895
1884
|
if (apiKeys !== void 0) consola.warn("Invalid auth.apiKeys config. Expected an array of strings.");
|
|
@@ -1956,8 +1945,7 @@ const compactAutoContinuePromptStarts = [
|
|
|
1956
1945
|
"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."
|
|
1957
1946
|
];
|
|
1958
1947
|
const compactMessageSections = ["Pending Tasks:", "Current Work:"];
|
|
1959
|
-
|
|
1960
|
-
//#region src/lib/opencode.ts
|
|
1948
|
+
// src/lib/opencode.ts
|
|
1961
1949
|
const execAsync = (command) => {
|
|
1962
1950
|
return new Promise((resolve, reject) => {
|
|
1963
1951
|
exec(command, (error, stdout) => {
|
|
@@ -1991,8 +1979,7 @@ const initOpencodeVersion = () => {
|
|
|
1991
1979
|
const getCachedOpencodeVersion = () => {
|
|
1992
1980
|
return opencodeVersionCache;
|
|
1993
1981
|
};
|
|
1994
|
-
|
|
1995
|
-
//#region src/lib/api-config.ts
|
|
1982
|
+
// src/lib/api-config.ts
|
|
1996
1983
|
const isOpencodeOauthApp = () => {
|
|
1997
1984
|
return process.env.COPILOT_API_OAUTH_APP?.trim() === "opencode";
|
|
1998
1985
|
};
|
|
@@ -2229,8 +2216,7 @@ const GITHUB_BASE_URL = "https://github.com";
|
|
|
2229
2216
|
const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
2230
2217
|
const GITHUB_APP_SCOPES = ["read:user"].join(" ");
|
|
2231
2218
|
const OPENCODE_GITHUB_CLIENT_ID = "Ov23li8tweQw6odWQebz";
|
|
2232
|
-
|
|
2233
|
-
//#region src/services/github/get-copilot-token.ts
|
|
2219
|
+
// src/services/github/get-copilot-token.ts
|
|
2234
2220
|
const getCopilotToken = async () => {
|
|
2235
2221
|
const response = await fetch(`${getGitHubApiBaseUrl()}/copilot_internal/v2/token`, { headers: githubHeaders(state) });
|
|
2236
2222
|
if (!response.ok) {
|
|
@@ -2240,8 +2226,7 @@ const getCopilotToken = async () => {
|
|
|
2240
2226
|
}
|
|
2241
2227
|
return await response.json();
|
|
2242
2228
|
};
|
|
2243
|
-
|
|
2244
|
-
//#region src/services/github/get-copilot-usage.ts
|
|
2229
|
+
// src/services/github/get-copilot-usage.ts
|
|
2245
2230
|
const getCopilotUsage = async (githubToken) => {
|
|
2246
2231
|
const resolvedGithubToken = githubToken ?? state.githubToken;
|
|
2247
2232
|
if (!resolvedGithubToken) return null;
|
|
@@ -2257,8 +2242,7 @@ const getCopilotUsage = async (githubToken) => {
|
|
|
2257
2242
|
}
|
|
2258
2243
|
return await response.json();
|
|
2259
2244
|
};
|
|
2260
|
-
|
|
2261
|
-
//#region src/services/github/get-device-code.ts
|
|
2245
|
+
// src/services/github/get-device-code.ts
|
|
2262
2246
|
async function getDeviceCode() {
|
|
2263
2247
|
const { clientId, headers, scope } = getOauthAppConfig();
|
|
2264
2248
|
const { deviceCodeUrl } = getOauthUrls();
|
|
@@ -2273,8 +2257,7 @@ async function getDeviceCode() {
|
|
|
2273
2257
|
if (!response.ok) throw new HTTPError("Failed to get device code", response);
|
|
2274
2258
|
return await response.json();
|
|
2275
2259
|
}
|
|
2276
|
-
|
|
2277
|
-
//#region src/lib/utils.ts
|
|
2260
|
+
// src/lib/utils.ts
|
|
2278
2261
|
const sleep = (ms) => new Promise((resolve) => {
|
|
2279
2262
|
setTimeout(resolve, ms);
|
|
2280
2263
|
});
|
|
@@ -2352,8 +2335,7 @@ const getUUID = (content) => {
|
|
|
2352
2335
|
const uuidHex = uuidBytes.toString("hex");
|
|
2353
2336
|
return `${uuidHex.slice(0, 8)}-${uuidHex.slice(8, 12)}-${uuidHex.slice(12, 16)}-${uuidHex.slice(16, 20)}-${uuidHex.slice(20)}`;
|
|
2354
2337
|
};
|
|
2355
|
-
|
|
2356
|
-
//#region src/services/github/poll-access-token.ts
|
|
2338
|
+
// src/services/github/poll-access-token.ts
|
|
2357
2339
|
const SLOW_DOWN_INTERVAL_INCREMENT_SECONDS = 5;
|
|
2358
2340
|
const defaultPollAccessTokenDependencies = {
|
|
2359
2341
|
now: () => Date.now(),
|
|
@@ -2436,8 +2418,7 @@ function describeError(error) {
|
|
|
2436
2418
|
const detail = cause.message || cause.code;
|
|
2437
2419
|
return detail ? `${error.message} (${detail})` : error.message;
|
|
2438
2420
|
}
|
|
2439
|
-
|
|
2440
|
-
//#region src/lib/token.ts
|
|
2421
|
+
// src/lib/token.ts
|
|
2441
2422
|
let copilotRefreshLoopController = null;
|
|
2442
2423
|
let codexRefreshLoopController = null;
|
|
2443
2424
|
let codexRuntimeGeneration = 0;
|
|
@@ -2760,7 +2741,6 @@ async function logUser(dependencies = defaultCopilotTokenDependencies) {
|
|
|
2760
2741
|
state.copilotApiUrl = copilotUser.endpoints.api;
|
|
2761
2742
|
state.tokenBasedBilling = copilotUser.token_based_billing;
|
|
2762
2743
|
}
|
|
2763
|
-
//#endregion
|
|
2764
2744
|
export { forwardCodexResponses as $, initOpencodeVersion as A, getXaiAccessToken as B, copilotHeaders as C, prepareForCompact as D, isOpencodeOauthApp as E, compactTextOnlyGuard as F, GITHUB_TOKEN_ENV as G, persistXaiCredentials as H, createAuthMiddleware as I, XAI_API_BASE_URL as J, readGitHubToken as K, getConfiguredAdminApiKeys as L, compactMessageSections as M, compactSummaryPromptStart as N, prepareInteractionHeaders as O, compactSystemPromptStarts as P, buildCodexRequestHeaders as Q, getConfiguredApiKeys as R, copilotBaseUrl as S, copilotWebSocketHeaders as T, removeXaiAccount as U, getXaiAccounts as V, selectXaiAccount as W, loginCodex as X, loginXai as Y, CODEX_API_BASE_URL as Z, isAsyncIterable as _, removeCodexAccount as a, createResponsesHttpEventStream as at, parseUserIdMetadata as b, setupCopilotToken as c, getResponsesStreamTerminalDisposition as ct, generateRequestIdFromPayload as d, FULL_MODEL_CATALOG_HEADER as dt, generateTraceId as et, getPromptCacheKey as f, stripInternalRequestHeaders as ft, getUUID as g, getSessionAffinityFromHeaders as h, persistCodexCredentials as i, fetchUpstreamWithLifecycle as it, compactAutoContinuePromptStarts as j, prepareMessageProxyHeaders as k, setupGitHubToken as l, createPooledWebSocketStream as lt, getRootSessionIdFromHeaders as m, invalidateCodexRuntime as n, resolveTraceId as nt, selectCodexAccount as o, createResponsesSafeStream as ot, getRootSessionId as p, readGitHubTokenFromEnv as q, logUser as r, setPluginRequestActualModel as rt, setupCodexToken as s, encodePoolKeyPart as st, getCodexAccounts as t, requestContext as tt, stopCopilotRefreshLoop as u, createWebSocketUrl as ut, isNullish as v, copilotModelsHeaders as w, getCopilotUsage as x, isResponsesStream as y, getMissingApiKeysMessage as z };
|
|
2765
2745
|
|
|
2766
|
-
//# sourceMappingURL=token-
|
|
2746
|
+
//# sourceMappingURL=token-_1CBLbqH.js.map
|