lceda-connect 0.2.0 → 0.4.1

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 (49) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +111 -45
  3. package/dist/{analyze-DBkWgG82.mjs → analyze-TRlZx-Jv.mjs} +2 -190
  4. package/dist/{cli-B3GGyoP_.mjs → cli-1_urvve3.mjs} +5 -3
  5. package/dist/{cli-BegYbK44.mjs → cli-C8-HjAP0.mjs} +2 -2
  6. package/dist/cli-CHbcaMwS.mjs +1 -0
  7. package/dist/cli-CXk5pvVm.mjs +1253 -0
  8. package/dist/cli-CZEoeuFW.mjs +1 -0
  9. package/dist/{cli-DphIx1EQ.mjs → cli-CZmNLW3Q.mjs} +1 -1
  10. package/dist/{cli-BekOvZjB.mjs → cli-DFqBHofJ.mjs} +19 -3
  11. package/dist/cli-bridge-server.mjs +1 -1
  12. package/dist/cli-bridge.mjs +1 -1
  13. package/dist/cli-cdp.mjs +1 -1
  14. package/dist/cli-mcp.mjs +1 -1
  15. package/dist/cli.mjs +1 -1
  16. package/dist/config-BKbwyvsG.mjs +516 -0
  17. package/dist/{discover-D4ouuCrn.mjs → discover-DmRYlAlR.mjs} +13 -90
  18. package/dist/environment-BegP0n2N.mjs +439 -0
  19. package/dist/environment-Clx1-nDW.mjs +146 -0
  20. package/dist/http-Cdp6S2rm.mjs +366 -0
  21. package/dist/http-D7sYy2y4.mjs +1 -0
  22. package/dist/index.d.mts +226 -6
  23. package/dist/index.mjs +12 -9
  24. package/dist/{main-CzMqMptH.mjs → main-B3aaKvqY.mjs} +695 -90
  25. package/dist/mcpHost-CRoN6MnG.mjs +331 -0
  26. package/dist/{registry-DaqVJuvF.mjs → registry-3WTFCZsR.mjs} +86 -25
  27. package/dist/registry-DdJ8LEdd.mjs +1 -0
  28. package/dist/{server-qYlcXfzp.mjs → server-zw6t1Pmk.mjs} +10 -15
  29. package/dist/{targets-DYfgkrq3.mjs → session-AQbRX6Ys.mjs} +3 -37
  30. package/dist/{sideEffects-D33hMchc.mjs → sideEffects-Ds_T-_B4.mjs} +3 -2
  31. package/dist/stdio-BZPlcfDR.mjs +27 -0
  32. package/dist/stdio-Du1oLqfJ.mjs +1 -0
  33. package/dist/targets-8LBEgvbq.mjs +36 -0
  34. package/dist/term-DlGIoccA.mjs +27 -0
  35. package/dist/{touchstone-DOhfmSNh.mjs → touchstone-D4Fdg4Om.mjs} +1 -1
  36. package/dist/{verbs-CD4ZM9Es.mjs → verbs-DjQQTL2k.mjs} +191 -53
  37. package/dist/windowsHost-CTZXMA8D.mjs +1 -0
  38. package/dist/windowsHost-CtRidgJp.mjs +309 -0
  39. package/dist/zip-CAd_yYte.mjs +190 -0
  40. package/docs/architecture.md +81 -0
  41. package/docs/environments.md +175 -0
  42. package/docs/extensions.md +207 -0
  43. package/docs/quickstart.md +59 -4
  44. package/docs/transports.md +189 -0
  45. package/package.json +6 -2
  46. package/dist/cli-BqILMvnF.mjs +0 -1
  47. package/dist/cli-BzrDKC7x.mjs +0 -1
  48. package/dist/registry-5K1G1XmC.mjs +0 -1
  49. package/dist/server-DNMAlzZJ.mjs +0 -1
@@ -1,13 +1,17 @@
1
1
  import { a as parseArgs, i as numberValue, n as boolValue, o as stringValue, r as formatOptions, t as CliUsageError } from "./cliArgs-BI3bJgCZ.mjs";
2
- import { T as loadConfig, b as hr, l as parseBrowserUuidLine, w as homeDir, x as paint } from "./discover-D4ouuCrn.mjs";
2
+ import { i as loadConfig, r as homeDir } from "./config-BKbwyvsG.mjs";
3
+ import { n as paint, t as hr } from "./term-DlGIoccA.mjs";
3
4
  import { t as packageVersion } from "./version-B39-elun.mjs";
4
5
  import { a as packageRoot } from "./assets-D48xh-kr.mjs";
5
6
  import { t as run } from "./exec-FuC8m-_m.mjs";
7
+ import { l as parseBrowserUuidLine } from "./discover-DmRYlAlR.mjs";
8
+ import { o as isLoopbackAddress, r as describeEnvironment } from "./environment-BegP0n2N.mjs";
6
9
  import os from "node:os";
7
10
  import path from "node:path";
8
11
  import fs from "node:fs";
9
- import { fileURLToPath } from "node:url";
10
12
  import { spawn } from "node:child_process";
13
+ import { z } from "zod";
14
+ import { fileURLToPath } from "node:url";
11
15
  // src/core/io.ts
