copilot-api-plus 1.0.14 → 1.0.16

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/main.js CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { PATHS, ensurePaths } from "./paths-Ch0ixSo2.js";
3
3
  import { state } from "./state-CcLGr8VN.js";
4
- import { GITHUB_API_BASE_URL, copilotBaseUrl, copilotHeaders, githubHeaders } from "./get-user-BFf5xJXg.js";
4
+ import { GITHUB_API_BASE_URL, copilotBaseUrl, copilotHeaders, githubHeaders } from "./get-user-BzIEATcF.js";
5
5
  import { HTTPError, forwardError } from "./error-CvU5otz-.js";
6
- import { cacheModels, cacheVSCodeVersion, clearGithubToken, isNullish, setupCopilotToken, setupGitHubToken, sleep } from "./token-B8crDDoA.js";
7
- import { clearAntigravityAuth, disableCurrentAccount, getAntigravityAuthPath, getValidAccessToken, rotateAccount } from "./auth-Cm_0h9bp.js";
6
+ import { cacheModels, cacheVSCodeVersion, clearGithubToken, isNullish, setupCopilotToken, setupGitHubToken, sleep } from "./token-BUmQ_BcM.js";
7
+ import { clearAntigravityAuth, disableCurrentAccount, getAntigravityAuthPath, getApiKey, getValidAccessToken, rotateAccount } from "./auth-CRTtRTU1.js";
8
8
  import { clearZenAuth, getZenAuthPath } from "./auth-Cua-c0dq.js";
9
- import { getAntigravityModels, isThinkingModel } from "./get-models-Bbb8B5jI.js";
9
+ import { getAntigravityModels, isThinkingModel } from "./get-models-Bcq7-pVL.js";
10
+ import { createRequire } from "node:module";
10
11
  import { defineCommand, runMain } from "citty";
11
12
  import consola from "consola";
12
13
  import fs from "node:fs/promises";
@@ -27,13 +28,21 @@ import { HTTPException } from "hono/http-exception";
27
28
  import { streamSSE } from "hono/streaming";
28
29
  import { events } from "fetch-event-stream";
29
30
 
31
+ //#region rolldown:runtime
32
+ var __getOwnPropNames = Object.getOwnPropertyNames;
33
+ var __commonJS = (cb, mod) => function() {
34
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
35
+ };
36
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
37
+
38
+ //#endregion
30
39
  //#region src/auth.ts
