lceda-connect 0.3.0 → 0.4.2

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +107 -31
  3. package/dist/{cli-C4ZkWlV2.mjs → cli-D-PphUlG.mjs} +1 -1
  4. package/dist/{cli-C6saKrQp.mjs → cli-D-kNq1F6.mjs} +18 -3
  5. package/dist/{cli-CjcJVM6z.mjs → cli-Dja1oai7.mjs} +4 -4
  6. package/dist/cli-bridge-server.mjs +1 -1
  7. package/dist/cli-bridge.mjs +1 -1
  8. package/dist/cli-cdp.mjs +1 -1
  9. package/dist/cli-mcp.mjs +1 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/config-B3dElEFD.mjs +516 -0
  12. package/dist/{discover-D5mRrsxg.mjs → discover-D-YAeRWh.mjs} +13 -64
  13. package/dist/environment-BegP0n2N.mjs +439 -0
  14. package/dist/environment-MMVlAqxo.mjs +146 -0
  15. package/dist/http-BNbYGS4p.mjs +1 -0
  16. package/dist/http-C9RtNg_O.mjs +366 -0
  17. package/dist/index.d.mts +226 -6
  18. package/dist/index.mjs +7 -5
  19. package/dist/{main-CcKvXSJG.mjs → main-CFHsfo5I.mjs} +758 -88
  20. package/dist/mcpHost-CRoN6MnG.mjs +331 -0
  21. package/dist/{registry-Dmti2u6s.mjs → registry-Be9DNS6F.mjs} +84 -24
  22. package/dist/registry-KmkmrusO.mjs +1 -0
  23. package/dist/{server-BduSjwzu.mjs → server-4ROmddm7.mjs} +9 -14
  24. package/dist/{session-DvIXO5Hf.mjs → session-BypD6Iab.mjs} +2 -2
  25. package/dist/{sideEffects-DF_tIVsf.mjs → sideEffects-3OHHy4VU.mjs} +3 -3
  26. package/dist/stdio-Ji0B6uQT.mjs +1 -0
  27. package/dist/stdio-rNTpzX2t.mjs +27 -0
  28. package/dist/{targets-D5nmbsyz.mjs → targets-DVmXbqhN.mjs} +1 -1
  29. package/dist/{verbs-5M7rj1-E.mjs → verbs-d3wbVcHt.mjs} +191 -54
  30. package/dist/windowsHost-CTZXMA8D.mjs +1 -0
  31. package/dist/windowsHost-CtRidgJp.mjs +309 -0
  32. package/docs/architecture.md +81 -0
  33. package/docs/environments.md +175 -0
  34. package/docs/quickstart.md +59 -4
  35. package/docs/transports.md +191 -0
  36. package/package.json +5 -2
  37. package/dist/registry-zIKWeXV6.mjs +0 -1
  38. package/dist/server-Chka6eAQ.mjs +0 -1
@@ -1,10 +1,11 @@
1
- import { _ as asCdpError, a as defaultPortFromEnv, i as browserUuid, m as versionBrowser, o as discover, p as resolveEndpoint } from "./discover-D5mRrsxg.mjs";
1
+ import { c as liveStrategy, n as cdpProbeHosts, r as describeEnvironment } from "./environment-BegP0n2N.mjs";
2
2
  import { o as readAssetJson } from "./assets-D48xh-kr.mjs";
3
3
  import { t as packageVersion } from "./version-B39-elun.mjs";
4
+ import { a as defaultPortFromEnv, c as fetchJson, h as versionBrowser, i as browserUuid, m as resolveEndpoint, o as discover, v as asCdpError } from "./discover-D-YAeRWh.mjs";
4
5
  import "./protocol-B4UcGrGa.mjs";
5
6
  import { i as execute, r as discover$1, s as windows, t as BridgeClientError } from "./client-_LVz5Zg0.mjs";
6
- import { i as evaluateExpression, t as CdpSession } from "./session-DvIXO5Hf.mjs";
7
- import { i as listTargets } from "./targets-D5nmbsyz.mjs";
7
+ import { i as evaluateExpression, t as CdpSession } from "./session-BypD6Iab.mjs";
8
+ import { i as listTargets } from "./targets-DVmXbqhN.mjs";
8
9
  import path from "node:path";
9
10
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
11
  import { createHash } from "node:crypto";
@@ -189,7 +190,7 @@ function bridgeCheckFromEndpoint(endpoint, host) {
189
190
  hint: "在客户端加载并启用 run-api-gateway 扩展"
190
191
  };
191
192
  }