12
16
  const stdIo = {
13
17
  out: (line = "") => {
@@ -17,6 +21,354 @@ const stdIo = {
17
21
  process.stderr.write(`${line}\n`);
18
22
  }
19
23
  };
24
+ // src/core/runtimeConfig.ts
25
+ var RuntimeConfigError = class extends Error {
26
+ file;
27
+ constructor(message, file = null) {
28
+ super(message);
29
+ this.name = "RuntimeConfigError";
30
+ this.file = file;
31
+ }
32
+ };
33
+ const DOTENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
34
+ /**
35
+ * 解析 .env。支持 `KEY=value`、`export KEY=value`、单/双引号、未加引号值里的
36
+ * ` # 注释`。不做变量展开(避免与 shell 语义混淆)。
37
+ */
38
+ function parseDotEnv(text, file = ".env") {
39
+ const values = {};
40
+ const warnings = [];
41
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
42
+ for (let index = 0; index < lines.length; index++) {
43
+ const line = (lines[index] ?? "").trim();
44
+ if (!line || line.startsWith("#")) continue;
45
+ const withoutExport = line.startsWith("export ") ? line.slice(7).trim() : line;
46
+ const equals = withoutExport.indexOf("=");
47
+ if (equals <= 0) {
48
+ warnings.push(`${file}:${index + 1} 不是 KEY=VALUE,已跳过`);
49
+ continue;
50
+ }
51
+ const key = withoutExport.slice(0, equals).trim();
52
+ if (!DOTENV_KEY.test(key)) {
53
+ warnings.push(`${file}:${index + 1} 键名不合法(${key}),已跳过`);
54
+ continue;
55
+ }
56
+ let value = withoutExport.slice(equals + 1).trim();
57
+ if (value.startsWith("\"")) {
58
+ const end = value.lastIndexOf("\"");
59
+ if (end <= 0) warnings.push(`${file}:${index + 1} 双引号未闭合,已按字面量处理`);
60
+ else value = value.slice(1, end).replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
61
+ } else if (value.startsWith("'")) {
62
+ const end = value.lastIndexOf("'");
63
+ if (end <= 0) warnings.push(`${file}:${index + 1} 单引号未闭合,已按字面量处理`);
64
+ else value = value.slice(1, end);
65
+ } else {
66
+ const comment = /\s+#/.exec(value);
67
+ if (comment) value = value.slice(0, comment.index).trim();
68
+ }
69
+ values[key] = value;
70
+ }
71
+ return {
72
+ values,
73
+ warnings
74
+ };
75
+ }
76
+ const EnvironmentConfigSchema = z.object({
77
+ kind: z.enum([
78
+ "auto",
79
+ "windows-native",
80
+ "wsl2",
81
+ "linux-native",
82
+ "macos-native"
83
+ ]).optional(),
84
+ windowsHost: z.string().min(1).optional(),
85
+ /** 客户端实例位置优先级:`["vm","host"]` 或 `"vm,host"`。 */
86
+ clientLocations: z.union([z.string(), z.array(z.enum(["host", "vm"]))]).optional()
87
+ }).strict();
88
+ const CdpConfigSchema = z.object({
89
+ host: z.string().min(1).optional(),
90
+ port: z.number().int().min(1).max(65535).optional(),
91
+ /** 附加扫描区间 [start, end]。 */
92
+ scan: z.tuple([z.number().int().min(1), z.number().int().min(1)]).optional()
93
+ }).strict();
94
+ const BridgeConfigSchema = z.object({
95
+ host: z.string().min(1).optional(),
96
+ portFirst: z.number().int().min(1).max(65535).optional(),
97
+ portLast: z.number().int().min(1).max(65535).optional(),
98
+ nodePath: z.string().min(1).optional(),
99
+ script: z.string().min(1).optional()
100
+ }).strict();
101
+ const ClientConfigSchema = z.object({ exePath: z.string().min(1).optional() }).strict();
102
+ const McpHttpConfigSchema = z.object({
103
+ host: z.string().min(1).optional(),
104
+ port: z.number().int().min(0).max(65535).optional(),
105
+ path: z.string().min(1).optional(),
106
+ token: z.string().min(1).optional(),
107
+ stateless: z.boolean().optional()
108
+ }).strict();
109
+ const McpConfigSchema = z.object({
110
+ toolsets: z.union([z.string(), z.array(z.string())]).optional(),
111
+ http: McpHttpConfigSchema.optional()
112
+ }).strict();
113
+ const ConfigFileSchema = z.object({
114
+ $schema: z.string().optional(),
115
+ environment: EnvironmentConfigSchema.optional(),
116
+ client: ClientConfigSchema.optional(),
117
+ cdp: CdpConfigSchema.optional(),
118
+ bridge: BridgeConfigSchema.optional(),
119
+ mcp: McpConfigSchema.optional()
120
+ }).strict();
121
+ function formatZodIssues(error) {
122
+ return error.issues.map((issue) => `${issue.path.length > 0 ? issue.path.join(".") : "<root>"}: ${issue.message}`).join("; ");
123
+ }
124
+ function parseConfigFile(text, file = "lceda-connect.config.json") {
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(text.replace(/^\uFEFF/, ""));
128
+ } catch (error) {
129
+ throw new RuntimeConfigError(`${file} 不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, file);
130
+ }
131
+ const result = ConfigFileSchema.safeParse(parsed);
132
+ if (!result.success) throw new RuntimeConfigError(`${file} 配置不合法:${formatZodIssues(result.error)}`, file);
133
+ return {
134
+ config: result.data,
135
+ warnings: []
136
+ };
137
+ }
138
+ /** 把配置文件映射成环境变量键;这是「配置文件 > .env / 进程环境」的落地点。 */
139
+ function configToEnv(config) {
140
+ const mapped = {};
141
+ const environment = config.environment;
142
+ if (environment) {
143
+ if (environment.kind) {
144
+ mapped.LCEDA_ENV = environment.kind;
145
+ mapped.LCEDA_ENV_SOURCE = "config-file";
146
+ }
147
+ if (environment.windowsHost) {
148
+ mapped.LCEDA_WINDOWS_HOST = environment.windowsHost;
149
+ mapped.LCEDA_WINDOWS_HOST_SOURCE = "config-file";
150
+ }
151
+ if (environment.clientLocations) {
152
+ mapped.LCEDA_LEDA_IN = Array.isArray(environment.clientLocations) ? environment.clientLocations.join(",") : environment.clientLocations;
153
+ mapped.LCEDA_LEDA_IN_SOURCE = "config-file";
154
+ }
155
+ }
156
+ if (config.client?.exePath) mapped.LCEDA_PRO_EXE = config.client.exePath;
157
+ if (config.cdp?.host) mapped.LCEDA_CDP_HOST = config.cdp.host;
158
+ if (typeof config.cdp?.port === "number") mapped.LCEDA_CDP_PORT = String(config.cdp.port);
159
+ if (config.cdp?.scan) mapped.LCEDA_CDP_SCAN = config.cdp.scan.join("-");
160
+ if (config.bridge?.host) mapped.LCEDA_BRIDGE_HOST = config.bridge.host;
161
+ if (typeof config.bridge?.portFirst === "number") mapped.LCEDA_BRIDGE_PORT_FIRST = String(config.bridge.portFirst);
162
+ if (typeof config.bridge?.portLast === "number") mapped.LCEDA_BRIDGE_PORT_LAST = String(config.bridge.portLast);
163
+ if (config.bridge?.nodePath) mapped.LCEDA_NODE = config.bridge.nodePath;
164
+ if (config.bridge?.script) mapped.LCEDA_BRIDGE_SCRIPT = config.bridge.script;
165
+ if (config.mcp?.toolsets) mapped.LCEDA_TOOLSETS = Array.isArray(config.mcp.toolsets) ? config.mcp.toolsets.join(",") : config.mcp.toolsets;
166
+ const http = config.mcp?.http;
167
+ if (http) {
168
+ if (http.host) mapped.LCEDA_HTTP_HOST = http.host;
169
+ if (typeof http.port === "number") mapped.LCEDA_HTTP_PORT = String(http.port);
170
+ if (http.path) mapped.LCEDA_HTTP_PATH = http.path;
171
+ if (http.token) mapped.LCEDA_HTTP_TOKEN = http.token;
172
+ if (http.stateless !== void 0) mapped.LCEDA_HTTP_STATELESS = String(http.stateless);
173
+ }
174
+ return mapped;
175
+ }
176
+ /** 全局选项名 → 环境变量键。全局选项在命令组解析前就被摘走。 */
177
+ const GLOBAL_OPTION_ENV = {
178
+ config: "LCEDA_CONFIG",
179
+ "env-file": "LCEDA_ENV_FILE",
180
+ env: "LCEDA_ENV",
181
+ "lceda-in": "LCEDA_LEDA_IN",
182
+ "windows-host": "LCEDA_WINDOWS_HOST",
183
+ "cdp-host": "LCEDA_CDP_HOST",
184
+ "bridge-host": "LCEDA_BRIDGE_HOST",
185
+ exe: "LCEDA_PRO_EXE"
186
+ };
187
+ const GLOBAL_NAMES = new Set(Object.keys(GLOBAL_OPTION_ENV));
188
+ /**
189
+ * 从 argv 里摘出全局选项,其余保持原顺序。只认 `--name value` 与 `--name=value`;
190
+ * `--` 之后的参数不动(交给命令实现)。值以 `-` 开头时也照收(路径可能以 - 开头)。
191
+ */
192
+ function extractGlobalOptions(argv, extract = {}) {
193
+ const rest = [];
194
+ const options = [];
195
+ const groupIndex = extract.groupIndex ?? -1;
196
+ const localOptions = new Set(extract.localOptions ?? []);
197
+ let optionsEnded = false;
198
+ for (let index = 0; index < argv.length; index++) {
199
+ const token = argv[index] ?? "";
200
+ if (optionsEnded) {
201
+ rest.push(token);
202
+ continue;
203
+ }
204
+ if (token === "--") {
205
+ optionsEnded = true;
206
+ rest.push(token);
207
+ continue;
208
+ }
209
+ if (!token.startsWith("--")) {
210
+ rest.push(token);
211
+ continue;
212
+ }
213
+ const withoutDashes = token.slice(2);
214
+ const equalsAt = withoutDashes.indexOf("=");
215
+ const name = (equalsAt >= 0 ? withoutDashes.slice(0, equalsAt) : withoutDashes).toLowerCase();
216
+ if (!GLOBAL_NAMES.has(name)) {
217
+ rest.push(token);
218
+ continue;
219
+ }
220
+ if (localOptions.has(name) && groupIndex >= 0 && index >= groupIndex) {
221
+ rest.push(token);
222
+ continue;
223
+ }
224
+ if (equalsAt >= 0) {
225
+ options.push({
226
+ name,
227
+ value: withoutDashes.slice(equalsAt + 1)
228
+ });
229
+ continue;
230
+ }
231
+ const next = argv[index + 1];
232
+ if (next === void 0) throw new RuntimeConfigError(`全局选项 --${name} 缺少取值`);
233
+ options.push({
234
+ name,
235
+ value: next
236
+ });
237
+ index += 1;
238
+ }
239
+ return {
240
+ argv: rest,
241
+ options
242
+ };
243
+ }
244
+ /** 全局选项的显示值(帮助文本用)。 */
245
+ const GLOBAL_HELP_ROWS = [
246
+ {
247
+ flag: "--config PATH",
248
+ description: "配置文件(JSON);显式参数 > 配置文件 > .env > 环境变量 > 默认"
249
+ },
250
+ {
251
+ flag: "--env-file PATH",
252
+ description: ".env 文件;只补未设置的键"
253
+ },
254
+ {
255
+ flag: "--env KIND",
256
+ description: "显式执行环境:auto/windows-native/wsl2/linux-native/macos-native(不自动发现)"
257
+ },
258
+ {
259
+ flag: "--lceda-in LIST",
260
+ description: "WSL2 下客户端实例位置优先级:host / vm / vm,host(默认 host)"
261
+ },
262
+ {
263
+ flag: "--windows-host HOST",
264
+ description: "WSL2 下 Windows 宿主地址(默认取默认网关)"
265
+ },
266
+ {
267
+ flag: "--cdp-host HOST",
268
+ description: "CDP 探测地址(覆盖环境推导)"
269
+ },
270
+ {
271
+ flag: "--bridge-host HOST",
272
+ description: "bridge 探测地址(覆盖环境推导)"
273
+ },
274
+ {
275
+ flag: "--exe PATH",
276
+ description: "客户端可执行文件(覆盖自动发现;WSL2 下可传 Windows 路径)"
277
+ }
278
+ ];
279
+ /** 关键环境项的「来源」标记键:让 loadConfig 能正确回报 argv / config-file / env。 */
280
+ const ENVIRONMENT_SOURCE_KEYS = {
281
+ LCEDA_ENV: "LCEDA_ENV_SOURCE",
282
+ LCEDA_WINDOWS_HOST: "LCEDA_WINDOWS_HOST_SOURCE",
283
+ LCEDA_LEDA_IN: "LCEDA_LEDA_IN_SOURCE"
284
+ };
285
+ const SOURCE_KEYS = [
286
+ "LCEDA_ENV",
287
+ "LCEDA_LEDA_IN",
288
+ "LCEDA_WINDOWS_HOST",
289
+ "LCEDA_PRO_EXE",
290
+ "LCEDA_CDP_HOST",
291
+ "LCEDA_CDP_PORT",
292
+ "LCEDA_BRIDGE_HOST",
293
+ "LCEDA_BRIDGE_PORT_FIRST",
294
+ "LCEDA_BRIDGE_PORT_LAST",
295
+ "LCEDA_NODE",
296
+ "LCEDA_BRIDGE_SCRIPT",
297
+ "LCEDA_TOOLSETS"
298
+ ];
299
+ /**
300
+ * 解析运行时配置。优先级(高 → 低):
301
+ * argv 全局参数 > 配置文件 > 显式 --env-file > 继承的进程环境 > 内置默认。
302
+ * `.env` 只补「还没设置」的键,不会覆盖真实环境变量;配置文件则可以覆盖,
303
+ * 因为它是用户为这个项目显式声明的。
304
+ */
305
+ function resolveRuntime(options) {
306
+ const baseEnv = { ...options.env ?? process.env };
307
+ const cwd = options.cwd ?? process.cwd();
308
+ const readFile = options.readFile ?? ((file) => {
309
+ try {
310
+ return fs.readFileSync(file, "utf8");
311
+ } catch {
312
+ return null;
313
+ }
314
+ });
315
+ const warnings = [];
316
+ const sources = {};
317
+ const { argv, options: globalOptions } = extractGlobalOptions(options.argv, options.global);
318
+ const argvValues = /* @__PURE__ */ new Map();
319
+ for (const option of globalOptions) argvValues.set(option.name, option.value);
320
+ let envFilePath = null;
321
+ const envFileRequested = argvValues.get("env-file") ?? baseEnv.LCEDA_ENV_FILE ?? null;
322
+ if (envFileRequested) {
323
+ const resolved = path.resolve(cwd, envFileRequested);
324
+ const text = readFile(resolved);
325
+ if (text === null) throw new RuntimeConfigError(`.env 文件不存在或不可读:${resolved}`, resolved);
326
+ envFilePath = resolved;
327
+ const parsed = parseDotEnv(text, path.basename(resolved));
328
+ warnings.push(...parsed.warnings);
329
+ for (const [key, value] of Object.entries(parsed.values)) if (baseEnv[key] === void 0) {
330
+ baseEnv[key] = value;
331
+ sources[key] = "env-file";
332
+ if (ENVIRONMENT_SOURCE_KEYS[key]) baseEnv[ENVIRONMENT_SOURCE_KEYS[key]] = "env";
333
+ }
334
+ }
335
+ let configPath = null;
336
+ const configRequested = argvValues.get("config") ?? baseEnv.LCEDA_CONFIG ?? null;
337
+ if (configRequested) {
338
+ const resolved = path.resolve(cwd, configRequested);
339
+ const text = readFile(resolved);
340
+ if (text === null) throw new RuntimeConfigError(`配置文件不存在或不可读:${resolved}`, resolved);
341
+ configPath = resolved;
342
+ const parsed = parseConfigFile(text, path.basename(resolved));
343
+ warnings.push(...parsed.warnings);
344
+ for (const [key, value] of Object.entries(configToEnv(parsed.config))) {
345
+ baseEnv[key] = value;
346
+ sources[key] = "config-file";
347
+ }
348
+ }
349
+ for (const [name, value] of argvValues) {
350
+ const key = GLOBAL_OPTION_ENV[name];
351
+ if (!key) continue;
352
+ baseEnv[key] = value;
353
+ sources[key] = "argv";
354
+ if (ENVIRONMENT_SOURCE_KEYS[key]) baseEnv[ENVIRONMENT_SOURCE_KEYS[key]] = "argv";
355
+ }
356
+ const merged = { ...baseEnv };
357
+ for (const key of SOURCE_KEYS) {
358
+ if (sources[key]) continue;
359
+ sources[key] = merged[key] !== void 0 ? "process-env" : "default";
360
+ const sourceKey = ENVIRONMENT_SOURCE_KEYS[key];
361
+ if (sourceKey && sources[key] === "process-env" && merged[sourceKey] === void 0) merged[sourceKey] = "env";
362
+ }
363
+ return {
364
+ argv,
365
+ env: merged,
366
+ configPath,
367
+ envFilePath,
368
+ sources,
369
+ warnings
370
+ };
371
+ }
20
372
  // src/core/fsx.ts
21
373
  function exists(target) {
22
374
  return fs.existsSync(target);
@@ -1387,6 +1739,13 @@ async function resolveManagedProcess(cfg) {
1387
1739
  imagePath
1388
1740
  };
1389
1741
  }
1742
+ /**
1743
+ * 实际可执行的客户端路径:环境发现优先(WSL2 下是 /mnt/d/...),
1744
+ * 找不到时才退回显式/历史路径,让报错信息保持原样。
1745
+ */
1746
+ function clientExecutable(cfg) {
1747
+ return cfg.client.exe?.path ?? cfg.cdp.exePath;
1748
+ }
1390
1749
  /** WMI 的 Name 带扩展名:exe 路径 → "lceda-pro.exe"。 */
1391
1750
  function processNameFilter(exePath) {
1392
1751
  return `${path.win32.basename(exePath).replace(/\.exe$/i, "")}.exe`;
@@ -1621,6 +1980,20 @@ var Reporter = class {
1621
1980
  async function runStart(options, ctx, label = "start") {
1622
1981
  const { cfg, env } = ctx;
1623
1982
  const reporter = new Reporter(ctx.io, options.json);
1983
+ const chosenLocation = cfg.client.exe?.location ?? cfg.environment.clientLocations[0] ?? "host";
1984
+ if (cfg.environment.kind === "wsl2" && cfg.environment.networkingMode !== "mirrored" && chosenLocation === "host") {
1985
+ const reason = "WSL2 NAT + 客户端在 Windows 宿主:跨命名空间,CDP 端点不可达,start/ensure 无法完成握手";
1986
+ reporter.say(reason, paint.red);
1987
+ reporter.say("可选:① 在 Windows 侧运行 MCP(npm i -g lceda-connect);② 启用 WSL mirrored 网络;③ 客户端装进 WSL VM 后按 --lceda-in vm 使用。", paint.yellow);
1988
+ reporter.emit({
1989
+ action: label,
1990
+ ok: false,
1991
+ reason,
1992
+ reason_code: "CROSS_OS_LOOPBACK"
1993
+ });
1994
+ return 2;
1995
+ }
1996
+ const exePath = clientExecutable(cfg);
1624
1997
  const managed = await resolveManagedProcess(cfg.cdp);
1625
1998
  if (managed) {
1626
1999
  reporter.say(`已经在运行(PID ${managed.pid})。先执行 stop --yes。`, paint.yellow);
@@ -1647,8 +2020,8 @@ async function runStart(options, ctx, label = "start") {
1647
2020
  return 1;
1648
2021
  }
1649
2022
  if (instances.length > 0) reporter.say(`警告:已有客户端实例(PID ${instances.join(", ")}),仍按 --force 继续。数据可能互相覆盖。`, paint.yellow);
1650
- if (!exists(cfg.cdp.exePath)) {
1651
- const reason = `找不到客户端主程序:${cfg.cdp.exePath}`;
2023
+ if (!exists(exePath)) {
2024
+ const reason = `找不到客户端主程序:${exePath}`;
1652
2025
  reporter.say(reason, paint.red);
1653
2026
  reporter.say("用 --exe 传入实际路径(或设置环境变量 LCEDA_PRO_EXE)。");
1654
2027
  reporter.emit({
@@ -1687,10 +2060,10 @@ async function runStart(options, ctx, label = "start") {
1687
2060
  reporter.say(" 网络恢复后点一下界面即可,不必重启客户端。", paint.yellow);
1688
2061
  reporter.say(" 若系统代理还没生效,可加:--proxy-server http://127.0.0.1:7897", paint.yellow);
1689
2062
  }
1690
- reporter.say(`启动:${cfg.cdp.exePath} ${startArgs.join(" ")}`);
1691
- const launched = launchClient(cfg.cdp.exePath, startArgs, cfg.cdp.logFile, env);
2063
+ reporter.say(`启动:${exePath} ${startArgs.join(" ")}`);
2064
+ const launched = launchClient(exePath, startArgs, cfg.cdp.logFile, env);
1692
2065
  if (launched.pid === null) {
1693
- const reason = `启动失败:无法拉起 ${cfg.cdp.exePath}`;
2066
+ const reason = `启动失败:无法拉起 ${exePath}`;
1694
2067
  reporter.say(reason, paint.red);
1695
2068
  reporter.emit({
1696
2069
  action: label,
@@ -1702,7 +2075,7 @@ async function runStart(options, ctx, label = "start") {
1702
2075
  if (!launched.redirected) reporter.say("提示:走的是兼容启动路径,客户端 stderr 未落盘,只影响日志不影响连接。", paint.yellow);
1703
2076
  writePidRecord(cfg.cdp.pidFile, {
1704
2077
  pid: launched.pid,
1705
- exe: cfg.cdp.exePath
2078
+ exe: exePath
1706
2079
  });
1707
2080
  const activePort = await waitForActivePort(cfg.cdp, env, cfg.cdp.startWaitMs);
1708
2081
  if (activePort <= 0) {
@@ -1725,7 +2098,7 @@ async function runStart(options, ctx, label = "start") {
1725
2098
  finalPid = live[0];
1726
2099
  writePidRecord(cfg.cdp.pidFile, {
1727
2100
  pid: finalPid,
1728
- exe: cfg.cdp.exePath
2101
+ exe: exePath
1729
2102
  });
1730
2103
  reporter.say(`pid 已校准:${launched.pid} → ${finalPid}(启动器进程已退出,实际主进程是它)`);
1731
2104
  }
@@ -1736,7 +2109,7 @@ async function runStart(options, ctx, label = "start") {
1736
2109
  action: label,
1737
2110
  ok: true,
1738
2111
  pid: finalPid,
1739
- exe: cfg.cdp.exePath,
2112
+ exe: exePath,
1740
2113
  endpoint,
1741
2114
  browser: info?.Browser ?? null,
1742
2115
  webSocketDebuggerUrl: info?.webSocketDebuggerUrl ?? null,
@@ -1794,6 +2167,8 @@ async function runEnsure(options, ctx) {
1794
2167
  async function runStatus(options, ctx) {
1795
2168
  const { cfg, env } = ctx;
1796
2169
  const reporter = new Reporter(ctx.io, options.json);
2170
+ const chosenLocation = cfg.client.exe?.location ?? cfg.environment.clientLocations[0] ?? "host";
2171
+ if (cfg.environment.kind === "wsl2" && cfg.environment.networkingMode !== "mirrored" && chosenLocation === "host") reporter.say("提示:WSL2 NAT + 客户端在 Windows 宿主,本机回环看不到端点;status/endpoint 结果只代表 WSL 侧。", paint.gray);
1797
2172
  const managed = await resolveManagedProcess(cfg.cdp);
1798
2173
  const managedFile = readManagedPidFile(cfg.cdp);
1799
2174
  const processes = await instanceProcesses(cfg.cdp);
@@ -1967,6 +2342,261 @@ async function runCdpAction(action, options, ctx) {
1967
2342
  }
1968
2343
  }
1969
2344
  }
2345
+ // src/commands/mcp.ts
2346
+ const HTTP_OPTION_NAMES = [
2347
+ "host",
2348
+ "port",
2349
+ "path",
2350
+ "token",
2351
+ "stateless"
2352
+ ];
2353
+ const HTTP_ENV_KEYS = [
2354
+ "LCEDA_HTTP_HOST",
2355
+ "LCEDA_HTTP_PORT",
2356
+ "LCEDA_HTTP_PATH",
2357
+ "LCEDA_HTTP_TOKEN",
2358
+ "LCEDA_HTTP_STATELESS"
2359
+ ];
2360
+ /**
2361
+ * 找出「用户以为会启动 HTTP」的参数/环境变量。
2362
+ * 只有 `mcp http` 会启动 HTTP;其它动作看到这些参数时只告警、绝不隐式启动。
2363
+ */
2364
+ function httpOptionsRequested(values, env, action = "serve") {
2365
+ const optionNames = action === "host" ? HTTP_OPTION_NAMES.filter((name) => name !== "port") : HTTP_OPTION_NAMES;
2366
+ const requested = [];
2367
+ for (const name of optionNames) if (values[name] !== void 0) requested.push(`--${name}`);
2368
+ for (const key of HTTP_ENV_KEYS) if ((env[key] ?? "") !== "") requested.push(key);
2369
+ return requested;
2370
+ }
2371
+ /** `lceda-connect mcp` / `lceda-mcp` 的命令实现:只做参数解析与传输适配器选择。 */
2372
+ const MCP_OPTIONS = [
2373
+ {
2374
+ name: "toolsets",
2375
+ type: "string",
2376
+ placeholder: "N",
2377
+ description: "选择 core/offline/live 或逗号分隔的领域(默认全部)"
2378
+ },
2379
+ {
2380
+ name: "host",
2381
+ type: "string",
2382
+ placeholder: "HOST",
2383
+ description: "http 监听地址(默认 127.0.0.1;wsl=自动取 WSL 虚拟网卡地址)"
2384
+ },
2385
+ {
2386
+ name: "port",
2387
+ type: "number",
2388
+ placeholder: "PORT",
2389
+ description: "http 监听端口(默认 3939)"
2390
+ },
2391
+ {
2392
+ name: "path",
2393
+ type: "string",
2394
+ placeholder: "/mcp",
2395
+ description: "http 端点路径(默认 /mcp)"
2396
+ },
2397
+ {
2398
+ name: "token",
2399
+ type: "string",
2400
+ placeholder: "TOKEN",
2401
+ description: "http 要求 Authorization: Bearer <token>"
2402
+ },
2403
+ {
2404
+ name: "stateless",
2405
+ type: "boolean",
2406
+ description: "http 无状态模式(不管理 session)"
2407
+ },
2408
+ {
2409
+ name: "node",
2410
+ type: "string",
2411
+ placeholder: "PATH",
2412
+ description: "host 动作:Windows node.exe(默认自动发现)"
2413
+ },
2414
+ {
2415
+ name: "script",
2416
+ type: "string",
2417
+ placeholder: "PATH",
2418
+ description: "host 动作:Windows 侧 cli-mcp.mjs(默认按全局安装自动发现)"
2419
+ },
2420
+ {
2421
+ name: "print-config",
2422
+ type: "boolean",
2423
+ description: "host 动作:只打印可直接粘贴的 stdio 客户端配置"
2424
+ },
2425
+ {
2426
+ name: "start-client",
2427
+ type: "boolean",
2428
+ description: "host 动作:启动 MCP 前通过 Windows 侧 CLI 确保 EasyEDA 带调试端口运行"
2429
+ }
2430
+ ];
2431
+ function mcpHelp() {
2432
+ return [
2433
+ "",
2434
+ paint.cyan(" lceda-connect mcp -- MCP 服务(stdio / streamable-http / WSL→Windows)"),
2435
+ paint.gray(` ${hr()}`),
2436
+ " 用法: lceda-connect mcp [动作] [选项] (也可直接用 lceda-mcp)",
2437
+ "",
2438
+ paint.white(" 动作:"),
2439
+ " serve 以 stdio 运行 MCP 服务(默认动作,给 MCP 客户端调用)",
2440
+ " http 以 Streamable HTTP 运行 MCP 服务(默认只监听 127.0.0.1)",
2441
+ " host 在 WSL 里拉起 Windows 侧的 lceda-connect MCP(stdio 透传)",
2442
+ " tools 列出全部 MCP 工具名与说明",
2443
+ "",
2444
+ paint.white(" 选项:"),
2445
+ ...formatOptions(MCP_OPTIONS),
2446
+ ...GLOBAL_HELP_ROWS.map((row) => ` ${row.flag.padEnd(24)} ${row.description}`),
2447
+ "",
2448
+ paint.white(" 示例:"),
2449
+ " lceda-connect mcp http --host wsl --port 3939 --token secret",
2450
+ " lceda-connect mcp host --toolsets live",
2451
+ " lceda-connect mcp host --print-config",
2452
+ "",
2453
+ paint.white(" MCP 客户端配置示例:"),
2454
+ " { \"type\": \"stdio\", \"command\": \"npx\", \"args\": [\"-y\", \"lceda-connect\", \"mcp\"] }",
2455
+ " { \"type\": \"http\", \"url\": \"http://127.0.0.1:3939/mcp\" }",
2456
+ " { \"type\": \"stdio\", \"command\": \"npx\", \"args\": [\"-y\", \"lceda-connect\", \"mcp\", \"host\"] }",
2457
+ "",
2458
+ paint.gray(" 提示:http 默认只绑回环,WSL 里连不到 Windows 回环;跨 WSL 用 --host wsl 或在 Windows 侧启动。"),
2459
+ ""
2460
+ ];
2461
+ }
2462
+ async function waitForShutdown() {
2463
+ await new Promise((resolve) => {
2464
+ process.once("SIGINT", resolve);
2465
+ process.once("SIGTERM", resolve);
2466
+ });
2467
+ }
2468
+ async function runMcpGroup(argv, io, env, runtime) {
2469
+ if (argv[0] === "help" || argv[0] === "--help" || argv[0] === "-h" || argv.includes("--help") || argv.includes("-h")) {
2470
+ print$1(io, mcpHelp());
2471
+ return 0;
2472
+ }
2473
+ let parsed;
2474
+ try {
2475
+ parsed = parseArgs(argv, MCP_OPTIONS);
2476
+ } catch (error) {
2477
+ io.err(paint.red(` ${error instanceof Error ? error.message : String(error)}`));
2478
+ print$1(io, mcpHelp());
2479
+ return 1;
2480
+ }
2481
+ const action = (parsed.positionals[0] ?? "serve").trim().toLowerCase();
2482
+ const extras = parsed.positionals.slice(1);
2483
+ if (action === "help" || action === "--help" || action === "-h") {
2484
+ print$1(io, mcpHelp());
2485
+ return 0;
2486
+ }
2487
+ const selected = stringValue(parsed, "toolsets") ?? env.LCEDA_TOOLSETS;
2488
+ const normalized = (await import("./windowsHost-CTZXMA8D.mjs")).normalizeMcpEnv(env);
2489
+ for (const warning of normalized.warnings) io.err(paint.yellow(` ! ${warning}`));
2490
+ const effectiveEnv = normalized.env;
2491
+ if (action !== "http") {
2492
+ const requested = httpOptionsRequested(parsed.values, effectiveEnv, action);
2493
+ if (requested.length > 0) io.err(paint.yellow(` ! 检测到 HTTP 参数(${requested.join(", ")}),但当前动作是 ${action};未启动 HTTP 服务。需要 HTTP 请显式运行 \`mcp http\``));
2494
+ }
2495
+ if (action === "tools") {
2496
+ const { toolsForEnv } = await import("./registry-DdJ8LEdd.mjs");
2497
+ try {
2498
+ for (const tool of toolsForEnv(effectiveEnv, selected)) io.out(`${paint.cyan(tool.name.padEnd(28))} ${tool.description.split("。")[0] ?? ""}`);
2499
+ return 0;
2500
+ } catch (error) {
2501
+ io.err(paint.red(error instanceof Error ? error.message : String(error)));
2502
+ return 1;
2503
+ }
2504
+ }
2505
+ if (action === "serve") {
2506
+ if (extras.length > 0) {
2507
+ io.err(paint.red(` 多余的参数: ${extras.join(" ")}`));
2508
+ return 1;
2509
+ }
2510
+ const { serveStdio } = await import("./stdio-Du1oLqfJ.mjs");
2511
+ try {
2512
+ const cfg = loadConfig(effectiveEnv);
2513
+ io.err(paint.gray(` 环境: ${describeEnvironment(cfg.environment)}` + (runtime?.configPath ? ` · 配置 ${runtime.configPath}` : "") + (runtime?.envFilePath ? ` · .env ${runtime.envFilePath}` : "")));
2514
+ await serveStdio(effectiveEnv, selected);
2515
+ return 0;
2516
+ } catch (error) {
2517
+ io.err(paint.red(error instanceof Error ? error.message : String(error)));
2518
+ return 1;
2519
+ }
2520
+ }
2521
+ if (action === "http") {
2522
+ if (extras.length > 0) {
2523
+ io.err(paint.red(` 多余的参数: ${extras.join(" ")}`));
2524
+ return 1;
2525
+ }
2526
+ const requestedHost = stringValue(parsed, "host") ?? effectiveEnv.LCEDA_HTTP_HOST ?? "127.0.0.1";
2527
+ let host = requestedHost;
2528
+ if (requestedHost.trim().toLowerCase() === "wsl") {
2529
+ const envInfo = loadConfig(effectiveEnv).environment;
2530
+ if (envInfo.platform === "linux" && envInfo.kind !== "wsl2") {
2531
+ io.err(paint.red(" 当前不是 WSL2 环境,没有 WSL 虚拟网卡可绑;请直接传 --host <IP>"));
2532
+ return 1;
2533
+ }
2534
+ if (envInfo.kind === "wsl2" && envInfo.networkingMode === "mirrored") io.err(paint.yellow(" ! WSL mirrored 模式下宿主与 WSL 共享回环,--host wsl 取到的可能是 LAN 地址;建议用 127.0.0.1"));
2535
+ const { resolveWslFacingHost } = await import("./windowsHost-CTZXMA8D.mjs");
2536
+ const resolved = resolveWslFacingHost(effectiveEnv);
2537
+ if (!resolved) {
2538
+ io.err(paint.red(" 无法自动解析 WSL 虚拟网卡地址;请直接传 --host <宿主 vEthernet IP>"));
2539
+ return 1;
2540
+ }
2541
+ host = resolved.host;
2542
+ io.err(paint.gray(` --host wsl → ${host}(${resolved.source})`));
2543
+ for (const warning of resolved.warnings) io.err(paint.yellow(` ! ${warning}`));
2544
+ }
2545
+ const envPort = effectiveEnv.LCEDA_HTTP_PORT && /^\d+$/.test(effectiveEnv.LCEDA_HTTP_PORT.trim()) ? Number.parseInt(effectiveEnv.LCEDA_HTTP_PORT, 10) : void 0;
2546
+ const stateless = boolValue(parsed, "stateless") || (effectiveEnv.LCEDA_HTTP_STATELESS ?? "").toLowerCase() === "true";
2547
+ const token = stringValue(parsed, "token") ?? effectiveEnv.LCEDA_HTTP_TOKEN;
2548
+ if (!isLoopbackAddress(host) && !token) {
2549
+ io.err(paint.red(" 绑定非回环地址时必须提供 Bearer token(--token / LCEDA_HTTP_TOKEN / 配置 mcp.http.token);已拒绝启动 HTTP 服务"));
2550
+ return 1;
2551
+ }
2552
+ const { startHttpTransport } = await import("./http-D7sYy2y4.mjs");
2553
+ try {
2554
+ const handle = await startHttpTransport({
2555
+ env: effectiveEnv,
2556
+ toolsets: selected,
2557
+ host,
2558
+ port: numberValue(parsed, "port") ?? (Number.isFinite(envPort) ? envPort : void 0),
2559
+ path: stringValue(parsed, "path") ?? effectiveEnv.LCEDA_HTTP_PATH,
2560
+ token,
2561
+ stateless
2562
+ });
2563
+ io.err(paint.gray(` 按 Ctrl+C 或结束进程退出;端点 ${handle.url}`));
2564
+ await waitForShutdown();
2565
+ await handle.close();
2566
+ return 0;
2567
+ } catch (error) {
2568
+ io.err(paint.red(error instanceof Error ? error.message : String(error)));
2569
+ return 1;
2570
+ }
2571
+ }
2572
+ if (action === "host") {
2573
+ const forwardArgs = [];
2574
+ if (selected) forwardArgs.push("--toolsets", selected);
2575
+ forwardArgs.push(...extras);
2576
+ const clientPort = numberValue(parsed, "port");
2577
+ const hostEnv = clientPort !== void 0 ? {
2578
+ ...effectiveEnv,
2579
+ LCEDA_CDP_PORT: String(clientPort)
2580
+ } : effectiveEnv;
2581
+ const { runMcpHost } = await import("./mcpHost-CRoN6MnG.mjs");
2582
+ return await runMcpHost({
2583
+ env: hostEnv,
2584
+ io,
2585
+ forwardArgs,
2586
+ nodePath: stringValue(parsed, "node"),
2587
+ scriptPath: stringValue(parsed, "script"),
2588
+ printConfig: boolValue(parsed, "print-config"),
2589
+ startClient: boolValue(parsed, "start-client"),
2590
+ clientPort
2591
+ });
2592
+ }
2593
+ io.err(paint.red(` 不认识的命令: ${action}`));
2594
+ print$1(io, mcpHelp());
2595
+ return 1;
2596
+ }
2597
+ function print$1(io, lines) {
2598
+ for (const line of lines) io.out(line);
2599
+ }
1970
2600
  // src/main.ts
