mihomo-cli 4.12.0 → 4.14.0

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/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // node_modules/compare-versions/lib/esm/utils.js
3
+ // src/index.ts
4
+ import fs15 from "fs";
5
+
6
+ // ../../../node_modules/compare-versions/lib/esm/utils.js
4
7
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
5
8
  var validateAndParse = (version) => {
6
9
  if (typeof version !== "string") {
@@ -38,7 +41,7 @@ var compareSegments = (a, b) => {
38
41
  return 0;
39
42
  };
40
43
 
41
- // node_modules/compare-versions/lib/esm/compareVersions.js
44
+ // ../../../node_modules/compare-versions/lib/esm/compareVersions.js
42
45
  var compareVersions = (v1, v2) => {
43
46
  const n1 = validateAndParse(v1);
44
47
  const n2 = validateAndParse(v2);
@@ -79,7 +82,7 @@ import fs4 from "fs";
79
82
  import path4 from "path";
80
83
  import { promisify } from "util";
81
84
 
82
- // node_modules/js-yaml/dist/js-yaml.mjs
85
+ // ../../../node_modules/js-yaml/dist/js-yaml.mjs
83
86
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
84
87
  function defineScalarTag(tagName, options) {
85
88
  return {
@@ -3162,9 +3165,10 @@ var TUN_CONFIG = {
3162
3165
  }
3163
3166
  };
3164
3167
  var BASE_CONFIG = {
3165
- // 注意:mixed-port 与 external-controller 不在此表——它们来自 settings.ports(getPorts),
3166
- // config.ts 单独写入 systemConfig,订阅/覆写恒不可改
3167
- "allow-lan": false,
3168
+ // 注意:mixed-port、external-controller 与 allow-lan 不在此表——前两个来自
3169
+ // settings.ports(getPorts),allow-lan 恒为 false,三者都由 config.ts 单独写入
3170
+ // systemConfig,订阅/覆写恒不可改。本表的语义是「用户没写时的默认」(可被覆盖),
3171
+ // 锁定项的语义是「恒定此值」,两者不能混在一张表里
3168
3172
  "unified-delay": true,
3169
3173
  "tcp-concurrent": true,
3170
3174
  "geo-auto-update": true,
@@ -4007,10 +4011,22 @@ function normalizeEnabled(raw, fileName) {
4007
4011
  }
4008
4012
  );
4009
4013
  }
4010
- function loadOverwriteFile() {
4011
- const dir = USER_DATA_DIR;
4012
- if (!fs3.existsSync(dir)) return [];
4013
- const entries = fs3.readdirSync(dir);
4014
+ function toBrokenFile(file, filePath, e) {
4015
+ if (e instanceof CliError) {
4016
+ return { name: file, path: filePath, label: e.label, message: e.message, hint: e.hint };
4017
+ }
4018
+ const message = e.message || String(e);
4019
+ const hint = ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\uFF0C\u8BF7\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08mihomo ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\uFF09\u3002"];
4020
+ if (/alias/i.test(message)) {
4021
+ hint.push('\u82E5\u5199\u4E86\u4EE5 * \u5F00\u5934\u7684\u901A\u914D\u503C\uFF08\u5982 name: *edu\uFF09\uFF0CYAML \u4F1A\u628A\u5B83\u5F53\u522B\u540D\u8BED\u6CD5\uFF0C\u8BF7\u52A0\u5F15\u53F7\u5199\u6210 name: "*edu"');
4022
+ }
4023
+ return { name: file, path: filePath, label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF", message: `\u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}`, hint };
4024
+ }
4025
+ function readOverwriteFiles() {
4026
+ const ok = [];
4027
+ const broken = [];
4028
+ if (!fs3.existsSync(USER_DATA_DIR)) return { ok, broken };
4029
+ const entries = fs3.readdirSync(USER_DATA_DIR);
4014
4030
  const files = entries.filter(isOverwriteFilename).sort((a, b) => {
4015
4031
  if (a === "overwrite.yaml") return -1;
4016
4032
  if (b === "overwrite.yaml") return 1;
@@ -4021,27 +4037,35 @@ function loadOverwriteFile() {
4021
4037
  `\u8B66\u544A: "${typo}" \u4E0D\u4F1A\u88AB\u5F53\u4F5C\u8986\u5199\u6587\u4EF6\u52A0\u8F7D\uFF08\u5408\u6CD5\u6587\u4EF6\u540D: overwrite.yaml \u4E3B\u6587\u4EF6\u3001overwrite.*.yaml / overwrite.*.yml \u6269\u5C55\u6587\u4EF6\uFF1B\u4E3B\u6587\u4EF6\u4E0D\u652F\u6301 .yml\uFF09\uFF1B\u82E5\u662F\u7B14\u8BEF\u8BF7\u6539\u540D`
4022
4038
  );
4023
4039
  }
4024
- const results = [];
4025
4040
  for (const file of files) {
4026
- const filePath = path3.join(dir, file);
4041
+ const filePath = path3.join(USER_DATA_DIR, file);
4027
4042
  try {
4028
4043
  const content = fs3.readFileSync(filePath, "utf8");
4029
4044
  const parsed = load(content, { maxAliases: 200 });
4030
4045
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4031
4046
  const { match, enabled, ...config } = parsed;
4032
4047
  assertNoMetadataKeyLookalikes(config, file);
4033
- results.push({ name: file, path: filePath, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
4048
+ ok.push({ name: file, path: filePath, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
4034
4049
  } else if (parsed !== null) {
4035
- console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
4050
+ const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
4051
+ throw new CliError(`\u8986\u5199\u6587\u4EF6 "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u6620\u5C04\uFF08\u952E\u503C\u5BF9\uFF09\uFF0C\u5F53\u524D\u662F ${shape}`, {
4052
+ label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4053
+ hint: ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\u3002\u8986\u5199\u6587\u4EF6\u5F62\u5982:", " +rules:", " - DOMAIN-SUFFIX,example.com,DIRECT"]
4054
+ });
4036
4055
  }
4037
4056
  } catch (e) {
4038
- if (e instanceof CliError) throw e;
4039
- const message = e.message;
4040
- const aliasHint = /alias/i.test(message) ? '\uFF1B\u82E5\u662F\u4EE5 * \u5F00\u5934\u7684\u901A\u914D\u503C\uFF08\u5982 name: *edu\uFF09\uFF0CYAML \u4F1A\u628A\u5B83\u5F53\u522B\u540D\u8BED\u6CD5\uFF0C\u8BF7\u52A0\u5F15\u53F7\u5199\u6210 name: "*edu"' : "";
4041
- console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}${aliasHint}`);
4057
+ broken.push(toBrokenFile(file, filePath, e));
4042
4058
  }
4043
4059
  }
4044
- return results;
4060
+ return { ok, broken };
4061
+ }
4062
+ function loadOverwriteFile() {
4063
+ const { ok, broken } = readOverwriteFiles();
4064
+ if (broken.length > 0) {
4065
+ const first = broken[0];
4066
+ throw new CliError(first.message, { label: first.label, hint: first.hint });
4067
+ }
4068
+ return ok;
4045
4069
  }
4046
4070
  function applyOverwrite(baseConfig, files) {
4047
4071
  let result = { ...baseConfig };
@@ -4056,25 +4080,23 @@ function applyOverwrite(baseConfig, files) {
4056
4080
  return { config: result, skipped, operatorShapedKeys };
4057
4081
  }
4058
4082
  function listOverwriteFile(scope) {
4059
- const files = loadOverwriteFile();
4083
+ const { ok, broken } = readOverwriteFiles();
4060
4084
  const enabled = isOverwriteEnabled();
4061
4085
  return {
4062
4086
  enabled,
4063
4087
  dir: USER_DATA_DIR,
4064
- files: files.map((f) => ({
4088
+ files: ok.map((f) => ({
4065
4089
  name: f.name,
4066
4090
  path: f.path,
4067
4091
  keys: Object.keys(f.config || {}),
4068
4092
  scope: summarizeMatch(f.match),
4069
4093
  enabled: f.enabled !== false,
4070
4094
  ...scope ? { matched: matchesScope(f.match, scope) } : {}
4071
- }))
4095
+ })),
4096
+ broken
4072
4097
  };
4073
4098
  }
4074
4099
 
4075
- // src/utils.ts
4076
- import os2 from "os";
4077
-
4078
4100
  // src/flags.ts
4079
4101
  var FLAGS = [
4080
4102
  // === start 的选项(重启透传) ===
@@ -4124,6 +4146,21 @@ function sanitizeTerminal(s) {
4124
4146
  function shellQuote(s) {
4125
4147
  return `'${s.replace(/'/g, "'\\''")}'`;
4126
4148
  }
4149
+ function proxyEnvPointsAtSelf(value, selfPort) {
4150
+ let parsed;
4151
+ try {
4152
+ parsed = new URL(value);
4153
+ } catch {
4154
+ try {
4155
+ parsed = new URL(`http://${value}`);
4156
+ } catch {
4157
+ return false;
4158
+ }
4159
+ }
4160
+ const host = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
4161
+ if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1") return false;
4162
+ return Number.parseInt(parsed.port, 10) === selfPort;
4163
+ }
4127
4164
  function displayWidth(s) {
4128
4165
  let width = 0;
4129
4166
  for (const ch of s) {
@@ -4300,12 +4337,12 @@ function assertRestartOptionValues(args) {
4300
4337
  if (!args) return;
4301
4338
  parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
4302
4339
  }
4303
- function getNonFlagArg(args, startIdx, valueFlags = VALUE_FLAGS) {
4340
+ function getNonFlagArg(args, startIdx) {
4304
4341
  if (!args) return null;
4305
4342
  for (let i = startIdx; i < args.length; i++) {
4306
4343
  const a = args[i];
4307
4344
  if (a.startsWith("-")) {
4308
- if (valueFlags.has(a)) i++;
4345
+ if (VALUE_FLAGS.has(a)) i++;
4309
4346
  continue;
4310
4347
  }
4311
4348
  return a;
@@ -4342,19 +4379,6 @@ function suggestSimilar(input, candidates) {
4342
4379
  scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
4343
4380
  return scored.slice(0, 3).map((s) => s.name);
4344
4381
  }
4345
- function hasGlobalIpv6() {
4346
- for (const addrs of Object.values(os2.networkInterfaces())) {
4347
- for (const addr of addrs ?? []) {
4348
- if (addr.family !== "IPv6" || addr.internal) continue;
4349
- if (/^(fe80|f[c-d])/i.test(addr.address)) continue;
4350
- return true;
4351
- }
4352
- }
4353
- return false;
4354
- }
4355
- function getDefaultMirror() {
4356
- return hasGlobalIpv6() ? MIRROR_ALIASES.v6 : MIRROR_BARE;
4357
- }
4358
4382
  function normalizeMirrorUrl(val) {
4359
4383
  if (!val) return null;
4360
4384
  if (val === "direct") return null;
@@ -4400,7 +4424,7 @@ function parseMirrorArg(args) {
4400
4424
  const inline = mirrorEq?.slice("--mirror=".length);
4401
4425
  const nextArg = inline ?? args[mirrorIdx + 1];
4402
4426
  if (!nextArg || nextArg.startsWith("-")) {
4403
- return { mirror: getDefaultMirror(), isOverride: true };
4427
+ return { mirror: MIRROR_BARE, isOverride: true };
4404
4428
  }
4405
4429
  const normalized = normalizeMirrorUrl(nextArg);
4406
4430
  return { mirror: normalized, isOverride: true };
@@ -4446,7 +4470,32 @@ var LOCKED_CONFIG_KEYS = [
4446
4470
  // 与 README「入站默认关闭 / 入站与控制面由本工具独占」的承诺直接冲突。
4447
4471
  // 需要额外入站的用户改由本机另起实例,不接受远端订阅投递
4448
4472
  "listeners",
4449
- "tunnels"
4473
+ "tunnels",
4474
+ // 局域网暴露与入站鉴权:上游 `config.Inbound` 里与上面几个并列的字段,只因形态是
4475
+ // 布尔/字符串而非映射或 URL 被漏看了五轮(与 ss-config 当年被漏的原因一模一样)。
4476
+ // 实测链条(v1.19.30):
4477
+ // - `listener.genAddr(host, port, allowLan)` 在 allowLan 为真、bind-address 为默认
4478
+ // `"*"` 时返回 `":%d"`,即**全网卡监听**——订阅一行 `allow-lan: true` 就把 Mixed
4479
+ // 端口挪出回环;bind-address 则直接指定监听地址
4480
+ // - `authentication` 是这种情况下唯一的补偿防线,而 `skip-auth-prefixes` 能把它废掉:
4481
+ // `listener/http/server.go` 的 accept 循环里
4482
+ // `if inbound.SkipAuthRemoteAddr(conn.RemoteAddr()) { store = authStore.Nil }`,
4483
+ // `0.0.0.0/0` 命中所有来源,鉴权 store 被换成空实现
4484
+ // 即远端订阅三行 YAML = 全网卡无鉴权开放代理。lan-allowed-ips/lan-disallowed-ips
4485
+ // 同属这套来源准入判定,一并锁死;bind-address 单看无害(allow-lan 为假时 genAddr
4486
+ // 根本不读它),锁它是为了消除「两个键配合才危险」这种要跨键推理的组合。
4487
+ //
4488
+ // allow-lan 恒为 false 由下方 systemConfig 写入(**不在 BASE_CONFIG**,理由同
4489
+ // mixed-port:锁定项是「恒定此值」,不是「用户没写时的默认」)。需要局域网入站的
4490
+ // 用户请在本机另起一个 mihomo 实例,不通过订阅投递。
4491
+ // 代价:剥除来源盲,故覆写也不能再给 Mixed 端口设 authentication——缓解是
4492
+ // allow-lan 已强制 false、Mixed 只在回环,残余威胁面是同机其他进程(见 CODE_REVIEW)
4493
+ "allow-lan",
4494
+ "bind-address",
4495
+ "authentication",
4496
+ "skip-auth-prefixes",
4497
+ "lan-allowed-ips",
4498
+ "lan-disallowed-ips"
4450
4499
  ];
4451
4500
  function loadYamlSafe(content) {
4452
4501
  return load(content, SAFE_YAML_LOAD_OPTIONS);
@@ -4564,7 +4613,7 @@ function buildConfig(subRawContent, mode, scope) {
4564
4613
  }
4565
4614
  if (hit.size > 0) {
4566
4615
  lockedWarnings.push(
4567
- `\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${[...hit].join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u4E0E\u63A7\u5236\u5668\u8BC1\u4E66\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF09`
4616
+ `\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${[...hit].join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo \u5B9E\u4F8B\uFF09`
4568
4617
  );
4569
4618
  }
4570
4619
  }
@@ -4575,6 +4624,7 @@ function buildConfig(subRawContent, mode, scope) {
4575
4624
  const ports = getPorts(settings);
4576
4625
  systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
4577
4626
  systemConfig["mixed-port"] = ports.mixed;
4627
+ systemConfig["allow-lan"] = false;
4578
4628
  const controllerSecret = settings.controller_secret;
4579
4629
  if (controllerSecret !== void 0) {
4580
4630
  if (typeof controllerSecret !== "string") {
@@ -4638,7 +4688,13 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4638
4688
  for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
4639
4689
  hint.push(`${HINT_INDENT}\u82E5\u62A5\u9519\u7684\u5143\u7D20\u6765\u81EA\u8986\u5199\u8FFD\u52A0\uFF08~key \u672A\u5339\u914D\u5230\u540C\u540D\u5143\u7D20\u65F6\u4F1A\u65B0\u589E\uFF09\uFF0C\u6539\u7528 ~?key \u53EF\u5728\u7F3A\u5C11\u8BE5\u5143\u7D20\u7684\u8BA2\u9605\u4E0A\u8DF3\u8FC7\u3002`);
4640
4690
  }
4641
- hint.push("", `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
4691
+ hint.push(
4692
+ "",
4693
+ `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`,
4694
+ // 「未知键/字段」类报错的另一个真实根因是内核落后于订阅:机场开始用新协议字段,
4695
+ // 旧内核 -t 一律按不认识拒绝。只提示「修正订阅或覆写」会把方向带反
4696
+ `${HINT_INDENT}\u82E5\u8BA2\u9605\u6216\u8986\u5199\u672C\u8EAB\u6CA1\u6709\u660E\u663E\u9519\u8BEF\uFF0C\u4E5F\u53EF\u80FD\u662F\u5185\u6838\u7248\u672C\u8FC7\u65E7\u3001\u4E0D\u8BA4\u8BC6\u65B0\u914D\u7F6E\u952E\uFF0C\u53EF\u5C1D\u8BD5: mihomo kernel`
4697
+ );
4642
4698
  return hint;
4643
4699
  }
4644
4700
  async function validateConfigWithKernel(config, overwriteSummaries) {
@@ -4736,18 +4792,19 @@ import path7 from "path";
4736
4792
  import fs5 from "fs";
4737
4793
  import path5 from "path";
4738
4794
  var DEFAULT_LOG_RETENTION_DAYS = 7;
4795
+ var LOG_TAIL_LINES = 15;
4739
4796
  var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
4740
4797
  function isArchiveLogFilename(filename) {
4741
4798
  return ARCHIVE_LOG_RE.test(filename);
4742
4799
  }
4743
4800
  function rotateAndCleanupLogs() {
4744
4801
  rotateLog();
4745
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4802
+ cleanupOldLogs();
4746
4803
  }
4747
4804
  function getLogPath() {
4748
4805
  return PATHS.logFile;
4749
4806
  }
4750
- function readLogTail(maxLines = 15) {
4807
+ function readLogTail() {
4751
4808
  const TAIL_BYTES = 64 * 1024;
4752
4809
  let fd = null;
4753
4810
  try {
@@ -4758,7 +4815,7 @@ function readLogTail(maxLines = 15) {
4758
4815
  const buf = Buffer.alloc(length);
4759
4816
  fd = fs5.openSync(PATHS.logFile, "r");
4760
4817
  fs5.readSync(fd, buf, 0, length, start);
4761
- return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-maxLines);
4818
+ return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
4762
4819
  } catch {
4763
4820
  return [];
4764
4821
  } finally {
@@ -4817,12 +4874,12 @@ function rotateLog() {
4817
4874
  }
4818
4875
  return rotatedPath;
4819
4876
  }
4820
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4877
+ function cleanupOldLogs() {
4821
4878
  const logsDir = DIRS.logs;
4822
4879
  if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4823
4880
  const files = fs5.readdirSync(logsDir);
4824
4881
  const now = Date.now();
4825
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4882
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
4826
4883
  let deleted = 0;
4827
4884
  let errors = 0;
4828
4885
  for (const file of files) {
@@ -5608,6 +5665,38 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
5608
5665
  );
5609
5666
  console.log(lines.join("\n"));
5610
5667
  }
5668
+ function printCommandHelp(command) {
5669
+ const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
5670
+ const lines = ["", `${colors.cyan(colors.bold(`mihomo ${command.name}`))}${aliasText}`];
5671
+ if (command.usage.length > 0) {
5672
+ lines.push("", "\u7528\u6CD5:");
5673
+ const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
5674
+ for (const u of command.usage) {
5675
+ lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
5676
+ }
5677
+ } else {
5678
+ lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo help"));
5679
+ }
5680
+ console.log(lines.join("\n"));
5681
+ }
5682
+ function printHelpEntry(args, commands, finder) {
5683
+ const token = args[1];
5684
+ if (!token) {
5685
+ printHelp(commands);
5686
+ return;
5687
+ }
5688
+ const command = finder(token.toLowerCase());
5689
+ if (!command) {
5690
+ const suggestion = suggestSimilar(
5691
+ token,
5692
+ commands.flatMap((c) => [c.name, ...c.aliases])
5693
+ );
5694
+ throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
5695
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
5696
+ });
5697
+ }
5698
+ printCommandHelp(command);
5699
+ }
5611
5700
  function printVersion() {
5612
5701
  const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5613
5702
  console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
@@ -5615,322 +5704,111 @@ function printVersion() {
5615
5704
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5616
5705
  }
5617
5706
 
5618
- // src/commands/completion.ts
5619
- import fs12 from "fs";
5620
- import os3 from "os";
5621
- import path9 from "path";
5622
-
5623
- // src/open.ts
5624
- import { spawn } from "child_process";
5625
-
5626
- // src/lifecycle.ts
5627
- var silentSigint = false;
5628
- function setSilentSigint(value) {
5629
- silentSigint = value;
5707
+ // src/redact.ts
5708
+ var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "secret"]);
5709
+ var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
5710
+ function walk(node, withinProvider, state) {
5711
+ if (Array.isArray(node)) {
5712
+ return node.map((item) => walk(item, withinProvider, state));
5713
+ }
5714
+ if (node !== null && typeof node === "object") {
5715
+ const out = {};
5716
+ for (const [key, value] of Object.entries(node)) {
5717
+ if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
5718
+ out[key] = "***";
5719
+ state.changed = true;
5720
+ } else if (typeof value === "string" && withinProvider && key === "url") {
5721
+ const masked = maskUrl(value);
5722
+ out[key] = masked;
5723
+ if (masked !== value) state.changed = true;
5724
+ } else {
5725
+ out[key] = walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state);
5726
+ }
5727
+ }
5728
+ return out;
5729
+ }
5730
+ return node;
5630
5731
  }
5631
- function isSilentSigint() {
5632
- return silentSigint;
5732
+ function redactConfigSecrets(config) {
5733
+ const state = { changed: false };
5734
+ return { config: walk(config, false, state), changed: state.changed };
5633
5735
  }
5634
5736
 
5635
- // src/open.ts
5636
- function openUrl(url) {
5737
+ // src/http.ts
5738
+ var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5739
+ var MAX_ERROR_BODY_BYTES = 64 * 1024;
5740
+ function isHttpsUrl(url) {
5637
5741
  try {
5638
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5639
- child.unref();
5640
- child.on("error", () => {
5641
- });
5742
+ return new URL(url).protocol === "https:";
5642
5743
  } catch {
5744
+ return false;
5643
5745
  }
5644
5746
  }
5645
- function openLogFile(logPath, label) {
5646
- const displayLabel = label || logPath;
5647
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
5648
- openUrl(logPath);
5649
- }
5650
- function viewLogWithTail(logPath, options) {
5651
- const follow = options?.follow;
5652
- const lines = options?.lines || 100;
5653
- console.log(`\u65E5\u5FD7: ${logPath}`);
5654
- if (follow) {
5655
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5656
- } else {
5657
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5658
- `);
5747
+ function createHttpError(status, bodyText) {
5748
+ const error = new Error(`HTTP ${status}`);
5749
+ error.response = { status };
5750
+ try {
5751
+ error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
5752
+ } catch {
5659
5753
  }
5660
- const tailArgs = [];
5661
- if (follow) tailArgs.push("-f");
5662
- tailArgs.push("-n", lines.toString());
5663
- tailArgs.push(logPath);
5664
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5665
- if (follow) setSilentSigint(true);
5666
- tail.on("close", (code) => process.exit(code ?? 0));
5667
- tail.on("error", (e) => {
5668
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5669
- process.exit(1);
5670
- });
5671
- }
5672
-
5673
- // src/commands/shared.ts
5674
- import readline from "readline";
5675
-
5676
- // src/process-start.ts
5677
- import fs9 from "fs";
5678
- var TUN_MODE_POST_WAIT_MS = 500;
5679
- function buildTunLaunchScript() {
5680
- const binary = shellQuote(PATHS.mihomoBinary);
5681
- const configFile = shellQuote(PATHS.configFile);
5682
- const logFile = shellQuote(PATHS.logFile);
5683
- const pidFile = shellQuote(PATHS.pidFile);
5684
- const dataDir = shellQuote(DIRS.data);
5685
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5686
- return `#!/bin/bash
5687
- BINARY=${binary}
5688
- CONFIG_FILE=${configFile}
5689
- LOG_FILE=${logFile}
5690
- PID_FILE=${pidFile}
5691
- DATA_DIR=${dataDir}
5692
- KILL_PATTERN=${killPattern}
5693
-
5694
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5695
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5696
- sleep 0.2
5697
- rm -f "\${PID_FILE}" 2>/dev/null || true
5698
-
5699
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5700
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5701
-
5702
- # \u542F\u52A8
5703
- cd /tmp
5704
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5705
- NEW_PID=$!
5706
- echo \${NEW_PID} > "\${PID_FILE}"
5707
-
5708
- # \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
5709
- #\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
5710
- # 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
5711
- is_alive() {
5712
- local stat
5713
- stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
5714
- case "\${stat}" in
5715
- Z*|'') return 1 ;;
5716
- *) return 0 ;;
5717
- esac
5718
- }
5719
-
5720
- # \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
5721
- # \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
5722
- # \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
5723
- i=0
5724
- while [ $i -lt 12 ]; do
5725
- sleep 0.1
5726
- is_alive \${NEW_PID} || break
5727
- i=$((i+1))
5728
- done
5729
- if is_alive \${NEW_PID}; then
5730
- exit 0
5731
- fi
5732
-
5733
- # \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
5734
- rm -f "\${PID_FILE}" 2>/dev/null || true
5735
- echo "TUN \u542F\u52A8\u5931\u8D25"
5736
- echo ""
5737
- echo "--- \u65E5\u5FD7 ---"
5738
- tail -25 "\${LOG_FILE}" 2>/dev/null
5739
- exit 2
5740
- `;
5754
+ return error;
5741
5755
  }
5742
- async function startTun() {
5743
- ensureDirs();
5744
- rotateAndCleanupLogs();
5745
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
5746
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5747
- }
5748
- if (!fs9.existsSync(PATHS.configFile)) {
5749
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5750
- }
5751
- const logFile = PATHS.logFile;
5752
- if (fs9.existsSync(logFile)) {
5753
- try {
5754
- fs9.accessSync(logFile, fs9.constants.W_OK);
5755
- } catch {
5756
+ function createHttpClient(options = {}) {
5757
+ const { timeout = 6e4 } = options;
5758
+ return {
5759
+ async get(url, config) {
5760
+ const controller = new AbortController();
5761
+ const timer = setTimeout(() => controller.abort(), timeout);
5762
+ const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
5756
5763
  try {
5757
- fs9.unlinkSync(logFile);
5758
- } catch {
5764
+ const response = await fetch(url, {
5765
+ signal,
5766
+ headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5767
+ });
5768
+ if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
5769
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5770
+ }
5771
+ if (!response.ok) {
5772
+ let text2 = "";
5773
+ try {
5774
+ text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
5775
+ } catch {
5776
+ }
5777
+ throw createHttpError(response.status, text2);
5778
+ }
5779
+ const declaredLen = Number(response.headers.get("content-length"));
5780
+ if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
5781
+ throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5782
+ }
5783
+ const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5784
+ const data = config?.responseType === "json" ? JSON.parse(text) : text;
5785
+ return { data, headers: response.headers, status: response.status };
5786
+ } finally {
5787
+ clearTimeout(timer);
5759
5788
  }
5760
5789
  }
5761
- }
5762
- const staleState = checkStaleState();
5763
- if (staleState.needsCleanup) {
5764
- if (staleState.allPids.length > 0) {
5765
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5766
- } else {
5767
- console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
5790
+ };
5791
+ }
5792
+ async function readBodyWithLimit(response, controller, limit) {
5793
+ if (!response.body) return response.text();
5794
+ const reader = response.body.getReader();
5795
+ const chunks = [];
5796
+ let total = 0;
5797
+ try {
5798
+ while (true) {
5799
+ const { done, value } = await reader.read();
5800
+ if (done) break;
5801
+ if (value) {
5802
+ total += value.byteLength;
5803
+ if (total > limit) {
5804
+ controller.abort();
5805
+ throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5806
+ }
5807
+ chunks.push(value);
5808
+ }
5768
5809
  }
5769
- }
5770
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5771
- runSudoScript(buildTunLaunchScript(), {
5772
- action: "TUN \u542F\u52A8",
5773
- file: "launch-tun.sh",
5774
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5775
- });
5776
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5777
- const finalPid = getPid();
5778
- if (!finalPid || !isRunning()) {
5779
- const tail = readLogTail();
5780
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
5781
- hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
5782
- });
5783
- }
5784
- return { success: true, pid: finalPid, mode: "tun" };
5785
- }
5786
-
5787
- // src/runtime.ts
5788
- function getRuntimeMode() {
5789
- if (isServiceInstalled()) return "mixed";
5790
- return getConfigInfo()?.tun ? "tun" : "mixed";
5791
- }
5792
- function getRunningState(serviceStatus) {
5793
- const service = serviceStatus ?? getServiceStatus();
5794
- if (service.running) {
5795
- return { running: true, pid: service.pid, kind: "service", processInfo: null };
5796
- }
5797
- const status = getStatus();
5798
- if (status.running) {
5799
- return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
5800
- }
5801
- return { running: false, pid: null, kind: null, processInfo: null };
5802
- }
5803
- function restartModeFor(state, fallbackMode) {
5804
- return state.kind === "tun" ? "tun" : fallbackMode;
5805
- }
5806
- function restartModeOnChange() {
5807
- const state = getRunningState();
5808
- return state.running ? restartModeFor(state, getRuntimeMode()) : null;
5809
- }
5810
- async function launchOrRestart(mode, stopEpochBefore) {
5811
- if (mode === "tun") {
5812
- const result = await startTun();
5813
- return result.pid;
5814
- }
5815
- const status = getServiceStatus();
5816
- let hotReloaded = false;
5817
- let started;
5818
- if (status.running && !status.disabled) {
5819
- ({ hotReloaded, started } = await restartService(stopEpochBefore));
5820
- } else {
5821
- ({ started } = await startService(stopEpochBefore));
5822
- }
5823
- if (!started) throw cancelledByConcurrentStop();
5824
- if (hotReloaded) return getServiceStatus().pid;
5825
- try {
5826
- return await assertServiceHealthy();
5827
- } catch (e) {
5828
- if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) throw cancelledByConcurrentStop();
5829
- throw e;
5830
- }
5831
- }
5832
- function cancelledByConcurrentStop() {
5833
- return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
5834
- label: "\u542F\u52A8\u5931\u8D25",
5835
- hint: [
5836
- "\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
5837
- "",
5838
- "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
5839
- ]
5840
- });
5841
- }
5842
- async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
5843
- const health = await waitServiceHealthy();
5844
- if (health.healthy) return health.pid;
5845
- const tail = readLogTail();
5846
- const cause = describeExitCause(health.exitCode, health.terminatingSignal);
5847
- const reason = health.crashed ? `\u5185\u6838\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08${cause ?? "\u6B7B\u56E0\u672A\u8BB0\u5F55"}\uFF09` : "\u5185\u6838\u672A\u80FD\u8FDB\u5165\u8FD0\u884C\u72B6\u6001";
5848
- throw new CliError(reason, {
5849
- label,
5850
- hint: [
5851
- ...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo stop\u3002"] : [],
5852
- ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
5853
- "",
5854
- "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"
5855
- ]
5856
- });
5857
- }
5858
-
5859
- // src/http.ts
5860
- var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5861
- var MAX_ERROR_BODY_BYTES = 64 * 1024;
5862
- function isHttpsUrl(url) {
5863
- try {
5864
- return new URL(url).protocol === "https:";
5865
- } catch {
5866
- return false;
5867
- }
5868
- }
5869
- function createHttpError(status, bodyText) {
5870
- const error = new Error(`HTTP ${status}`);
5871
- error.response = { status };
5872
- try {
5873
- error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
5874
- } catch {
5875
- }
5876
- return error;
5877
- }
5878
- function createHttpClient(options = {}) {
5879
- const { timeout = 6e4 } = options;
5880
- return {
5881
- async get(url, config) {
5882
- const controller = new AbortController();
5883
- const timer = setTimeout(() => controller.abort(), timeout);
5884
- const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
5885
- try {
5886
- const response = await fetch(url, {
5887
- signal,
5888
- headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5889
- });
5890
- if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
5891
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5892
- }
5893
- if (!response.ok) {
5894
- let text2 = "";
5895
- try {
5896
- text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
5897
- } catch {
5898
- }
5899
- throw createHttpError(response.status, text2);
5900
- }
5901
- const declaredLen = Number(response.headers.get("content-length"));
5902
- if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
5903
- throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5904
- }
5905
- const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5906
- const data = config?.responseType === "json" ? JSON.parse(text) : text;
5907
- return { data, headers: response.headers, status: response.status };
5908
- } finally {
5909
- clearTimeout(timer);
5910
- }
5911
- }
5912
- };
5913
- }
5914
- async function readBodyWithLimit(response, controller, limit) {
5915
- if (!response.body) return response.text();
5916
- const reader = response.body.getReader();
5917
- const chunks = [];
5918
- let total = 0;
5919
- try {
5920
- while (true) {
5921
- const { done, value } = await reader.read();
5922
- if (done) break;
5923
- if (value) {
5924
- total += value.byteLength;
5925
- if (total > limit) {
5926
- controller.abort();
5927
- throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5928
- }
5929
- chunks.push(value);
5930
- }
5931
- }
5932
- } finally {
5933
- reader.releaseLock();
5810
+ } finally {
5811
+ reader.releaseLock();
5934
5812
  }
5935
5813
  return Buffer.concat(chunks).toString("utf8");
5936
5814
  }
@@ -6049,10 +5927,10 @@ function getActiveSubscription() {
6049
5927
  }
6050
5928
  return subs[0];
6051
5929
  }
6052
- function requireActiveSubscription(emptyMsg = "\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605") {
5930
+ function requireActiveSubscription() {
6053
5931
  const sub = getActiveSubscription();
6054
5932
  if (!sub) {
6055
- throw new CliError(emptyMsg);
5933
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
6056
5934
  }
6057
5935
  return sub;
6058
5936
  }
@@ -6144,7 +6022,9 @@ async function downloadSubscription(url, subName = "default", signal) {
6144
6022
  async function prepareConfigForStart(mode, subName = "default") {
6145
6023
  const rawContent = readSubscriptionRawConfig(subName);
6146
6024
  if (!rawContent) {
6147
- throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605\u914D\u7F6E "${subName}"\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605`);
6025
+ throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, {
6026
+ hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${subName}`
6027
+ });
6148
6028
  }
6149
6029
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6150
6030
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
@@ -6235,1718 +6115,781 @@ async function autoUpdateStaleSubscription(options = {}) {
6235
6115
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
6236
6116
  }
6237
6117
 
6238
- // src/proxy-probe.ts
6239
- import { execFile as execFile2 } from "child_process";
6240
- import { promisify as promisify2 } from "util";
6241
- var execFileAsync = promisify2(execFile2);
6242
- var PROBE_URL = "https://www.gstatic.com/generate_204";
6243
- function isProbeSuccessStatus(code) {
6244
- return code !== null && code >= 200 && code < 300;
6245
- }
6246
- async function probeProxyConnectivity(port, timeoutMs = 2e3) {
6247
- const start = Date.now();
6248
- try {
6249
- const { stdout } = await execFileAsync(
6250
- "curl",
6251
- [
6252
- "-x",
6253
- `http://127.0.0.1:${port}`,
6254
- "-s",
6255
- "-o",
6256
- "/dev/null",
6257
- "-w",
6258
- "%{http_code}",
6259
- "--connect-timeout",
6260
- "3",
6261
- "--max-time",
6262
- String(Math.ceil(timeoutMs / 1e3)),
6263
- PROBE_URL
6264
- ],
6265
- { timeout: timeoutMs + 2e3 }
6266
- );
6267
- const code = Number.parseInt(stdout.trim(), 10);
6268
- const statusCode = Number.isFinite(code) ? code : null;
6269
- const ok = isProbeSuccessStatus(statusCode);
6270
- return {
6271
- ok,
6272
- statusCode,
6273
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6274
- durationMs: Date.now() - start
6275
- };
6276
- } catch (e) {
6277
- const err = e;
6278
- const stderr = err.stderr?.toString().trim();
6279
- const lastLine = stderr ? stderr.split("\n").pop() : void 0;
6280
- const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6281
- return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
6118
+ // src/commands/config.ts
6119
+ function cmdConfig(args = []) {
6120
+ assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
6121
+ assertPositionalCount(args, 0, 1, "mihomo config [--json] [--reveal]");
6122
+ const asJson = hasFlag(args, "-j", "--json");
6123
+ const reveal = hasFlag(args, "--reveal");
6124
+ const active = getActiveSubscription();
6125
+ if (!active) {
6126
+ throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
6127
+ }
6128
+ const rawContent = readSubscriptionRawConfig(active.name);
6129
+ if (!rawContent) {
6130
+ throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${active.name}` });
6131
+ }
6132
+ const mode = getConfigInfo()?.tun ? "tun" : "mixed";
6133
+ const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
6134
+ const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
6135
+ const shown = redacted.config;
6136
+ if (asJson) {
6137
+ console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
6138
+ return;
6139
+ }
6140
+ console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
6141
+ console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
6142
+ if (!reveal && redacted.changed) {
6143
+ console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
6144
+ }
6145
+ console.log("");
6146
+ console.log(dumpYaml(shown).trimEnd());
6147
+ if (warnings.length > 0) {
6148
+ console.log("");
6149
+ for (const w of warnings) console.log(colors.yellow(`# ${w}`));
6282
6150
  }
6283
6151
  }
6284
6152
 
6285
- // src/commands/status.ts
6286
- function connectivityHint(urgency) {
6287
- if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6288
- if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6289
- return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
6290
- }
6291
- function trafficColor(line, urgency, total, upload, download) {
6292
- if (urgency === "traffic-exhausted") return colors.red(line);
6293
- if (total && total > 0) {
6294
- const used = (upload || 0) + (download || 0);
6295
- if (used / total >= 0.9) return colors.yellow(line);
6296
- }
6297
- return line;
6153
+ // src/open.ts
6154
+ import { spawn } from "child_process";
6155
+
6156
+ // src/lifecycle.ts
6157
+ var silentSigint = false;
6158
+ function setSilentSigint(value) {
6159
+ silentSigint = value;
6298
6160
  }
6299
- function expireColor(line, urgency) {
6300
- if (urgency === "expired") return colors.red(line);
6301
- if (urgency === "expiring") return colors.yellow(line);
6302
- return line;
6161
+ function isSilentSigint() {
6162
+ return silentSigint;
6303
6163
  }
6304
- function buildStatusJson(args) {
6305
- const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
6306
- return {
6307
- version: VERSION,
6308
- running: args.running,
6309
- connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
6310
- mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
6311
- carrier: args.kind,
6312
- pid: args.pid,
6313
- kernel: getKernelVersion(),
6314
- kernelInstalled: hasKernel(),
6315
- ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
6316
- ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {}
6317
- } : {},
6318
- subscription: args.activeSub ? {
6319
- name: args.activeSub.name,
6320
- proxies: args.info?.proxies ?? 0,
6321
- proxyGroups: args.info?.proxyGroups ?? 0,
6322
- ...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
6323
- ...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
6324
- ...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
6325
- ...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
6326
- ...args.cached?.updated_at !== void 0 ? { updatedAt: args.cached.updated_at } : {},
6327
- stale: args.cached ? isSubscriptionStale(args.cached) : false,
6328
- urgency
6329
- } : null,
6330
- overwrite: {
6331
- enabled: args.overwriteEnabled,
6332
- files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6333
- // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6334
- // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6335
- applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : []
6336
- },
6337
- service: {
6338
- installed: args.service.installed,
6339
- loaded: args.service.loaded,
6340
- running: args.service.running,
6341
- disabled: args.service.disabled,
6342
- lastExitCode: args.service.lastExitCode,
6343
- lastTerminatingSignal: args.service.lastTerminatingSignal,
6344
- legacySystemInstall: args.legacy
6345
- }
6346
- };
6347
- }
6348
- async function printStatus(args = []) {
6349
- assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
6350
- assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
6351
- const asJson = hasFlag(args, "-j", "--json");
6352
- const skipProbe = hasFlag(args, "--no-probe");
6353
- const service = getServiceStatus();
6354
- const state = getRunningState(service);
6355
- const info = getConfigInfo();
6356
- const activeSub = getActiveSubscription();
6357
- const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6358
- const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6359
- const legacy = detectLegacySystemInstall();
6360
- const { running, pid, kind } = state;
6361
- let probe = null;
6362
- if (running && info?.mixedPort && !skipProbe) {
6363
- probe = await probeProxyConnectivity(info.mixedPort);
6364
- }
6365
- if (asJson) {
6366
- console.log(
6367
- JSON.stringify(
6368
- buildStatusJson({
6369
- running,
6370
- kind,
6371
- pid,
6372
- probe,
6373
- info,
6374
- activeSub,
6375
- cached,
6376
- overwriteEnabled,
6377
- // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
6378
- // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
6379
- overwriteFiles,
6380
- service,
6381
- legacy
6382
- }),
6383
- null,
6384
- 2
6385
- )
6386
- );
6387
- return;
6388
- }
6389
- const urgency = cached ? subscriptionUrgency(cached) : null;
6390
- console.log("");
6391
- let modeLabel = "";
6392
- if (info) {
6393
- const mode = info.tun ? "TUN" : "Mixed";
6394
- const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
6395
- modeLabel = colors.cyan(` (${mode}${carrier})`);
6396
- }
6397
- let statusText;
6398
- if (!running) {
6399
- statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
6400
- } else if (probe && !probe.ok) {
6401
- statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
6402
- } else {
6403
- statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
6404
- }
6405
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
6406
- if (running && probe && !probe.ok) {
6407
- console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
6408
- }
6409
- const abnormalExit = describeAbnormalExit(service);
6410
- if (!running && service.installed && !service.disabled && abnormalExit) {
6411
- console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
6412
- console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
6413
- }
6414
- const kernelVersion = getKernelVersion();
6415
- console.log(
6416
- kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
6417
- );
6418
- if (pid) {
6419
- console.log(`${colors.gray("PID: ")}${pid}`);
6420
- if (kind === "tun" && state.processInfo) {
6421
- console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
6422
- }
6423
- }
6424
- if (info) {
6425
- if (info.tun) {
6426
- const extra = info.mixedPort ? `\uFF0C\u53E6\u76D1\u542C ${info.mixedPort}` : "";
6427
- console.log(`${colors.gray("\u7AEF\u53E3: ")}TUN \u63A5\u7BA1${extra}`);
6428
- } else if (info.mixedPort) {
6429
- console.log(`${colors.gray("\u7AEF\u53E3: ")}${info.mixedPort}`);
6430
- } else {
6431
- console.log(`${colors.gray("\u7AEF\u53E3: ")}\u672A\u77E5`);
6432
- }
6433
- }
6434
- if (activeSub) {
6435
- let subLine = `${colors.gray("\u8BA2\u9605: ")}${activeSub.name}`;
6436
- if (info) {
6437
- subLine += ` (${formatProxySummary(info)})`;
6438
- }
6439
- console.log(subLine);
6440
- if (cached?.updated_at) {
6441
- const rel = formatRelativeTime(cached.updated_at) || formatDate(cached.updated_at);
6442
- if (isSubscriptionStale(cached)) {
6443
- console.log(colors.yellow(`\u66F4\u65B0: ${rel}\uFF08\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694\uFF0C\u5EFA\u8BAE mihomo sub update\uFF09`));
6444
- } else {
6445
- console.log(`${colors.gray("\u66F4\u65B0: ")}${rel}`);
6446
- }
6447
- }
6448
- const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
6449
- if (traffic) {
6450
- console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
6451
- }
6452
- if (cached?.expire !== void 0) {
6453
- console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
6454
- }
6455
- } else {
6456
- console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
6457
- }
6458
- printOverwriteLines(overwriteEnabled, overwriteFiles, activeSub);
6459
- printServiceLines(service, legacy);
6460
- console.log("");
6461
- }
6462
- function shortOverwriteName(name) {
6463
- return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6464
- }
6465
- function printOverwriteLines(enabled, files, activeSub) {
6466
- if (!enabled) {
6467
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
6468
- return;
6469
- }
6470
- const active = files.filter((f) => f.enabled && f.matched !== false);
6471
- const unmatched = files.filter((f) => f.enabled && f.matched === false);
6472
- const disabledCount = files.filter((f) => !f.enabled).length;
6473
- const suffixes = [];
6474
- if (unmatched.length > 0) suffixes.push(`${unmatched.length} \u4E2A\u4E0D\u9002\u7528`);
6475
- if (disabledCount > 0) suffixes.push(`${disabledCount} \u4E2A\u5DF2\u7981\u7528`);
6476
- const suffix = suffixes.length > 0 ? `\uFF0C${suffixes.join("\uFF0C")}` : "";
6477
- if (active.length > 0) {
6478
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
6479
- } else {
6480
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
6481
- }
6482
- for (const f of unmatched) {
6483
- const scope = f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
6484
- console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${scope}\uFF09`));
6485
- }
6486
- }
6487
- function printServiceLines(service, legacy) {
6488
- if (!service.installed && !service.loaded) {
6489
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
6490
- } else if (!service.installed) {
6491
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u5F02\u5E38")} ${colors.gray("(plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001)")}`);
6492
- console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
6493
- printAutoStart(service);
6494
- } else {
6495
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
6496
- printAutoStart(service);
6497
- }
6498
- if (legacy) {
6499
- console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
6500
- console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
6501
- }
6502
- }
6503
- function printAutoStart(service) {
6504
- const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
6505
- console.log(`${colors.gray("\u81EA\u542F: ")}${autoStart}`);
6506
- }
6507
-
6508
- // src/commands/start.ts
6509
- function resolveStartMode(args) {
6510
- const modeArg = getNonFlagArg(args, 1);
6511
- const modeToken = modeArg?.toLowerCase();
6512
- if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
6513
- throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
6514
- }
6515
- return modeToken === "tun" ? "tun" : "mixed";
6516
- }
6517
- async function cmdStart(args) {
6518
- assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
6519
- assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
6520
- const targetMode = resolveStartMode(args);
6521
- if (!hasKernel()) {
6522
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
6523
- }
6524
- const skipUpdate = hasFlag(args, "-s", "--no-update");
6525
- const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6526
- const stopEpochBefore = readStopEpoch();
6527
- const serviceBefore = getServiceStatus();
6528
- if (targetMode === "tun") {
6529
- if (detectLegacySystemInstall()) {
6530
- console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
6531
- console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
6532
- cleanupLegacyInstallOrThrow();
6533
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6534
- console.log("");
6535
- }
6536
- if (serviceBefore.loaded) {
6537
- throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6538
- hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D\u670D\u52A1"]
6539
- });
6540
- }
6541
- if (serviceBefore.installed && !serviceBefore.disabled) {
6542
- disableServiceAutoStart();
6543
- console.log(colors.gray("\u5DF2\u4E34\u65F6\u5173\u95ED\u670D\u52A1\u81EA\u542F\uFF08\u907F\u514D\u91CD\u542F\u540E\u670D\u52A1\u62FF TUN \u914D\u7F6E\u542F\u52A8\uFF09"));
6544
- console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D"));
6545
- console.log("");
6546
- }
6547
- } else if (!serviceBefore.installed) {
6548
- if (serviceBefore.loaded) {
6549
- throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
6550
- hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
6551
- });
6552
- }
6553
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
6554
- hint: ["Mixed \u6A21\u5F0F\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u9700\u5148\u5B89\u88C5:", " mihomo install", "", "\u4E34\u65F6\u4F7F\u7528\u53EF\u8D70 TUN: mihomo tun"]
6555
- });
6556
- }
6557
- const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6558
- if (!skipUpdate) {
6559
- await autoUpdateStaleSubscription({ timeout: updateTimeout });
6560
- }
6561
- let prepared;
6562
- try {
6563
- prepared = await prepareConfigForStart(targetMode, sub.name);
6564
- } catch (e) {
6565
- if (e instanceof CliError) throw e;
6566
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
6567
- }
6568
- const configInfo = commitPreparedConfig(prepared);
6569
- const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6570
- console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6571
- try {
6572
- const pid = await launchOrRestart(targetMode, stopEpochBefore);
6573
- console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
6574
- } catch (e) {
6575
- if (e instanceof CliError) throw e;
6576
- const lines = e.message.split("\n");
6577
- throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
6578
- }
6579
- await printStatus();
6580
- if (targetMode === "mixed") {
6581
- console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${getPorts().mixed}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
6582
- console.log("");
6583
- }
6584
- }
6585
-
6586
- // src/commands/shared.ts
6587
- var validatedTables = /* @__PURE__ */ new WeakSet();
6588
- function assertUniqueTokens(table) {
6589
- if (validatedTables.has(table)) return;
6590
- const owner = /* @__PURE__ */ new Map();
6591
- for (const cmd of table) {
6592
- for (const token of [cmd.name, ...cmd.aliases ?? []]) {
6593
- const prev = owner.get(token);
6594
- if (prev !== void 0) {
6595
- throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
6596
- }
6597
- owner.set(token, cmd.name);
6598
- }
6599
- }
6600
- validatedTables.add(table);
6601
- }
6602
- async function dispatchSubcommand(args, table, options) {
6603
- assertUniqueTokens(table);
6604
- const action = args[1];
6605
- if (action) {
6606
- const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
6607
- if (cmd) return cmd.handler(args);
6608
- return options.onUnknown(action);
6609
- }
6610
- return options.fallback(args);
6611
- }
6612
- async function confirmPrompt(question) {
6613
- if (!process.stdin.isTTY) return false;
6614
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
6615
- const answer = await new Promise((resolve) => {
6616
- rl.question(`${question} (y/N) `, (a) => {
6617
- rl.close();
6618
- resolve(a);
6619
- });
6620
- });
6621
- return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6622
- }
6623
- async function confirmOrThrow(question, opts) {
6624
- if (!process.stdin.isTTY) {
6625
- throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6626
- }
6627
- return confirmPrompt(question);
6628
- }
6629
- async function restartToApply(args) {
6630
- const currentMode = restartModeOnChange();
6631
- if (!currentMode) return false;
6632
- console.log("");
6633
- await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6634
- return true;
6635
- }
6636
-
6637
- // src/commands/directory.ts
6638
- function openDirectory(args) {
6639
- assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
6640
- const target = args[2];
6641
- if (target === void 0 || target === "root") {
6642
- console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
6643
- openUrl(USER_DATA_DIR);
6644
- return;
6645
- }
6646
- const key = target.toLowerCase();
6647
- const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
6648
- if (targetInfo) {
6649
- const targetPath = targetInfo.path || USER_DATA_DIR;
6650
- console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetPath})`);
6651
- openUrl(targetPath);
6652
- return;
6653
- }
6654
- const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
6655
- for (const [k, val] of Object.entries(DIRECTORY_TARGETS)) {
6656
- if (k !== "root") {
6657
- hint.push(` ${k.padEnd(14)}${val.label}`);
6658
- }
6659
- }
6660
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u76EE\u6807 "${target}"`, { hint });
6661
- }
6662
- function printDirectoryInfo() {
6663
- const entries = Object.entries(DIRECTORY_TARGETS).filter(([key]) => key !== "root");
6664
- const pathWidth = Math.max(...entries.map(([, val]) => val.path.replace(USER_DATA_DIR, ".").length));
6665
- console.log("");
6666
- console.log(`\u6570\u636E\u76EE\u5F55: ${USER_DATA_DIR}`);
6667
- console.log("");
6668
- for (const [key, val] of entries) {
6669
- const rel = val.path.replace(USER_DATA_DIR, ".");
6670
- console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
6671
- }
6672
- console.log("");
6673
- console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
6674
- console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6675
- console.log("");
6676
- }
6677
- var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
6678
- async function cmdDirectory(args) {
6679
- assertKnownFlags(args.slice(1), [], "dir");
6680
- await dispatchSubcommand(args, SUBCOMMANDS, {
6681
- fallback: printDirectoryInfo,
6682
- onUnknown: (action) => {
6683
- if (action.startsWith("-")) {
6684
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
6685
- label: "\u53C2\u6570\u9519\u8BEF",
6686
- hint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo dir open [root|subs|logs|data|runtime|kernel]"]
6687
- });
6688
- }
6689
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6690
- const suggestion = suggestSimilar(action, names);
6691
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6692
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
6693
- });
6694
- }
6695
- });
6696
- }
6697
-
6698
- // src/commands/overwrite.ts
6699
- import path8 from "path";
6700
- function printOverwriteList() {
6701
- const info = listOverwriteFile();
6702
- const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6703
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6704
- console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6705
- console.log("");
6706
- if (info.files.length === 0) {
6707
- console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6708
- console.log("");
6709
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6710
- console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6711
- console.log("");
6712
- } else {
6713
- const disabledCount = info.files.filter((f) => !f.enabled).length;
6714
- const countText = disabledCount > 0 ? `${info.files.length} \u4E2A\uFF0C${info.files.length - disabledCount} \u4E2A\u672A\u7981\u7528\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D` : `${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D`;
6715
- console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${countText}):`);
6716
- console.log("");
6717
- info.files.forEach((f, i) => {
6718
- const num = i < 10 ? ` ${i}` : `${i}`;
6719
- const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
6720
- console.log(` ${num}. ${f.name}${mark}`);
6721
- if (f.scope) {
6722
- console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6723
- }
6724
- if (f.keys.length > 0) {
6725
- console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6726
- }
6727
- });
6728
- console.log("");
6729
- }
6730
- console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6731
- console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6732
- console.log("\u505C\u7528\u5355\u4E2A\u6587\u4EF6: \u5728\u8BE5\u6587\u4EF6\u9876\u90E8\u5199 enabled: false");
6733
- console.log("");
6734
- }
6735
- async function setOverwrite(enabled, args) {
6736
- assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
6737
- assertRestartOptionValues(args);
6738
- if (isOverwriteEnabled() === enabled) {
6739
- console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
6740
- console.log("");
6741
- printOverwriteList();
6742
- return;
6743
- }
6744
- setOverwriteEnabled(enabled);
6745
- console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
6746
- if (await restartToApply(args)) return;
6747
- console.log("");
6748
- printOverwriteList();
6749
- }
6750
- var SUBCOMMANDS2 = [
6751
- { name: "on", aliases: ["enable"], description: "\u542F\u7528\u8986\u5199", handler: (args) => setOverwrite(true, args) },
6752
- { name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
6753
- ];
6754
- async function cmdOverwrite(args) {
6755
- assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
6756
- await dispatchSubcommand(args, SUBCOMMANDS2, {
6757
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6758
- fallback: () => {
6759
- console.log("");
6760
- printOverwriteList();
6761
- },
6762
- onUnknown: (action) => {
6763
- if (action.startsWith("-")) {
6764
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
6765
- label: "\u53C2\u6570\u9519\u8BEF",
6766
- hint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo ow on|off [-s] [-u ms]"]
6767
- });
6768
- }
6769
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6770
- const suggestion = suggestSimilar(action, names);
6771
- throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6772
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6773
- });
6774
- }
6775
- });
6776
- }
6777
-
6778
- // src/commands/reset.ts
6779
- import fs11 from "fs";
6780
-
6781
- // src/process-stop.ts
6782
- import { spawnSync as spawnSync5 } from "child_process";
6783
- import fs10 from "fs";
6784
- var PROCESS_WAIT_ATTEMPTS = 50;
6785
- var PROCESS_WAIT_INTERVAL = 100;
6786
- var BATCH_KILL_THRESHOLD = 3;
6787
- function clearRuntime() {
6788
- if (fs10.existsSync(DIRS.runtime)) {
6789
- rmrf(DIRS.runtime);
6790
- }
6791
- ensureDirs();
6792
- }
6793
- function clearPid() {
6794
- if (!fs10.existsSync(PATHS.pidFile)) return;
6795
- if (isPidFileOwnedByRoot()) {
6796
- try {
6797
- spawnSync5("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
6798
- } catch {
6799
- }
6800
- } else {
6801
- try {
6802
- fs10.unlinkSync(PATHS.pidFile);
6803
- } catch {
6804
- }
6805
- }
6806
- }
6807
- function killProcess(pid) {
6808
- try {
6809
- process.kill(pid, "SIGKILL");
6810
- return true;
6811
- } catch {
6812
- return false;
6813
- }
6814
- }
6815
- function killAllMihomo(forceSudo = false) {
6816
- const pattern = MAIN_INSTANCE_PATTERN;
6817
- const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
6818
- const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
6164
+
6165
+ // src/open.ts
6166
+ function openUrl(url) {
6819
6167
  try {
6820
- const result = spawnSync5(argv[0], argv[1], options);
6821
- if (result.error) return false;
6822
- return result.status === 0 || result.status === 1;
6168
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
6169
+ child.unref();
6170
+ child.on("error", () => {
6171
+ });
6823
6172
  } catch {
6824
- return false;
6825
6173
  }
6826
6174
  }
6827
- async function cleanupAll(forceSudo = false) {
6828
- const pids = getMihomoPids();
6829
- if (pids.length === 0) {
6830
- clearPid();
6831
- return { killed: 0, failed: 0, remaining: [] };
6832
- }
6833
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
6834
- const needsSudo = forceSudo || hasRootProcess;
6835
- let killedCount = 0;
6836
- const failedPids = [];
6837
- if (needsSudo) {
6838
- const success = killAllMihomo(true);
6839
- if (success) {
6840
- killedCount = pids.length;
6841
- } else {
6842
- failedPids.push(...pids);
6843
- }
6844
- } else {
6845
- if (pids.length > BATCH_KILL_THRESHOLD) {
6846
- if (killAllMihomo(false)) {
6847
- killedCount = pids.length;
6848
- } else {
6849
- failedPids.push(...pids);
6850
- }
6851
- } else {
6852
- for (const pid of pids) {
6853
- if (killProcess(pid)) {
6854
- killedCount++;
6855
- } else {
6856
- failedPids.push(pid);
6857
- }
6858
- }
6859
- }
6860
- }
6861
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6862
- if (getMihomoPids().length === 0) break;
6863
- await sleep(PROCESS_WAIT_INTERVAL);
6864
- }
6865
- clearPid();
6866
- return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
6175
+ function openLogFile(logPath) {
6176
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
6177
+ openUrl(logPath);
6867
6178
  }
6868
- async function stop(forceSudo = false) {
6869
- const allPids = getMihomoPids();
6870
- if (allPids.length === 0) {
6871
- clearPid();
6872
- clearRuntime();
6873
- return { success: true, notRunning: true };
6874
- }
6875
- const result = await cleanupAll(forceSudo);
6876
- const remaining = getMihomoPids();
6877
- if (remaining.length > 0) {
6878
- console.log("");
6879
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6880
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6881
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
6882
- console.log("");
6883
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
6179
+ function viewLogWithTail(logPath, options) {
6180
+ const follow = options?.follow;
6181
+ const lines = options?.lines || 100;
6182
+ console.log(`\u65E5\u5FD7: ${logPath}`);
6183
+ if (follow) {
6184
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6185
+ } else {
6186
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6187
+ `);
6884
6188
  }
