copilot-api-plus 1.2.4 → 1.2.6

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,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { n as forwardError, t as HTTPError } from "./error-CvwUkoEo.js";
3
- import { _ as ensurePaths, a as stopCopilotTokenRefresh, c as accountManager, d as cacheVSCodeVersion, f as findModel, g as PATHS, h as sleep, i as setupGitHubToken, l as getCopilotUsage, m as rootCause, n as refreshCopilotToken, o as pollAccessToken, p as isNullish, r as setupCopilotToken, s as getDeviceCode, t as clearGithubToken, u as cacheModels } from "./token-CMRVLQJZ.js";
4
- import { a as GITHUB_BASE_URL, c as copilotHeaders, n as state, o as GITHUB_CLIENT_ID, s as copilotBaseUrl, u as standardHeaders } from "./get-user-BT7hEyDN.js";
2
+ import { _ as GITHUB_BASE_URL, a as PATHS, b as copilotHeaders, c as forwardError, d as findModel, f as isNullish, h as state, l as cacheModels, m as sleep, o as ensurePaths, p as rootCause, r as getCopilotUsage, s as HTTPError, t as accountManager, u as cacheVSCodeVersion, v as GITHUB_CLIENT_ID, x as standardHeaders, y as copilotBaseUrl } from "./account-manager-DmXXcFBW.js";
3
+ import { a as stopCopilotTokenRefresh, i as setupGitHubToken, n as refreshCopilotToken, o as pollAccessToken, r as setupCopilotToken, s as getDeviceCode, t as clearGithubToken } from "./token-DUSd-gxE.js";
5
4
  import { createRequire } from "node:module";
6
5
  import { defineCommand, runMain } from "citty";
7
6
  import consola from "consola";
@@ -121,16 +120,18 @@ async function applyProxyConfig() {
121
120
  }
122
121
  //#endregion
123
122
  //#region src/lib/proxy.ts
123
+ const agentOptions = {
124
+ keepAliveTimeout: 3e4,
125
+ keepAliveMaxTimeout: 6e4,
126
+ connect: { timeout: 15e3 }
127
+ };
128
+ let direct;
129
+ let proxies = /* @__PURE__ */ new Map();
124
130
  function initProxyFromEnv() {
125
131
  if (typeof Bun !== "undefined") return;
126
132
  try {
127
- const agentOptions = {
128
- keepAliveTimeout: 3e4,
129
- keepAliveMaxTimeout: 6e4,
130
- connect: { timeout: 15e3 }
131
- };
132
- const direct = new Agent(agentOptions);
133
- const proxies = /* @__PURE__ */ new Map();
133
+ direct = new Agent(agentOptions);
134
+ proxies = /* @__PURE__ */ new Map();
134
135
  setGlobalDispatcher({
135
136
  dispatch(options, handler) {
136
137
  try {
@@ -174,6 +175,28 @@ function initProxyFromEnv() {
174
175
  consola.debug("Proxy setup skipped:", err);
175
176
  }
176
177
  }
178
+ /**
179
+ * Destroy all pooled connections (direct + proxy agents) and replace them
180
+ * with fresh instances. The global dispatcher's `dispatch` method captures
181
+ * `direct` and `proxies` by reference, so subsequent requests automatically
182
+ * use the new agents — no need to call `setGlobalDispatcher` again.
183
+ *
184
+ * Call this after a network error to discard stale/half-closed sockets that
185
+ * would otherwise cause every retry to wait ~60 s before timing out.
186
+ *
187
+ * Under the Bun runtime (which doesn't use undici) this is a no-op.
188
+ */
189
+ function resetConnections() {
190
+ if (typeof Bun !== "undefined") return;
191
+ if (!direct) return;
192
+ const oldDirect = direct;
193
+ const oldProxies = proxies;
194
+ direct = new Agent(agentOptions);
195
+ proxies = /* @__PURE__ */ new Map();
196
+ oldDirect.close().catch(() => {});
197
+ for (const agent of oldProxies.values()) agent.close().catch(() => {});
198
+ consola.debug("Connection pool reset — stale sockets cleared");
199
+ }
177
200
  //#endregion
178
201
  //#region src/account.ts
179
202
  const addAccount = defineCommand({
@@ -1398,7 +1421,8 @@ accountRoutes.get("/", (c) => {
1398
1421
  const accounts = accountManager.getAccounts().map((a) => sanitiseAccount(a));
1399
1422
  return c.json({ accounts });
1400
1423
  } catch (error) {
1401
- consola.error("Error listing accounts:", error);
1424
+ consola.warn(`Error listing accounts: ${rootCause(error)}`);
1425
+ consola.debug("Error listing accounts:", error);
1402
1426
  return c.json({ error: "Failed to list accounts" }, 500);
1403
1427
  }
1404
1428
  });
@@ -1409,7 +1433,8 @@ accountRoutes.post("/", async (c) => {
1409
1433
  const account = await accountManager.addAccount(body.githubToken, body.label, body.accountType);
1410
1434
  return c.json({ account: sanitiseAccount(account) }, 201);
1411
1435
  } catch (error) {
1412
- consola.error("Error adding account:", error);
1436
+ consola.warn(`Error adding account: ${rootCause(error)}`);
1437
+ consola.debug("Error adding account:", error);
1413
1438
  return c.json({ error: "Failed to add account" }, 500);
1414
1439
  }
1415
1440
  });
@@ -1419,7 +1444,8 @@ accountRoutes.delete("/:id", async (c) => {
1419
1444
  if (!await accountManager.removeAccount(id)) return c.json({ error: "Account not found" }, 404);
1420
1445
  return c.json({ success: true });
1421
1446
  } catch (error) {
1422
- consola.error("Error removing account:", error);
1447
+ consola.warn(`Error removing account: ${rootCause(error)}`);
1448
+ consola.debug("Error removing account:", error);
1423
1449
  return c.json({ error: "Failed to remove account" }, 500);
1424
1450
  }
1425
1451
  });
@@ -1439,7 +1465,8 @@ accountRoutes.put("/:id/status", async (c) => {
1439
1465
  await accountManager.saveAccounts();
1440
1466
  return c.json({ account: sanitiseAccount(account) });
1441
1467
  } catch (error) {
1442
- consola.error("Error updating account status:", error);
1468
+ consola.warn(`Error updating account status: ${rootCause(error)}`);
1469
+ consola.debug("Error updating account status:", error);
1443
1470
  return c.json({ error: "Failed to update account status" }, 500);
1444
1471
  }
1445
1472
  });
@@ -1452,7 +1479,8 @@ accountRoutes.post("/:id/refresh", async (c) => {
1452
1479
  await accountManager.refreshAccountUsage(account);
1453
1480
  return c.json({ account: sanitiseAccount(account) });
1454
1481
  } catch (error) {
1455
- consola.error("Error refreshing account:", error);
1482
+ consola.warn(`Error refreshing account: ${rootCause(error)}`);
1483
+ consola.debug("Error refreshing account:", error);
1456
1484
  return c.json({ error: "Failed to refresh account" }, 500);
1457
1485
  }
1458
1486
  });
@@ -1461,7 +1489,8 @@ accountRoutes.post("/auth/start", async (c) => {
1461
1489
  const deviceCode = await getDeviceCode();
1462
1490
  return c.json(deviceCode);
1463
1491
  } catch (error) {
1464
- consola.error("Error starting device code flow:", error);
1492
+ consola.warn(`Error starting device code flow: ${rootCause(error)}`);
1493
+ consola.debug("Error starting device code flow:", error);
1465
1494
  return c.json({ error: "Failed to start device code authorization" }, 500);
1466
1495
  }
1467
1496
  });
@@ -1503,7 +1532,8 @@ accountRoutes.post("/auth/poll", async (c) => {
1503
1532
  }
1504
1533
  return c.json({ status: "pending" });
1505
1534
  } catch (error) {
1506
- consola.error("Error polling device code:", error);
1535
+ consola.warn(`Error polling device code: ${rootCause(error)}`);
1536
+ consola.debug("Error polling device code:", error);
1507
1537
  return c.json({ error: "Failed to poll device code authorization" }, 500);
1508
1538
  }
1509
1539
  });