192
- /** 探测本机 bridge。找不到是 missing;身份/协议错误是 unavailable。 */
193
+ /** 探测 bridge。找不到是 missing;身份/协议错误是 unavailable。 */
193
194
  async function probeBridgeChannel(options = {}) {
194
195
  const host = options.host ?? "127.0.0.1";
195
196
  try {
@@ -225,6 +226,7 @@ function cdpCheckFromOutput(output, host) {
225
226
  reason_code: "ok",
226
227
  detail: `${host}:${best.port} · ${browser || "unknown"}`,
227
228
  hint: "",
229
+ port: best.port,
228
230
  version: {
229
231
  browser: browser || null,
230
232
  protocol: best.version !== null && typeof best.version === "object" && typeof best.version["Protocol-Version"] === "string" ? best.version["Protocol-Version"] : null,
@@ -232,27 +234,105 @@ function cdpCheckFromOutput(output, host) {
232
234
  }
233
235
  };
234
236
  }
235
- /** 探测 CDP 端点。默认先看 profile 的端口文件,再试 9222 / EASYEDA_CDP_PORT。 */
237
+ const EASYEDA_TARGET_MARKERS = [
238
+ /嘉立创\s*EDA/i,
239
+ /EasyEDA/i,
240
+ /easyeda/i,
241
+ /pro\.lceda\.cn/i,
242
+ /client\/editor/i
243
+ ];
244
+ /**
245
+ * 判断 CDP 端口背后是不是嘉立创 EDA。
246
+ * `/json/version` 只能证明“这是 Chromium”,任何 Electron 应用都满足;要看 target 标题/URL。
247
+ * 目标列表为空时返回 null(应用刚启动、还没建页面,不做判断)。
248
+ */
249
+ function identifyCdpApplication(targets) {
250
+ if (!Array.isArray(targets)) return null;
251
+ const pages = targets.filter((item) => item !== null && typeof item === "object");
252
+ if (pages.length === 0) return null;
253
+ for (const page of pages) {
254
+ const title = typeof page.title === "string" ? page.title : "";
255
+ const url = typeof page.url === "string" ? page.url : "";
256
+ const text = `${title} ${url}`;
257
+ if (EASYEDA_TARGET_MARKERS.some((marker) => marker.test(text))) return {
258
+ match: true,
259
+ sample: title || url
260
+ };
261
+ }
262
+ const first = pages[0] ?? {};
263
+ return {
264
+ match: false,
265
+ sample: typeof first.title === "string" && first.title || typeof first.url === "string" && first.url || "(unknown target)"
266
+ };
267
+ }
268
+ async function probeCdpApplication(host, port, timeoutMs) {
269
+ try {
270
+ return identifyCdpApplication(await fetchJson(host, port, "/json/list", timeoutMs));
271
+ } catch {
272
+ return null;
273
+ }
274
+ }
275
+ /**
276
+ * 探测 CDP。按 hosts 顺序尝试,命中即返回;全部失败时把试过的地址写进 detail。
277
+ * 默认先看 profile 的端口文件,再试 9222 / EASYEDA_CDP_PORT。
278
+ */
236
279
  async function probeCdpChannel(options = {}) {
237
- const host = options.host ?? "127.0.0.1";
238
280
  const env = options.env ?? process.env;
239
281
  const port = options.port ?? defaultPortFromEnv(env) ?? 9222;
240
- try {
241
- return cdpCheckFromOutput(await discover(host, {
242
- port,
243
- scan: options.scan,
244
- timeoutMs: options.timeoutMs ?? CDP_PROBE_TIMEOUT_MS,
245
- env
246
- }), host);
247
- } catch (error) {
248
- return {
249
- id: "cdp-endpoint",
250
- status: "unavailable",
251
- reason_code: "probe_failed",
252
- detail: error instanceof Error ? error.message : String(error),
253
- hint: "只允许回环地址;确认客户端与端口配置"
254
- };
282
+ const hosts = options.hosts && options.hosts.length > 0 ? options.hosts : [options.host ?? "127.0.0.1"];
283
+ const tried = [];
284
+ let last = null;
285
+ for (const host of hosts) {
286
+ tried.push(host);
287
+ try {
288
+ const check = cdpCheckFromOutput(await discover(host, {
289
+ port,
290
+ scan: options.scan,
291
+ timeoutMs: options.timeoutMs ?? CDP_PROBE_TIMEOUT_MS,
292
+ env,
293
+ allowedHosts: hosts
294
+ }), host);
295
+ if (check.status === "ready") {
296
+ const port = Number(check.port ?? 0);
297
+ if (port > 0) {
298
+ const app = await probeCdpApplication(host, port, Math.min(options.timeoutMs ?? CDP_PROBE_TIMEOUT_MS, 1200));
299
+ if (app && !app.match) return {
300
+ ...check,
301
+ status: "partial",
302
+ reason_code: "wrong_application",
303
+ detail: `${host}:${port} · ${app.sample}`,
304
+ hint: "该 CDP 端口不是嘉立创EDA(可能是其它 Electron 应用);请用 --port 指定 EDA 的调试端口,或关闭占用程序后重启客户端",
305
+ hosts: tried
306
+ };
307
+ }
308
+ return {
309
+ ...check,
310
+ hosts: tried
311
+ };
312
+ }
313
+ last = check;
314
+ } catch (error) {
315
+ last = {
316
+ id: "cdp-endpoint",
317
+ status: "unavailable",
318
+ reason_code: "probe_failed",
319
+ detail: error instanceof Error ? error.message : String(error),
320
+ hint: `试过 ${tried.join(" → ")};确认客户端调试端口、Windows 防火墙或 WSL 网络模式`
321
+ };
322
+ }
255
323
  }
324
+ const base = last ?? {
325
+ id: "cdp-endpoint",
326
+ status: "missing",
327
+ reason_code: "service_unavailable",
328
+ detail: "",
329
+ hint: "彻底退出客户端后带 --remote-debugging-port=9222 启动;或用 lceda-connect cdp start"
330
+ };
331
+ return {
332
+ ...base,
333
+ detail: base.detail || `试过 ${tried.join(" → ")}`,
334
+ hosts: tried
335
+ };
256
336
  }
257
337
  function checkNodeVersion(nodeVersion) {
258
338
  const match = /^v?(\d+)\./.exec(nodeVersion.trim());
@@ -274,9 +354,18 @@ function versionFingerprint(bridge, cdp) {
274
354
  } : null
275
355
  };
276
356
  }
357
+ /** 是否是「WSL2 NAT + 客户端在 Windows 宿主」这种跨命名空间组合。 */
358
+ function isCrossOsHostEnvironment(info) {
359
+ if (!info || info.kind !== "wsl2") return false;
360
+ if (info.networkingMode === "mirrored") return false;
361
+ if (info.clientLocations.includes("vm")) return false;
362
+ return true;
363
+ }
277
364
  /** 完整自检;`probeBridge` / `probeCdp` 可注入,便于离线测试四态。 */
278
365
  async function checkEnvironment(options = {}) {
279
366
  const env = options.env ?? process.env;
367
+ const info = options.environment;
368
+ const strategy = options.strategy ?? (info ? liveStrategy(info) : void 0);
280
369
  const nodeItem = checkNodeVersion(options.nodeVersion ?? process.version);
281
370
  const cdpModuleItem = {
282
371
  id: "cdp-module",
@@ -285,9 +374,23 @@ async function checkEnvironment(options = {}) {
285
374
  detail: "内置 CDP 连接层(src/cdp)",
286
375
  hint: ""
287
376
  };
288
- const bridgeItem = options.probeBridge ? await options.probeBridge() : await probeBridgeChannel(options.bridge);
377
+ const bridgeHost = options.bridgeHost ?? options.bridge?.host ?? (info ? strategy?.bridgeHost ?? "127.0.0.1" : "127.0.0.1");
378
+ const cdpHosts = options.cdpHosts ?? (info ? cdpProbeHosts(info) : void 0) ?? (options.cdp?.hosts && options.cdp.hosts.length > 0 ? options.cdp.hosts : [options.cdp?.host ?? "127.0.0.1"]);
379
+ let bridgeItem = options.probeBridge ? await options.probeBridge() : await probeBridgeChannel({
380
+ ...options.bridge,
381
+ host: bridgeHost
382
+ });
383
+ if (!options.probeBridge && isCrossOsHostEnvironment(info)) {
384
+ if (bridgeItem.status === "missing" || bridgeItem.status === "unavailable") bridgeItem = {
385
+ ...bridgeItem,
386
+ reason_code: "cross_os_loopback",
387
+ hint: strategy?.nextAction ?? "bridge 只监听回环,跨 WSL/Windows 不可达;在 Windows 侧运行 MCP 或启用 WSL mirrored 网络"
388
+ };
389
+ }
289
390
  const cdpItem = options.probeCdp ? await options.probeCdp() : await probeCdpChannel({
290
391
  ...options.cdp,
392
+ host: cdpHosts[0],
393
+ hosts: cdpHosts,
291
394
  env
292
395
  });
293
396
  const bridgeOk = bridgeItem.status === "ready";
@@ -305,23 +408,27 @@ async function checkEnvironment(options = {}) {
305
408
  status = "needs_setup";
306
409
  }
307
410
  const sessionOk = bridgeOk || cdpOk;
308
- const checks = [
309
- nodeItem,
310
- cdpModuleItem,
311
- {
312
- id: "client-session",
313
- status: sessionOk ? "ready" : "missing",
314
- reason_code: sessionOk ? "ok" : "service_unavailable",
315
- detail: sessionOk ? "至少一条通道可见客户端" : "两条通道都看不到客户端",
316
- hint: sessionOk ? "" : "先启动客户端;bridge 需加载扩展,CDP 需带调试端口启动"
317
- },
318
- bridgeItem,
319
- cdpItem
320
- ];
411
+ const crossOs = isCrossOsHostEnvironment(info);
412
+ const checks = [];
413
+ if (info) checks.push({
414
+ id: "environment",
415
+ status: "ready",
416
+ reason_code: "ok",
417
+ detail: describeEnvironment(info),
418
+ hint: strategy?.summary ?? ""
419
+ });
420
+ checks.push(nodeItem, cdpModuleItem, {
421
+ id: "client-session",
422
+ status: sessionOk ? "ready" : "missing",
423
+ reason_code: sessionOk ? "ok" : crossOs ? "cross_os_loopback" : "service_unavailable",
424
+ detail: sessionOk ? "至少一条通道可见客户端" : crossOs ? "两条通道都看不到客户端(WSL2 与 Windows 宿主回环不互通)" : "两条通道都看不到客户端",
425
+ hint: sessionOk ? "" : crossOs ? strategy?.nextAction ?? "在 Windows 侧运行 MCP,或启用 WSL mirrored 网络" : "先启动客户端;bridge 需加载扩展,CDP 需带调试端口启动"
426
+ }, bridgeItem, cdpItem);
321
427
  const functionalDegradations = [];
322
428
  if (!bridgeOk) functionalDegradations.push("无官方 API 面:工程管理、制造导出不可用");
323
429
  if (!cdpOk) functionalDegradations.push("无视觉回路:截图类审查降级为人工截图");
324
- const nextAction = status === "ready" ? "两条通道都可用,直接进入路由决策" : status === "partial" ? "单通道可用:按路由表执行,跳过不可用通道相关的动词" : "先搭一条通道:bridge 需启动服务并加载扩展,或按 setup-guide 开 CDP 端口";
430
+ if (crossOs) functionalDegradations.push("WSL2 NAT:在线通道跨命名空间,bridge 不可达(CDP 仅在客户端监听非回环时可达)");
431
+ const nextAction = status === "ready" ? "两条通道都可用,直接进入路由决策" : status === "partial" ? "单通道可用:按路由表执行,跳过不可用通道相关的动词" : strategy?.nextAction ?? "先搭一条通道:bridge 需启动服务并加载扩展,或按 setup-guide 开 CDP 端口";
325
432
  return {
326
433
  status,
327
434
  channel_state: channelState,
@@ -351,7 +458,21 @@ async function checkEnvironment(options = {}) {
351
458
  functional_degradations: functionalDegradations,
352
459
  version_fingerprint: versionFingerprint(bridgeItem, cdpItem),
353
460
  next_action: nextAction,
354
- exit_code: status === "ready" ? 0 : status === "partial" ? 1 : 2
461
+ exit_code: status === "ready" ? 0 : status === "partial" ? 1 : 2,
462
+ ...info ? {
463
+ environment: info,
464
+ live_strategy: strategy ? {
465
+ summary: strategy.summary,
466
+ next_action: strategy.nextAction,
467
+ locations: strategy.locations
468
+ } : void 0
469
+ } : {},
470
+ client_exe: options.clientExe ? {
471
+ status: options.clientExe.status,
472
+ path: options.clientExe.path,
473
+ location: options.clientExe.location,
474
+ source: options.clientExe.source
475
+ } : null
355
476
  };
356
477
  }
357
478
  // src/eda/payloads.ts
@@ -945,12 +1066,16 @@ function pageCandidates(targets, match) {
945
1066
  }
946
1067
  /** CDP 适配器:逐页探测文档类型,选中匹配页后求值。 */
947
1068
  var DefaultCdpChannel = class {
948
- host;
1069
+ hosts;
1070
+ allowedHosts;
1071
+ activeHost;
949
1072
  portOption;
950
1073
  env;
951
1074
  defaultTimeoutMs;
952
1075
  constructor(options = {}) {
953
- this.host = options.host ?? "127.0.0.1";
1076
+ this.hosts = options.hosts && options.hosts.length > 0 ? options.hosts : [options.host ?? "127.0.0.1"];
1077
+ this.activeHost = this.hosts[0] ?? "127.0.0.1";
1078
+ this.allowedHosts = options.allowedHosts ?? this.hosts;
954
1079
  this.portOption = options.port;
955
1080
  this.env = options.env ?? process.env;
956
1081
  this.defaultTimeoutMs = options.defaultTimeoutMs;
@@ -968,7 +1093,8 @@ var DefaultCdpChannel = class {
968
1093
  session = await CdpSession.connect(String(page.webSocketDebuggerUrl), {
969
1094
  env: this.env,
970
1095
  timeoutMs: options.timeoutMs ?? this.defaultTimeoutMs,
971
- signal: options.signal
1096
+ signal: options.signal,
1097
+ allowedHosts: this.allowedHosts
972
1098
  });
973
1099
  } catch (error) {
974
1100
  if (error?.code === "CANCELLED") throw error;
@@ -1016,23 +1142,31 @@ var DefaultCdpChannel = class {
1016
1142
  }
1017
1143
  async endpoint(signal) {
1018
1144
  const port = this.portOption ?? defaultPortFromEnv(this.env);
1019
- try {
1020
- const endpoint = await resolveEndpoint(this.host, {
1021
- port,
1022
- env: this.env,
1023
- signal
1024
- });
1025
- if (!endpoint) throw new ChannelError("cdp", "CDP_NOT_FOUND", "找不到 CDP 端点:客户端需带 --remote-debugging-port 启动", 2);
1026
- return { port: endpoint.port };
1027
- } catch (error) {
1028
- if (error?.code === "CANCELLED") throw error;
1029
- if (error instanceof ChannelError) throw error;
1030
- throw timeoutExitCode("cdp", error);
1145
+ const tried = [];
1146
+ let lastMessage = "";
1147
+ for (const host of this.hosts) {
1148
+ tried.push(host);
1149
+ try {
1150
+ const endpoint = await resolveEndpoint(host, {
1151
+ port,
1152
+ env: this.env,
1153
+ signal,
1154
+ allowedHosts: this.allowedHosts
1155
+ });
1156
+ if (endpoint) {
1157
+ this.activeHost = host;
1158
+ return { port: endpoint.port };
1159
+ }
1160
+ } catch (error) {
1161
+ if (error?.code === "CANCELLED") throw error;
1162
+ lastMessage = error instanceof Error ? error.message : String(error);
1163
+ }
1031
1164
  }
1165
+ throw new ChannelError("cdp", "CDP_NOT_FOUND", `找不到 CDP 端点:试过 ${tried.join(" → ")}${lastMessage ? `(${lastMessage})` : ""};客户端需带 --remote-debugging-port 启动`, 2);
1032
1166
  }
1033
1167
  async targets(port, signal) {
1034
1168
  try {
1035
- return await listTargets(this.host, port, void 0, signal);
1169
+ return await listTargets(this.activeHost, port, void 0, signal);
1036
1170
  } catch (error) {
1037
1171
  if (error?.code === "CANCELLED") throw error;
1038
1172
  throw timeoutExitCode("cdp", error);
@@ -1045,13 +1179,16 @@ function createDefaultExecContext(options = {}) {
1045
1179
  return {
1046
1180
  env,
1047
1181
  bridge: new DefaultBridgeChannel({
1182
+ host: options.bridgeHost,
1048
1183
  portFirst: options.bridgePortFirst,
1049
1184
  portLast: options.bridgePortLast,
1050
1185
  env
1051
1186
  }),
1052
1187
  cdp: new DefaultCdpChannel({
1188
+ hosts: options.cdpHosts,
1053
1189
  port: options.cdpPort,
1054
- env
1190
+ env,
1191
+ allowedHosts: options.allowedHosts ?? options.cdpHosts
1055
1192
  }),
1056
1193
  match: options.match,
1057
1194
  windowId: options.windowId,
@@ -0,0 +1 @@
1
+ export { t as normalizeMcpEnv, o as resolveWslFacingHost } from "./windowsHost-CtRidgJp.mjs";
@@ -0,0 +1,309 @@
1
+ import { l as windowsPathToWslPath, u as wslPathToWindowsPath } from "./environment-BegP0n2N.mjs";
2
+ import { networkInterfaces } from "node:os";
3
+ import fs from "node:fs";
4
+ import { spawnSync } from "node:child_process";
5
+ // src/core/windowsHost.ts
6
+ function resolveProbes(probes = {}) {
7
+ return {
8
+ platform: probes.platform ?? process.platform,
9
+ env: probes.env ?? process.env,
10
+ runText: probes.runText ?? ((command, args, timeoutMs) => {
11
+ try {
12
+ const result = spawnSync(command, [...args], {
13
+ timeout: timeoutMs,
14
+ encoding: "utf8",
15
+ windowsHide: true
16
+ });
17
+ if (result.status !== 0) return null;
18
+ return `${result.stdout ?? ""}`.trim() || null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }),
23
+ exists: probes.exists ?? ((file) => fs.existsSync(file)),
24
+ listDir: probes.listDir ?? ((dir) => {
25
+ try {
26
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map((entry) => entry.name);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }),
31
+ interfaces: probes.interfaces ?? (() => networkInterfaces())
32
+ };
33
+ }
34
+ /** 解析 `cmd.exe /d /c set` 的输出;跳过 `=C:=...` 这类驱动器当前目录项。 */
35
+ function parseWindowsEnvSet(text) {
36
+ const env = {};
37
+ for (const line of text.split(/\r?\n/)) {
38
+ if (!line || line.startsWith("=")) continue;
39
+ const index = line.indexOf("=");
40
+ if (index <= 0) continue;
41
+ const key = line.slice(0, index).trim();
42
+ if (!/^[A-Za-z_][A-Za-z0-9_()#@]*$/.test(key)) continue;
43
+ env[key] = line.slice(index + 1);
44
+ }
45
+ return env;
46
+ }
47
+ const TRANSLATE_ENV_KEYS = [
48
+ "LCEDA_CONFIG",
49
+ "LCEDA_ENV_FILE",
50
+ "LCEDA_PRO_EXE",
51
+ "LCEDA_NODE",
52
+ "LCEDA_BRIDGE_SCRIPT",
53
+ "LCEDA_CONNECT_HOME",
54
+ "LCEDA_CONNECT_ASSETS",
55
+ "LCEDA_BRIDGE_RUNTIME",
56
+ "LCEDA_ALLOWED_ROOTS"
57
+ ];
58
+ const OVERLAY_ENV_KEYS = [
59
+ "LCEDA_ENV",
60
+ "LCEDA_ENV_SOURCE",
61
+ "LCEDA_LEDA_IN",
62
+ "LCEDA_LEDA_IN_SOURCE",
63
+ "LCEDA_WINDOWS_HOST",
64
+ "LCEDA_WINDOWS_HOST_SOURCE",
65
+ "LCEDA_CDP_HOST",
66
+ "LCEDA_CDP_PORT",
67
+ "LCEDA_CDP_SCAN",
68
+ "LCEDA_BRIDGE_HOST",
69
+ "LCEDA_BRIDGE_PORT_FIRST",
70
+ "LCEDA_BRIDGE_PORT_LAST",
71
+ "LCEDA_TOOLSETS",
72
+ "EASYEDA_CDP_TIMEOUT",
73
+ "LCEDA_PYTHON",
74
+ "NGSPICE_BIN"
75
+ ];
76
+ /** 这些 WSL 专用配置在 Windows 子进程里没有意义,强制丢弃。 */
77
+ const WSL_ONLY_ENV_KEYS = [
78
+ "LCEDA_LEDA_IN",
79
+ "LCEDA_LEDA_IN_SOURCE",
80
+ "LCEDA_WINDOWS_HOST",
81
+ "LCEDA_WINDOWS_HOST_SOURCE"
82
+ ];
83
+ function translateValueForWindows(value) {
84
+ if (!value) return value;
85
+ if (value.startsWith("/mnt/")) return wslPathToWindowsPath(value);
86
+ if (value.startsWith("/")) return null;
87
+ return value;
88
+ }
89
+ /**
90
+ * 为 Windows 子进程准备环境:优先用 `cmd.exe /d /c set` 的真实 Windows 环境,
91
+ * 再把当前进程里显式设置的 LCEDA_* 覆盖进去(/mnt 路径转 Windows 路径)。
92
+ * 这样从 WSL 互操作拉起 Windows MCP 时,不会把 POSIX PATH/HOME 带过去。
93
+ */
94
+ function resolveWindowsEnvironment(env = process.env, probes = {}) {
95
+ const resolved = resolveProbes({
96
+ ...probes,
97
+ env
98
+ });
99
+ const warnings = [];
100
+ const raw = resolved.runText("cmd.exe", [
101
+ "/d",
102
+ "/c",
103
+ "set"
104
+ ], 8e3);
105
+ const windowsEnv = raw ? parseWindowsEnvSet(raw) : null;
106
+ let base;
107
+ let source;
108
+ if (windowsEnv && Object.keys(windowsEnv).length > 0) {
109
+ base = { ...windowsEnv };
110
+ source = "windows-set";
111
+ } else {
112
+ warnings.push("读不到 Windows 环境变量(cmd.exe set 失败);只传递显式 LCEDA_* 配置");
113
+ base = {};
114
+ source = "translated-only";
115
+ }
116
+ for (const key of WSL_ONLY_ENV_KEYS) delete base[key];
117
+ for (const key of [...TRANSLATE_ENV_KEYS, ...OVERLAY_ENV_KEYS]) {
118
+ const value = env[key];
119
+ if (value === void 0) continue;
120
+ let translated;
121
+ if (key === "LCEDA_ALLOWED_ROOTS") {
122
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
123
+ const kept = [];
124
+ for (const item of items) {
125
+ const one = translateValueForWindows(item);
126
+ if (one === null) warnings.push(`LCEDA_ALLOWED_ROOTS 中的 ${item} 是 WSL 内部路径,Windows 进程不可读,已移除`);
127
+ else kept.push(one);
128
+ }
129
+ translated = kept.join(";");
130
+ } else {
131
+ translated = translateValueForWindows(value);
132
+ if (translated === null) {
133
+ warnings.push(`${key}=${value} 是 WSL 内部路径,Windows 进程不可读,已从子进程环境移除`);
134
+ continue;
135
+ }
136
+ }
137
+ base[key] = translated;
138
+ }
139
+ if (base.LCEDA_ENV && base.LCEDA_ENV !== "windows-native") warnings.push(`Windows 子进程强制使用 windows-native(原 LCEDA_ENV=${base.LCEDA_ENV},WSL 位置/宿主配置已丢弃)`);
140
+ base.LCEDA_ENV = "windows-native";
141
+ delete base.LCEDA_ENV_SOURCE;
142
+ const pathValue = base.Path ?? base.PATH;
143
+ if (pathValue) {
144
+ base.Path = pathValue;
145
+ base.PATH = pathValue;
146
+ }
147
+ return {
148
+ env: base,
149
+ warnings,
150
+ source
151
+ };
152
+ }
153
+ /**
154
+ * 在 Windows 上被 WSL 互操作直接拉起时,继承来的是 WSL 的 POSIX 环境(PATH/HOME 等)。
155
+ * 检测到 WSL 标记就换回真实 Windows 环境,避免 exe 发现、运行态目录被 /root、/mnt 带偏。
156
+ */
157
+ function normalizeMcpEnv(env = process.env, probes = {}) {
158
+ const platform = probes.platform ?? process.platform;
159
+ const looksWsl = (env.WSL_INTEROP ?? "").trim() !== "" || (env.WSL_DISTRO_NAME ?? "").trim() !== "";
160
+ if (platform !== "win32" || !looksWsl) return {
161
+ env,
162
+ warnings: []
163
+ };
164
+ const resolved = resolveWindowsEnvironment(env, probes);
165
+ return {
166
+ env: resolved.env,
167
+ warnings: resolved.warnings
168
+ };
169
+ }
170
+ function executableOf(value, source) {
171
+ const trimmed = value.trim();
172
+ if (!trimmed) return null;
173
+ if (trimmed.startsWith("/") && !trimmed.startsWith("/mnt/")) return null;
174
+ const winPath = trimmed.startsWith("/mnt/") ? wslPathToWindowsPath(trimmed) ?? trimmed : trimmed;
175
+ return {
176
+ wslPath: trimmed.startsWith("/mnt/") ? trimmed : windowsPathToWslPath(trimmed),
177
+ winPath,
178
+ source
179
+ };
180
+ }
181
+ /** 找 Windows node.exe:显式 env > where.exe > 常见安装位置。 */
182
+ function resolveWindowsNode(env = process.env, probes = {}) {
183
+ const resolved = resolveProbes({
184
+ ...probes,
185
+ env
186
+ });
187
+ const explicit = env.LCEDA_WINDOWS_NODE?.trim();
188
+ if (explicit) {
189
+ const item = executableOf(explicit, "env:LCEDA_WINDOWS_NODE");
190
+ if (item && resolved.exists(item.wslPath)) return item;
191
+ }
192
+ const where = resolved.runText("cmd.exe", [
193
+ "/d",
194
+ "/c",
195
+ "where node.exe"
196
+ ], 8e3);
197
+ if (where) for (const line of where.split(/\r?\n/)) {
198
+ const value = line.trim();
199
+ if (!value) continue;
200
+ const item = executableOf(value, "where.exe node");
201
+ if (item && resolved.exists(item.wslPath)) return item;
202
+ }
203
+ const candidates = [];
204
+ const programFiles = env.ProgramFiles ?? "C:\\Program Files";
205
+ candidates.push(`${programFiles}\\nodejs\\node.exe`);
206
+ if (env.LOCALAPPDATA) candidates.push(`${env.LOCALAPPDATA}\\vite-plus\\bin\\node.exe`);
207
+ for (const candidate of candidates) {
208
+ const item = executableOf(candidate, "常见安装位置");
209
+ if (item && resolved.exists(item.wslPath)) return item;
210
+ }
211
+ return null;
212
+ }
213
+ const PACKAGE_ENTRY = "lceda-connect\\dist\\cli-mcp.mjs";
214
+ /** 找 Windows 侧安装的 lceda-connect 入口:显式配置 > 全局 pnpm/npm root > %APPDATA%\npm。 */
215
+ function resolveWindowsMcpEntry(env = process.env, probes = {}, explicit) {
216
+ const resolved = resolveProbes({
217
+ ...probes,
218
+ env
219
+ });
220
+ const requested = explicit?.trim() || env.LCEDA_WINDOWS_MCP?.trim();
221
+ if (requested) {
222
+ const item = executableOf(requested, "显式指定");
223
+ return item && resolved.exists(item.wslPath) ? item : null;
224
+ }
225
+ const roots = [];
226
+ for (const command of ["pnpm", "npm"]) {
227
+ const root = resolved.runText("cmd.exe", [
228
+ "/d",
229
+ "/c",
230
+ `${command} root -g`
231
+ ], 15e3);
232
+ if (root) for (const line of root.split(/\r?\n/)) {
233
+ const value = line.trim();
234
+ if (value && /^[A-Za-z]:[\\/]/.test(value)) roots.push(value);
235
+ }
236
+ }
237
+ if (env.APPDATA) roots.push(`${env.APPDATA}\\npm\\node_modules`);
238
+ const seen = /* @__PURE__ */ new Set();
239
+ const tryEntry = (entry, root) => {
240
+ if (seen.has(entry.toLowerCase())) return null;
241
+ seen.add(entry.toLowerCase());
242
+ const item = executableOf(entry, `全局安装(${root})`);
243
+ return item && resolved.exists(item.wslPath) ? item : null;
244
+ };
245
+ for (const root of roots) {
246
+ const direct = tryEntry(`${root}\\${PACKAGE_ENTRY}`, root);
247
+ if (direct) return direct;
248
+ const wslRoot = windowsPathToWslPath(root);
249
+ if (!wslRoot) continue;
250
+ for (const name of (resolved.listDir(wslRoot) ?? []).slice(0, 64)) {
251
+ const hashEntry = tryEntry(`${root}\\${name}\\node_modules\\${PACKAGE_ENTRY}`, root);
252
+ if (hashEntry) return hashEntry;
253
+ }
254
+ const nested = tryEntry(`${root}\\node_modules\\${PACKAGE_ENTRY}`, root);
255
+ if (nested) return nested;
256
+ }
257
+ return null;
258
+ }
259
+ /**
260
+ * 解析 `--host wsl`:
261
+ * - 在 WSL 里:取 eth0 的 IPv4(Windows 可经这个地址访问 WSL);
262
+ * - 在 Windows 里:取 WSL 默认网关(即宿主 vEthernet 地址,WSL 可访问它)。
263
+ */
264
+ function resolveWslFacingHost(env = process.env, probes = {}) {
265
+ const resolved = resolveProbes({
266
+ ...probes,
267
+ env
268
+ });
269
+ const warnings = [];
270
+ if (resolved.platform === "linux") {
271
+ const interfaces = resolved.interfaces();
272
+ const candidates = interfaces.eth0 ?? interfaces.eth1 ?? Object.values(interfaces).flat().filter(Boolean);
273
+ for (const item of candidates ?? []) {
274
+ if (!item || item.internal) continue;
275
+ if (item.family === "IPv4") return {
276
+ host: item.address,
277
+ source: "WSL eth0",
278
+ warnings
279
+ };
280
+ }
281
+ warnings.push("找不到 WSL eth0 的 IPv4 地址");
282
+ return null;
283
+ }
284
+ if (resolved.platform === "win32") {
285
+ const host = resolved.runText("wsl.exe", [
286
+ "-e",
287
+ "sh",
288
+ "-lc",
289
+ "ip route show default 2>/dev/null | awk '{print $3}'"
290
+ ], 1e4)?.split(/\r?\n/)[0]?.trim() ?? "";
291
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) {
292
+ if ((resolved.runText("wsl.exe", [
293
+ "-e",
294
+ "wslinfo",
295
+ "--networking-mode"
296
+ ], 8e3) ?? "").trim().toLowerCase() === "mirrored") warnings.push("WSL 处于 mirrored 网络模式:WSL 与宿主共享回环,默认网关可能是 LAN 地址;优先考虑 --host 127.0.0.1");
297
+ return {
298
+ host,
299
+ source: "WSL 默认网关",
300
+ warnings
301
+ };
302
+ }
303
+ warnings.push("无法从 WSL 读取默认网关;请直接传 --host <宿主 vEthernet IP>");
304
+ return null;
305
+ }
306
+ warnings.push(`平台 ${resolved.platform} 不支持 --host wsl`);
307
+ return null;
308
+ }
309
+ export { resolveWindowsNode as a, resolveWindowsMcpEntry as i, parseWindowsEnvSet as n, resolveWslFacingHost as o, resolveWindowsEnvironment as r, normalizeMcpEnv as t };