6885
- clearRuntime();
6886
- return { success: true, killed: result.killed };
6189
+ const tailArgs = [];
6190
+ if (follow) tailArgs.push("-f");
6191
+ tailArgs.push("-n", lines.toString());
6192
+ tailArgs.push(logPath);
6193
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
6194
+ if (follow) setSilentSigint(true);
6195
+ tail.on("close", (code) => process.exit(code ?? 0));
6196
+ tail.on("error", (e) => {
6197
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6198
+ process.exit(1);
6199
+ });
6887
6200
  }
6888
6201
 
6889
- // src/commands/reset.ts
6890
- var RESET_TARGETS = [
6891
- { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
6892
- { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
6893
- { id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
6894
- { id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
6895
- {
6896
- id: "overwrites",
6897
- aliases: ["overwrite", "overwrites", "ow"],
6898
- label: "\u8986\u5199",
6899
- needsStop: false,
6900
- preserveOnBare: true,
6901
- paths: () => fs11.existsSync(USER_DATA_DIR) ? fs11.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
6902
- },
6903
- {
6904
- id: "settings",
6905
- aliases: ["setting", "settings", "config"],
6906
- label: "\u8BBE\u7F6E",
6907
- needsStop: false,
6908
- preserveOnBare: true,
6909
- // 损坏备份也包含订阅凭据,需要一起删除
6910
- paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
6911
- },
6912
- { id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
6913
- { id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
6914
- ];
6915
- function resolveResetTargets(names) {
6916
- const matched = /* @__PURE__ */ new Set();
6917
- for (const name of names) {
6918
- const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
6919
- if (!target) {
6920
- throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
6921
- }
6922
- matched.add(target);
6923
- }
6924
- return [...matched];
6925
- }
6926
- async function cmdReset(args) {
6927
- assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
6928
- const names = args.slice(1).filter((a) => !a.startsWith("-"));
6929
- const namedTargets = resolveResetTargets(names);
6930
- const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
6931
- const ids = new Set(targets.map((t) => t.id));
6932
- const needsStop = targets.some((t) => t.needsStop);
6933
- const serviceTargeted = ids.has("service");
6934
- const service = getServiceStatus();
6935
- const serviceActive = service.installed || service.loaded;
6936
- const legacy = detectLegacySystemInstall();
6937
- if (targets.length === 1) {
6938
- if (serviceTargeted && !serviceActive && !legacy) {
6939
- console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
6940
- return;
6941
- }
6942
- }
6943
- if (ids.has("kernel") && getMihomoPids().length > 0) {
6944
- console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
6945
- }
6946
- if (serviceTargeted && serviceActive) {
6947
- console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
6948
- } else if (needsStop && serviceActive) {
6949
- console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
6950
- }
6951
- if ((needsStop || serviceTargeted) && legacy) {
6952
- console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
6953
- }
6954
- console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6955
- if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
6956
- nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
6957
- hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
6958
- })) {
6959
- console.log("\u5DF2\u53D6\u6D88");
6960
- return;
6961
- }
6962
- if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
6963
- if (serviceActive) {
6964
- if (serviceTargeted) await uninstallService();
6965
- else if (needsStop) await stopService();
6966
- }
6967
- if (needsStop) {
6968
- const cleanup = await cleanupAll();
6969
- if (cleanup.remaining.length > 0) {
6970
- throw new CliError(cleanup.remaining.join(", "), {
6971
- label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
6972
- hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
6973
- });
6974
- }
6975
- recordServiceStopped();
6976
- }
6977
- const deleted = /* @__PURE__ */ new Set();
6978
- for (const target of targets) {
6979
- let hadContent = target.id === "service" && (serviceActive || legacy);
6980
- for (const filePath of target.paths()) {
6981
- if (!fs11.existsSync(filePath)) continue;
6982
- try {
6983
- rmrf(filePath);
6984
- } catch (e) {
6985
- throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
6986
- }
6987
- hadContent = true;
6988
- }
6989
- if (hadContent) deleted.add(target.id);
6990
- }
6991
- if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
6992
- updateSettings((settings) => {
6993
- const patch = {};
6994
- if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
6995
- patch.subscriptions = void 0;
6996
- patch.active_subscription = void 0;
6997
- deleted.add("subs");
6998
- }
6999
- if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
7000
- patch.overwrite_enabled = void 0;
7001
- deleted.add("overwrites");
7002
- }
7003
- return patch;
7004
- });
7005
- }
7006
- if (ids.has("kernel")) clearKernelVersionCache();
7007
- ensureDirs();
7008
- const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
7009
- console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
6202
+ // src/commands/shared.ts
6203
+ import readline from "readline";
6204
+
6205
+ // src/process-start.ts
6206
+ import fs9 from "fs";
6207
+ var TUN_MODE_POST_WAIT_MS = 500;
6208
+ function buildTunLaunchScript() {
6209
+ const binary = shellQuote(PATHS.mihomoBinary);
6210
+ const configFile = shellQuote(PATHS.configFile);
6211
+ const logFile = shellQuote(PATHS.logFile);
6212
+ const pidFile = shellQuote(PATHS.pidFile);
6213
+ const dataDir = shellQuote(DIRS.data);
6214
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
6215
+ return `#!/bin/bash
6216
+ BINARY=${binary}
6217
+ CONFIG_FILE=${configFile}
6218
+ LOG_FILE=${logFile}
6219
+ PID_FILE=${pidFile}
6220
+ DATA_DIR=${dataDir}
6221
+ KILL_PATTERN=${killPattern}
6222
+
6223
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
6224
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
6225
+ sleep 0.2
6226
+ rm -f "\${PID_FILE}" 2>/dev/null || true
6227
+
6228
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
6229
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
6230
+
6231
+ # \u542F\u52A8
6232
+ cd /tmp
6233
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
6234
+ NEW_PID=$!
6235
+ echo \${NEW_PID} > "\${PID_FILE}"
6236
+
6237
+ # \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
6238
+ #\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
6239
+ # 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
6240
+ is_alive() {
6241
+ local stat
6242
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
6243
+ case "\${stat}" in
6244
+ Z*|'') return 1 ;;
6245
+ *) return 0 ;;
6246
+ esac
7010
6247
  }
7011
6248
 
7012
- // src/commands/subscription.ts
7013
- import { spawnSync as spawnSync6 } from "child_process";
7014
- function printRestartHintIfRunning() {
7015
- const state = getRunningState();
7016
- if (state.running) {
7017
- const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
7018
- console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`));
7019
- console.log("");
7020
- }
7021
- }
7022
- function printSubscriptionList() {
7023
- const subs = getSubscriptionsWithCache();
7024
- if (subs.length === 0) {
7025
- console.log("\u6CA1\u6709\u8BA2\u9605");
7026
- console.log("");
7027
- console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
7028
- console.log("");
7029
- return;
7030
- }
7031
- const activeSub = getActiveSubscription();
7032
- console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
7033
- subs.forEach((s, i) => {
7034
- const rel = formatRelativeTime(s.updated_at);
7035
- const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
7036
- const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
7037
- const interval = resolveUpdateInterval(s.update_interval);
7038
- console.log(` ${i + 1}. ${s.name}${defaultMark}`);
7039
- console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
7040
- if (s.username) {
7041
- console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
7042
- }
7043
- const traffic = formatTraffic(s.upload, s.download, s.total);
7044
- if (traffic) {
7045
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
7046
- }
7047
- if (s.expire !== void 0) {
7048
- console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
7049
- }
7050
- if (s.web_page_url) {
7051
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
7052
- }
7053
- });
7054
- console.log("");
7055
- console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
7056
- console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
7057
- console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
7058
- console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
7059
- console.log("");
6249
+ # \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
6250
+ # \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
6251
+ # \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
6252
+ i=0
6253
+ while [ $i -lt 12 ]; do
6254
+ sleep 0.1
6255
+ is_alive \${NEW_PID} || break
6256
+ i=$((i+1))
6257
+ done
6258
+ if is_alive \${NEW_PID}; then
6259
+ exit 0
6260
+ fi
6261
+
6262
+ # \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
6263
+ rm -f "\${PID_FILE}" 2>/dev/null || true
6264
+ echo "TUN \u542F\u52A8\u5931\u8D25"
6265
+ echo ""
6266
+ echo "--- \u65E5\u5FD7 ---"
6267
+ tail -25 "\${LOG_FILE}" 2>/dev/null
6268
+ exit 2
6269
+ `;
7060
6270
  }
7061
- function assertNotFlagLike(name, usage) {
7062
- if (name.startsWith("-")) {
7063
- throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
7064
- label: "\u53C2\u6570\u9519\u8BEF",
7065
- hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
7066
- });
6271
+ async function startTun() {
6272
+ ensureDirs();
6273
+ rotateAndCleanupLogs();
6274
+ if (!fs9.existsSync(PATHS.mihomoBinary)) {
6275
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
7067
6276
  }
7068
- }
7069
- function readUrlFromClipboard() {
7070
- if (!process.stdin.isTTY) return null;
7071
- try {
7072
- const r = spawnSync6("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
7073
- if (r.status !== 0) return null;
7074
- const text = (r.stdout || "").trim();
7075
- return isValidHttpUrl(text) ? text : null;
7076
- } catch {
7077
- return null;
6277
+ if (!fs9.existsSync(PATHS.configFile)) {
6278
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
7078
6279
  }
7079
- }
7080
- async function subAdd(args) {
7081
- assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
7082
- let url = args[2]?.trim();
7083
- const name = args[3] || "default";
7084
- if (!url) {
7085
- const clipped = readUrlFromClipboard();
7086
- if (clipped) {
7087
- console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
7088
- console.log(` ${maskUrl(clipped)}`);
7089
- if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
7090
- console.log("\u5DF2\u53D6\u6D88");
7091
- return;
6280
+ const logFile = PATHS.logFile;
6281
+ if (fs9.existsSync(logFile)) {
6282
+ try {
6283
+ fs9.accessSync(logFile, fs9.constants.W_OK);
6284
+ } catch {
6285
+ try {
6286
+ fs9.unlinkSync(logFile);
6287
+ } catch {
7092
6288
  }
7093
- url = clipped;
7094
- } else if (process.stdin.isTTY) {
7095
- throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
7096
- hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
7097
- });
7098
- } else {
7099
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
7100
6289
  }
7101
6290
  }
7102
- if (!isValidHttpUrl(url)) {
7103
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
7104
- }
7105
- assertNotFlagLike(name, "mihomo sub add <url> [name]");
7106
- console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
7107
- addSubscription(url, name);
7108
- try {
7109
- const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
7110
- setDefaultSubscription(name);
7111
- console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
7112
- } catch (e) {
7113
- removeSubscription(name);
7114
- if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
7115
- throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
7116
- }
7117
- console.log("");
7118
- printRestartHintIfRunning();
7119
- printSubscriptionList();
7120
- }
7121
- async function subUpdate(args) {
7122
- assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
7123
- const nameArg = getNonFlagArg(args, 2);
7124
- const subs = getSubscriptions();
7125
- if (subs.length === 0) {
7126
- throw new CliError("\u6CA1\u6709\u8BA2\u9605");
7127
- }
7128
- if (nameArg === "") {
7129
- throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo sub update <\u540D\u79F0>`] });
7130
- }
7131
- if (nameArg === null) {
7132
- console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
7133
- const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
7134
- let ok = 0;
7135
- for (const r of results) {
7136
- if (r.success) ok++;
7137
- printUpdateResult(r);
6291
+ const staleState = checkStaleState();
6292
+ if (staleState.needsCleanup) {
6293
+ if (staleState.allPids.length > 0) {
6294
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
6295
+ } else {
6296
+ console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
7138
6297
  }
7139
- if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
7140
- console.log("");
7141
- printRestartHintIfRunning();
7142
- printSubscriptionList();
7143
- return;
7144
- }
7145
- const target = resolveSubscription(subs, nameArg);
7146
- console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
7147
- const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
7148
- if (!result.success) {
7149
- throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
7150
- }
7151
- console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
7152
- console.log("");
7153
- printRestartHintIfRunning();
7154
- printSubscriptionList();
7155
- }
7156
- async function subUse(args) {
7157
- assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
7158
- assertRestartOptionValues(args);
7159
- const name = getNonFlagArg(args, 2);
7160
- const subs = getSubscriptions();
7161
- if (subs.length === 0) {
7162
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
7163
6298
  }
7164
- if (!name) {
7165
- throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
7166
- hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
6299
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
6300
+ runSudoScript(buildTunLaunchScript(), {
6301
+ action: "TUN \u542F\u52A8",
6302
+ file: "launch-tun.sh",
6303
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
6304
+ });
6305
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
6306
+ const finalPid = getPid();
6307
+ if (!finalPid || !isRunning()) {
6308
+ const tail = readLogTail();
6309
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
6310
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
7167
6311
  });
7168
6312
  }
7169
- const target = resolveSubscription(subs, name);
7170
- const currentDefault = getActiveSubscription();
7171
- const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
7172
- if (isAlreadyDefault) {
7173
- console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
7174
- console.log("");
7175
- printSubscriptionList();
7176
- return;
6313
+ return { success: true, pid: finalPid, mode: "tun" };
6314
+ }
6315
+
6316
+ // src/runtime.ts
6317
+ function getRuntimeMode() {
6318
+ if (isServiceInstalled()) return "mixed";
6319
+ return getConfigInfo()?.tun ? "tun" : "mixed";
6320
+ }
6321
+ function getRunningState(serviceStatus) {
6322
+ const service = serviceStatus ?? getServiceStatus();
6323
+ if (service.running) {
6324
+ return { running: true, pid: service.pid, kind: "service", processInfo: null };
7177
6325
  }
7178
- const success = setDefaultSubscription(target.name);
7179
- if (!success) {
7180
- throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
6326
+ const status = getStatus();
6327
+ if (status.running) {
6328
+ return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
7181
6329
  }
7182
- console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
7183
- if (await restartToApply(args)) return;
7184
- console.log("");
7185
- printSubscriptionList();
6330
+ return { running: false, pid: null, kind: null, processInfo: null };
7186
6331
  }
7187
- async function subRemove(args) {
7188
- assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
7189
- const name = getNonFlagArg(args, 2);
7190
- const subs = getSubscriptions();
7191
- if (!name) {
7192
- throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
7193
- hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
7194
- });
7195
- }
7196
- const target = resolveSubscription(subs, name);
7197
- const isExact = target.name === name;
7198
- const skipConfirm = hasFlag(args, "-y", "--yes");
7199
- if (!isExact && !skipConfirm) {
7200
- console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7201
- if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7202
- nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7203
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7204
- })) {
7205
- console.log("\u5DF2\u53D6\u6D88");
7206
- return;
7207
- }
6332
+ function restartModeFor(state, fallbackMode) {
6333
+ return state.kind === "tun" ? "tun" : fallbackMode;
6334
+ }
6335
+ function restartModeOnChange() {
6336
+ const state = getRunningState();
6337
+ return state.running ? restartModeFor(state, getRuntimeMode()) : null;
6338
+ }
6339
+ async function launchOrRestart(mode, stopEpochBefore) {
6340
+ if (mode === "tun") {
6341
+ const result = await startTun();
6342
+ return result.pid;
7208
6343
  }
7209
- const switchedTo = removeSubscription(target.name);
7210
- console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
7211
- if (switchedTo) {
7212
- console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
6344
+ const status = getServiceStatus();
6345
+ let hotReloaded = false;
6346
+ let started;
6347
+ if (status.running && !status.disabled) {
6348
+ ({ hotReloaded, started } = await restartService(stopEpochBefore));
6349
+ } else {
6350
+ ({ started } = await startService(stopEpochBefore));
6351
+ }
6352
+ if (!started) throw cancelledByConcurrentStop();
6353
+ if (hotReloaded) return getServiceStatus().pid;
6354
+ try {
6355
+ return await assertServiceHealthy();
6356
+ } catch (e) {
6357
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) throw cancelledByConcurrentStop();
6358
+ throw e;
7213
6359
  }
7214
- console.log("");
7215
- printSubscriptionList();
7216
6360
  }