@@ -1537,7 +1567,8 @@ accountRoutes.get("/usage", (c) => {
1537
1567
  accounts: accountSummaries
1538
1568
  });
1539
1569
  } catch (error) {
1540
- consola.error("Error fetching aggregated usage:", error);
1570
+ consola.warn(`Error fetching aggregated usage: ${rootCause(error)}`);
1571
+ consola.debug("Error fetching aggregated usage:", error);
1541
1572
  return c.json({ error: "Failed to fetch aggregated usage" }, 500);
1542
1573
  }
1543
1574
  });
@@ -1549,7 +1580,8 @@ modelAdminRoutes.get("/available", (c) => {
1549
1580
  const models = state.models?.data ?? [];
1550
1581
  return c.json(models);
1551
1582
  } catch (error) {
1552
- consola.error("Error fetching available models:", error);
1583
+ consola.warn(`Error fetching available models: ${rootCause(error)}`);
1584
+ consola.debug("Error fetching available models:", error);
1553
1585
  return c.json({ error: "Failed to fetch available models" }, 500);
1554
1586
  }
1555
1587
  });
@@ -1557,7 +1589,8 @@ modelAdminRoutes.get("/mapping", (c) => {
1557
1589
  try {
1558
1590
  return c.json(modelRouter.getConfig());
1559
1591
  } catch (error) {
1560
- consola.error("Error fetching model mapping:", error);
1592
+ consola.warn(`Error fetching model mapping: ${rootCause(error)}`);
1593
+ consola.debug("Error fetching model mapping:", error);
1561
1594
  return c.json({ error: "Failed to fetch model mapping" }, 500);
1562
1595
  }
1563
1596
  });
@@ -1570,7 +1603,8 @@ modelAdminRoutes.put("/mapping", async (c) => {
1570
1603
  await saveModelMappingConfig(modelRouter.getConfig());
1571
1604
  return c.json(modelRouter.getConfig());
1572
1605
  } catch (error) {
1573
- consola.error("Error updating model mapping:", error);
1606
+ consola.warn(`Error updating model mapping: ${rootCause(error)}`);
1607
+ consola.debug("Error updating model mapping:", error);
1574
1608
  return c.json({ error: "Failed to update model mapping" }, 500);
1575
1609
  }
1576
1610
  });
