@jeffreycao/copilot-api 2.7.2 → 2.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/README.zh-CN.md +7 -7
- package/dist/{auth-DC-EO-eb.js → auth-Db9N85kJ.js} +5 -5
- package/dist/auth-Db9N85kJ.js.map +1 -0
- package/dist/auth-Dr0MaZp1.js +2 -0
- package/dist/{config-DIDLVXMU.js → config-D1F-TyTn.js} +3 -3
- package/dist/{config-DIDLVXMU.js.map → config-D1F-TyTn.js.map} +1 -1
- package/dist/{config-store-CMgB1mCV.js → config-store-Bgmf82i_.js} +29 -5
- package/dist/config-store-Bgmf82i_.js.map +1 -0
- package/dist/{copilot-runtime-CRTYwDWy.js → copilot-runtime-eo27cGBr.js} +4 -90
- package/dist/copilot-runtime-eo27cGBr.js.map +1 -0
- package/dist/{debug-B0URJ4gT.js → debug-EkODckEE.js} +3 -3
- package/dist/{debug-B0URJ4gT.js.map → debug-EkODckEE.js.map} +1 -1
- package/dist/{github-copilot-provider-CLEAHyT-.js → github-copilot-provider-Cx4Afaco.js} +2 -2
- package/dist/{github-copilot-provider-CLEAHyT-.js.map → github-copilot-provider-Cx4Afaco.js.map} +1 -1
- package/dist/main.js +4 -4
- package/dist/{provider-C2Hs8Dua.js → provider-DXivPd6W.js} +2 -2
- package/dist/{provider-C2Hs8Dua.js.map → provider-DXivPd6W.js.map} +1 -1
- package/dist/{provider-management-BjU3aJnC.js → provider-management-DiQ92JMT.js} +12 -12
- package/dist/provider-management-DiQ92JMT.js.map +1 -0
- package/dist/{server-DbkseGH6.js → server-MhaCql-j.js} +178 -38
- package/dist/server-MhaCql-j.js.map +1 -0
- package/dist/{start-C_Svr70X.js → start-ylV_hpnB.js} +13 -111
- package/dist/start-ylV_hpnB.js.map +1 -0
- package/dist/{token-BjzzuPSb.js → token-D53u0RgN.js} +4 -4
- package/dist/{token-BjzzuPSb.js.map → token-D53u0RgN.js.map} +1 -1
- package/package.json +1 -2
- package/dist/auth-C3_rHdk6.js +0 -2
- package/dist/auth-DC-EO-eb.js.map +0 -1
- package/dist/config-store-CMgB1mCV.js.map +0 -1
- package/dist/copilot-runtime-CRTYwDWy.js.map +0 -1
- package/dist/provider-management-BjU3aJnC.js.map +0 -1
- package/dist/server-DbkseGH6.js.map +0 -1
- package/dist/start-C_Svr70X.js.map +0 -1
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import { S as ensurePaths, g as mergeConfigWithDefaults } from "./config-store-
|
|
2
|
-
import { i as listEnabledProviders, m as startModelsDevCache } from "./config-
|
|
3
|
-
import { r as isGitHubCopilotEnabled } from "./github-copilot-provider-
|
|
4
|
-
import { E as initOpencodeVersion, F as getMissingApiKeysMessage, H as readGitHubToken, P as getConfiguredApiKeys, U as readGitHubTokenFromEnv, V as GITHUB_TOKEN_ENV, at as state } from "./token-
|
|
5
|
-
import { o as runProviderSetup } from "./auth-
|
|
6
|
-
import {
|
|
1
|
+
import { S as ensurePaths, g as mergeConfigWithDefaults } from "./config-store-Bgmf82i_.js";
|
|
2
|
+
import { i as listEnabledProviders, m as startModelsDevCache } from "./config-D1F-TyTn.js";
|
|
3
|
+
import { r as isGitHubCopilotEnabled } from "./github-copilot-provider-Cx4Afaco.js";
|
|
4
|
+
import { E as initOpencodeVersion, F as getMissingApiKeysMessage, H as readGitHubToken, P as getConfiguredApiKeys, U as readGitHubTokenFromEnv, V as GITHUB_TOKEN_ENV, at as state } from "./token-D53u0RgN.js";
|
|
5
|
+
import { o as runProviderSetup } from "./auth-Db9N85kJ.js";
|
|
6
|
+
import { t as setupCopilotRuntime } from "./copilot-runtime-eo27cGBr.js";
|
|
7
7
|
import { defineCommand } from "citty";
|
|
8
8
|
import consola from "consola";
|
|
9
9
|
import { getProxyForUrl } from "proxy-from-env";
|
|
10
10
|
import { Agent, ProxyAgent, setGlobalDispatcher } from "undici";
|
|
11
|
-
import { execSync } from "node:child_process";
|
|
12
|
-
import clipboard from "clipboardy";
|
|
13
11
|
import { serve } from "srvx";
|
|
14
|
-
import invariant from "tiny-invariant";
|
|
15
12
|
import { isIP } from "node:net";
|
|
16
|
-
import process$1 from "node:process";
|
|
17
13
|
//#region src/lib/proxy.ts
|
|
18
14
|
let proxyEnvDispatcher;
|
|
19
15
|
function initProxyFromEnv() {
|
|
@@ -123,58 +119,6 @@ function formatServerUrl(hostname, port) {
|
|
|
123
119
|
return `http://${isIP(hostname) === 6 ? `[${hostname.replace("%", "%25")}]` : hostname}:${port}`;
|
|
124
120
|
}
|
|
125
121
|
//#endregion
|
|
126
|
-
//#region src/lib/shell.ts
|
|
127
|
-
function getShell() {
|
|
128
|
-
const { platform, ppid, env } = process$1;
|
|
129
|
-
if (platform === "win32") {
|
|
130
|
-
try {
|
|
131
|
-
const command = `wmic process get ParentProcessId,Name | findstr "${ppid}"`;
|
|
132
|
-
if (execSync(command, { stdio: "pipe" }).toString().toLowerCase().includes("powershell.exe")) return "powershell";
|
|
133
|
-
} catch {
|
|
134
|
-
return "cmd";
|
|
135
|
-
}
|
|
136
|
-
return "cmd";
|
|
137
|
-
} else {
|
|
138
|
-
const shellPath = env.SHELL;
|
|
139
|
-
if (shellPath) {
|
|
140
|
-
if (shellPath.endsWith("zsh")) return "zsh";
|
|
141
|
-
if (shellPath.endsWith("fish")) return "fish";
|
|
142
|
-
if (shellPath.endsWith("bash")) return "bash";
|
|
143
|
-
}
|
|
144
|
-
return "sh";
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Generates a copy-pasteable script to set multiple environment variables
|
|
149
|
-
* and run a subsequent command.
|
|
150
|
-
* @param {EnvVars} envVars - An object of environment variables to set.
|
|
151
|
-
* @param {string} commandToRun - The command to run after setting the variables.
|
|
152
|
-
* @returns {string} The formatted script string.
|
|
153
|
-
*/
|
|
154
|
-
function generateEnvScript(envVars, commandToRun = "") {
|
|
155
|
-
const shell = getShell();
|
|
156
|
-
const filteredEnvVars = Object.entries(envVars).filter(([, value]) => value !== void 0);
|
|
157
|
-
let commandBlock;
|
|
158
|
-
switch (shell) {
|
|
159
|
-
case "powershell":
|
|
160
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `$env:${key} = ${value}`).join("; ");
|
|
161
|
-
break;
|
|
162
|
-
case "cmd":
|
|
163
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `set ${key}=${value}`).join(" & ");
|
|
164
|
-
break;
|
|
165
|
-
case "fish":
|
|
166
|
-
commandBlock = filteredEnvVars.map(([key, value]) => `set -gx ${key} ${value}`).join("; ");
|
|
167
|
-
break;
|
|
168
|
-
default: {
|
|
169
|
-
const assignments = filteredEnvVars.map(([key, value]) => `${key}=${value}`).join(" ");
|
|
170
|
-
commandBlock = filteredEnvVars.length > 0 ? `export ${assignments}` : "";
|
|
171
|
-
break;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
if (commandBlock && commandToRun) return `${commandBlock}${shell === "cmd" ? " & " : " && "}${commandToRun}`;
|
|
175
|
-
return commandBlock || commandToRun;
|
|
176
|
-
}
|
|
177
|
-
//#endregion
|
|
178
122
|
//#region src/start.ts
|
|
179
123
|
async function resolveGitHubToken(cliToken) {
|
|
180
124
|
if (cliToken) return {
|
|
@@ -193,47 +137,12 @@ async function resolveGitHubToken(cliToken) {
|
|
|
193
137
|
};
|
|
194
138
|
return null;
|
|
195
139
|
}
|
|
196
|
-
async function setupCopilotMode(githubToken, source
|
|
140
|
+
async function setupCopilotMode(githubToken, source) {
|
|
197
141
|
state.githubTokenSource = source;
|
|
198
142
|
consola.info(source === "cli" ? "Using provided GitHub token" : source === "env" ? `Using GitHub token from the ${GITHUB_TOKEN_ENV} environment variable` : "Using GitHub token from local file");
|
|
199
143
|
await setupCopilotRuntime(githubToken);
|
|
200
|
-
if (claudeCode) runClaudeCode(serverUrl);
|
|
201
144
|
}
|
|
202
|
-
function
|
|
203
|
-
consola.log("\n💡 Tip: The --claude-code flag simply generates a clipboard command for launching Claude Code. \nAll models remain fully accessible without this flag, just configure the model ID directly in your settings.json file.");
|
|
204
|
-
invariant(state.models, "Models should be loaded by now");
|
|
205
|
-
const opusModel = getLatestModelForFamily("opus")?.id;
|
|
206
|
-
const sonnetModel = getLatestModelForFamily("sonnet")?.id;
|
|
207
|
-
const haikuModel = getLatestModelForFamily("haiku")?.id;
|
|
208
|
-
consola.info(`Selected default Claude Code models:
|
|
209
|
-
- Opus: ${opusModel ?? "(none available)"}\n- Sonnet: ${sonnetModel ?? "(none available)"}\n- Haiku: ${haikuModel ?? "(none available)"}`);
|
|
210
|
-
const command = generateEnvScript({
|
|
211
|
-
ANTHROPIC_BASE_URL: serverUrl,
|
|
212
|
-
ANTHROPIC_AUTH_TOKEN: "dummy",
|
|
213
|
-
ANTHROPIC_MODEL: sonnetModel ?? opusModel,
|
|
214
|
-
ANTHROPIC_DEFAULT_OPUS_MODEL: opusModel,
|
|
215
|
-
ANTHROPIC_DEFAULT_SONNET_MODEL: sonnetModel,
|
|
216
|
-
ANTHROPIC_DEFAULT_HAIKU_MODEL: haikuModel,
|
|
217
|
-
CLAUDE_CODE_USE_VERTEX: "0",
|
|
218
|
-
CLAUDE_CODE_USE_BEDROCK: "0",
|
|
219
|
-
DISABLE_NON_ESSENTIAL_MODEL_CALLS: "1",
|
|
220
|
-
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
|
|
221
|
-
CLAUDE_CODE_ATTRIBUTION_HEADER: "0",
|
|
222
|
-
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION: "false",
|
|
223
|
-
CLAUDE_CODE_DISABLE_TERMINAL_TITLE: "true",
|
|
224
|
-
CLAUDE_CODE_ENABLE_AWAY_SUMMARY: "0",
|
|
225
|
-
CLAUDE_CODE_TOTAL_TOKENS_REMINDER: "off",
|
|
226
|
-
MCP_CONNECT_TIMEOUT_MS: "20000"
|
|
227
|
-
}, "claude");
|
|
228
|
-
try {
|
|
229
|
-
clipboard.writeSync(command);
|
|
230
|
-
consola.success("Copied Claude Code command to clipboard!");
|
|
231
|
-
} catch {
|
|
232
|
-
consola.warn("Failed to copy to clipboard. Here is the Claude Code command:");
|
|
233
|
-
consola.log(command);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
async function setupProviderMode(serverUrl, claudeCode) {
|
|
145
|
+
async function setupProviderMode() {
|
|
237
146
|
const enabledProviders = listEnabledProviders();
|
|
238
147
|
if (enabledProviders.length > 0) {
|
|
239
148
|
consola.info(`Using enabled providers: ${enabledProviders.join(", ")}`);
|
|
@@ -243,7 +152,7 @@ async function setupProviderMode(serverUrl, claudeCode) {
|
|
|
243
152
|
consola.info("No enabled providers found. Setting one up...");
|
|
244
153
|
await runProviderSetup();
|
|
245
154
|
if (state.githubToken && isGitHubCopilotEnabled()) {
|
|
246
|
-
await setupCopilotMode(state.githubToken, "file"
|
|
155
|
+
await setupCopilotMode(state.githubToken, "file");
|
|
247
156
|
return;
|
|
248
157
|
}
|
|
249
158
|
const providersAfterSetup = listEnabledProviders();
|
|
@@ -270,10 +179,10 @@ async function runServer(options) {
|
|
|
270
179
|
await startModelsDevCache();
|
|
271
180
|
const serverUrl = formatServerUrl(binding.clientHostname, options.port);
|
|
272
181
|
const resolvedGitHubToken = isGitHubCopilotEnabled() ? await resolveGitHubToken(options.githubToken) : null;
|
|
273
|
-
if (resolvedGitHubToken && isGitHubCopilotEnabled()) await setupCopilotMode(resolvedGitHubToken.token, resolvedGitHubToken.source
|
|
274
|
-
else await setupProviderMode(
|
|
182
|
+
if (resolvedGitHubToken && isGitHubCopilotEnabled()) await setupCopilotMode(resolvedGitHubToken.token, resolvedGitHubToken.source);
|
|
183
|
+
else await setupProviderMode();
|
|
275
184
|
consola.box(`🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`);
|
|
276
|
-
const { createServer } = await import("./server-
|
|
185
|
+
const { createServer } = await import("./server-MhaCql-j.js");
|
|
277
186
|
const server = createServer({ networkExposed: binding.networkExposed });
|
|
278
187
|
serve({
|
|
279
188
|
fetch: server.fetch,
|
|
@@ -310,12 +219,6 @@ const start = defineCommand({
|
|
|
310
219
|
type: "string",
|
|
311
220
|
description: "Provide GitHub token directly (must be generated using the `auth` subcommand)"
|
|
312
221
|
},
|
|
313
|
-
"claude-code": {
|
|
314
|
-
alias: "c",
|
|
315
|
-
type: "boolean",
|
|
316
|
-
default: false,
|
|
317
|
-
description: "Generate a command to launch Claude Code with Copilot API config"
|
|
318
|
-
},
|
|
319
222
|
"show-token": {
|
|
320
223
|
type: "boolean",
|
|
321
224
|
default: false,
|
|
@@ -333,7 +236,6 @@ const start = defineCommand({
|
|
|
333
236
|
port: Number.parseInt(args.port, 10),
|
|
334
237
|
verbose: args.verbose,
|
|
335
238
|
githubToken: args["github-token"],
|
|
336
|
-
claudeCode: args["claude-code"],
|
|
337
239
|
showToken: args["show-token"],
|
|
338
240
|
proxyEnv: args["proxy-env"]
|
|
339
241
|
});
|
|
@@ -342,4 +244,4 @@ const start = defineCommand({
|
|
|
342
244
|
//#endregion
|
|
343
245
|
export { start };
|
|
344
246
|
|
|
345
|
-
//# sourceMappingURL=start-
|
|
247
|
+
//# sourceMappingURL=start-ylV_hpnB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start-ylV_hpnB.js","names":["get"],"sources":["../src/lib/proxy.ts","../src/lib/server-host-shared.ts","../src/lib/server-host.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","#!/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 } 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\"\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 server = createServer({ networkExposed: binding.networkExposed })\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,IAAI,CAAC,OAAO;MACV,QAAQ,IAAI,WAAW,QAAQ;MAC/B,QAAQ,IAAI,UAAU,KAAK;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,6 +1,6 @@
|
|
|
1
|
-
import { C as writeFileAtomically, _ as readEditableConfigFromDisk, c as getConfig, h as isResponsesApiWebSocketEnabled, u as getUpstreamTransportConfig, x as PATHS } from "./config-store-
|
|
2
|
-
import { c as setProviderConfig, n as getRawProviderConfig } from "./config-
|
|
3
|
-
import { a as UpstreamHeadersTimeoutError, i as HTTPError, n as assertGitHubCopilotEnabled, o as UpstreamStreamInactivityTimeoutError } from "./github-copilot-provider-
|
|
1
|
+
import { C as writeFileAtomically, _ as readEditableConfigFromDisk, c as getConfig, h as isResponsesApiWebSocketEnabled, u as getUpstreamTransportConfig, x as PATHS } from "./config-store-Bgmf82i_.js";
|
|
2
|
+
import { c as setProviderConfig, n as getRawProviderConfig } from "./config-D1F-TyTn.js";
|
|
3
|
+
import { a as UpstreamHeadersTimeoutError, i as HTTPError, n as assertGitHubCopilotEnabled, o as UpstreamStreamInactivityTimeoutError } from "./github-copilot-provider-Cx4Afaco.js";
|
|
4
4
|
import consola from "consola";
|
|
5
5
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
6
6
|
import path from "node:path";
|
|
@@ -2742,4 +2742,4 @@ async function logUser(dependencies = defaultCopilotTokenDependencies) {
|
|
|
2742
2742
|
//#endregion
|
|
2743
2743
|
export { createResponsesHttpEventStream as $, compactSystemPromptStarts as A, selectXaiAccount as B, prepareForCompact as C, compactAutoContinuePromptStarts as D, initOpencodeVersion as E, getMissingApiKeysMessage as F, loginCodex as G, readGitHubToken as H, getXaiAccessToken as I, forwardCodexResponses as J, CODEX_API_BASE_URL as K, getXaiAccounts as L, createAuthMiddleware as M, getConfiguredAdminApiKeys as N, compactMessageSections as O, getConfiguredApiKeys as P, fetchUpstreamWithLifecycle as Q, persistXaiCredentials as R, copilotWebSocketHeaders as S, prepareMessageProxyHeaders as T, readGitHubTokenFromEnv as U, GITHUB_TOKEN_ENV as V, loginXai as W, requestContext as X, generateTraceId as Y, resolveTraceId as Z, parseUserIdMetadata as _, removeCodexAccount as a, state as at, copilotHeaders as b, setupCopilotToken as c, generateRequestIdFromPayload as d, createResponsesSafeStream as et, getRootSessionId as f, isResponsesStream as g, isNullish as h, persistCodexCredentials as i, createWebSocketUrl as it, compactTextOnlyGuard as j, compactSummaryPromptStart as k, setupGitHubToken as l, isAsyncIterable as m, invalidateCodexRuntime as n, getResponsesStreamTerminalDisposition as nt, selectCodexAccount as o, FULL_MODEL_CATALOG_HEADER as ot, getUUID as p, buildCodexRequestHeaders as q, logUser as r, createPooledWebSocketStream as rt, setupCodexToken as s, stripInternalRequestHeaders as st, getCodexAccounts as t, encodePoolKeyPart as tt, stopCopilotRefreshLoop as u, getCopilotUsage as v, prepareInteractionHeaders as w, copilotModelsHeaders as x, copilotBaseUrl as y, removeXaiAccount as z };
|
|
2744
2744
|
|
|
2745
|
-
//# sourceMappingURL=token-
|
|
2745
|
+
//# sourceMappingURL=token-D53u0RgN.js.map
|