1971
2601
  const CDP_ACTIONS = [
1972
2602
  "start",
@@ -2085,7 +2715,7 @@ function globalHelp() {
2085
2715
  paint.white(" 命令组:"),
2086
2716
  " cdp 带 CDP 调试端口启动 / 管理立创EDA专业版",
2087
2717
  " bridge EasyEDA AI Bridge 服务管理",
2088
- " mcp 以 stdio 运行 MCP 服务 / 列出工具",
2718
+ " mcp stdio / Streamable HTTP 服务、WSL→Windows 启动与工具清单",
2089
2719
  ...DOMAIN_GROUPS.map((g) => ` ${g.name.padEnd(10)} ${g.summary}`),
2090
2720
  "",
2091
2721
  paint.white(" 等价写法:"),
@@ -2102,6 +2732,7 @@ function globalHelp() {
2102
2732
  paint.white(" 全局选项:"),
2103
2733
  " --version, -v 打印版本",
2104
2734
  " --help, -h 打印帮助",
2735
+ ...GLOBAL_HELP_ROWS.map((row) => ` ${row.flag.padEnd(24)} ${row.description}`),
2105
2736
  ""
2106
2737
  ];
2107
2738
  }
@@ -2174,6 +2805,16 @@ function bridgeHelp() {
2174
2805
  * 启动时把所有领域模块都读进来。
2175
2806
  */
2176
2807
  const DOMAIN_GROUPS = [
2808
+ {
2809
+ name: "env",
2810
+ summary: "执行环境、客户端路径与在线通道策略自检(auto / windows-native / wsl2 / linux / macos)",
2811
+ load: async () => (await import("./environment-Clx1-nDW.mjs")).runEnvironmentCommand
2812
+ },
2813
+ {
2814
+ name: "extension",
2815
+ summary: "预检 .eext;在隔离的可见客户端安装、卸载扩展(实验性,仅 CLI)",
2816
+ load: async () => (await import("./cli-CXk5pvVm.mjs")).runExtensionCommand
2817
+ },
2177
2818
  {
2178
2819
  name: "api",
2179
2820
  summary: "离线检索 EasyEDA Pro 扩展 API 文档(search / get)",
@@ -2182,7 +2823,7 @@ const DOMAIN_GROUPS = [
2182
2823
  {
2183
2824
  name: "epro2",
2184
2825
  summary: "离线解析 .epro2 工程:网表、PCB 几何、一致性报告、版本对比",
2185
- load: async () => (await import("./cli-BzrDKC7x.mjs")).runEpro2Command
2826
+ load: async () => (await import("./cli-CHbcaMwS.mjs")).runEpro2Command
2186
2827
  },
2187
2828
  {
2188
2829
  name: "eprj3",
@@ -2197,12 +2838,12 @@ const DOMAIN_GROUPS = [
2197
2838
  {
2198
2839
  name: "eda",
2199
2840
  summary: "编辑器动词:双通道自检、读板、DRC、板指纹、自动布线、动词台账检索",
2200
- load: async () => (await import("./cli-BekOvZjB.mjs")).runEdaCommand
2841
+ load: async () => (await import("./cli-DFqBHofJ.mjs")).runEdaCommand
2201
2842
  },
2202
2843
  {
2203
2844
  name: "sim",
2204
2845
  summary: "ngspice 仿真:网表生成、运行、raw 解析、指标、叠层与 Touchstone",
2205
- load: async () => (await import("./cli-BqILMvnF.mjs")).runSimCommand
2846
+ load: async () => (await import("./cli-CZEoeuFW.mjs")).runSimCommand
2206
2847
  }
2207
2848
  ];
2208
2849
  /** cdp 命令组里由 CDP 客户端(src/cdp)处理的动作,其余仍归启动器。 */
@@ -2221,79 +2862,23 @@ const BRIDGE_CLIENT_ACTIONS = [
2221
2862
  "select",
2222
2863
  "exec"
2223
2864
  ];
2224
- function mcpHelp() {
2225
- return [
2226
- "",
2227
- paint.cyan(" lceda-connect mcp -- MCP 服务(stdio)"),
2228
- paint.gray(` ${hr()}`),
2229
- " 用法: lceda-connect mcp [动作] (也可直接用 lceda-mcp)",
2230
- "",
2231
- paint.white(" 动作:"),
2232
- " serve 以 stdio 运行 MCP 服务(默认动作,给 MCP 客户端调用)",
2233
- " tools 列出全部 MCP 工具名与说明",
2234
- "",
2235
- paint.white(" 选项:"),
2236
- " --toolsets N 选择 core/offline/live 或逗号分隔的领域(默认全部)",
2237
- "",
2238
- paint.white(" MCP 客户端配置示例:"),
2239
- " { \"command\": \"npx\", \"args\": [\"-y\", \"lceda-connect\", \"mcp\"] }",
2240
- ""
2241
- ];
2242
- }
2243
- async function runMcpGroup(argv, io, env) {
2244
- const positional = [];
2245
- let toolsets;
2865
+ /** 命令组 token 集合:用来定位全局选项与组内同名选项的分界。 */
2866
+ const COMMAND_GROUP_TOKENS = /* @__PURE__ */ new Set([
2867
+ ...DOMAIN_GROUPS.map((group) => group.name),
2868
+ "mcp",
2869
+ "cdp",
2870
+ "bridge"
2871
+ ]);
2872
+ function findGroupIndex(argv) {
2246
2873
  for (let index = 0; index < argv.length; index++) {
2247
2874
  const token = argv[index] ?? "";
2248
- if (token === "--toolsets") {
2249
- const value = argv[++index];
2250
- if (!value || value.startsWith("-")) {
2251
- io.err(paint.red(" --toolsets 需要一个逗号分隔的值"));
2252
- return 1;
2253
- }
2254
- toolsets = value;
2255
- continue;
2256
- }
2257
- if (token.startsWith("--toolsets=")) {
2258
- const value = token.slice(11).trim();
2259
- if (!value) {
2260
- io.err(paint.red(" --toolsets 需要一个逗号分隔的值"));
2261
- return 1;
2262
- }
2263
- toolsets = value;
2264
- continue;
2875
+ if (COMMAND_GROUP_TOKENS.has(token)) return index;
2876
+ if (token.startsWith("--") && !token.includes("=")) {
2877
+ const name = token.slice(2).toLowerCase();
2878
+ if (GLOBAL_HELP_ROWS.some((row) => row.flag.startsWith(`--${name} `))) index += 1;
2265
2879
  }
2266
- positional.push(token);
2267
2880
  }
2268
- const action = (positional[0] ?? "serve").trim().toLowerCase();
2269
- if (action === "help" || action === "--help" || action === "-h") {
2270
- print(io, mcpHelp());
2271
- return 0;
2272
- }
2273
- const selected = toolsets ?? env.LCEDA_TOOLSETS;
2274
- if (action === "tools") {
2275
- const { toolsForEnv } = await import("./registry-5K1G1XmC.mjs");
2276
- try {
2277
- for (const tool of toolsForEnv(env, selected)) io.out(`${paint.cyan(tool.name.padEnd(28))} ${tool.description.split("。")[0] ?? ""}`);
2278
- return 0;
2279
- } catch (error) {
2280
- io.err(paint.red(error instanceof Error ? error.message : String(error)));
2281
- return 1;
2282
- }
2283
- }
2284
- if (action === "serve") {
2285
- const { serveStdio } = await import("./server-DNMAlzZJ.mjs");
2286
- try {
2287
- await serveStdio(env, selected);
2288
- return 0;
2289
- } catch (error) {
2290
- io.err(paint.red(error instanceof Error ? error.message : String(error)));
2291
- return 1;
2292
- }
2293
- }
2294
- io.err(paint.red(` 不认识的命令: ${action}`));
2295
- print(io, mcpHelp());
2296
- return 1;
2881
+ return -1;
2297
2882
  }
2298
2883
  function print(io, lines) {
2299
2884
  for (const line of lines) io.out(line);
@@ -2304,17 +2889,37 @@ function print(io, lines) {
2304
2889
  */
2305
2890
  async function main(options) {
2306
2891
  const io = options.io ?? stdIo;
2307
- const env = options.env ?? process.env;
2308
- const argv = [...options.argv];
2309
- if (argv.includes("--version") || argv.includes("-v") || argv.includes("-version")) {
2892
+ const rawArgv = [...options.argv];
2893
+ if (rawArgv.includes("--version") || rawArgv.includes("-v") || rawArgv.includes("-version")) {
2310
2894
  io.out(`lceda-connect v${packageVersion()}`);
2311
2895
  return 0;
2312
2896
  }
2897
+ const groupIndex = findGroupIndex(rawArgv);
2898
+ const localOptions = (groupIndex >= 0 ? rawArgv[groupIndex] : options.defaultGroup) === "sim" ? ["config"] : [];
2899
+ let runtime;
2900
+ try {
2901
+ runtime = resolveRuntime({
2902
+ argv: rawArgv,
2903
+ env: options.env ?? process.env,
2904
+ global: {
2905
+ groupIndex: groupIndex >= 0 ? groupIndex : 0,
2906
+ localOptions
2907
+ }
2908
+ });
2909
+ } catch (error) {
2910
+ if (error instanceof RuntimeConfigError) {
2911
+ io.err(paint.red(` ${error.message}`));
2912
+ return 1;
2913
+ }
2914
+ throw error;
2915
+ }
2916
+ const env = runtime.env;
2917
+ const argv = runtime.argv;
2313
2918
  const [first, ...rest] = argv;
2314
2919
  const isHelpFlag = (token) => token === "--help" || token === "-h" || token === "-help" || token === "help";
2315
- if (first === "mcp") return await runMcpGroup(rest, io, env);
2316
- const domain = DOMAIN_GROUPS.find((g) => g.name === first);
2317
- if (domain) return await (await domain.load())(rest, io, env);
2920
+ if (first === "mcp") return await runMcpGroup(rest, io, env, runtime);
2921
+ const domain = DOMAIN_GROUPS.find((group) => group.name === first && !(options.defaultGroup && group.name === "env"));
2922
+ if (domain) return await (await domain.load())(rest, io, env, runtime);
2318
2923
  let group;
2319
2924
  let tail;
2320
2925
  if (first === "cdp" || first === "bridge") {
@@ -2333,7 +2938,7 @@ async function main(options) {
2333
2938
  }
2334
2939
  const clientAction = tail[0]?.trim().toLowerCase() ?? "";
2335
2940
  if (group === "cdp" && CDP_CLIENT_ACTIONS.includes(clientAction)) {
2336
- const { runCdpClientCommand } = await import("./cli-B3GGyoP_.mjs");
2941
+ const { runCdpClientCommand } = await import("./cli-1_urvve3.mjs");
2337
2942
  return await runCdpClientCommand(tail, io, env);
2338
2943
  }
2339
2944
  if (group === "bridge" && BRIDGE_CLIENT_ACTIONS.includes(clientAction)) {