31
- async function runAuth(options) {
32
- if (options.verbose) {
40
+ async function runAuth(options$1) {
41
+ if (options$1.verbose) {
33
42
  consola.level = 5;
34
43
  consola.info("Verbose logging enabled");
35
44
  }
36
- state.showToken = options.showToken;
45
+ state.showToken = options$1.showToken;
37
46
  await ensurePaths();
38
47
  await setupGitHubToken({ force: true });
39
48
  consola.success("GitHub token written to", PATHS.GITHUB_TOKEN_PATH);
@@ -132,9 +141,9 @@ async function loadConfig() {
132
141
  /**
133
142
  * Save configuration to file
134
143
  */
135
- async function saveConfig(config) {
144
+ async function saveConfig(config$1) {
136
145
  const configPath = getConfigPath();
137
- await fs.writeFile(configPath, JSON.stringify(config, null, 2), "utf8");
146
+ await fs.writeFile(configPath, JSON.stringify(config$1, null, 2), "utf8");
138
147
  consola.debug(`Configuration saved to ${configPath}`);
139
148
  }
140
149
  /**
@@ -147,17 +156,17 @@ async function getProxyConfig() {
147
156
  * Save proxy configuration
148
157
  */
149
158
  async function saveProxyConfig(proxyConfig) {
150
- const config = await loadConfig();
151
- config.proxy = proxyConfig;
152
- await saveConfig(config);
159
+ const config$1 = await loadConfig();
160
+ config$1.proxy = proxyConfig;
161
+ await saveConfig(config$1);
153
162
  }
154
163
  /**
155
164
  * Clear proxy configuration
156
165
  */
157
166
  async function clearProxyConfig() {
158
- const config = await loadConfig();
159
- delete config.proxy;
160
- await saveConfig(config);
167
+ const config$1 = await loadConfig();
168
+ delete config$1.proxy;
169
+ await saveConfig(config$1);
161
170
  }
162
171
  /**
163
172
  * Apply saved proxy configuration to environment variables
@@ -212,10 +221,10 @@ async function checkTokenExists() {
212
221
  return false;
213
222
  }
214
223
  }
215
- async function checkFileExists(path$1) {
224
+ async function checkFileExists(path$2) {
216
225
  try {
217
- if (!(await fs.stat(path$1)).isFile()) return false;
218
- return (await fs.readFile(path$1, "utf8")).trim().length > 0;
226
+ if (!(await fs.stat(path$2)).isFile()) return false;
227
+ return (await fs.readFile(path$2, "utf8")).trim().length > 0;
219
228
  } catch {
220
229
  return false;
221
230
  }
@@ -223,7 +232,7 @@ async function checkFileExists(path$1) {
223
232
  async function getDebugInfo() {
224
233
  const zenAuthPath = getZenAuthPath();
225
234
  const antigravityAuthPath = getAntigravityAuthPath();
226
- const [version, githubExists, zenExists, antigravityExists, proxyConfig] = await Promise.all([
235
+ const [version$1, githubExists, zenExists, antigravityExists, proxyConfig] = await Promise.all([
227
236
  getPackageVersion(),
228
237
  checkTokenExists(),
229
238
  checkFileExists(zenAuthPath),
@@ -231,7 +240,7 @@ async function getDebugInfo() {
231
240
  getProxyConfig()
232
241
  ]);
233
242
  return {
234
- version,
243
+ version: version$1,
235
244
  runtime: getRuntimeInfo(),
236
245
  paths: {
237
246
  APP_DIR: PATHS.APP_DIR,
@@ -271,9 +280,9 @@ Proxy: ${proxyStatus}`);
271
280
  function printDebugInfoJson(info) {
272
281
  console.log(JSON.stringify(info, null, 2));
273
282
  }
274
- async function runDebug(options) {
283
+ async function runDebug(options$1) {
275
284
  const debugInfo = await getDebugInfo();
276
- if (options.json) printDebugInfoJson(debugInfo);
285
+ if (options$1.json) printDebugInfoJson(debugInfo);
277
286
  else printDebugInfoPlain(debugInfo);
278
287
  }
279
288
  const debug = defineCommand({
@@ -293,9 +302,9 @@ const debug = defineCommand({
293
302
 
294
303
  //#endregion
295
304
  //#region src/logout.ts
296
- async function runLogout(options) {
305
+ async function runLogout(options$1) {
297
306
  await ensurePaths();
298
- if (options.all) {
307
+ if (options$1.all) {
299
308
  await clearGithubToken();
300
309
  await clearZenAuth();
301
310
  await clearAntigravityAuth();
@@ -305,19 +314,19 @@ async function runLogout(options) {
305
314
  consola.info(`Antigravity accounts: ${getAntigravityAuthPath()}`);
306
315
  return;
307
316
  }
308
- if (options.github) {
317
+ if (options$1.github) {
309
318
  await clearGithubToken();
310
319
  consola.success("Logged out from GitHub Copilot");
311
320
  consola.info(`Token file location: ${PATHS.GITHUB_TOKEN_PATH}`);
312
321
  return;
313
322
  }
314
- if (options.zen) {
323
+ if (options$1.zen) {
315
324
  await clearZenAuth();
316
325
  consola.success("Logged out from OpenCode Zen");
317
326
  consola.info(`Zen API key location: ${getZenAuthPath()}`);
318
327
  return;
319
328
  }
320
- if (options.antigravity) {
329
+ if (options$1.antigravity) {
321
330
  await clearAntigravityAuth();
322
331
  consola.success("Logged out from Google Antigravity");
323
332
  consola.info(`Antigravity accounts location: ${getAntigravityAuthPath()}`);
@@ -444,8 +453,8 @@ const proxy = defineCommand({
444
453
  async run({ args }) {
445
454
  await ensurePaths();
446
455
  if (args.show || !args.set && !args.enable && !args.disable && !args.clear && !args["http-proxy"] && !args["https-proxy"]) {
447
- const config = await getProxyConfig();
448
- if (!config) {
456
+ const config$1 = await getProxyConfig();
457
+ if (!config$1) {
449
458
  consola.info("No proxy configuration saved.");
450
459
  consola.info("");
451
460
  consola.info("To configure proxy, use one of:");
@@ -454,10 +463,10 @@ const proxy = defineCommand({
454
463
  return;
455
464
  }
456
465
  consola.info("Current proxy configuration:");
457
- consola.info(` Status: ${config.enabled ? "✅ Enabled" : "❌ Disabled"}`);
458
- if (config.httpProxy) consola.info(` HTTP_PROXY: ${config.httpProxy}`);
459
- if (config.httpsProxy) consola.info(` HTTPS_PROXY: ${config.httpsProxy}`);
460
- if (config.noProxy) consola.info(` NO_PROXY: ${config.noProxy}`);
466
+ consola.info(` Status: ${config$1.enabled ? "✅ Enabled" : "❌ Disabled"}`);
467
+ if (config$1.httpProxy) consola.info(` HTTP_PROXY: ${config$1.httpProxy}`);
468
+ if (config$1.httpsProxy) consola.info(` HTTPS_PROXY: ${config$1.httpsProxy}`);
469
+ if (config$1.noProxy) consola.info(` NO_PROXY: ${config$1.noProxy}`);
461
470
  return;
462
471
  }
463
472
  if (args.clear) {
@@ -466,24 +475,24 @@ const proxy = defineCommand({
466
475
  return;
467
476
  }
468
477
  if (args.enable) {
469
- const config = await getProxyConfig();
470
- if (!config) {
478
+ const config$1 = await getProxyConfig();
479
+ if (!config$1) {
471
480
  consola.error("No proxy configuration saved. Use --set to configure first.");
472
481
  return;
473
482
  }
474
- config.enabled = true;
475
- await saveProxyConfig(config);
483
+ config$1.enabled = true;
484
+ await saveProxyConfig(config$1);
476
485
  consola.success("Proxy enabled. It will be used on next server start.");
477
486
  return;
478
487
  }
479
488
  if (args.disable) {
480
- const config = await getProxyConfig();
481
- if (!config) {
489
+ const config$1 = await getProxyConfig();
490
+ if (!config$1) {
482
491
  consola.info("No proxy configuration to disable.");
483
492
  return;
484
493
  }
485
- config.enabled = false;
486
- await saveProxyConfig(config);
494
+ config$1.enabled = false;
495
+ await saveProxyConfig(config$1);
487
496
  consola.success("Proxy disabled. Settings are preserved.");
488
497
  return;
489
498
  }
@@ -550,6 +559,383 @@ const proxy = defineCommand({
550
559
  }
551
560
  });
552
561
 
562
+ //#endregion
563
+ //#region node_modules/dotenv/package.json
564
+ var require_package = /* @__PURE__ */ __commonJS({ "node_modules/dotenv/package.json": ((exports, module) => {
565
+ module.exports = {
566
+ "name": "dotenv",
567
+ "version": "17.2.3",
568
+ "description": "Loads environment variables from .env file",
569
+ "main": "lib/main.js",
570
+ "types": "lib/main.d.ts",
571
+ "exports": {
572
+ ".": {
573
+ "types": "./lib/main.d.ts",
574
+ "require": "./lib/main.js",
575
+ "default": "./lib/main.js"
576
+ },
577
+ "./config": "./config.js",
578
+ "./config.js": "./config.js",
579
+ "./lib/env-options": "./lib/env-options.js",
580
+ "./lib/env-options.js": "./lib/env-options.js",
581
+ "./lib/cli-options": "./lib/cli-options.js",
582
+ "./lib/cli-options.js": "./lib/cli-options.js",
583
+ "./package.json": "./package.json"
584
+ },
585
+ "scripts": {
586
+ "dts-check": "tsc --project tests/types/tsconfig.json",
587
+ "lint": "standard",
588
+ "pretest": "npm run lint && npm run dts-check",
589
+ "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
590
+ "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
591
+ "prerelease": "npm test",
592
+ "release": "standard-version"
593
+ },
594
+ "repository": {
595
+ "type": "git",
596
+ "url": "git://github.com/motdotla/dotenv.git"
597
+ },
598
+ "homepage": "https://github.com/motdotla/dotenv#readme",
599
+ "funding": "https://dotenvx.com",
600
+ "keywords": [
601
+ "dotenv",
602
+ "env",
603
+ ".env",
604
+ "environment",
605
+ "variables",
606
+ "config",
607
+ "settings"
608
+ ],
609
+ "readmeFilename": "README.md",
610
+ "license": "BSD-2-Clause",
611
+ "devDependencies": {
612
+ "@types/node": "^18.11.3",
613
+ "decache": "^4.6.2",
614
+ "sinon": "^14.0.1",
615
+ "standard": "^17.0.0",
616
+ "standard-version": "^9.5.0",
617
+ "tap": "^19.2.0",
618
+ "typescript": "^4.8.4"
619
+ },
620
+ "engines": { "node": ">=12" },
621
+ "browser": { "fs": false }
622
+ };
623
+ }) });
624
+
625
+ //#endregion
626
+ //#region node_modules/dotenv/lib/main.js
627
+ var require_main = /* @__PURE__ */ __commonJS({ "node_modules/dotenv/lib/main.js": ((exports, module) => {
628
+ const fs$1 = __require("fs");
629
+ const path$1 = __require("path");
630
+ const os$1 = __require("os");
631
+ const crypto = __require("crypto");
632
+ const version = require_package().version;
633
+ const TIPS = [
634
+ "🔐 encrypt with Dotenvx: https://dotenvx.com",
635
+ "🔐 prevent committing .env to code: https://dotenvx.com/precommit",
636
+ "🔐 prevent building .env in docker: https://dotenvx.com/prebuild",
637
+ "📡 add observability to secrets: https://dotenvx.com/ops",
638
+ "👥 sync secrets across teammates & machines: https://dotenvx.com/ops",
639
+ "🗂️ backup and recover secrets: https://dotenvx.com/ops",
640
+ "✅ audit secrets and track compliance: https://dotenvx.com/ops",
641
+ "🔄 add secrets lifecycle management: https://dotenvx.com/ops",
642
+ "🔑 add access controls to secrets: https://dotenvx.com/ops",
643
+ "🛠️ run anywhere with `dotenvx run -- yourcommand`",
644
+ "⚙️ specify custom .env file path with { path: '/custom/path/.env' }",
645
+ "⚙️ enable debug logging with { debug: true }",
646
+ "⚙️ override existing env vars with { override: true }",
647
+ "⚙️ suppress all logs with { quiet: true }",
648
+ "⚙️ write to custom object with { processEnv: myObject }",
649
+ "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"
650
+ ];
651
+ function _getRandomTip() {
652
+ return TIPS[Math.floor(Math.random() * TIPS.length)];
653
+ }
654
+ function parseBoolean(value) {
655
+ if (typeof value === "string") return ![
656
+ "false",
657
+ "0",
658
+ "no",
659
+ "off",
660
+ ""
661
+ ].includes(value.toLowerCase());
662
+ return Boolean(value);
663
+ }
664
+ function supportsAnsi() {
665
+ return process.stdout.isTTY;
666
+ }
667
+ function dim(text) {
668
+ return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
669
+ }
670
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
671
+ function parse(src) {
672
+ const obj = {};
673
+ let lines = src.toString();
674
+ lines = lines.replace(/\r\n?/gm, "\n");
675
+ let match;
676
+ while ((match = LINE.exec(lines)) != null) {
677
+ const key = match[1];
678
+ let value = match[2] || "";
679
+ value = value.trim();
680
+ const maybeQuote = value[0];
681
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
682
+ if (maybeQuote === "\"") {
683
+ value = value.replace(/\\n/g, "\n");
684
+ value = value.replace(/\\r/g, "\r");
685
+ }
686
+ obj[key] = value;
687
+ }
688
+ return obj;
689
+ }
690
+ function _parseVault(options$1) {
691
+ options$1 = options$1 || {};
692
+ const vaultPath = _vaultPath(options$1);
693
+ options$1.path = vaultPath;
694
+ const result = DotenvModule.configDotenv(options$1);
695
+ if (!result.parsed) {
696
+ const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
697
+ err.code = "MISSING_DATA";
698
+ throw err;
699
+ }
700
+ const keys = _dotenvKey(options$1).split(",");
701
+ const length = keys.length;
702
+ let decrypted;
703
+ for (let i = 0; i < length; i++) try {
704
+ const key = keys[i].trim();
705
+ const attrs = _instructions(result, key);
706
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
707
+ break;
708
+ } catch (error) {
709
+ if (i + 1 >= length) throw error;
710
+ }
711
+ return DotenvModule.parse(decrypted);
712
+ }
713
+ function _warn(message) {
714
+ console.error(`[dotenv@${version}][WARN] ${message}`);
715
+ }
716
+ function _debug(message) {
717
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
718
+ }
719
+ function _log(message) {
720
+ console.log(`[dotenv@${version}] ${message}`);
721
+ }
722
+ function _dotenvKey(options$1) {
723
+ if (options$1 && options$1.DOTENV_KEY && options$1.DOTENV_KEY.length > 0) return options$1.DOTENV_KEY;
724
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
725
+ return "";
726
+ }
727
+ function _instructions(result, dotenvKey) {
728
+ let uri;
729
+ try {
730
+ uri = new URL(dotenvKey);
731
+ } catch (error) {
732
+ if (error.code === "ERR_INVALID_URL") {
733
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
734
+ err.code = "INVALID_DOTENV_KEY";
735
+ throw err;
736
+ }
737
+ throw error;
738
+ }
739
+ const key = uri.password;
740
+ if (!key) {
741
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
742
+ err.code = "INVALID_DOTENV_KEY";
743
+ throw err;
744
+ }
745
+ const environment = uri.searchParams.get("environment");
746
+ if (!environment) {
747
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
748
+ err.code = "INVALID_DOTENV_KEY";
749
+ throw err;
750
+ }
751
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
752
+ const ciphertext = result.parsed[environmentKey];
753
+ if (!ciphertext) {
754
+ const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
755
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
756
+ throw err;
757
+ }
758
+ return {
759
+ ciphertext,
760
+ key
761
+ };
762
+ }
763
+ function _vaultPath(options$1) {
764
+ let possibleVaultPath = null;
765
+ if (options$1 && options$1.path && options$1.path.length > 0) if (Array.isArray(options$1.path)) {
766
+ for (const filepath of options$1.path) if (fs$1.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
767
+ } else possibleVaultPath = options$1.path.endsWith(".vault") ? options$1.path : `${options$1.path}.vault`;
768
+ else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
769
+ if (fs$1.existsSync(possibleVaultPath)) return possibleVaultPath;
770
+ return null;
771
+ }
772
+ function _resolveHome(envPath) {
773
+ return envPath[0] === "~" ? path$1.join(os$1.homedir(), envPath.slice(1)) : envPath;
774
+ }
775
+ function _configVault(options$1) {
776
+ const debug$1 = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options$1 && options$1.debug);
777
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options$1 && options$1.quiet);
778
+ if (debug$1 || !quiet) _log("Loading env from encrypted .env.vault");
779
+ const parsed = DotenvModule._parseVault(options$1);
780
+ let processEnv = process.env;
781
+ if (options$1 && options$1.processEnv != null) processEnv = options$1.processEnv;
782
+ DotenvModule.populate(processEnv, parsed, options$1);
783
+ return { parsed };
784
+ }
785
+ function configDotenv(options$1) {
786
+ const dotenvPath = path$1.resolve(process.cwd(), ".env");
787
+ let encoding = "utf8";
788
+ let processEnv = process.env;
789
+ if (options$1 && options$1.processEnv != null) processEnv = options$1.processEnv;
790
+ let debug$1 = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options$1 && options$1.debug);
791
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options$1 && options$1.quiet);
792
+ if (options$1 && options$1.encoding) encoding = options$1.encoding;
793
+ else if (debug$1) _debug("No encoding is specified. UTF-8 is used by default");
794
+ let optionPaths = [dotenvPath];
795
+ if (options$1 && options$1.path) if (!Array.isArray(options$1.path)) optionPaths = [_resolveHome(options$1.path)];
796
+ else {
797
+ optionPaths = [];
798
+ for (const filepath of options$1.path) optionPaths.push(_resolveHome(filepath));
799
+ }
800
+ let lastError;
801
+ const parsedAll = {};
802
+ for (const path$2 of optionPaths) try {
803
+ const parsed = DotenvModule.parse(fs$1.readFileSync(path$2, { encoding }));
804
+ DotenvModule.populate(parsedAll, parsed, options$1);
805
+ } catch (e) {
806
+ if (debug$1) _debug(`Failed to load ${path$2} ${e.message}`);
807
+ lastError = e;
808
+ }
809
+ const populated = DotenvModule.populate(processEnv, parsedAll, options$1);
810
+ debug$1 = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug$1);
811
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
812
+ if (debug$1 || !quiet) {
813
+ const keysCount = Object.keys(populated).length;
814
+ const shortPaths = [];
815
+ for (const filePath of optionPaths) try {
816
+ const relative = path$1.relative(process.cwd(), filePath);
817
+ shortPaths.push(relative);
818
+ } catch (e) {
819
+ if (debug$1) _debug(`Failed to load ${filePath} ${e.message}`);
820
+ lastError = e;
821
+ }
822
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`);
823
+ }
824
+ if (lastError) return {
825
+ parsed: parsedAll,
826
+ error: lastError
827
+ };
828
+ else return { parsed: parsedAll };
829
+ }
830
+ function config(options$1) {
831
+ if (_dotenvKey(options$1).length === 0) return DotenvModule.configDotenv(options$1);
832
+ const vaultPath = _vaultPath(options$1);
833
+ if (!vaultPath) {
834
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
835
+ return DotenvModule.configDotenv(options$1);
836
+ }
837
+ return DotenvModule._configVault(options$1);
838
+ }
839
+ function decrypt(encrypted, keyStr) {
840
+ const key = Buffer.from(keyStr.slice(-64), "hex");
841
+ let ciphertext = Buffer.from(encrypted, "base64");
842
+ const nonce = ciphertext.subarray(0, 12);
843
+ const authTag = ciphertext.subarray(-16);
844
+ ciphertext = ciphertext.subarray(12, -16);
845
+ try {
846
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
847
+ aesgcm.setAuthTag(authTag);
848
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
849
+ } catch (error) {
850
+ const isRange = error instanceof RangeError;
851
+ const invalidKeyLength = error.message === "Invalid key length";
852
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
853
+ if (isRange || invalidKeyLength) {
854
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
855
+ err.code = "INVALID_DOTENV_KEY";
856
+ throw err;
857
+ } else if (decryptionFailed) {
858
+ const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
859
+ err.code = "DECRYPTION_FAILED";
860
+ throw err;
861
+ } else throw error;
862
+ }
863
+ }
864
+ function populate(processEnv, parsed, options$1 = {}) {
865
+ const debug$1 = Boolean(options$1 && options$1.debug);
866
+ const override = Boolean(options$1 && options$1.override);
867
+ const populated = {};
868
+ if (typeof parsed !== "object") {
869
+ const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
870
+ err.code = "OBJECT_REQUIRED";
871
+ throw err;
872
+ }
873
+ for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
874
+ if (override === true) {
875
+ processEnv[key] = parsed[key];
876
+ populated[key] = parsed[key];
877
+ }
878
+ if (debug$1) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
879
+ else _debug(`"${key}" is already defined and was NOT overwritten`);
880
+ } else {
881
+ processEnv[key] = parsed[key];
882
+ populated[key] = parsed[key];
883
+ }
884
+ return populated;
885
+ }
886
+ const DotenvModule = {
887
+ configDotenv,
888
+ _configVault,
889
+ _parseVault,
890
+ config,
891
+ decrypt,
892
+ parse,
893
+ populate
894
+ };
895
+ module.exports.configDotenv = DotenvModule.configDotenv;
896
+ module.exports._configVault = DotenvModule._configVault;
897
+ module.exports._parseVault = DotenvModule._parseVault;
898
+ module.exports.config = DotenvModule.config;
899
+ module.exports.decrypt = DotenvModule.decrypt;
900
+ module.exports.parse = DotenvModule.parse;
901
+ module.exports.populate = DotenvModule.populate;
902
+ module.exports = DotenvModule;
903
+ }) });
904
+
905
+ //#endregion
906
+ //#region node_modules/dotenv/lib/env-options.js
907
+ var require_env_options = /* @__PURE__ */ __commonJS({ "node_modules/dotenv/lib/env-options.js": ((exports, module) => {
908
+ const options = {};
909
+ if (process.env.DOTENV_CONFIG_ENCODING != null) options.encoding = process.env.DOTENV_CONFIG_ENCODING;
910
+ if (process.env.DOTENV_CONFIG_PATH != null) options.path = process.env.DOTENV_CONFIG_PATH;
911
+ if (process.env.DOTENV_CONFIG_QUIET != null) options.quiet = process.env.DOTENV_CONFIG_QUIET;
912
+ if (process.env.DOTENV_CONFIG_DEBUG != null) options.debug = process.env.DOTENV_CONFIG_DEBUG;
913
+ if (process.env.DOTENV_CONFIG_OVERRIDE != null) options.override = process.env.DOTENV_CONFIG_OVERRIDE;
914
+ if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
915
+ module.exports = options;
916
+ }) });
917
+
918
+ //#endregion
919
+ //#region node_modules/dotenv/lib/cli-options.js
920
+ var require_cli_options = /* @__PURE__ */ __commonJS({ "node_modules/dotenv/lib/cli-options.js": ((exports, module) => {
921
+ const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;
922
+ module.exports = function optionMatcher(args) {
923
+ const options$1 = args.reduce(function(acc, cur) {
924
+ const matches = cur.match(re);
925
+ if (matches) acc[matches[1]] = matches[2];
926
+ return acc;
927
+ }, {});
928
+ if (!("quiet" in options$1)) options$1.quiet = "true";
929
+ return options$1;
930
+ };
931
+ }) });
932
+
933
+ //#endregion
934
+ //#region node_modules/dotenv/config.js
935
+ (function() {
936
+ require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
937
+ })();
938
+
553
939
  //#endregion
554
940
  //#region src/lib/proxy.ts
555
941
  function initProxyFromEnv() {
@@ -558,14 +944,14 @@ function initProxyFromEnv() {
558
944
  const direct = new Agent();
559
945
  const proxies = /* @__PURE__ */ new Map();
560
946
  setGlobalDispatcher({
561
- dispatch(options, handler) {
947
+ dispatch(options$1, handler) {
562
948
  try {
563
- const origin = typeof options.origin === "string" ? new URL(options.origin) : options.origin;
949
+ const origin = typeof options$1.origin === "string" ? new URL(options$1.origin) : options$1.origin;
564
950
  const raw = getProxyForUrl(origin.toString());
565
951
  const proxyUrl = raw && raw.length > 0 ? raw : void 0;
566
952
  if (!proxyUrl) {
567
953
  consola.debug(`HTTP proxy bypass: ${origin.hostname}`);
568
- return direct.dispatch(options, handler);
954
+ return direct.dispatch(options$1, handler);
569
955
  }
570
956
  let agent = proxies.get(proxyUrl);
571
957
  if (!agent) {
@@ -578,9 +964,9 @@ function initProxyFromEnv() {
578
964
  label = `${u.protocol}//${u.host}`;
579
965
  } catch {}
580
966
  consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`);
581
- return agent.dispatch(options, handler);
967
+ return agent.dispatch(options$1, handler);
582
968
  } catch {
583
- return direct.dispatch(options, handler);
969
+ return direct.dispatch(options$1, handler);
584
970
  }
585
971
  },
586
972
  close() {
@@ -846,6 +1232,9 @@ const ANTIGRAVITY_API_HOST$1 = "daily-cloudcode-pa.sandbox.googleapis.com";
846
1232
  const ANTIGRAVITY_STREAM_URL$1 = `https://${ANTIGRAVITY_API_HOST$1}/v1internal:streamGenerateContent?alt=sse`;
847
1233
  const ANTIGRAVITY_NO_STREAM_URL$1 = `https://${ANTIGRAVITY_API_HOST$1}/v1internal:generateContent`;
848
1234
  const ANTIGRAVITY_USER_AGENT$1 = "antigravity/1.11.3 windows/amd64";
1235
+ const GEMINI_API_HOST = "generativelanguage.googleapis.com";
1236
+ const getGeminiStreamUrl = (model, apiKey) => `https://${GEMINI_API_HOST}/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${apiKey}`;
1237
+ const getGeminiNoStreamUrl = (model, apiKey) => `https://${GEMINI_API_HOST}/v1beta/models/${model}:generateContent?key=${apiKey}`;
849
1238
  /**
850
1239
  * Convert OpenAI format messages to Antigravity format
851
1240
  */
@@ -957,11 +1346,40 @@ function createErrorResponse$1(message, type, status, details) {
957
1346
  });
958
1347
  }
959
1348
  /**
960
- * Create chat completion with Antigravity
1349
+ * Create chat completion with Antigravity or standard Gemini API
1350
+ * Priority: API Key > OAuth
961
1351
  */
962
1352
  async function createAntigravityChatCompletion(request) {
1353
+ const apiKey = getApiKey();
1354
+ if (apiKey) return await createWithApiKey(request, apiKey);
963
1355
  const accessToken = await getValidAccessToken();
964
- if (!accessToken) return createErrorResponse$1("No valid Antigravity access token available. Please run login first.", "auth_error", 401);
1356
+ if (!accessToken) return createErrorResponse$1("No valid authentication available. Please set GEMINI_API_KEY environment variable or run OAuth login.", "auth_error", 401);
1357
+ return await createWithOAuth(request, accessToken);
1358
+ }
1359
+ /**
1360
+ * Create chat completion using API Key (standard Gemini API)
1361
+ */
1362
+ async function createWithApiKey(request, apiKey) {
1363
+ const endpoint = request.stream ? getGeminiStreamUrl(request.model, apiKey) : getGeminiNoStreamUrl(request.model, apiKey);
1364
+ const body = buildRequestBody(request);
1365
+ consola.debug(`Gemini API request with model ${request.model}`);
1366
+ try {
1367
+ const response = await fetch(endpoint, {
1368
+ method: "POST",
1369
+ headers: { "Content-Type": "application/json" },
1370
+ body: JSON.stringify(body)
1371
+ });
1372
+ if (!response.ok) return await handleApiError$1(response);
1373
+ return request.stream ? transformStreamResponse$1(response, request.model) : await transformNonStreamResponse$1(response, request.model);
1374
+ } catch (error) {
1375
+ consola.error("Gemini API request error:", error);
1376
+ return createErrorResponse$1(`Request failed: ${String(error)}`, "request_error", 500);
1377
+ }
1378
+ }
1379
+ /**
1380
+ * Create chat completion using OAuth (Antigravity private API)
1381
+ */
1382
+ async function createWithOAuth(request, accessToken) {
965
1383
  const endpoint = request.stream ? ANTIGRAVITY_STREAM_URL$1 : ANTIGRAVITY_NO_STREAM_URL$1;
966
1384
  const body = buildRequestBody(request);
967
1385
  consola.debug(`Antigravity request to ${endpoint} with model ${request.model}`);
@@ -1882,14 +2300,23 @@ const createChatCompletions = async (payload) => {
1882
2300
  ...copilotHeaders(state, enableVision),
1883
2301
  "X-Initiator": isAgentCall ? "agent" : "user"
1884
2302
  };
2303
+ consola.info("Sending request to Copilot:", {
2304
+ model: payload.model,
2305
+ endpoint: `${copilotBaseUrl(state)}/chat/completions`
2306
+ });
1885
2307
  const response = await fetch(`${copilotBaseUrl(state)}/chat/completions`, {
1886
2308
  method: "POST",
1887
2309
  headers,
1888
2310
  body: JSON.stringify(payload)
1889
2311
  });
1890
2312
  if (!response.ok) {
1891
- consola.error("Failed to create chat completions", response);
1892
- throw new HTTPError("Failed to create chat completions", response);
2313
+ const errorBody = await response.text();
2314
+ consola.error("Failed to create chat completions", {
2315
+ status: response.status,
2316
+ statusText: response.statusText,
2317
+ body: errorBody
2318
+ });
2319
+ throw new HTTPError(`Failed to create chat completions: ${response.status} ${errorBody}`, response);
1893
2320
  }
1894
2321
  if (payload.stream) return events(response);
1895
2322
  return await response.json();
@@ -2351,18 +2778,13 @@ function translateChunkToAnthropicEvents(chunk, state$1) {
2351
2778
  async function handleCompletion(c) {
2352
2779
  await checkRateLimit(state);
2353
2780
  const anthropicPayload = await c.req.json();
2354
- consola.debug("Anthropic request payload:", JSON.stringify(anthropicPayload));
2355
2781
  const openAIPayload = translateToOpenAI(anthropicPayload);
2356
- consola.debug("Translated OpenAI request payload:", JSON.stringify(openAIPayload));
2357
2782
  if (state.manualApprove) await awaitApproval();
2358
2783
  const response = await createChatCompletions(openAIPayload);
2359
2784
  if (isNonStreaming(response)) {
2360
- consola.debug("Non-streaming response from Copilot:", JSON.stringify(response).slice(-400));
2361
2785
  const anthropicResponse = translateToAnthropic(response);
2362
- consola.debug("Translated Anthropic response:", JSON.stringify(anthropicResponse));
2363
2786
  return c.json(anthropicResponse);
2364
2787
  }
2365
- consola.debug("Streaming response from Copilot");
2366
2788
  return streamSSE(c, async (stream) => {
2367
2789
  const streamState = {
2368
2790
  messageStartSent: false,
@@ -2371,18 +2793,14 @@ async function handleCompletion(c) {
2371
2793
  toolCalls: {}
2372
2794
  };
2373
2795
  for await (const rawEvent of response) {
2374
- consola.debug("Copilot raw stream event:", JSON.stringify(rawEvent));
2375
2796
  if (rawEvent.data === "[DONE]") break;
2376
2797
  if (!rawEvent.data) continue;
2377
2798
  const chunk = JSON.parse(rawEvent.data);
2378
2799
  const events$1 = translateChunkToAnthropicEvents(chunk, streamState);
2379
- for (const event of events$1) {
2380
- consola.debug("Translated Anthropic event:", JSON.stringify(event));
2381
- await stream.writeSSE({
2382
- event: event.type,
2383
- data: JSON.stringify(event)
2384
- });
2385
- }
2800
+ for (const event of events$1) await stream.writeSSE({
2801
+ event: event.type,
2802
+ data: JSON.stringify(event)
2803
+ });
2386
2804
  }
2387
2805
  });
2388
2806
  }
@@ -2702,29 +3120,32 @@ server.route("/antigravity/v1/messages", antigravityMessagesRoute);
2702
3120
  * - apiKeys: Optional list of API keys to enable API key authentication
2703
3121
  * - zen: Enable OpenCode Zen mode (proxy to Zen instead of GitHub Copilot)
2704
3122
  * - zenApiKey: OpenCode Zen API key (optional; if omitted will prompt for setup)
3123
+ * - antigravity: Enable Google Antigravity mode
3124
+ * - antigravityClientId: Google OAuth Client ID (optional; overrides env/default)
3125
+ * - antigravityClientSecret: Google OAuth Client Secret (optional; overrides env/default)
2705
3126
  */
2706
- async function runServer(options) {
3127
+ async function runServer(options$1) {
2707
3128
  const savedProxyApplied = await applyProxyConfig();
2708
- if (options.proxyEnv) initProxyFromEnv();
3129
+ if (options$1.proxyEnv) initProxyFromEnv();
2709
3130
  else if (savedProxyApplied) initProxyFromEnv();
2710
- if (options.verbose) {
3131
+ if (options$1.verbose) {
2711
3132
  consola.level = 5;
2712
3133
  consola.info("Verbose logging enabled");
2713
3134
  }
2714
- state.accountType = options.accountType;
2715
- if (options.accountType !== "individual") consola.info(`Using ${options.accountType} plan GitHub account`);
2716
- state.manualApprove = options.manual;
2717
- state.rateLimitSeconds = options.rateLimit;
2718
- state.rateLimitWait = options.rateLimitWait;
2719
- state.showToken = options.showToken;
2720
- state.apiKeys = options.apiKeys;
3135
+ state.accountType = options$1.accountType;
3136
+ if (options$1.accountType !== "individual") consola.info(`Using ${options$1.accountType} plan GitHub account`);
3137
+ state.manualApprove = options$1.manual;
3138
+ state.rateLimitSeconds = options$1.rateLimit;
3139
+ state.rateLimitWait = options$1.rateLimitWait;
3140
+ state.showToken = options$1.showToken;
3141
+ state.apiKeys = options$1.apiKeys;
2721
3142
  if (state.apiKeys && state.apiKeys.length > 0) consola.info(`API key authentication enabled with ${state.apiKeys.length} key(s)`);
2722
3143
  await ensurePaths();
2723
- if (options.zen) {
3144
+ if (options$1.zen) {
2724
3145
  consola.info("OpenCode Zen mode enabled");
2725
3146
  state.zenMode = true;
2726
- if (options.zenApiKey) {
2727
- state.zenApiKey = options.zenApiKey;
3147
+ if (options$1.zenApiKey) {
3148
+ state.zenApiKey = options$1.zenApiKey;
2728
3149
  consola.info("Using provided Zen API key");
2729
3150
  } else {
2730
3151
  const { setupZenApiKey, loadZenAuth } = await import("./auth-BO-mwvoU.js");
@@ -2737,30 +3158,49 @@ async function runServer(options) {
2737
3158
  const { cacheZenModels } = await import("./get-models-DJfPj_Rg.js");
2738
3159
  await cacheZenModels();
2739
3160
  consola.info(`Available Zen models: \n${state.zenModels?.data.map((model) => `- ${model.id}`).join("\n")}`);
2740
- } else if (options.antigravity) {
3161
+ } else if (options$1.antigravity) {
2741
3162
  consola.info("Google Antigravity mode enabled");
2742
3163
  state.antigravityMode = true;
2743
- const { loadAntigravityAuth, setupAntigravity, getCurrentAccount } = await import("./auth-D2wtETTq.js");
2744
- const existingAuth = await loadAntigravityAuth();
2745
- if (!existingAuth || existingAuth.accounts.length === 0) {
2746
- consola.warn("No Antigravity accounts found");
2747
- await setupAntigravity();
3164
+ const { loadAntigravityAuth, setupAntigravity, getCurrentAccount, hasApiKey, getApiKey: getApiKey$1, setOAuthCredentials } = await import("./auth-DYaCSCGe.js");
3165
+ if (options$1.antigravityClientId && options$1.antigravityClientSecret) {
3166
+ setOAuthCredentials(options$1.antigravityClientId, options$1.antigravityClientSecret);
3167
+ consola.info("Using provided OAuth credentials from CLI");
3168
+ }
3169
+ if (hasApiKey()) {
3170
+ consola.info("Using Gemini API Key for authentication (from GEMINI_API_KEY)");
3171
+ consola.info("API Key: " + getApiKey$1()?.slice(0, 10) + "...");
2748
3172
  } else {
2749
- const enabledCount = existingAuth.accounts.filter((a) => a.enable).length;
2750
- consola.info(`Found ${existingAuth.accounts.length} Antigravity accounts (${enabledCount} enabled)`);
3173
+ const existingAuth = await loadAntigravityAuth();
3174
+ if (!existingAuth || existingAuth.accounts.length === 0) {
3175
+ consola.warn("No Antigravity accounts found and no GEMINI_API_KEY set");
3176
+ consola.info("");
3177
+ consola.info("You can authenticate using one of these methods:");
3178
+ consola.info("");
3179
+ consola.info("Method 1: API Key (Recommended - Simplest)");
3180
+ consola.info(" Set environment variable: GEMINI_API_KEY=your_api_key");
3181
+ consola.info(" Get your API key from: https://aistudio.google.com/apikey");
3182
+ consola.info("");
3183
+ consola.info("Method 2: OAuth (Current setup)");
3184
+ consola.info(" Will proceed with OAuth login flow...");
3185
+ consola.info("");
3186
+ await setupAntigravity();
3187
+ } else {
3188
+ const enabledCount = existingAuth.accounts.filter((a) => a.enable).length;
3189
+ consola.info(`Found ${existingAuth.accounts.length} Antigravity accounts (${enabledCount} enabled)`);
3190
+ }
3191
+ if (!await getCurrentAccount() && !hasApiKey()) throw new Error("No enabled Antigravity accounts available");
2751
3192
  }
2752
- if (!await getCurrentAccount()) throw new Error("No enabled Antigravity accounts available");
2753
- const { getAntigravityModels: getAntigravityModels$1 } = await import("./get-models-Dq2ZDU9m.js");
3193
+ const { getAntigravityModels: getAntigravityModels$1 } = await import("./get-models-BAElU3zd.js");
2754
3194
  const models = await getAntigravityModels$1();
2755
3195
  state.antigravityModels = models;
2756
3196
  consola.info(`Available Antigravity models: \n${models.data.map((model) => `- ${model.id}`).join("\n")}`);
2757
3197
  } else {
2758
3198
  await cacheVSCodeVersion();
2759
- if (options.githubToken) {
2760
- state.githubToken = options.githubToken;
3199
+ if (options$1.githubToken) {
3200
+ state.githubToken = options$1.githubToken;
2761
3201
  consola.info("Using provided GitHub token");
2762
3202
  try {
2763
- const { getGitHubUser } = await import("./get-user-hpkh0FzZ.js");
3203
+ const { getGitHubUser } = await import("./get-user-CsQCc3Qx.js");
2764
3204
  const user = await getGitHubUser();
2765
3205
  consola.info(`Logged in as ${user.login}`);
2766
3206
  } catch (error) {
@@ -2774,7 +3214,7 @@ async function runServer(options) {
2774
3214
  const { HTTPError: HTTPError$1 } = await import("./error-CsShqJjE.js");
2775
3215
  if (error instanceof HTTPError$1 && error.response.status === 401) {
2776
3216
  consola.error("Failed to get Copilot token - GitHub token may be invalid or Copilot access revoked");
2777
- const { clearGithubToken: clearGithubToken$1 } = await import("./token-DS09XjQ5.js");
3217
+ const { clearGithubToken: clearGithubToken$1 } = await import("./token-DhdRMuOy.js");
2778
3218
  await clearGithubToken$1();
2779
3219
  consola.info("Please restart to re-authenticate");
2780
3220
  }
@@ -2783,8 +3223,8 @@ async function runServer(options) {
2783
3223
  await cacheModels();
2784
3224
  consola.info(`Available models: \n${state.models?.data.map((model) => `- ${model.id}`).join("\n")}`);
2785
3225
  }
2786
- const serverUrl = `http://localhost:${options.port}`;
2787
- if (options.claudeCode) {
3226
+ const serverUrl = `http://localhost:${options$1.port}`;
3227
+ if (options$1.claudeCode) {
2788
3228
  let models = state.models;
2789
3229
  if (state.zenMode) models = state.zenModels;
2790
3230
  else if (state.antigravityMode) models = state.antigravityModels;
@@ -2818,7 +3258,7 @@ async function runServer(options) {
2818
3258
  consola.box(`🌐 Usage Viewer: https://imbuxiangnan-cyber.github.io/copilot-api-plus?endpoint=${serverUrl}/usage`);
2819
3259
  serve({
2820
3260
  fetch: server.fetch,
2821
- port: options.port
3261
+ port: options$1.port
2822
3262
  });
2823
3263
  }
2824
3264
  const start = defineCommand({
@@ -2900,6 +3340,14 @@ const start = defineCommand({
2900
3340
  type: "boolean",
2901
3341
  default: false,
2902
3342
  description: "Enable Google Antigravity mode (proxy to Antigravity instead of GitHub Copilot)"
3343
+ },
3344
+ "antigravity-client-id": {
3345
+ type: "string",
3346
+ description: "Google OAuth Client ID for Antigravity (create at https://console.cloud.google.com/apis/credentials)"
3347
+ },
3348
+ "antigravity-client-secret": {
3349
+ type: "string",
3350
+ description: "Google OAuth Client Secret for Antigravity"
2903
3351
  }
2904
3352
  },
2905
3353
  run({ args }) {
@@ -2922,7 +3370,9 @@ const start = defineCommand({
2922
3370
  apiKeys,
2923
3371
  zen: args.zen,
2924
3372
  zenApiKey: args["zen-api-key"],
2925
- antigravity: args.antigravity
3373
+ antigravity: args.antigravity,
3374
+ antigravityClientId: args["antigravity-client-id"],
3375
+ antigravityClientSecret: args["antigravity-client-secret"]
2926
3376
  });
2927
3377
  }
2928
3378
  });