7217
- var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
7218
- var REMOVE_FLAGS = ["-y", "--yes"];
7219
- function withKnownFlags(usage, known, handler) {
7220
- return async (args) => {
7221
- assertKnownFlags(args, known, usage);
7222
- await handler(args);
7223
- };
6361
+ function cancelledByConcurrentStop() {
6362
+ return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
6363
+ label: "\u542F\u52A8\u5931\u8D25",
6364
+ hint: [
6365
+ "\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
6366
+ "",
6367
+ "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
6368
+ ]
6369
+ });
7224
6370
  }
7225
- var SUBCOMMANDS3 = [
7226
- { name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
7227
- { name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: withKnownFlags("sub update [name]", [], subUpdate) },
7228
- { name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
7229
- { name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
7230
- ];
7231
- async function cmdSubscription(args) {
7232
- await dispatchSubcommand(args, SUBCOMMANDS3, {
7233
- // 无子命令 → 列表;未知子命令 → 报错
7234
- fallback: printSubscriptionList,
7235
- onUnknown: (action) => {
7236
- if (action.startsWith("-")) {
7237
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
7238
- label: "\u53C2\u6570\u9519\u8BEF",
7239
- hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
7240
- });
7241
- }
7242
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7243
- const suggestion = suggestSimilar(action, names);
7244
- throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7245
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
7246
- });
7247
- }
6371
+ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6372
+ const health = await waitServiceHealthy();
6373
+ if (health.healthy) return health.pid;
6374
+ const tail = readLogTail();
6375
+ const cause = describeExitCause(health.exitCode, health.terminatingSignal);
6376
+ const reason = health.crashed ? `\u5185\u6838\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08${cause ?? "\u6B7B\u56E0\u672A\u8BB0\u5F55"}\uFF09` : "\u5185\u6838\u672A\u80FD\u8FDB\u5165\u8FD0\u884C\u72B6\u6001";
6377
+ throw new CliError(reason, {
6378
+ label,
6379
+ hint: [
6380
+ ...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo stop\u3002"] : [],
6381
+ ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
6382
+ "",
6383
+ "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"
6384
+ ]
7248
6385
  });
7249
6386
  }
7250
6387
 
7251
- // src/commands/completion.ts
7252
- function commandWords(commands) {
7253
- return commands.flatMap((c) => [
7254
- { word: c.name, desc: c.usage[0]?.description ?? "" },
7255
- ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))
7256
- ]);
7257
- }
7258
- function subWords(subs) {
7259
- return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
7260
- }
7261
- function subGroups(commands) {
7262
- const groupOf = (name, subs) => {
7263
- const cmd = commands.find((c) => c.name === name);
7264
- return { tokens: cmd ? [cmd.name, ...cmd.aliases] : [name], words: subWords(subs) };
7265
- };
7266
- return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
7267
- }
7268
- var DIR_TARGETS = Object.keys(DIRECTORY_TARGETS);
7269
- var UI_NAMES = Object.keys(UI_URLS);
7270
- var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
7271
- var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
7272
- var SHELLS = ["zsh", "bash", "fish"];
7273
- function zshSingleQuote(s) {
7274
- return s.replace(/'/g, "'\\''");
7275
- }
7276
- function buildZsh(commands, groups) {
7277
- const lines = [
7278
- "#compdef mihomo mhm mh mihomo-cli",
7279
- "",
7280
- '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install zsh\uFF0C\u6216 eval "$(mihomo completion zsh)"\uFF09',
7281
- "",
7282
- "_mihomo() {",
7283
- " local -a commands subcmds",
7284
- " commands=(",
7285
- ...commandWords(commands).map((c) => ` '${c.word}:${zshSingleQuote(c.desc)}'`),
7286
- " )",
7287
- "",
7288
- " _arguments -C \\",
7289
- " '1: :->cmd' \\",
7290
- " '*::arg:->args'",
7291
- "",
7292
- " case $state in",
7293
- " cmd)",
7294
- " _describe 'command' commands",
7295
- " ;;",
7296
- " args)",
7297
- " case ${words[1]} in"
7298
- ];
7299
- for (const group of groups) {
7300
- const aliases = group.tokens.join("|");
7301
- const isDirectory = group.tokens.includes("directory");
7302
- lines.push(` ${aliases})`);
7303
- lines.push(" subcmds=(");
7304
- for (const s of group.words) lines.push(` '${s.word}:${zshSingleQuote(s.desc)}'`);
7305
- lines.push(" )");
7306
- lines.push(" if (( CURRENT == 2 )); then");
7307
- lines.push(" _describe 'subcommand' subcmds");
7308
- if (isDirectory) {
7309
- lines.push(" elif (( CURRENT == 3 )) && [[ ${words[2]} == open ]]; then");
7310
- lines.push(` _values 'target' ${DIR_TARGETS.join(" ")}`);
7311
- lines.push(" else");
7312
- lines.push(" _files");
7313
- } else {
7314
- lines.push(" else");
7315
- lines.push(" _files");
7316
- }
7317
- lines.push(" fi");
7318
- lines.push(" ;;");
7319
- }
7320
- lines.push(
7321
- " logs)",
7322
- " _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
7323
- " ;;",
7324
- " ui)",
7325
- ` _values 'ui' ${UI_NAMES.join(" ")}`,
7326
- " ;;",
7327
- " kernel)",
7328
- ` _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(${MIRROR_NAMES.join(" ")})'`,
7329
- " ;;",
7330
- " reset)",
7331
- ` _values 'target' ${RESET_TARGET_NAMES.join(" ")}`,
7332
- " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--yes[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
7333
- " ;;",
7334
- " completion)",
7335
- " if (( CURRENT == 2 )); then",
7336
- ` _values 'action' install uninstall ${SHELLS.join(" ")}`,
7337
- " elif (( CURRENT == 3 )) && [[ ${words[2]} == (install|uninstall) ]]; then",
7338
- ` _values 'shell' ${SHELLS.join(" ")}`,
7339
- " fi",
7340
- " ;;",
7341
- " *)",
7342
- " _files",
7343
- " ;;",
7344
- " esac",
7345
- " ;;",
7346
- " esac",
7347
- "}",
7348
- "",
7349
- // 结尾必须是 compdef 注册,**不能是裸调用 `_mihomo "$@"`**。
7350
- //
7351
- // 两条安装路径对结尾行的要求不同,而裸调用只满足其中一条:
7352
- // - 放进 fpath(`completion install zsh`):compinit 按 `#compdef` 首行自动注册,
7353
- // 函数体被 autoload,结尾写什么都行——两种写法实测都能注册全部四个别名
7354
- // - `eval "$(mihomo completion zsh)"`(README 与下方 CLI 提示都推荐):`#compdef`
7355
- // 只是条注释、不起作用,而裸调用会在补全上下文之外执行 `_arguments`,实测报
7356
- // `_arguments:comparguments:327: can only be called from completion function`,
7357
- // 且 `_comps[mihomo]` 前后都是 0 —— 补全完全没注册,eval 却返回 0。
7358
- // 用户照文档做了、看到没报错(错误在 stderr 一闪而过)、补全就是不工作。
7359
- //
7360
- // compdef 同时满足两条:实测 eval 后四个别名 `_comps` 全部为 1,fpath 安装不受影响。
7361
- "compdef _mihomo mihomo mhm mh mihomo-cli"
7362
- );
7363
- return lines.join("\n");
7364
- }
7365
- function buildBash(commands, groups) {
7366
- const top = commandWords(commands).map((c) => c.word).join(" ");
7367
- const subCase = groups.map((group) => {
7368
- const aliases = group.tokens.join("|");
7369
- const words = group.words.map((w) => w.word).join(" ");
7370
- if (group.tokens[0] === "directory") {
7371
- return ` ${aliases})
7372
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7373
- COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7374
- elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
7375
- COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
7376
- fi
7377
- ;;`;
7378
- }
7379
- return ` ${aliases})
7380
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7381
- COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7382
- fi
7383
- ;;`;
7384
- }).join("\n");
7385
- return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install bash\uFF0C\u6216 eval "$(mihomo completion bash)"\uFF09
7386
-
7387
- _mihomo_completions() {
7388
- local cur prev
7389
- COMPREPLY=()
7390
- cur="\${COMP_WORDS[COMP_CWORD]}"
7391
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
7392
-
7393
- if [[ \${COMP_CWORD} -eq 1 ]]; then
7394
- COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
7395
- return 0
7396
- fi
7397
-
7398
- case "\${COMP_WORDS[1]}" in
7399
- ${subCase}
7400
- logs)
7401
- COMPREPLY=( $(compgen -W "-f -n -o --lines --follow --open" -- "\${cur}") )
7402
- ;;
7403
- ui)
7404
- COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
7405
- ;;
7406
- kernel)
7407
- if [[ "\${prev}" == "--mirror" ]]; then
7408
- COMPREPLY=( $(compgen -W "${MIRROR_NAMES.join(" ")}" -- "\${cur}") )
7409
- else
7410
- COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
7411
- fi
7412
- ;;
7413
- reset)
7414
- COMPREPLY=( $(compgen -W "${RESET_TARGET_NAMES.join(" ")} --full -y --yes" -- "\${cur}") )
7415
- ;;
7416
- completion)
7417
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7418
- COMPREPLY=( $(compgen -W "install uninstall ${SHELLS.join(" ")}" -- "\${cur}") )
7419
- elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install || "\${COMP_WORDS[2]}" == uninstall ]]; then
7420
- COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
7421
- fi
7422
- ;;
7423
- esac
6388
+ // src/proxy-probe.ts
6389
+ import { execFile as execFile2 } from "child_process";
6390
+ import { promisify as promisify2 } from "util";
6391
+ var execFileAsync = promisify2(execFile2);
6392
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
6393
+ function isProbeSuccessStatus(code) {
6394
+ return code !== null && code >= 200 && code < 300;
7424
6395
  }