@@ -1578,7 +1612,8 @@ modelAdminRoutes.get("/concurrency", (c) => {
1578
1612
  try {
1579
1613
  return c.json({ concurrency: modelRouter.getConfig().concurrency });
1580
1614
  } catch (error) {
1581
- consola.error("Error fetching concurrency config:", error);
1615
+ consola.warn(`Error fetching concurrency config: ${rootCause(error)}`);
1616
+ consola.debug("Error fetching concurrency config:", error);
1582
1617
  return c.json({ error: "Failed to fetch concurrency config" }, 500);
1583
1618
  }
1584
1619
  });
@@ -1591,7 +1626,8 @@ modelAdminRoutes.put("/concurrency", async (c) => {
1591
1626
  await saveModelMappingConfig(modelRouter.getConfig());
1592
1627
  return c.json({ concurrency: modelRouter.getConfig().concurrency });
1593
1628
  } catch (error) {
1594
- consola.error("Error updating concurrency config:", error);
1629
+ consola.warn(`Error updating concurrency config: ${rootCause(error)}`);
1630
+ consola.debug("Error updating concurrency config:", error);
1595
1631
  return c.json({ error: "Failed to update concurrency config" }, 500);
1596
1632
  }
1597
1633
  });
@@ -1715,6 +1751,7 @@ async function fetchWithRetry(url, buildInit) {
1715
1751
  return await fetchWithTimeout(url, buildInit());
1716
1752
  } catch (error) {
1717
1753
  lastError = error;
1754
+ if (attempt === 0) resetConnections();
1718
1755
  if (attempt < maxAttempts - 1) {
1719
1756
  const delay = RETRY_DELAYS[attempt];
1720
1757
  consola.warn(`Network error on attempt ${attempt + 1}/${maxAttempts}, retrying in ${delay}ms:`, error instanceof Error ? error.message : error);
@@ -2583,7 +2620,8 @@ async function handleCountTokens(c) {
2583
2620
  console.log("Token count:", finalTokenCount);
2584
2621
  return c.json({ input_tokens: finalTokenCount });
2585
2622
  } catch (error) {
2586
- consola.error("Error counting tokens:", error);
2623
+ consola.warn(`Error counting tokens: ${rootCause(error)}`);
2624
+ consola.debug("Error counting tokens:", error);
2587
2625
  return c.json({ input_tokens: 1 });
2588
2626
  }
2589
2627
  }
@@ -2871,7 +2909,8 @@ tokenRoute.get("/", (c) => {
2871
2909
  try {
2872
2910
  return c.json({ token: state.copilotToken });
2873
2911
  } catch (error) {
2874
- consola.error("Error fetching token:", error);
2912
+ consola.warn(`Error fetching token: ${rootCause(error)}`);
2913
+ consola.debug("Error fetching token:", error);
2875
2914
  return c.json({
2876
2915
  error: "Failed to fetch token",
2877
2916
  token: null
@@ -2893,7 +2932,8 @@ usageRoute.get("/", async (c) => {
2893
2932
  const usage = await getCopilotUsage();
2894
2933
  return c.json(usage);
2895
2934
  } catch (error) {
2896
- consola.error("Error fetching usage:", error);
2935
+ consola.warn(`Error fetching usage: ${rootCause(error)}`);
2936
+ consola.debug("Error fetching usage:", error);
2897
2937
  return c.json({ error: "Failed to fetch Copilot usage" }, 500);
2898
2938
  }
2899
2939
  });
@@ -3010,7 +3050,7 @@ async function validateGitHubToken(token) {
3010
3050
  state.githubToken = token;
3011
3051
  consola.info("Using provided GitHub token");
3012
3052
  try {
3013
- const { getGitHubUser } = await import("./get-user-BTN_-eOk.js");
3053
+ const { getGitHubUser } = await import("./get-user-DHr540ak.js");
3014
3054
  const user = await getGitHubUser();
3015
3055
  consola.info(`Logged in as ${user.login}`);
3016
3056
  } catch (error) {
@@ -3056,10 +3096,10 @@ async function runServer(options) {
3056
3096
  try {
3057
3097
  await setupCopilotToken();
3058
3098
  } catch (error) {
3059
- const { HTTPError } = await import("./error-DLqcVQL_.js");
3099
+ const { HTTPError } = await import("./error-Cc8bY0ph.js");
3060
3100
  if (error instanceof HTTPError && error.response.status === 401) {
3061
3101
  consola.error("Failed to get Copilot token - GitHub token may be invalid or Copilot access revoked");
3062
- const { clearGithubToken } = await import("./token-CHJ7rYg0.js");
3102
+ const { clearGithubToken } = await import("./token-B_m1icXz.js");
3063
3103
  await clearGithubToken();
3064
3104
  consola.info("Please restart to re-authenticate");
3065
3105
  }