7425
- complete -F _mihomo_completions mihomo mhm mh mihomo-cli
7426
- `;
6396
+ var PROBE_TIMEOUT_MS = 2e3;
6397
+ async function probeProxyConnectivity(port) {
6398
+ const start = Date.now();
6399
+ try {
6400
+ const { stdout } = await execFileAsync(
6401
+ "curl",
6402
+ [
6403
+ "-x",
6404
+ `http://127.0.0.1:${port}`,
6405
+ "-s",
6406
+ "-o",
6407
+ "/dev/null",
6408
+ "-w",
6409
+ "%{http_code}",
6410
+ "--connect-timeout",
6411
+ "3",
6412
+ "--max-time",
6413
+ String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)),
6414
+ PROBE_URL
6415
+ ],
6416
+ { timeout: PROBE_TIMEOUT_MS + 2e3 }
6417
+ );
6418
+ const code = Number.parseInt(stdout.trim(), 10);
6419
+ const statusCode = Number.isFinite(code) ? code : null;
6420
+ const ok = isProbeSuccessStatus(statusCode);
6421
+ return {
6422
+ ok,
6423
+ statusCode,
6424
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6425
+ durationMs: Date.now() - start
6426
+ };
6427
+ } catch (e) {
6428
+ const err = e;
6429
+ const stderr = err.stderr?.toString().trim();
6430
+ const lastLine = stderr ? stderr.split("\n").pop() : void 0;
6431
+ const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6432
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
6433
+ }
7427
6434
  }
7428
- function fishSingleQuote(s) {
7429
- return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
6435
+
6436
+ // src/commands/status.ts
6437
+ function connectivityHint(urgency) {
6438
+ if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6439
+ if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6440
+ return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
7430
6441
  }
7431
- function buildFish(commands, groups) {
7432
- const lines = [
7433
- "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install fish\uFF0C\u6216 mihomo completion fish | source\uFF09",
7434
- "",
7435
- "for cmd in mihomo mhm mh mihomo-cli"
7436
- ];
7437
- for (const c of commandWords(commands)) {
7438
- lines.push(` complete -c $cmd -f -a '${c.word}' -d '${fishSingleQuote(c.desc)}'`);
7439
- }
7440
- for (const group of groups) {
7441
- const seen = group.tokens.join(" ");
7442
- const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
7443
- for (const s of group.words) {
7444
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${fishSingleQuote(s.desc)}'`);
7445
- }
7446
- }
7447
- const directoryTokens = groups.find((g) => g.tokens.includes("directory"))?.tokens.join(" ") ?? "directory";
7448
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${directoryTokens}; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`);
7449
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
7450
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
7451
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
7452
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -l mirror -d '\u8D70\u955C\u50CF\u4E0B\u8F7D' -a '${MIRROR_NAMES.join(" ")}'`);
7453
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -a '${RESET_TARGET_NAMES.join(" ")}'`);
7454
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -s y -l yes -d '\u8DF3\u8FC7\u786E\u8BA4'`);
7455
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -l full -d '\u5220\u5168\u90E8'`);
7456
- lines.push("end");
7457
- return lines.join("\n");
7458
- }
7459
- function buildCompletionScript(shell, commands, usageVerb = "") {
7460
- const groups = subGroups(commands);
7461
- switch (shell) {
7462
- case "zsh":
7463
- return buildZsh(commands, groups);
7464
- case "bash":
7465
- return buildBash(commands, groups);
7466
- case "fish":
7467
- return buildFish(commands, groups);
7468
- default: {
7469
- const suggestion = suggestSimilar(shell, [...SHELLS]);
7470
- const usage = `\u7528\u6CD5: mihomo completion ${usageVerb ? `${usageVerb} ` : ""}<${SHELLS.join("|")}>`;
7471
- throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
7472
- label: "\u53C2\u6570\u9519\u8BEF",
7473
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], usage]
7474
- });
7475
- }
6442
+ function trafficColor(line, urgency, total, upload, download) {
6443
+ if (urgency === "traffic-exhausted") return colors.red(line);
6444
+ if (total && total > 0) {
6445
+ const used = (upload || 0) + (download || 0);
6446
+ if (used / total >= 0.9) return colors.yellow(line);
7476
6447
  }
6448
+ return line;
7477
6449
  }
7478
- var BASH_MARKER = "# >>> mihomo-cli completion (append)";
7479
- var BASH_END_MARKER = BASH_MARKER.replace(">>>", "<<<");
7480
- function hasBashMarkerBlock(content) {
7481
- const start = content.indexOf(BASH_MARKER);
7482
- const end = content.indexOf(BASH_END_MARKER);
7483
- return start !== -1 && end !== -1 && end > start;
7484
- }
7485
- function productFingerprint(shell) {
7486
- if (shell === "zsh") return "#compdef mihomo mhm mh mihomo-cli";
7487
- if (shell === "fish") return "for cmd in mihomo mhm mh mihomo-cli";
7488
- return null;
6450
+ function expireColor(line, urgency) {
6451
+ if (urgency === "expired") return colors.red(line);
6452
+ if (urgency === "expiring") return colors.yellow(line);
6453
+ return line;
7489
6454
  }
7490
- function completionInstallPath(shell) {
7491
- const home = os3.homedir();
7492
- switch (shell) {
7493
- case "zsh":
7494
- return path9.join(home, ".zsh", "completions", "_mihomo");
7495
- case "bash":
7496
- return path9.join(home, ".bash_completion");
7497
- case "fish": {
7498
- const fishConfigDir = process.env.XDG_CONFIG_HOME ? path9.join(process.env.XDG_CONFIG_HOME, "fish") : path9.join(home, ".config", "fish");
7499
- return path9.join(fishConfigDir, "completions", "mihomo.fish");
6455
+ function buildStatusJson(args) {
6456
+ const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
6457
+ return {
6458
+ version: VERSION,
6459
+ running: args.running,
6460
+ connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
6461
+ mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
6462
+ carrier: args.kind,
6463
+ pid: args.pid,
6464
+ kernel: getKernelVersion(),
6465
+ kernelInstalled: hasKernel(),
6466
+ ports: args.info ? {
6467
+ ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {},
6468
+ ...args.controllerPort !== null ? { controller: args.controllerPort } : {},
6469
+ ...args.info.tun ? { tun: true } : {}
6470
+ } : {},
6471
+ subscription: args.activeSub ? {
6472
+ name: args.activeSub.name,
6473
+ proxies: args.info?.proxies ?? 0,
6474
+ proxyGroups: args.info?.proxyGroups ?? 0,
6475
+ ...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
6476
+ ...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
6477
+ ...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
6478
+ ...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
6479
+ ...args.cached?.updated_at !== void 0 ? { updatedAt: args.cached.updated_at } : {},
6480
+ stale: args.cached ? isSubscriptionStale(args.cached) : false,
6481
+ urgency
6482
+ } : null,
6483
+ overwrite: {
6484
+ enabled: args.overwriteEnabled,
6485
+ files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6486
+ // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6487
+ // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6488
+ applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : [],
6489
+ // 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors
6490
+ errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message }))
6491
+ },
6492
+ service: {
6493
+ installed: args.service.installed,
6494
+ loaded: args.service.loaded,
6495
+ running: args.service.running,
6496
+ disabled: args.service.disabled,
6497
+ lastExitCode: args.service.lastExitCode,
6498
+ lastTerminatingSignal: args.service.lastTerminatingSignal,
6499
+ legacySystemInstall: args.legacy
7500
6500
  }
7501
- default:
7502
- return null;
6501
+ };
6502
+ }
6503
+ async function printStatus(args = []) {
6504
+ assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
6505
+ assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
6506
+ const asJson = hasFlag(args, "-j", "--json");
6507
+ const skipProbe = hasFlag(args, "--no-probe");
6508
+ const service = getServiceStatus();
6509
+ const state = getRunningState(service);
6510
+ const info = getConfigInfo();
6511
+ const activeSub = getActiveSubscription();
6512
+ const {
6513
+ enabled: overwriteEnabled,
6514
+ files: overwriteFiles,
6515
+ broken: overwriteBroken
6516
+ } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6517
+ const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6518
+ const legacy = detectLegacySystemInstall();
6519
+ let controllerPort = null;
6520
+ try {
6521
+ controllerPort = getPorts().controller;
6522
+ } catch {
6523
+ controllerPort = null;
6524
+ }
6525
+ const { running, pid, kind } = state;
6526
+ let probe = null;
6527
+ if (running && info?.mixedPort && !skipProbe) {
6528
+ probe = await probeProxyConnectivity(info.mixedPort);
6529
+ }
6530
+ if (asJson) {
6531
+ console.log(
6532
+ JSON.stringify(
6533
+ buildStatusJson({
6534
+ running,
6535
+ kind,
6536
+ pid,
6537
+ probe,
6538
+ controllerPort,
6539
+ info,
6540
+ activeSub,
6541
+ cached,
6542
+ overwriteEnabled,
6543
+ // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
6544
+ // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
6545
+ overwriteFiles,
6546
+ overwriteBroken,
6547
+ service,
6548
+ legacy
6549
+ }),
6550
+ null,
6551
+ 2
6552
+ )
6553
+ );
6554
+ return;
6555
+ }
6556
+ const urgency = cached ? subscriptionUrgency(cached) : null;
6557
+ console.log("");
6558
+ let modeLabel = "";
6559
+ if (info) {
6560
+ const mode = info.tun ? "TUN" : "Mixed";
6561
+ const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
6562
+ modeLabel = colors.cyan(` (${mode}${carrier})`);
6563
+ }
6564
+ let statusText;
6565
+ if (!running) {
6566
+ statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
6567
+ } else if (probe && !probe.ok) {
6568
+ statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
6569
+ } else {
6570
+ statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
7503
6571
  }
7504
- }
7505
- function installCompletion(shell, commands) {
7506
- if (!shell) {
7507
- throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion install <${SHELLS.join("|")}>`] });
6572
+ console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
6573
+ if (running && probe && !probe.ok) {
6574
+ console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
7508
6575
  }
7509
- const target = completionInstallPath(shell);
7510
- if (!target) {
7511
- buildCompletionScript(shell, commands, "install");
7512
- return;
6576
+ const abnormalExit = describeAbnormalExit(service);
6577
+ if (!running && service.installed && !service.disabled && abnormalExit) {
6578
+ console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
6579
+ console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
7513
6580
  }
7514
- const script = buildCompletionScript(shell, commands);
7515
- console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
7516
- try {
7517
- if (shell === "bash") {
7518
- const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
7519
- if (hasBashMarkerBlock(existing)) {
7520
- console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
7521
- return;
7522
- }
7523
- fs12.mkdirSync(path9.dirname(target), { recursive: true });
7524
- fs12.appendFileSync(target, `
7525
- ${BASH_MARKER}
7526
- ${script}${BASH_END_MARKER}
7527
- `);
7528
- console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7529
- return;
7530
- }
7531
- const fingerprint = productFingerprint(shell);
7532
- if (fingerprint && fs12.existsSync(target)) {
7533
- const existing = fs12.readFileSync(target, "utf8");
7534
- if (!existing.includes(fingerprint)) {
7535
- throw new CliError(`${target} \u5DF2\u5B58\u5728\u4E14\u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5B89\u88C5`, {
7536
- label: "\u5B89\u88C5\u4E2D\u6B62",
7537
- hint: [
7538
- "\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\uFF0C\u8986\u76D6\u4F1A\u9020\u6210\u4E0D\u53EF\u6062\u590D\u7684\u4E22\u5931\u3002",
7539
- "\u786E\u8BA4\u65E0\u7528\u540E\u5148\u624B\u52A8\u5220\u9664\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:",
7540
- ` rm ${target}`,
7541
- ` mihomo completion install ${shell}`,
7542
- "",
7543
- "\u6216\u6539\u4E3A\u624B\u52A8\u8F93\u51FA\u5230\u522B\u5904:",
7544
- ` mihomo completion ${shell} > <\u4F60\u9009\u62E9\u7684\u8DEF\u5F84>`
7545
- ]
7546
- });
7547
- }
6581
+ const kernelVersion = getKernelVersion();
6582
+ console.log(
6583
+ kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
6584
+ );
6585
+ if (pid) {
6586
+ console.log(`${colors.gray("PID: ")}${pid}`);
6587
+ if (kind === "tun" && state.processInfo) {
6588
+ console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
7548
6589
  }
7549
- fs12.mkdirSync(path9.dirname(target), { recursive: true });
7550
- fs12.writeFileSync(target, script, { mode: 420 });
7551
- console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7552
- } catch (e) {
7553
- throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
7554
- label: "\u5B89\u88C5\u5931\u8D25",
7555
- hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u76EE\u5F55\u7684\u5199\u6743\u9650\uFF0C\u6216\u624B\u52A8\u91CD\u5B9A\u5411\u8865\u5168\u811A\u672C:", ` mihomo completion ${shell} >> ${target}`]
7556
- });
7557
- }
7558
- if (shell === "zsh") {
7559
- console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
7560
- }
7561
- }
7562
- function uninstallCompletion(shell, commands) {
7563
- if (!shell) {
7564
- throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion uninstall <${SHELLS.join("|")}>`] });
7565
- }
7566
- const target = completionInstallPath(shell);
7567
- if (!target) {
7568
- buildCompletionScript(shell, commands, "uninstall");
7569
- return;
7570
6590
  }
7571
- if (!fs12.existsSync(target)) {
7572
- console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
7573
- return;
6591
+ if (info) {
6592
+ const controllerSuffix = controllerPort !== null ? `\uFF0C\u63A7\u5236\u5668 ${controllerPort}` : "";
6593
+ if (info.tun) {
6594
+ const extra = info.mixedPort ? `\uFF0C\u6DF7\u5408\u7AEF\u53E3 ${info.mixedPort}` : "";
6595
+ console.log(`${colors.gray("\u7AEF\u53E3: ")}TUN \u63A5\u7BA1${extra}${controllerSuffix}`);
6596
+ } else if (info.mixedPort) {
6597
+ console.log(`${colors.gray("\u7AEF\u53E3: ")}${info.mixedPort}${controllerSuffix}`);
6598
+ } else {
6599
+ console.log(`${colors.gray("\u7AEF\u53E3: ")}\u672A\u77E5${controllerSuffix}`);
6600
+ }
7574
6601
  }
7575
- console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
7576
- try {
7577
- if (shell === "bash") {
7578
- const existing2 = fs12.readFileSync(target, "utf8");
7579
- if (!hasBashMarkerBlock(existing2)) {
7580
- console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
7581
- console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
7582
- return;
7583
- }
7584
- let rest = existing2;
7585
- let removed = 0;
7586
- while (hasBashMarkerBlock(rest)) {
7587
- const start = rest.indexOf(BASH_MARKER);
7588
- const end = rest.indexOf(BASH_END_MARKER);
7589
- const before = rest.slice(0, start).replace(/\n+$/, "\n");
7590
- const after = rest.slice(end + BASH_END_MARKER.length).replace(/^\n/, "");
7591
- rest = `${before}${after}`;
7592
- removed++;
7593
- }
7594
- if (rest.trim() === "") {
7595
- fs12.rmSync(target);
7596
- console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7597
- return;
7598
- }
7599
- fs12.writeFileSync(target, rest);
7600
- if (removed > 1) {
7601
- console.log(colors.gray(` \u53D1\u73B0\u5E76\u79FB\u9664\u4E86 ${removed} \u4EFD\u91CD\u590D\u7684\u8865\u5168\u6BB5`));
6602
+ if (activeSub) {
6603
+ let subLine = `${colors.gray("\u8BA2\u9605: ")}${activeSub.name}`;
6604
+ if (info) {
6605
+ subLine += ` (${formatProxySummary(info)})`;
6606
+ }
6607
+ console.log(subLine);
6608
+ if (cached?.updated_at) {
6609
+ const rel = formatRelativeTime(cached.updated_at) || formatDate(cached.updated_at);
6610
+ if (isSubscriptionStale(cached)) {
6611
+ console.log(colors.yellow(`\u66F4\u65B0: ${rel}\uFF08\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694\uFF0C\u5EFA\u8BAE mihomo sub update\uFF09`));
6612
+ } else {
6613
+ console.log(`${colors.gray("\u66F4\u65B0: ")}${rel}`);
7602
6614
  }
7603
- console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7604
- return;
7605
6615
  }
7606
- const existing = fs12.readFileSync(target, "utf8");
7607
- const fingerprint = productFingerprint(shell);
7608
- if (!fingerprint || !existing.includes(fingerprint)) {
7609
- throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
7610
- label: "\u5378\u8F7D\u4E2D\u6B62",
7611
- hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
7612
- });
6616
+ const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
6617
+ if (traffic) {
6618
+ console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
7613
6619
  }
7614
- fs12.rmSync(target);
7615
- console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7616
- } catch (e) {
7617
- if (e instanceof CliError) throw e;
7618
- throw new CliError(`\u8865\u5168\u5378\u8F7D\u5931\u8D25: ${e.message}`, {
7619
- label: "\u5378\u8F7D\u5931\u8D25",
7620
- hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u6587\u4EF6\u7684\u6743\u9650\uFF0C\u6216\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
7621
- });
7622
- }
7623
- }
7624
- function cmdCompletion(args, commands) {
7625
- assertKnownFlags(args.slice(1), [], "completion");
7626
- if (args[1] === "install") {
7627
- assertPositionalCount(args, 1, 2, `mihomo completion install <${SHELLS.join("|")}>`);
7628
- installCompletion(args[2], commands);
7629
- return;
7630
- }
7631
- if (args[1] === "uninstall") {
7632
- assertPositionalCount(args, 1, 2, `mihomo completion uninstall <${SHELLS.join("|")}>`);
7633
- uninstallCompletion(args[2], commands);
7634
- return;
6620
+ if (cached?.expire !== void 0) {
6621
+ console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
6622
+ }
6623
+ } else {
6624
+ console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
7635
6625
  }
7636
- assertPositionalCount(args, 1, 1, `mihomo completion <${SHELLS.join("|")}>`);
7637
- const shell = args[1];
7638
- if (!shell) {
7639
- throw new CliError("\u8BF7\u6307\u5B9A shell", {
7640
- hint: [
7641
- `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`,
7642
- `\u5B89\u88C5\u5230\u9ED8\u8BA4\u4F4D\u7F6E: mihomo completion install <${SHELLS.join("|")}>`,
7643
- `\u5378\u8F7D: mihomo completion uninstall <${SHELLS.join("|")}>`,
7644
- '\u4E34\u65F6\u542F\u7528: eval "$(mihomo completion zsh)"'
7645
- ]
7646
- });
6626
+ printOverwriteLines(overwriteEnabled, overwriteFiles, overwriteBroken, activeSub);
6627
+ printServiceLines(service, legacy);
6628
+ if (kind === "tun") {
6629
+ console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF1B\u505C\u6B62: mihomo stop\uFF08\u4E4B\u540E mihomo start \u6062\u590D Mixed\uFF09"));
7647
6630
  }
7648
- console.log(buildCompletionScript(shell, commands));
6631
+ console.log("");
7649
6632
  }
7650
-
7651
- // src/commands/config.ts
7652
- function cmdConfig(args = []) {
7653
- assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
7654
- assertPositionalCount(args, 0, 1, "mihomo config [--json]");
7655
- const asJson = hasFlag(args, "-j", "--json");
7656
- const active = getActiveSubscription();
7657
- if (!active) {
7658
- throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
7659
- }
7660
- const rawContent = readSubscriptionRawConfig(active.name);
7661
- if (!rawContent) {
7662
- throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${active.name}` });
7663
- }
7664
- const mode = getConfigInfo()?.tun ? "tun" : "mixed";
7665
- const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
7666
- const shown = { ...config };
7667
- if ("secret" in shown) shown.secret = "***";
7668
- if (asJson) {
7669
- console.log(JSON.stringify({ config: shown, warnings }, null, 2));
6633
+ function shortOverwriteName(name) {
6634
+ return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6635
+ }
6636
+ function printOverwriteLines(enabled, files, broken, activeSub) {
6637
+ if (!enabled) {
6638
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
7670
6639
  return;
7671
6640
  }
7672
- console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
7673
- console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
7674
- if ("secret" in config) {
7675
- console.log(colors.gray("# secret \u5DF2\u8131\u654F\u663E\u793A"));
6641
+ const active = files.filter((f) => f.enabled && f.matched !== false);
6642
+ const unmatched = files.filter((f) => f.enabled && f.matched === false);
6643
+ const disabledCount = files.filter((f) => !f.enabled).length;
6644
+ const suffixes = [];
6645
+ if (unmatched.length > 0) suffixes.push(`${unmatched.length} \u4E2A\u4E0D\u9002\u7528`);
6646
+ if (disabledCount > 0) suffixes.push(`${disabledCount} \u4E2A\u5DF2\u7981\u7528`);
6647
+ const suffix = suffixes.length > 0 ? `\uFF0C${suffixes.join("\uFF0C")}` : "";
6648
+ if (active.length > 0) {
6649
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
6650
+ } else {
6651
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7676
6652
  }
7677
- console.log("");
7678
- console.log(dumpYaml(shown).trimEnd());
7679
- if (warnings.length > 0) {
7680
- console.log("");
7681
- for (const w of warnings) console.log(colors.yellow(`# ${w}`));
6653
+ for (const f of unmatched) {
6654
+ const scope = f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
6655
+ console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${scope}\uFF09`));
7682
6656
  }
7683
- }
7684
-
7685
- // src/commands/doctor.ts
7686
- import { spawnSync as spawnSync7 } from "child_process";
7687
- import fs13 from "fs";
7688
-
7689
- // src/commands/update.ts
7690
- import { execFile as execFile3, spawn as spawn2 } from "child_process";
7691
- import { promisify as promisify3 } from "util";
7692
- var execFileAsync2 = promisify3(execFile3);
7693
- var NPM_VIEW_TIMEOUT_MS = 15e3;
7694
- async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
7695
- try {
7696
- const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs });
7697
- const version = stdout.trim().split("\n").pop()?.trim();
7698
- return version || null;
7699
- } catch {
7700
- return null;
6657
+ for (const b of broken) {
6658
+ console.log(colors.red(` ${b.message}`));
7701
6659
  }
7702
6660
  }
7703
- async function cmdUpdate(args = []) {
7704
- assertKnownFlags(args.slice(1), [], "update");
7705
- assertPositionalCount(args, 0, 1, "mihomo update");
7706
- console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7707
- console.log("");
7708
- const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7709
- if (latest) {
7710
- try {
7711
- const cmp = compareVersions(VERSION, latest);
7712
- if (cmp > 0) {
7713
- console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
7714
- console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
7715
- return;
7716
- }
7717
- if (cmp === 0) {
7718
- console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7719
- return;
7720
- }
7721
- } catch {
7722
- }
7723
- console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
6661
+ function printServiceLines(service, legacy) {
6662
+ if (!service.installed && !service.loaded) {
6663
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
6664
+ } else if (!service.installed) {
6665
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u5F02\u5E38")} ${colors.gray("(plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001)")}`);
6666
+ console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
6667
+ printAutoStart(service);
7724
6668
  } else {
7725
- console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
6669
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
6670
+ printAutoStart(service);
7726
6671
  }
7727
- console.log("");
7728
- console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7729
- console.log("");
7730
- await new Promise((resolve, reject) => {
7731
- const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7732
- npm.on("close", (code) => {
7733
- if (code === 0) {
7734
- resolve();
7735
- } else {
7736
- reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
7737
- }
7738
- });
7739
- npm.on("error", (e) => {
7740
- const perm = e.message.includes("EACCES") || e.message.includes("permission");
7741
- reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7742
- });
7743
- });
7744
- try {
7745
- const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7746
- const result = JSON.parse(stdout);
7747
- const newVersion = result.dependencies?.[PKG_NAME]?.version;
7748
- console.log("");
7749
- if (newVersion) {
7750
- console.log(`\u66F4\u65B0\u5B8C\u6210\uFF0C\u6700\u65B0\u7248\u672C: ${colors.green(newVersion)}`);
7751
- } else {
7752
- console.log("\u66F4\u65B0\u5B8C\u6210");
7753
- }
7754
- } catch {
7755
- console.log("");
7756
- console.log("\u66F4\u65B0\u5B8C\u6210");
6672
+ if (legacy) {
6673
+ console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
6674
+ console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7757
6675
  }
7758
6676
  }
6677
+ function printAutoStart(service) {
6678
+ const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
6679
+ console.log(`${colors.gray("\u81EA\u542F: ")}${autoStart}`);
6680
+ }
7759
6681
 
7760
- // src/commands/doctor.ts
7761
- function isPortListening(port) {
7762
- try {
7763
- const r = spawnSync7("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7764
- return r.status === 0 && (r.stdout || "").trim().length > 0;
7765
- } catch {
7766
- return false;
6682
+ // src/commands/start.ts
6683
+ function resolveStartMode(args) {
6684
+ const modeArg = getNonFlagArg(args, 1);
6685
+ const modeToken = modeArg?.toLowerCase();
6686
+ if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
6687
+ throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
7767
6688
  }
6689
+ return modeToken === "tun" ? "tun" : "mixed";
7768
6690
  }
7769
- async function collectChecks() {
7770
- const checks = [];
7771
- const push = (name, status, detail, fix, notes) => {
7772
- checks.push({ name, status, detail, fix, notes });
7773
- };
7774
- const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
6691
+ async function cmdStart(args) {
6692
+ assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
6693
+ assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
6694
+ const targetMode = resolveStartMode(args);
6695
+ let disabledAutoStartForTun = false;
7775
6696
  if (!hasKernel()) {
7776
- push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7777
- } else {
7778
- const v = getKernelVersion();
7779
- const r = spawnSync7(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7780
- if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7781
- push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7782
- } else if (r.error) {
7783
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7784
- } else {
7785
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7786
- }
7787
- }
7788
- try {
7789
- fs13.accessSync(USER_DATA_DIR, fs13.constants.W_OK);
7790
- push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7791
- } catch {
7792
- push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
6697
+ throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
7793
6698
  }
7794
- if (fs13.existsSync(PATHS.settingsFile)) {
7795
- if (isValidSettingsContent(fs13.readFileSync(PATHS.settingsFile, "utf8"))) {
7796
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7797
- } else {
7798
- push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6699
+ const skipUpdate = hasFlag(args, "-s", "--no-update");
6700
+ const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6701
+ const stopEpochBefore = readStopEpoch();
6702
+ const serviceBefore = getServiceStatus();
6703
+ if (targetMode === "tun") {
6704
+ if (detectLegacySystemInstall()) {
6705
+ console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
6706
+ console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
6707
+ cleanupLegacyInstallOrThrow();
6708
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6709
+ console.log("");
7799
6710
  }
7800
- } else {
7801
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
7802
- }
7803
- const subs = getSubscriptionsWithCache();
7804
- const active = getActiveSubscription();
7805
- if (subs.length === 0) {
7806
- push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
7807
- } else {
7808
- push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7809
- if (active) {
7810
- if (!readSubscriptionRawConfig(active.name)) {
7811
- push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
7812
- } else {
7813
- push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
7814
- }
7815
- const cached = subs.find((s) => s.name === active.name);
7816
- if (cached?.updated_at) {
7817
- const rel = formatRelativeTime(cached.updated_at);
7818
- if (isSubscriptionStale(cached)) {
7819
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
7820
- } else {
7821
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
7822
- }
7823
- }
6711
+ if (serviceBefore.loaded) {
6712
+ throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6713
+ hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D\u670D\u52A1"]
6714
+ });
7824
6715
  }
7825
- }
7826
- const service = getServiceStatus();
7827
- const legacy = detectLegacySystemInstall();
7828
- if (legacy) {
7829
- push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
7830
- } else if (!service.installed && !service.loaded) {
7831
- push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
7832
- } else if (!service.installed) {
7833
- push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
7834
- } else if (service.running) {
7835
- const abnormalExit = describeAbnormalExit(service);
7836
- push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
7837
- if (abnormalExit) {
7838
- push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6716
+ if (serviceBefore.installed && !serviceBefore.disabled) {
6717
+ disableServiceAutoStart();
6718
+ disabledAutoStartForTun = true;
6719
+ console.log(colors.gray("\u5DF2\u4E34\u65F6\u5173\u95ED\u670D\u52A1\u81EA\u542F\uFF08\u907F\u514D\u91CD\u542F\u540E\u670D\u52A1\u62FF TUN \u914D\u7F6E\u542F\u52A8\uFF09"));
6720
+ console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D"));
6721
+ console.log("");
7839
6722
  }
7840
- } else {
7841
- const abnormalExit = describeAbnormalExit(service);
7842
- if (!service.disabled && abnormalExit) {
7843
- push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo stop \u505C\u6B62\u91CD\u8BD5");
7844
- } else {
7845
- push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
6723
+ } else if (!serviceBefore.installed) {
6724
+ if (serviceBefore.loaded) {
6725
+ throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
6726
+ hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
6727
+ });
7846
6728
  }
6729
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
6730
+ hint: ["Mixed \u6A21\u5F0F\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u9700\u5148\u5B89\u88C5:", " mihomo install", "", "\u4E34\u65F6\u4F7F\u7528\u53EF\u8D70 TUN: mihomo tun"]
6731
+ });
7847
6732
  }
7848
- const state = getRunningState();
7849
- const info = getConfigInfo();
7850
- let mixedPortDefault = DEFAULT_MIXED_PORT;
6733
+ const sub = requireActiveSubscription();
6734
+ if (!skipUpdate) {
6735
+ await autoUpdateStaleSubscription({ timeout: updateTimeout });
6736
+ }
6737
+ let prepared;
7851
6738
  try {
7852
- const ports = getPorts();
7853
- mixedPortDefault = ports.mixed;
6739
+ prepared = await prepareConfigForStart(targetMode, sub.name);
7854
6740
  } catch (e) {
7855
- push("\u7AEF\u53E3\u914D\u7F6E", "fail", e.message, "\u4FEE\u6B63 settings.json \u7684 ports\uFF081-65535 \u6574\u6570\uFF0Cmixed \u4E0E controller \u4E0D\u80FD\u76F8\u540C\uFF09");
6741
+ if (e instanceof CliError) throw e;
6742
+ throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
7856
6743
  }
7857
- const mixedPort = info?.mixedPort ?? mixedPortDefault;
7858
- if (state.running) {
7859
- if (isPortListening(mixedPort)) {
7860
- push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
7861
- } else {
7862
- push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6744
+ const configInfo = commitPreparedConfig(prepared);
6745
+ const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6746
+ console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6747
+ try {
6748
+ const pid = await launchOrRestart(targetMode, stopEpochBefore);
6749
+ console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
6750
+ } catch (e) {
6751
+ const lines = e.message.split("\n");
6752
+ const extraHint = [];
6753
+ if (targetMode === "tun" && disabledAutoStartForTun) {
6754
+ extraHint.push("", "\u670D\u52A1\u81EA\u542F\u5DF2\u88AB\u5173\u95ED\uFF08\u542F\u52A8 TUN \u524D\u5173\u95ED\u4EE5\u907F\u514D\u81EA\u542F\u5931\u8D25\u5FAA\u73AF\uFF09\u3002", "\u6062\u590D Mixed \u6A21\u5F0F: mihomo start");
7863
6755
  }
7864
- } else if (isPortListening(mixedPort)) {
7865
- push("\u7AEF\u53E3", "warn", `${mixedPort} \u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\uFF0Cstart \u4F1A\u5931\u8D25`, `lsof -nP -iTCP:${mixedPort} \u67E5\u770B\u5360\u7528\u8005`);
6756
+ if (e instanceof CliError) {
6757
+ throw new CliError(e.message, { label: e.label, hint: [...e.hint, ...extraHint] });
6758
+ }
6759
+ throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: [...lines.slice(1), ...extraHint] });
6760
+ }
6761
+ await printStatus();
6762
+ if (targetMode === "mixed") {
6763
+ console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${getPorts().mixed}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
7866
6764
  } else {
7867
- push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
6765
+ console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo stop\uFF08\u4E4B\u540E mihomo start \u6062\u590D Mixed\uFF09"));
7868
6766
  }
7869
- if (active && hasKernel()) {
7870
- try {
7871
- const mode = info?.tun ? "tun" : "mixed";
7872
- const prepared = await prepareConfigForStart(mode, active.name);
7873
- const warnings = prepared.buildResult.warnings;
7874
- if (warnings.length > 0) {
7875
- push(
7876
- "\u914D\u7F6E\u6784\u5EFA",
7877
- "warn",
7878
- `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
7879
- void 0,
7880
- warnings.map((w) => ` ${w}`)
7881
- );
7882
- } else {
7883
- push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
6767
+ console.log("");
6768
+ }
6769
+
6770
+ // src/commands/shared.ts
6771
+ function assertUniqueTokens(table) {
6772
+ const owner = /* @__PURE__ */ new Map();
6773
+ for (const cmd of table) {
6774
+ for (const token of [cmd.name, ...cmd.aliases ?? []]) {
6775
+ const prev = owner.get(token);
6776
+ if (prev !== void 0) {
6777
+ throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
7884
6778
  }
7885
- } catch (e) {
7886
- const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
7887
- push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
6779
+ owner.set(token, cmd.name);
7888
6780
  }
7889
- } else {
7890
- push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
7891
6781
  }
7892
- if (state.running && info?.mixedPort) {
7893
- const probe = await probeProxyConnectivity(info.mixedPort);
7894
- if (probe.ok) {
7895
- push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
7896
- } else {
7897
- push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
7898
- }
7899
- } else {
7900
- push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
6782
+ }
6783
+ async function dispatchSubcommand(args, table, options) {
6784
+ assertUniqueTokens(table);
6785
+ const action = args[1];
6786
+ if (action) {
6787
+ const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
6788
+ if (cmd) return cmd.handler(args);
6789
+ return options.onUnknown(action);
7901
6790
  }
7902
- const latest = await latestVersionPromise;
7903
- if (latest === null) {
7904
- push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7905
- } else if (compareVersions(latest, VERSION) > 0) {
7906
- push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo update");
7907
- } else {
7908
- push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
6791
+ return options.fallback(args);
6792
+ }
6793
+ async function confirmPrompt(question) {
6794
+ if (!process.stdin.isTTY) return false;
6795
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
6796
+ const answer = await new Promise((resolve) => {
6797
+ rl.question(`${question} (y/N) `, (a) => {
6798
+ rl.close();
6799
+ resolve(a);
6800
+ });
6801
+ });
6802
+ return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6803
+ }
6804
+ async function confirmOrThrow(question, opts) {
6805
+ if (!process.stdin.isTTY) {
6806
+ throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
7909
6807
  }
7910
- return checks;
6808
+ return confirmPrompt(question);
7911
6809
  }
7912
- async function cmdDoctor(args = []) {
7913
- assertKnownFlags(args.slice(1), [], "doctor");
7914
- assertPositionalCount(args, 0, 1, "mihomo doctor");
7915
- const checks = await collectChecks();
6810
+ async function restartToApply(args) {
6811
+ const currentMode = restartModeOnChange();
6812
+ if (!currentMode) return false;
7916
6813
  console.log("");
7917
- for (const c of checks) {
7918
- const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
7919
- console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
7920
- if (c.status !== "ok" && c.status !== "skip") {
7921
- for (const line of c.notes ?? []) console.log(colors.gray(line));
7922
- if (c.fix) console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
6814
+ await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6815
+ return true;
6816
+ }
6817
+
6818
+ // src/commands/directory.ts
6819
+ function openDirectory(args) {
6820
+ assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
6821
+ const target = args[2];
6822
+ if (target === void 0 || target === "root") {
6823
+ console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
6824
+ openUrl(USER_DATA_DIR);
6825
+ return;
6826
+ }
6827
+ const key = target.toLowerCase();
6828
+ const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
6829
+ if (targetInfo) {
6830
+ const targetPath = targetInfo.path || USER_DATA_DIR;
6831
+ console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetPath})`);
6832
+ openUrl(targetPath);
6833
+ return;
6834
+ }
6835
+ const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
6836
+ for (const [k, val] of Object.entries(DIRECTORY_TARGETS)) {
6837
+ if (k !== "root") {
6838
+ hint.push(` ${k.padEnd(14)}${val.label}`);
7923
6839
  }
7924
6840
  }
7925
- const ok = checks.filter((c) => c.status === "ok").length;
7926
- const warn = checks.filter((c) => c.status === "warn").length;
7927
- const fail = checks.filter((c) => c.status === "fail").length;
7928
- const skip = checks.filter((c) => c.status === "skip").length;
6841
+ throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u76EE\u6807 "${target}"`, { hint });
6842
+ }
6843
+ function printDirectoryInfo() {
6844
+ const entries = Object.entries(DIRECTORY_TARGETS).filter(([key]) => key !== "root");
6845
+ const pathWidth = Math.max(...entries.map(([, val]) => val.path.replace(USER_DATA_DIR, ".").length));
7929
6846
  console.log("");
7930
- console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38${skip > 0 ? `\uFF0C${skip} \u9879\u8DF3\u8FC7` : ""}`);
6847
+ console.log(`\u6570\u636E\u76EE\u5F55: ${USER_DATA_DIR}`);
7931
6848
  console.log("");
7932
- if (fail > 0) {
7933
- throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
7934
- label: "\u4F53\u68C0\u672A\u901A\u8FC7",
7935
- hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
7936
- });
6849
+ for (const [key, val] of entries) {
6850
+ const rel = val.path.replace(USER_DATA_DIR, ".");
6851
+ console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
7937
6852
  }
6853
+ console.log("");
6854
+ console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
6855
+ console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6856
+ console.log("");
6857
+ }
6858
+ var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
6859
+ async function cmdDirectory(args) {
6860
+ assertKnownFlags(args.slice(1), [], "dir");
6861
+ await dispatchSubcommand(args, SUBCOMMANDS, {
6862
+ fallback: printDirectoryInfo,
6863
+ onUnknown: (action) => {
6864
+ if (action.startsWith("-")) {
6865
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
6866
+ label: "\u53C2\u6570\u9519\u8BEF",
6867
+ hint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo dir open [root|subs|logs|data|runtime|kernel]"]
6868
+ });
6869
+ }
6870
+ const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6871
+ const suggestion = suggestSimilar(action, names);
6872
+ throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6873
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
6874
+ });
6875
+ }
6876
+ });
7938
6877
  }
7939
6878
 
6879
+ // src/commands/doctor.ts
6880
+ import { spawnSync as spawnSync6 } from "child_process";
6881
+ import fs11 from "fs";
6882
+
7940
6883
  // src/kernel.ts
7941
- import { execFile as execFile4, spawnSync as spawnSync8 } from "child_process";
7942
- import fs14 from "fs";
7943
- import path10 from "path";
7944
- import { promisify as promisify4 } from "util";
6884
+ import { execFile as execFile3, spawnSync as spawnSync5 } from "child_process";
6885
+ import fs10 from "fs";
6886
+ import path8 from "path";
6887
+ import { promisify as promisify3 } from "util";
7945
6888
  var GITHUB_REPO = "MetaCubeX/mihomo";
7946
6889
  var KERNEL_HTTP_TIMEOUT = 12e4;
7947
6890
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
7948
6891
  var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
7949
- var execFileAsync3 = promisify4(execFile4);
6892
+ var execFileAsync2 = promisify3(execFile3);
7950
6893
  function withMirror(url, mirror) {
7951
6894
  if (mirror && url.startsWith("https://github.com/")) {
7952
6895
  return mirror + url;
@@ -7978,7 +6921,7 @@ function resolveDownloadChannel(input) {
7978
6921
  return { kind: "direct" };
7979
6922
  }
7980
6923
  function hasGh() {
7981
- const result = spawnSync8("gh", ["--version"], { stdio: "ignore" });
6924
+ const result = spawnSync5("gh", ["--version"], { stdio: "ignore" });
7982
6925
  return !result.error && result.status === 0;
7983
6926
  }
7984
6927
  function getArch() {
@@ -7989,9 +6932,7 @@ function getArch() {
7989
6932
  }
7990
6933
  function findMatchingAsset(assets, platform, arch) {
7991
6934
  const prefix = `mihomo-${platform}-${arch}`;
7992
- const matchingAssets = assets.filter(
7993
- (a) => a.name.startsWith(prefix) && a.name.endsWith(".gz") || a.name.startsWith(`${prefix}-`) && a.name.endsWith(".gz")
7994
- );
6935
+ const matchingAssets = assets.filter((a) => a.name.startsWith(prefix) && a.name.endsWith(".gz"));
7995
6936
  if (matchingAssets.length === 0) return null;
7996
6937
  if (matchingAssets.length === 1) return matchingAssets[0];
7997
6938
  const standardAsset = matchingAssets.find((a) => new RegExp(`^${escapeRegExp(prefix)}-v?\\d+\\.\\d+\\.\\d+$`).test(a.name.slice(0, -3)));
@@ -8060,7 +7001,7 @@ async function getLatestRelease(repo, proxyPort) {
8060
7001
  if (proxyPort) {
8061
7002
  let stdout;
8062
7003
  try {
8063
- const result = await execFileAsync3("curl", buildReleaseApiCurlArgs(proxyPort, url), {
7004
+ const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(proxyPort, url), {
8064
7005
  encoding: "utf8",
8065
7006
  maxBuffer: 50 * 1024 * 1024,
8066
7007
  timeout: KERNEL_HTTP_TIMEOUT + 1e4
@@ -8107,32 +7048,6 @@ async function checkUpdate(proxyPort) {
8107
7048
  release: latest
8108
7049
  };
8109
7050
  }
8110
- function findBinaryInDir(dir, maxDepth = 4) {
8111
- if (maxDepth <= 0) return null;
8112
- const files = fs14.readdirSync(dir);
8113
- for (const f of files) {
8114
- const fullPath = path10.join(dir, f);
8115
- const stat = fs14.lstatSync(fullPath);
8116
- if (stat.isDirectory()) {
8117
- const found = findBinaryInDir(fullPath, maxDepth - 1);
8118
- if (found) return found;
8119
- continue;
8120
- }
8121
- if (!stat.isFile()) continue;
8122
- if (f === "mihomo") return fullPath;
8123
- if (f.includes("mihomo") && !f.endsWith(".gz")) return fullPath;
8124
- }
8125
- return null;
8126
- }
8127
- var MAX_EXTRACTED_BYTES = 512 * 1024 * 1024;
8128
- function parseTarEntrySize(line) {
8129
- const tokens = line.trim().split(/\s+/);
8130
- if (tokens.length < 5) return null;
8131
- const sizeToken = tokens[1].includes("/") ? tokens[2] : tokens[4];
8132
- if (!/^\d+$/.test(sizeToken)) return null;
8133
- const size = Number(sizeToken);
8134
- return Number.isSafeInteger(size) ? size : null;
8135
- }
8136
7051
  function buildKernelCurlArgs(args) {
8137
7052
  const argv = [
8138
7053
  "-L",
@@ -8177,8 +7092,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8177
7092
  }
8178
7093
  assertTrustedAssetUrl(asset.browser_download_url);
8179
7094
  const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
8180
- const tempDir = fs14.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
8181
- const tempPath = path10.join(tempDir, path10.basename(asset.name));
7095
+ const tempDir = fs10.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7096
+ const tempPath = path8.join(tempDir, path8.basename(asset.name));
8182
7097
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
8183
7098
  try {
8184
7099
  if (channel.kind === "mirror" && progressCallback) {
@@ -8188,10 +7103,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8188
7103
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
8189
7104
  }
8190
7105
  if (channel.kind === "gh") {
8191
- if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
7106
+ if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
8192
7107
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
8193
7108
  }
8194
- const ghResult = spawnSync8("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7109
+ const ghResult = spawnSync5("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
8195
7110
  stdio: "inherit",
8196
7111
  timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
8197
7112
  });
@@ -8209,7 +7124,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8209
7124
  }
8210
7125
  } else {
8211
7126
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
8212
- const curlResult = spawnSync8(
7127
+ const curlResult = spawnSync5(
8213
7128
  "curl",
8214
7129
  buildKernelCurlArgs({
8215
7130
  url: downloadUrl,
@@ -8232,11 +7147,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8232
7147
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
8233
7148
  }
8234
7149
  }
8235
- if (!fs14.existsSync(tempPath)) {
7150
+ if (!fs10.existsSync(tempPath)) {
8236
7151
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
8237
7152
  }
8238
7153
  if (Number.isFinite(asset.size) && asset.size > 0) {
8239
- const actual = fs14.statSync(tempPath).size;
7154
+ const actual = fs10.statSync(tempPath).size;
8240
7155
  if (actual !== asset.size) {
8241
7156
  throw new Error(
8242
7157
  `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
@@ -8247,57 +7162,19 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8247
7162
  if (progressCallback) {
8248
7163
  progressCallback("\u89E3\u538B\u5185\u6838...");
8249
7164
  }
8250
- let extractedBinary = null;
8251
- if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
8252
- const listResult = spawnSync8("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
8253
- if (listResult.error) throw listResult.error;
8254
- if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
8255
- for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
8256
- if (entry.startsWith("/") || entry.split("/").includes("..")) {
8257
- throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
8258
- }
8259
- }
8260
- const typeResult = spawnSync8("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
8261
- if (typeResult.error) throw typeResult.error;
8262
- if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
8263
- let extractedBytes = 0;
8264
- for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
8265
- const typeChar = line[0];
8266
- if (typeChar !== "-" && typeChar !== "d") {
8267
- throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
8268
- }
8269
- const entrySize = parseTarEntrySize(line);
8270
- if (entrySize !== null) extractedBytes += entrySize;
8271
- }
8272
- if (extractedBytes > MAX_EXTRACTED_BYTES) {
8273
- throw new Error(
8274
- `\u5F52\u6863\u89E3\u538B\u540E\u603B\u91CF ${(extractedBytes / 1024 / 1024).toFixed(1)}MB \u8D85\u8FC7 ${MAX_EXTRACTED_BYTES / 1024 / 1024}MB \u4E0A\u9650\uFF0C\u7591\u4F3C\u538B\u7F29\u70B8\u5F39\uFF0C\u5DF2\u62D2\u7EDD\u89E3\u538B`
8275
- );
8276
- }
8277
- const tarResult = spawnSync8("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
8278
- stdio: ["ignore", "ignore", "inherit"],
8279
- timeout: 6e4
8280
- });
8281
- if (tarResult.error) throw tarResult.error;
8282
- if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
8283
- } else if (tempPath.endsWith(".gz")) {
8284
- const baseName = path10.basename(tempPath, ".gz");
8285
- const outputPath = path10.join(tempDir, baseName);
8286
- const gzipResult = spawnSync8("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
8287
- if (gzipResult.error) throw gzipResult.error;
8288
- if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
8289
- fs14.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
8290
- extractedBinary = outputPath;
8291
- }
8292
- const foundBinary = extractedBinary || findBinaryInDir(tempDir);
8293
- if (!foundBinary) {
8294
- throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
7165
+ if (!tempPath.endsWith(".gz")) {
7166
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
8295
7167
  }
7168
+ const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
7169
+ const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7170
+ if (gzipResult.error) throw gzipResult.error;
7171
+ if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7172
+ fs10.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
8296
7173
  if (progressCallback) {
8297
7174
  progressCallback("\u6821\u9A8C\u5185\u6838...");
8298
7175
  }
8299
- fs14.chmodSync(foundBinary, 493);
8300
- const check = spawnSync8(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7176
+ fs10.chmodSync(foundBinary, 493);
7177
+ const check = spawnSync5(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
8301
7178
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
8302
7179
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
8303
7180
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
@@ -8313,15 +7190,300 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8313
7190
  }
8314
7191
  }
8315
7192
  const targetPath = PATHS.mihomoBinary;
8316
- fs14.renameSync(foundBinary, targetPath);
8317
- fs14.chmodSync(targetPath, 493);
7193
+ fs10.renameSync(foundBinary, targetPath);
7194
+ fs10.chmodSync(targetPath, 493);
8318
7195
  clearKernelVersionCache();
8319
7196
  return { version: latest.tag_name, path: targetPath };
8320
7197
  } finally {
8321
7198
  try {
8322
- fs14.rmSync(tempDir, { recursive: true, force: true });
7199
+ fs10.rmSync(tempDir, { recursive: true, force: true });
7200
+ } catch {
7201
+ }
7202
+ }
7203
+ }
7204
+
7205
+ // src/commands/update.ts
7206
+ import { execFile as execFile4, spawn as spawn2 } from "child_process";
7207
+ import { promisify as promisify4 } from "util";
7208
+ var execFileAsync3 = promisify4(execFile4);
7209
+ var NPM_VIEW_TIMEOUT_MS = 15e3;
7210
+ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
7211
+ try {
7212
+ const { stdout } = await execFileAsync3("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs });
7213
+ const version = stdout.trim().split("\n").pop()?.trim();
7214
+ return version || null;
7215
+ } catch {
7216
+ return null;
7217
+ }
7218
+ }
7219
+ async function cmdUpdate(args = []) {
7220
+ assertKnownFlags(args.slice(1), [], "update");
7221
+ assertPositionalCount(args, 0, 1, "mihomo update");
7222
+ console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7223
+ console.log("");
7224
+ const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7225
+ if (latest) {
7226
+ try {
7227
+ const cmp = compareVersions(VERSION, latest);
7228
+ if (cmp > 0) {
7229
+ console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
7230
+ console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
7231
+ return;
7232
+ }
7233
+ if (cmp === 0) {
7234
+ console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7235
+ return;
7236
+ }
8323
7237
  } catch {
8324
7238
  }
7239
+ console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
7240
+ } else {
7241
+ console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
7242
+ }
7243
+ console.log("");
7244
+ console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7245
+ console.log("");
7246
+ await new Promise((resolve, reject) => {
7247
+ const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7248
+ npm.on("close", (code) => {
7249
+ if (code === 0) {
7250
+ resolve();
7251
+ } else {
7252
+ reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
7253
+ }
7254
+ });
7255
+ npm.on("error", (e) => {
7256
+ const perm = e.message.includes("EACCES") || e.message.includes("permission");
7257
+ reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7258
+ });
7259
+ });
7260
+ try {
7261
+ const { stdout } = await execFileAsync3("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7262
+ const result = JSON.parse(stdout);
7263
+ const newVersion = result.dependencies?.[PKG_NAME]?.version;
7264
+ console.log("");
7265
+ if (newVersion) {
7266
+ console.log(`\u66F4\u65B0\u5B8C\u6210\uFF0C\u6700\u65B0\u7248\u672C: ${colors.green(newVersion)}`);
7267
+ } else {
7268
+ console.log("\u66F4\u65B0\u5B8C\u6210");
7269
+ }
7270
+ } catch {
7271
+ console.log("");
7272
+ console.log("\u66F4\u65B0\u5B8C\u6210");
7273
+ }
7274
+ }
7275
+
7276
+ // src/commands/doctor.ts
7277
+ function withTimeout2(promise, ms) {
7278
+ return new Promise((resolve, reject) => {
7279
+ const timer = setTimeout(() => reject(new Error("timeout")), ms);
7280
+ promise.then(
7281
+ (v) => {
7282
+ clearTimeout(timer);
7283
+ resolve(v);
7284
+ },
7285
+ (e) => {
7286
+ clearTimeout(timer);
7287
+ reject(e);
7288
+ }
7289
+ );
7290
+ });
7291
+ }
7292
+ function isPortListening(port) {
7293
+ try {
7294
+ const r = spawnSync6("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7295
+ return r.status === 0 && (r.stdout || "").trim().length > 0;
7296
+ } catch {
7297
+ return false;
7298
+ }
7299
+ }
7300
+ async function collectChecks() {
7301
+ const checks = [];
7302
+ const push = (name, status, detail, fix, notes) => {
7303
+ checks.push({ name, status, detail, fix, notes });
7304
+ };
7305
+ const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7306
+ const earlyState = getRunningState();
7307
+ let kernelProxyPort = null;
7308
+ try {
7309
+ kernelProxyPort = earlyState.running ? getPorts().mixed : null;
7310
+ } catch {
7311
+ kernelProxyPort = null;
7312
+ }
7313
+ const kernelVersionPromise = hasKernel() ? withTimeout2(checkUpdate(kernelProxyPort), 4e3).then(
7314
+ (v) => v,
7315
+ () => null
7316
+ ) : Promise.resolve(null);
7317
+ if (!hasKernel()) {
7318
+ push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7319
+ } else {
7320
+ const v = getKernelVersion();
7321
+ const r = spawnSync6(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7322
+ if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7323
+ push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7324
+ } else if (r.error) {
7325
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7326
+ } else {
7327
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7328
+ }
7329
+ }
7330
+ try {
7331
+ fs11.accessSync(USER_DATA_DIR, fs11.constants.W_OK);
7332
+ push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7333
+ } catch {
7334
+ push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
7335
+ }
7336
+ if (fs11.existsSync(PATHS.settingsFile)) {
7337
+ if (isValidSettingsContent(fs11.readFileSync(PATHS.settingsFile, "utf8"))) {
7338
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7339
+ } else {
7340
+ push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
7341
+ }
7342
+ } else {
7343
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
7344
+ }
7345
+ const subs = getSubscriptionsWithCache();
7346
+ const active = getActiveSubscription();
7347
+ if (subs.length === 0) {
7348
+ push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
7349
+ } else {
7350
+ push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7351
+ if (active) {
7352
+ if (!readSubscriptionRawConfig(active.name)) {
7353
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
7354
+ } else {
7355
+ push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
7356
+ }
7357
+ const cached = subs.find((s) => s.name === active.name);
7358
+ if (cached?.updated_at) {
7359
+ const rel = formatRelativeTime(cached.updated_at);
7360
+ if (isSubscriptionStale(cached)) {
7361
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
7362
+ } else {
7363
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
7364
+ }
7365
+ }
7366
+ }
7367
+ }
7368
+ const service = getServiceStatus();
7369
+ const legacy = detectLegacySystemInstall();
7370
+ if (legacy) {
7371
+ push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
7372
+ } else if (!service.installed && !service.loaded) {
7373
+ push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
7374
+ } else if (!service.installed) {
7375
+ push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
7376
+ } else if (service.running) {
7377
+ const abnormalExit = describeAbnormalExit(service);
7378
+ push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
7379
+ if (abnormalExit) {
7380
+ push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
7381
+ }
7382
+ } else {
7383
+ const abnormalExit = describeAbnormalExit(service);
7384
+ if (!service.disabled && abnormalExit) {
7385
+ push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo stop \u505C\u6B62\u91CD\u8BD5");
7386
+ } else {
7387
+ push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
7388
+ }
7389
+ }
7390
+ const state = getRunningState();
7391
+ const info = getConfigInfo();
7392
+ let mixedPortDefault = DEFAULT_MIXED_PORT;
7393
+ try {
7394
+ const ports = getPorts();
7395
+ mixedPortDefault = ports.mixed;
7396
+ } catch (e) {
7397
+ push("\u7AEF\u53E3\u914D\u7F6E", "fail", e.message, "\u4FEE\u6B63 settings.json \u7684 ports\uFF081-65535 \u6574\u6570\uFF0Cmixed \u4E0E controller \u4E0D\u80FD\u76F8\u540C\uFF09");
7398
+ }
7399
+ const mixedPort = info?.mixedPort ?? mixedPortDefault;
7400
+ if (state.running) {
7401
+ if (isPortListening(mixedPort)) {
7402
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
7403
+ } else {
7404
+ push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
7405
+ }
7406
+ } else if (isPortListening(mixedPort)) {
7407
+ push("\u7AEF\u53E3", "warn", `${mixedPort} \u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\uFF0Cstart \u4F1A\u5931\u8D25`, `lsof -nP -iTCP:${mixedPort} \u67E5\u770B\u5360\u7528\u8005`);
7408
+ } else {
7409
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
7410
+ }
7411
+ if (active && hasKernel()) {
7412
+ try {
7413
+ const mode = info?.tun ? "tun" : "mixed";
7414
+ const prepared = await prepareConfigForStart(mode, active.name);
7415
+ const warnings = prepared.buildResult.warnings;
7416
+ if (warnings.length > 0) {
7417
+ push(
7418
+ "\u914D\u7F6E\u6784\u5EFA",
7419
+ "warn",
7420
+ `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
7421
+ void 0,
7422
+ warnings.map((w) => ` ${w}`)
7423
+ );
7424
+ } else {
7425
+ push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
7426
+ }
7427
+ } catch (e) {
7428
+ const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
7429
+ push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
7430
+ }
7431
+ } else {
7432
+ push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
7433
+ }
7434
+ if (state.running && info?.mixedPort) {
7435
+ const probe = await probeProxyConnectivity(info.mixedPort);
7436
+ if (probe.ok) {
7437
+ push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
7438
+ } else {
7439
+ push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
7440
+ }
7441
+ } else {
7442
+ push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
7443
+ }
7444
+ const kernelInfo = await kernelVersionPromise;
7445
+ if (hasKernel() && kernelInfo === null) {
7446
+ push("\u5185\u6838\u7248\u672C", "skip", "GitHub \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7447
+ } else if (kernelInfo?.needsUpdate) {
7448
+ push("\u5185\u6838\u7248\u672C", "warn", `\u5F53\u524D ${kernelInfo.current}\uFF0C\u6700\u65B0 ${kernelInfo.latest}`, "mihomo kernel");
7449
+ } else if (kernelInfo) {
7450
+ push("\u5185\u6838\u7248\u672C", "ok", `${kernelInfo.current}\uFF08\u6700\u65B0\uFF09`);
7451
+ }
7452
+ const latest = await latestVersionPromise;
7453
+ if (latest === null) {
7454
+ push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7455
+ } else if (compareVersions(latest, VERSION) > 0) {
7456
+ push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo update");
7457
+ } else {
7458
+ push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
7459
+ }
7460
+ return checks;
7461
+ }
7462
+ async function cmdDoctor(args = []) {
7463
+ assertKnownFlags(args.slice(1), [], "doctor");
7464
+ assertPositionalCount(args, 0, 1, "mihomo doctor");
7465
+ const checks = await collectChecks();
7466
+ console.log("");
7467
+ for (const c of checks) {
7468
+ const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
7469
+ console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
7470
+ if (c.status !== "ok" && c.status !== "skip") {
7471
+ for (const line of c.notes ?? []) console.log(colors.gray(line));
7472
+ if (c.fix) console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
7473
+ }
7474
+ }
7475
+ const ok = checks.filter((c) => c.status === "ok").length;
7476
+ const warn = checks.filter((c) => c.status === "warn").length;
7477
+ const fail = checks.filter((c) => c.status === "fail").length;
7478
+ const skip = checks.filter((c) => c.status === "skip").length;
7479
+ console.log("");
7480
+ console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38${skip > 0 ? `\uFF0C${skip} \u9879\u8DF3\u8FC7` : ""}`);
7481
+ console.log("");
7482
+ if (fail > 0) {
7483
+ throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
7484
+ label: "\u4F53\u68C0\u672A\u901A\u8FC7",
7485
+ hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
7486
+ });
8325
7487
  }
8326
7488
  }
8327
7489
 
@@ -8367,120 +7529,448 @@ async function cmdKernel(args) {
8367
7529
  if (err.response?.data?.documentation_url) {
8368
7530
  hint.push(`\u6587\u6863: ${err.response.data.documentation_url}`);
8369
7531
  }
8370
- if (!effectiveMirror) {
8371
- if (proxyRunning && !forceDirect) {
8372
- hint.push("", "\u63D0\u793A: \u7ECF\u672C\u673A\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u72B6\u6001\uFF08mihomo status\uFF09\uFF0C\u6216 mihomo kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
7532
+ if (!effectiveMirror) {
7533
+ if (proxyRunning && !forceDirect) {
7534
+ hint.push("", "\u63D0\u793A: \u7ECF\u672C\u673A\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u72B6\u6001\uFF08mihomo status\uFF09\uFF0C\u6216 mihomo kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
7535
+ } else {
7536
+ hint.push(
7537
+ "",
7538
+ "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
7539
+ " mihomo kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
7540
+ ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
7541
+ );
7542
+ }
7543
+ }
7544
+ throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
7545
+ }
7546
+ console.log(`\u5F53\u524D: ${info.current}`);
7547
+ console.log(`\u6700\u65B0: ${info.latest}`);
7548
+ if (!info.needsUpdate) {
7549
+ console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
7550
+ } else {
7551
+ console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
7552
+ let result;
7553
+ try {
7554
+ result = await downloadKernel((msg) => console.log(msg), channel, info.release);
7555
+ } catch (e) {
7556
+ if (e instanceof CliError) throw e;
7557
+ throw new CliError(e.message, {
7558
+ label: "\u4E0B\u8F7D\u5931\u8D25",
7559
+ hint: [
7560
+ "",
7561
+ "\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
7562
+ "\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09"
7563
+ ]
7564
+ });
7565
+ }
7566
+ console.log(`
7567
+ \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
7568
+ const state = getRunningState();
7569
+ if (state.running) {
7570
+ const restartCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
7571
+ console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
7572
+ }
7573
+ console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
7574
+ }
7575
+ }
7576
+
7577
+ // src/commands/log.ts
7578
+ function cmdLogs(args) {
7579
+ assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
7580
+ assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
7581
+ const lines = parseIntArg(args, "-n", "--lines", 100);
7582
+ const openInViewer = hasFlag(args, "-o", "--open");
7583
+ const follow = hasFlag(args, "-f", "--follow");
7584
+ const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
7585
+ const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
7586
+ if (targetName) {
7587
+ let logPath;
7588
+ if (targetName === "0") {
7589
+ logPath = getLogPath();
7590
+ } else {
7591
+ const parsedIdx = parseInt(targetName, 10);
7592
+ if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
7593
+ throw new CliError(`\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 "${targetName}"`, { hint: "\u7528\u6CD5: mihomo logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo logs" });
7594
+ }
7595
+ const archive = listLogs().archives[parsedIdx - 1];
7596
+ if (!archive) {
7597
+ throw new CliError(`\u672A\u627E\u5230\u65E5\u5FD7 "${targetName}"`, { hint: '\u4F7F\u7528 "mihomo logs" \u67E5\u770B\u53EF\u7528\u65E5\u5FD7\u5217\u8868' });
7598
+ }
7599
+ logPath = archive.path;
7600
+ }
7601
+ if (openInViewer) {
7602
+ openLogFile(logPath);
7603
+ return;
7604
+ }
7605
+ viewLogWithTail(logPath, { follow, lines });
7606
+ return;
7607
+ }
7608
+ const logs = listLogs();
7609
+ const all = [];
7610
+ if (logs.current) all.push(logs.current);
7611
+ all.push(...logs.archives);
7612
+ if (all.length === 0) {
7613
+ console.log("\u6682\u65E0\u65E5\u5FD7");
7614
+ return;
7615
+ }
7616
+ console.log("");
7617
+ console.log("\u65E5\u5FD7\u5217\u8868:");
7618
+ console.log("");
7619
+ let archiveCounter = 0;
7620
+ for (const log of all) {
7621
+ let num;
7622
+ if (log.isCurrent) {
7623
+ num = " 0";
7624
+ } else {
7625
+ archiveCounter++;
7626
+ num = archiveCounter < 10 ? ` ${archiveCounter}` : `${archiveCounter}`;
7627
+ }
7628
+ const time = formatDate(log.mtime);
7629
+ const size = formatBytes(log.size);
7630
+ const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
7631
+ console.log(` ${num}. ${name}`);
7632
+ console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
7633
+ if (!log.isCurrent) {
7634
+ console.log(` \u67E5\u770B: mihomo logs ${archiveCounter} \u6216 mihomo logs ${archiveCounter} -o`);
7635
+ }
7636
+ console.log("");
7637
+ }
7638
+ console.log("\u7528\u6CD5:");
7639
+ console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
7640
+ console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
7641
+ console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
7642
+ console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
7643
+ console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
7644
+ console.log("");
7645
+ }
7646
+
7647
+ // src/commands/overwrite.ts
7648
+ import path9 from "path";
7649
+ function printOverwriteList() {
7650
+ const info = listOverwriteFile();
7651
+ const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
7652
+ console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
7653
+ console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
7654
+ console.log("");
7655
+ if (info.files.length === 0 && info.broken.length === 0) {
7656
+ console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
7657
+ console.log("");
7658
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path9.join(info.dir, "overwrite.yaml")}`);
7659
+ console.log(` \u6216 ${path9.join(info.dir, "overwrite.dns.yaml")}`);
7660
+ console.log("");
7661
+ } else {
7662
+ const disabledCount = info.files.filter((f) => !f.enabled).length;
7663
+ const countText = disabledCount > 0 ? `${info.files.length} \u4E2A\uFF0C${info.files.length - disabledCount} \u4E2A\u672A\u7981\u7528\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D` : `${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D`;
7664
+ console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${countText}):`);
7665
+ console.log("");
7666
+ info.files.forEach((f, i) => {
7667
+ const num = i < 10 ? ` ${i}` : `${i}`;
7668
+ const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
7669
+ console.log(` ${num}. ${f.name}${mark}`);
7670
+ if (f.scope) {
7671
+ console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
7672
+ }
7673
+ if (f.keys.length > 0) {
7674
+ console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
7675
+ }
7676
+ });
7677
+ if (info.broken.length > 0) {
7678
+ console.log(colors.red(`\u52A0\u8F7D\u5931\u8D25 (${info.broken.length} \u4E2A\uFF0C\u672A\u53C2\u4E0E\u5408\u5E76\uFF1Bstart/doctor \u4F1A\u62A5\u9519):`));
7679
+ info.broken.forEach((b, i) => {
7680
+ const num = info.files.length + i < 10 ? ` ${info.files.length + i}` : `${info.files.length + i}`;
7681
+ console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
7682
+ console.log(colors.red(` ${b.message}`));
7683
+ });
7684
+ console.log("");
7685
+ }
7686
+ }
7687
+ console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
7688
+ console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
7689
+ console.log("\u505C\u7528\u5355\u4E2A\u6587\u4EF6: \u5728\u8BE5\u6587\u4EF6\u9876\u90E8\u5199 enabled: false");
7690
+ console.log("");
7691
+ }
7692
+ async function setOverwrite(enabled, args) {
7693
+ assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
7694
+ assertRestartOptionValues(args);
7695
+ if (isOverwriteEnabled() === enabled) {
7696
+ console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
7697
+ console.log("");
7698
+ printOverwriteList();
7699
+ return;
7700
+ }
7701
+ setOverwriteEnabled(enabled);
7702
+ console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
7703
+ if (await restartToApply(args)) return;
7704
+ console.log("");
7705
+ printOverwriteList();
7706
+ }
7707
+ var SUBCOMMANDS2 = [
7708
+ { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
7709
+ { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
7710
+ ];
7711
+ async function cmdOverwrite(args) {
7712
+ assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
7713
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
7714
+ // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
7715
+ fallback: () => {
7716
+ console.log("");
7717
+ printOverwriteList();
7718
+ },
7719
+ onUnknown: (action) => {
7720
+ if (action.startsWith("-")) {
7721
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
7722
+ label: "\u53C2\u6570\u9519\u8BEF",
7723
+ hint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo ow on|off [-s] [-u ms]"]
7724
+ });
7725
+ }
7726
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
7727
+ const suggestion = suggestSimilar(action, names);
7728
+ throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
7729
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
7730
+ });
7731
+ }
7732
+ });
7733
+ }
7734
+
7735
+ // src/commands/reset.ts
7736
+ import fs13 from "fs";
7737
+
7738
+ // src/process-stop.ts
7739
+ import { spawnSync as spawnSync7 } from "child_process";
7740
+ import fs12 from "fs";
7741
+ var PROCESS_WAIT_ATTEMPTS = 50;
7742
+ var PROCESS_WAIT_INTERVAL = 100;
7743
+ var BATCH_KILL_THRESHOLD = 3;
7744
+ function clearRuntime() {
7745
+ if (fs12.existsSync(DIRS.runtime)) {
7746
+ rmrf(DIRS.runtime);
7747
+ }
7748
+ ensureDirs();
7749
+ }
7750
+ function clearPid() {
7751
+ if (!fs12.existsSync(PATHS.pidFile)) return;
7752
+ if (isPidFileOwnedByRoot()) {
7753
+ try {
7754
+ spawnSync7("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
7755
+ } catch {
7756
+ }
7757
+ } else {
7758
+ try {
7759
+ fs12.unlinkSync(PATHS.pidFile);
7760
+ } catch {
7761
+ }
7762
+ }
7763
+ }
7764
+ function killProcess(pid) {
7765
+ try {
7766
+ process.kill(pid, "SIGKILL");
7767
+ return true;
7768
+ } catch {
7769
+ return false;
7770
+ }
7771
+ }
7772
+ function killAllMihomo(forceSudo = false) {
7773
+ const pattern = MAIN_INSTANCE_PATTERN;
7774
+ const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
7775
+ const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
7776
+ try {
7777
+ const result = spawnSync7(argv[0], argv[1], options);
7778
+ if (result.error) return false;
7779
+ return result.status === 0 || result.status === 1;
7780
+ } catch {
7781
+ return false;
7782
+ }
7783
+ }
7784
+ async function cleanupAll(forceSudo = false) {
7785
+ const pids = getMihomoPids();
7786
+ if (pids.length === 0) {
7787
+ clearPid();
7788
+ return { killed: 0, failed: 0, remaining: [] };
7789
+ }
7790
+ const hasRootProcess = pids.some((p) => isProcessRoot(p));
7791
+ const needsSudo = forceSudo || hasRootProcess;
7792
+ let killedCount = 0;
7793
+ const failedPids = [];
7794
+ if (needsSudo) {
7795
+ const success = killAllMihomo(true);
7796
+ if (success) {
7797
+ killedCount = pids.length;
7798
+ } else {
7799
+ failedPids.push(...pids);
7800
+ }
7801
+ } else {
7802
+ if (pids.length > BATCH_KILL_THRESHOLD) {
7803
+ if (killAllMihomo(false)) {
7804
+ killedCount = pids.length;
8373
7805
  } else {
8374
- hint.push(
8375
- "",
8376
- "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
8377
- " mihomo kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
8378
- ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
8379
- );
7806
+ failedPids.push(...pids);
7807
+ }
7808
+ } else {
7809
+ for (const pid of pids) {
7810
+ if (killProcess(pid)) {
7811
+ killedCount++;
7812
+ } else {
7813
+ failedPids.push(pid);
7814
+ }
8380
7815
  }
8381
7816
  }
8382
- throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
8383
7817
  }
8384
- console.log(`\u5F53\u524D: ${info.current}`);
8385
- console.log(`\u6700\u65B0: ${info.latest}`);
8386
- if (!info.needsUpdate) {
8387
- console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
8388
- } else {
8389
- console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
8390
- let result;
8391
- try {
8392
- result = await downloadKernel((msg) => console.log(msg), channel, info.release);
8393
- } catch (e) {
8394
- if (e instanceof CliError) throw e;
8395
- throw new CliError(e.message, {
8396
- label: "\u4E0B\u8F7D\u5931\u8D25",
8397
- hint: [
8398
- "",
8399
- "\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
8400
- "\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09"
8401
- ]
8402
- });
8403
- }
8404
- console.log(`
8405
- \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8406
- if (getRunningState().running) {
8407
- console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C mihomo start \u91CD\u542F\u540E\u751F\u6548"));
8408
- }
7818
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
7819
+ if (getMihomoPids().length === 0) break;
7820
+ await sleep(PROCESS_WAIT_INTERVAL);
7821
+ }
7822
+ clearPid();
7823
+ return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
7824
+ }
7825
+ async function stop(forceSudo = false) {
7826
+ const allPids = getMihomoPids();
7827
+ if (allPids.length === 0) {
7828
+ clearPid();
7829
+ clearRuntime();
7830
+ return { success: true, notRunning: true };
7831
+ }
7832
+ const result = await cleanupAll(forceSudo);
7833
+ const remaining = getMihomoPids();
7834
+ if (remaining.length > 0) {
7835
+ console.log("");
7836
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
7837
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
7838
+ console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
7839
+ console.log("");
7840
+ return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
8409
7841
  }
7842
+ clearRuntime();
7843
+ return { success: true, killed: result.killed };
8410
7844
  }
8411
7845
 
8412
- // src/commands/log.ts
8413
- function cmdLogs(args) {
8414
- assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8415
- assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
8416
- const lines = parseIntArg(args, "-n", "--lines", 100);
8417
- const openInViewer = hasFlag(args, "-o", "--open");
8418
- const follow = hasFlag(args, "-f", "--follow");
8419
- const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8420
- const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8421
- if (targetName) {
8422
- let logPath;
8423
- if (targetName === "0") {
8424
- logPath = getLogPath();
8425
- } else {
8426
- const parsedIdx = parseInt(targetName, 10);
8427
- if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
8428
- throw new CliError(`\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 "${targetName}"`, { hint: "\u7528\u6CD5: mihomo logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo logs" });
8429
- }
8430
- const archive = listLogs().archives[parsedIdx - 1];
8431
- if (!archive) {
8432
- throw new CliError(`\u672A\u627E\u5230\u65E5\u5FD7 "${targetName}"`, { hint: '\u4F7F\u7528 "mihomo logs" \u67E5\u770B\u53EF\u7528\u65E5\u5FD7\u5217\u8868' });
8433
- }
8434
- logPath = archive.path;
7846
+ // src/commands/reset.ts
7847
+ var RESET_TARGETS = [
7848
+ { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
7849
+ { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
7850
+ { id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
7851
+ { id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
7852
+ {
7853
+ id: "overwrites",
7854
+ aliases: ["overwrite", "overwrites", "ow"],
7855
+ label: "\u8986\u5199",
7856
+ needsStop: false,
7857
+ preserveOnBare: true,
7858
+ paths: () => fs13.existsSync(USER_DATA_DIR) ? fs13.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
7859
+ },
7860
+ {
7861
+ id: "settings",
7862
+ aliases: ["setting", "settings", "config"],
7863
+ label: "\u8BBE\u7F6E",
7864
+ needsStop: false,
7865
+ preserveOnBare: true,
7866
+ // 损坏备份也包含订阅凭据,需要一起删除
7867
+ paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
7868
+ },
7869
+ { id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
7870
+ { id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
7871
+ ];
7872
+ function resolveResetTargets(names) {
7873
+ const matched = /* @__PURE__ */ new Set();
7874
+ for (const name of names) {
7875
+ const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
7876
+ if (!target) {
7877
+ throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
8435
7878
  }
8436
- if (openInViewer) {
8437
- openLogFile(logPath);
7879
+ matched.add(target);
7880
+ }
7881
+ return [...matched];
7882
+ }
7883
+ async function cmdReset(args) {
7884
+ assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
7885
+ const names = args.slice(1).filter((a) => !a.startsWith("-"));
7886
+ const namedTargets = resolveResetTargets(names);
7887
+ const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
7888
+ const ids = new Set(targets.map((t) => t.id));
7889
+ const needsStop = targets.some((t) => t.needsStop);
7890
+ const serviceTargeted = ids.has("service");
7891
+ const service = getServiceStatus();
7892
+ const serviceActive = service.installed || service.loaded;
7893
+ const legacy = detectLegacySystemInstall();
7894
+ if (targets.length === 1) {
7895
+ if (serviceTargeted && !serviceActive && !legacy) {
7896
+ console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
8438
7897
  return;
8439
7898
  }
8440
- viewLogWithTail(logPath, { follow, lines });
8441
- return;
8442
7899
  }
8443
- const logs = listLogs();
8444
- const all = [];
8445
- if (logs.current) all.push(logs.current);
8446
- all.push(...logs.archives);
8447
- if (all.length === 0) {
8448
- console.log("\u6682\u65E0\u65E5\u5FD7");
7900
+ if (ids.has("kernel") && getMihomoPids().length > 0) {
7901
+ console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
7902
+ }
7903
+ if (serviceTargeted && serviceActive) {
7904
+ console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
7905
+ } else if (needsStop && serviceActive) {
7906
+ console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
7907
+ }
7908
+ if ((needsStop || serviceTargeted) && legacy) {
7909
+ console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7910
+ }
7911
+ console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
7912
+ if (ids.has("subs")) {
7913
+ console.log(colors.yellow("\u8BA2\u9605\u94FE\u63A5\u4E0E\u672C\u5730\u914D\u7F6E\u5C06\u88AB\u5220\u9664\u4E14\u65E0\u6CD5\u6062\u590D\uFF0C\u9700\u91CD\u65B0\u4ECE\u673A\u573A\u83B7\u53D6\u8BA2\u9605\u5730\u5740"));
7914
+ }
7915
+ if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
7916
+ nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
7917
+ hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
7918
+ })) {
7919
+ console.log("\u5DF2\u53D6\u6D88");
8449
7920
  return;
8450
7921
  }
8451
- console.log("");
8452
- console.log("\u65E5\u5FD7\u5217\u8868:");
8453
- console.log("");
8454
- let archiveCounter = 0;
8455
- for (const log of all) {
8456
- let num;
8457
- if (log.isCurrent) {
8458
- num = " 0";
8459
- } else {
8460
- archiveCounter++;
8461
- num = archiveCounter < 10 ? ` ${archiveCounter}` : `${archiveCounter}`;
7922
+ if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
7923
+ if (serviceActive) {
7924
+ if (serviceTargeted) await uninstallService();
7925
+ else if (needsStop) await stopService();
7926
+ }
7927
+ if (needsStop) {
7928
+ const cleanup = await cleanupAll();
7929
+ if (cleanup.remaining.length > 0) {
7930
+ throw new CliError(cleanup.remaining.join(", "), {
7931
+ label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
7932
+ hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
7933
+ });
8462
7934
  }
8463
- const time = formatDate(log.mtime);
8464
- const size = formatBytes(log.size);
8465
- const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8466
- console.log(` ${num}. ${name}`);
8467
- console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
8468
- if (!log.isCurrent) {
8469
- console.log(` \u67E5\u770B: mihomo logs ${archiveCounter} \u6216 mihomo logs ${archiveCounter} -o`);
7935
+ recordServiceStopped();
7936
+ }
7937
+ const deleted = /* @__PURE__ */ new Set();
7938
+ for (const target of targets) {
7939
+ let hadContent = target.id === "service" && (serviceActive || legacy);
7940
+ for (const filePath of target.paths()) {
7941
+ if (!fs13.existsSync(filePath)) continue;
7942
+ try {
7943
+ rmrf(filePath);
7944
+ } catch (e) {
7945
+ throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
7946
+ }
7947
+ hadContent = true;
8470
7948
  }
8471
- console.log("");
7949
+ if (hadContent) deleted.add(target.id);
8472
7950
  }
8473
- console.log("\u7528\u6CD5:");
8474
- console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8475
- console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
8476
- console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
8477
- console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8478
- console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8479
- console.log("");
7951
+ if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
7952
+ updateSettings((settings) => {
7953
+ const patch = {};
7954
+ if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
7955
+ patch.subscriptions = void 0;
7956
+ patch.active_subscription = void 0;
7957
+ deleted.add("subs");
7958
+ }
7959
+ if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
7960
+ patch.overwrite_enabled = void 0;
7961
+ deleted.add("overwrites");
7962
+ }
7963
+ return patch;
7964
+ });
7965
+ }
7966
+ if (ids.has("kernel")) clearKernelVersionCache();
7967
+ ensureDirs();
7968
+ const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
7969
+ console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
8480
7970
  }
8481
7971
 
8482
7972
  // src/commands/service.ts
8483
- import fs15 from "fs";
7973
+ import fs14 from "fs";
8484
7974
  async function handleLegacyInstall() {
8485
7975
  if (!detectLegacySystemInstall()) return;
8486
7976
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -8532,7 +8022,7 @@ async function cmdInstall(args) {
8532
8022
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8533
8023
  } else {
8534
8024
  console.log("\u542F\u52A8: mihomo start");
8535
- if (!fs15.existsSync(PATHS.configFile)) {
8025
+ if (!fs14.existsSync(PATHS.configFile)) {
8536
8026
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8537
8027
  }
8538
8028
  }
@@ -8616,12 +8106,261 @@ async function cmdStop(args) {
8616
8106
  console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
8617
8107
  }
8618
8108
 
8109
+ // src/commands/subscription.ts
8110
+ import { spawnSync as spawnSync8 } from "child_process";
8111
+ function printRestartHintIfRunning() {
8112
+ const state = getRunningState();
8113
+ if (state.running) {
8114
+ const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
8115
+ console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`));
8116
+ console.log("");
8117
+ }
8118
+ }
8119
+ function printSubscriptionList() {
8120
+ const subs = getSubscriptionsWithCache();
8121
+ if (subs.length === 0) {
8122
+ console.log("\u6CA1\u6709\u8BA2\u9605");
8123
+ console.log("");
8124
+ console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
8125
+ console.log("");
8126
+ return;
8127
+ }
8128
+ const activeSub = getActiveSubscription();
8129
+ console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
8130
+ subs.forEach((s, i) => {
8131
+ const rel = formatRelativeTime(s.updated_at);
8132
+ const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
8133
+ const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
8134
+ const interval = resolveUpdateInterval(s.update_interval);
8135
+ console.log(` ${i + 1}. ${s.name}${defaultMark}`);
8136
+ console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
8137
+ if (s.username) {
8138
+ console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
8139
+ }
8140
+ const traffic = formatTraffic(s.upload, s.download, s.total);
8141
+ if (traffic) {
8142
+ console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
8143
+ }
8144
+ if (s.expire !== void 0) {
8145
+ console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
8146
+ }
8147
+ if (s.web_page_url) {
8148
+ console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
8149
+ }
8150
+ });
8151
+ console.log("");
8152
+ console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
8153
+ console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
8154
+ console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
8155
+ console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
8156
+ console.log("");
8157
+ }
8158
+ function assertNotFlagLike(name, usage) {
8159
+ if (name.startsWith("-")) {
8160
+ throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
8161
+ label: "\u53C2\u6570\u9519\u8BEF",
8162
+ hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
8163
+ });
8164
+ }
8165
+ }
8166
+ function readUrlFromClipboard() {
8167
+ if (!process.stdin.isTTY) return null;
8168
+ try {
8169
+ const r = spawnSync8("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8170
+ if (r.status !== 0) return null;
8171
+ const text = (r.stdout || "").trim();
8172
+ return isValidHttpUrl(text) ? text : null;
8173
+ } catch {
8174
+ return null;
8175
+ }
8176
+ }
8177
+ async function subAdd(args) {
8178
+ assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
8179
+ let url = args[2]?.trim();
8180
+ const name = args[3] || "default";
8181
+ if (!url) {
8182
+ const clipped = readUrlFromClipboard();
8183
+ if (clipped) {
8184
+ console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
8185
+ console.log(` ${maskUrl(clipped)}`);
8186
+ if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
8187
+ console.log("\u5DF2\u53D6\u6D88");
8188
+ return;
8189
+ }
8190
+ url = clipped;
8191
+ } else if (process.stdin.isTTY) {
8192
+ throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
8193
+ hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
8194
+ });
8195
+ } else {
8196
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
8197
+ }
8198
+ }
8199
+ if (!isValidHttpUrl(url)) {
8200
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
8201
+ }
8202
+ assertNotFlagLike(name, "mihomo sub add <url> [name]");
8203
+ console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
8204
+ addSubscription(url, name);
8205
+ try {
8206
+ const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
8207
+ setDefaultSubscription(name);
8208
+ console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
8209
+ } catch (e) {
8210
+ removeSubscription(name);
8211
+ if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
8212
+ throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
8213
+ }
8214
+ console.log("");
8215
+ printRestartHintIfRunning();
8216
+ printSubscriptionList();
8217
+ }
8218
+ async function subUpdate(args) {
8219
+ assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
8220
+ const nameArg = getNonFlagArg(args, 2);
8221
+ const subs = getSubscriptions();
8222
+ if (subs.length === 0) {
8223
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605");
8224
+ }
8225
+ if (nameArg === "") {
8226
+ throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo sub update <\u540D\u79F0>`] });
8227
+ }
8228
+ if (nameArg === null) {
8229
+ console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
8230
+ const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
8231
+ let ok = 0;
8232
+ for (const r of results) {
8233
+ if (r.success) ok++;
8234
+ printUpdateResult(r);
8235
+ }
8236
+ const failedResults = results.filter((r) => !r.success);
8237
+ console.log("");
8238
+ if (failedResults.length > 0) {
8239
+ console.log(colors.yellow(`\u66F4\u65B0\u5B8C\u6210: ${ok} \u4E2A\u6210\u529F\uFF0C${failedResults.length} \u4E2A\u5931\u8D25`));
8240
+ }
8241
+ printRestartHintIfRunning();
8242
+ printSubscriptionList();
8243
+ if (failedResults.length > 0) {
8244
+ const allFailed = failedResults.length === results.length;
8245
+ throw new CliError(allFailed ? "\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25" : `${failedResults.length} \u4E2A\u8BA2\u9605\u66F4\u65B0\u5931\u8D25: ${failedResults.map((r) => r.name).join("\u3001")}`, {
8246
+ hint: failedResults.map((r) => `\u91CD\u8BD5: mihomo sub update ${r.name}`)
8247
+ });
8248
+ }
8249
+ return;
8250
+ }
8251
+ const target = resolveSubscription(subs, nameArg);
8252
+ console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
8253
+ const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
8254
+ if (!result.success) {
8255
+ throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
8256
+ }
8257
+ console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
8258
+ console.log("");
8259
+ printRestartHintIfRunning();
8260
+ printSubscriptionList();
8261
+ }
8262
+ async function subUse(args) {
8263
+ assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
8264
+ assertRestartOptionValues(args);
8265
+ const name = getNonFlagArg(args, 2);
8266
+ const subs = getSubscriptions();
8267
+ if (subs.length === 0) {
8268
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
8269
+ }
8270
+ if (!name) {
8271
+ throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
8272
+ hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
8273
+ });
8274
+ }
8275
+ const target = resolveSubscription(subs, name);
8276
+ const currentDefault = getActiveSubscription();
8277
+ const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
8278
+ if (isAlreadyDefault) {
8279
+ console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
8280
+ console.log("");
8281
+ printSubscriptionList();
8282
+ return;
8283
+ }
8284
+ const success = setDefaultSubscription(target.name);
8285
+ if (!success) {
8286
+ throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
8287
+ }
8288
+ console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
8289
+ if (await restartToApply(args)) return;
8290
+ console.log("");
8291
+ printSubscriptionList();
8292
+ }
8293
+ async function subRemove(args) {
8294
+ assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
8295
+ const name = getNonFlagArg(args, 2);
8296
+ const subs = getSubscriptions();
8297
+ if (!name) {
8298
+ throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
8299
+ hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
8300
+ });
8301
+ }
8302
+ const target = resolveSubscription(subs, name);
8303
+ const isExact = target.name === name;
8304
+ const skipConfirm = hasFlag(args, "-y", "--yes");
8305
+ if (!isExact && !skipConfirm) {
8306
+ console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
8307
+ if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
8308
+ nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
8309
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
8310
+ })) {
8311
+ console.log("\u5DF2\u53D6\u6D88");
8312
+ return;
8313
+ }
8314
+ }
8315
+ const switchedTo = removeSubscription(target.name);
8316
+ console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
8317
+ if (switchedTo) {
8318
+ console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
8319
+ }
8320
+ console.log("");
8321
+ printSubscriptionList();
8322
+ }
8323
+ var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
8324
+ var REMOVE_FLAGS = ["-y", "--yes"];
8325
+ function withKnownFlags(usage, known, handler) {
8326
+ return async (args) => {
8327
+ assertKnownFlags(args, known, usage);
8328
+ await handler(args);
8329
+ };
8330
+ }
8331
+ var SUBCOMMANDS3 = [
8332
+ { name: "add", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
8333
+ { name: "update", handler: withKnownFlags("sub update [name]", [], subUpdate) },
8334
+ { name: "use", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
8335
+ { name: "remove", aliases: ["rm", "delete"], handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
8336
+ ];
8337
+ async function cmdSubscription(args) {
8338
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
8339
+ // 无子命令 → 列表;未知子命令 → 报错
8340
+ fallback: printSubscriptionList,
8341
+ onUnknown: (action) => {
8342
+ if (action.startsWith("-")) {
8343
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
8344
+ label: "\u53C2\u6570\u9519\u8BEF",
8345
+ hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
8346
+ });
8347
+ }
8348
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
8349
+ const suggestion = suggestSimilar(action, names);
8350
+ throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
8351
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
8352
+ });
8353
+ }
8354
+ });
8355
+ }
8356
+
8619
8357
  // src/commands/ui.ts
8620
8358
  import { spawnSync as spawnSync9 } from "child_process";
8621
8359
  function resolveUiName(args) {
8622
- const name = (args[1] ?? "zash").toLowerCase();
8360
+ const raw = getNonFlagArg(args, 1);
8361
+ const name = (raw ?? "zash").toLowerCase();
8623
8362
  if (name === "" || !Object.hasOwn(UI_URLS, name)) {
8624
- throw new CliError(`\u672A\u77E5\u7684 UI "${args[1] ?? ""}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
8363
+ throw new CliError(`\u672A\u77E5\u7684 UI "${raw ?? ""}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
8625
8364
  }
8626
8365
  return name;
8627
8366
  }
@@ -8633,22 +8372,30 @@ function copyToClipboard(text) {
8633
8372
  }
8634
8373
  }
8635
8374
  function cmdUI(args) {
8636
- assertKnownFlags(args.slice(1), [], "ui");
8637
- assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd]");
8375
+ assertKnownFlags(args.slice(1), ["-c", "--copy-secret"], "ui [zash|dash|yacd] [-c]");
8376
+ assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd] [-c]");
8638
8377
  const uiName = resolveUiName(args);
8378
+ const copySecret = hasFlag(args, "-c", "--copy-secret");
8639
8379
  if (!getRunningState().running) {
8640
8380
  console.log(colors.yellow("\u63D0\u793A: mihomo \u672A\u8FD0\u884C\uFF0CUI \u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\uFF08\u5148\u6267\u884C mihomo start \u542F\u52A8\uFF09"));
8641
8381
  console.log("");
8642
8382
  }
8643
8383
  const url = UI_URLS[uiName];
8384
+ const controllerPort = getPorts().controller;
8644
8385
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
8645
- console.log(`\u5730\u5740: ${url}`);
8386
+ console.log(`\u9875\u9762: ${url}`);
8387
+ console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${controllerPort}`);
8646
8388
  const secret = readSettings().controller_secret;
8647
8389
  if (typeof secret === "string" && secret) {
8648
- console.log(
8649
- copyToClipboard(secret) ? "\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34\uFF09" : `\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08UI \u8FDE\u63A5 127.0.0.1:${getPorts().controller} \u65F6\u9700\u8F93\u5165\uFF0C\u5BC6\u94A5\u89C1 settings.json\uFF09`
8650
- );
8390
+ if (copySecret) {
8391
+ console.log(
8392
+ copyToClipboard(secret) ? "\u8BBF\u95EE\u5BC6\u94A5\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34" : colors.yellow("\u8BBF\u95EE\u5BC6\u94A5\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u5230 settings.json \u67E5\u770B controller_secret")
8393
+ );
8394
+ } else {
8395
+ console.log(colors.gray("\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF0CUI \u8FDE\u63A5\u65F6\u9700\u8F93\u5165\uFF08mihomo ui -c \u53EF\u590D\u5236\u5230\u526A\u8D34\u677F\uFF09"));
8396
+ }
8651
8397
  }
8398
+ console.log("");
8652
8399
  openUrl(url);
8653
8400
  }
8654
8401
 
@@ -8704,7 +8451,7 @@ var COMMANDS = [
8704
8451
  aliases: [],
8705
8452
  handler: cmdUI,
8706
8453
  group: "interface",
8707
- usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
8454
+ usage: [{ signature: "ui [zash|dash|yacd] [-c]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF1B-c \u590D\u5236\u63A7\u5236\u5668\u8BBF\u95EE\u5BC6\u94A5\uFF09" }]
8708
8455
  },
8709
8456
  {
8710
8457
  name: "logs",
@@ -8742,7 +8489,7 @@ var COMMANDS = [
8742
8489
  aliases: [],
8743
8490
  handler: cmdConfig,
8744
8491
  group: "config",
8745
- usage: [{ signature: "config [--json]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF09" }]
8492
+ usage: [{ signature: "config [--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
8746
8493
  },
8747
8494
  {
8748
8495
  name: "overwrite",
@@ -8791,26 +8538,15 @@ var COMMANDS = [
8791
8538
  aliases: [],
8792
8539
  handler: cmdDoctor,
8793
8540
  group: "system",
8794
- usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027/CLI \u7248\u672C\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
8795
- },
8796
- {
8797
- name: "completion",
8798
- aliases: [],
8799
- handler: (args) => cmdCompletion(args, COMMANDS),
8800
- group: "system",
8801
- usage: [
8802
- { signature: "completion install <zsh|bash|fish>", description: "\u5B89\u88C5\u8865\u5168\u5230\u5BF9\u5E94 shell \u7684\u9ED8\u8BA4\u4F4D\u7F6E" },
8803
- { signature: "completion uninstall <zsh|bash|fish>", description: "\u79FB\u9664\u5DF2\u5B89\u88C5\u7684\u8865\u5168" },
8804
- { signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA\u8865\u5168\u811A\u672C\uFF08\u91CD\u5B9A\u5411\u6216 eval \u4F7F\u7528\uFF09" }
8805
- ]
8541
+ usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027/\u5185\u6838\u4E0E CLI \u7248\u672C\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
8806
8542
  },
8807
8543
  // === meta(不在分组清单展示,help 末尾单列) ===
8808
8544
  {
8809
8545
  name: "help",
8810
8546
  aliases: ["-h", "--help"],
8811
- handler: () => printHelp(COMMANDS),
8547
+ handler: (args) => printHelpEntry(args, COMMANDS, findCommand),
8812
8548
  group: "meta",
8813
- usage: [{ signature: "help, -h", description: "\u663E\u793A\u5E2E\u52A9" }]
8549
+ usage: [{ signature: "help [\u547D\u4EE4]", description: "\u663E\u793A\u5E2E\u52A9\uFF08\u65E0\u53C2\u6570\u663E\u793A\u5168\u90E8\u547D\u4EE4\uFF09" }]
8814
8550
  },
8815
8551
  {
8816
8552
  name: "version",
@@ -8862,13 +8598,24 @@ process.on("unhandledRejection", (reason) => {
8862
8598
  \u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
8863
8599
  process.exit(1);
8864
8600
  });
8601
+ var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
8602
+ function readSelfMixedPortEarly() {
8603
+ try {
8604
+ const raw = JSON.parse(fs15.readFileSync(PATHS.settingsFile, "utf8"));
8605
+ const mixed = raw?.ports?.mixed;
8606
+ if (typeof mixed === "number" && Number.isInteger(mixed) && mixed >= 1 && mixed <= 65535) return mixed;
8607
+ } catch {
8608
+ }
8609
+ return DEFAULT_MIXED_PORT;
8610
+ }
8865
8611
  function clearProxyEnv() {
8866
- delete process.env.http_proxy;
8867
- delete process.env.https_proxy;
8868
- delete process.env.HTTP_PROXY;
8869
- delete process.env.HTTPS_PROXY;
8870
- delete process.env.all_proxy;
8871
- delete process.env.ALL_PROXY;
8612
+ const selfPort = readSelfMixedPortEarly();
8613
+ for (const key of PROXY_ENV_KEYS) {
8614
+ const value = process.env[key];
8615
+ if (value && proxyEnvPointsAtSelf(value, selfPort)) {
8616
+ delete process.env[key];
8617
+ }
8618
+ }
8872
8619
  }
8873
8620
  var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
8874
8621
  function assertNotRoot(commandName) {
@@ -8939,7 +8686,11 @@ async function main() {
8939
8686
  }
8940
8687
  if (command.group === "meta") {
8941
8688
  assertKnownFlags(args.slice(1), [], command.name);
8942
- assertPositionalCount(args, 0, 1, `mihomo ${command.name}`);
8689
+ assertPositionalCount(args, command.name === "help" ? 1 : 0, 1, `mihomo ${command.name}`);
8690
+ }
8691
+ if (command.group !== "meta" && (args[1] === "-h" || args[1] === "--help" || args[1] === "help")) {
8692
+ printCommandHelp(command);
8693
+ return;
8943
8694
  }
8944
8695
  await command.handler(command.rewrite ? command.rewrite(args) : args);
8945
8696
  }