mihomo-cli 4.13.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 {
@@ -4008,10 +4011,22 @@ function normalizeEnabled(raw, fileName) {
4008
4011
  }
4009
4012
  );
4010
4013
  }
4011
- function loadOverwriteFile() {
4012
- const dir = USER_DATA_DIR;
4013
- if (!fs3.existsSync(dir)) return [];
4014
- 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);
4015
4030
  const files = entries.filter(isOverwriteFilename).sort((a, b) => {
4016
4031
  if (a === "overwrite.yaml") return -1;
4017
4032
  if (b === "overwrite.yaml") return 1;
@@ -4022,27 +4037,35 @@ function loadOverwriteFile() {
4022
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`
4023
4038
  );
4024
4039
  }
4025
- const results = [];
4026
4040
  for (const file of files) {
4027
- const filePath = path3.join(dir, file);
4041
+ const filePath = path3.join(USER_DATA_DIR, file);
4028
4042
  try {
4029
4043
  const content = fs3.readFileSync(filePath, "utf8");
4030
4044
  const parsed = load(content, { maxAliases: 200 });
4031
4045
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4032
4046
  const { match, enabled, ...config } = parsed;
4033
4047
  assertNoMetadataKeyLookalikes(config, file);
4034
- 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) });
4035
4049
  } else if (parsed !== null) {
4036
- 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
+ });
4037
4055
  }
4038
4056
  } catch (e) {
4039
- if (e instanceof CliError) throw e;
4040
- const message = e.message;
4041
- 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"' : "";
4042
- console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}${aliasHint}`);
4057
+ broken.push(toBrokenFile(file, filePath, e));
4043
4058
  }
4044
4059
  }
4045
- 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;
4046
4069
  }
4047
4070
  function applyOverwrite(baseConfig, files) {
4048
4071
  let result = { ...baseConfig };
@@ -4057,25 +4080,23 @@ function applyOverwrite(baseConfig, files) {
4057
4080
  return { config: result, skipped, operatorShapedKeys };
4058
4081
  }
4059
4082
  function listOverwriteFile(scope) {
4060
- const files = loadOverwriteFile();
4083
+ const { ok, broken } = readOverwriteFiles();
4061
4084
  const enabled = isOverwriteEnabled();
4062
4085
  return {
4063
4086
  enabled,
4064
4087
  dir: USER_DATA_DIR,
4065
- files: files.map((f) => ({
4088
+ files: ok.map((f) => ({
4066
4089
  name: f.name,
4067
4090
  path: f.path,
4068
4091
  keys: Object.keys(f.config || {}),
4069
4092
  scope: summarizeMatch(f.match),
4070
4093
  enabled: f.enabled !== false,
4071
4094
  ...scope ? { matched: matchesScope(f.match, scope) } : {}
4072
- }))
4095
+ })),
4096
+ broken
4073
4097
  };
4074
4098
  }
4075
4099
 
4076
- // src/utils.ts
4077
- import os2 from "os";
4078
-
4079
4100
  // src/flags.ts
4080
4101
  var FLAGS = [
4081
4102
  // === start 的选项(重启透传) ===
@@ -4125,6 +4146,21 @@ function sanitizeTerminal(s) {
4125
4146
  function shellQuote(s) {
4126
4147
  return `'${s.replace(/'/g, "'\\''")}'`;
4127
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
+ }
4128
4164
  function displayWidth(s) {
4129
4165
  let width = 0;
4130
4166
  for (const ch of s) {
@@ -4301,12 +4337,12 @@ function assertRestartOptionValues(args) {
4301
4337
  if (!args) return;
4302
4338
  parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
4303
4339
  }
4304
- function getNonFlagArg(args, startIdx, valueFlags = VALUE_FLAGS) {
4340
+ function getNonFlagArg(args, startIdx) {
4305
4341
  if (!args) return null;
4306
4342
  for (let i = startIdx; i < args.length; i++) {
4307
4343
  const a = args[i];
4308
4344
  if (a.startsWith("-")) {
4309
- if (valueFlags.has(a)) i++;
4345
+ if (VALUE_FLAGS.has(a)) i++;
4310
4346
  continue;
4311
4347
  }
4312
4348
  return a;
@@ -4343,19 +4379,6 @@ function suggestSimilar(input, candidates) {
4343
4379
  scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
4344
4380
  return scored.slice(0, 3).map((s) => s.name);
4345
4381
  }
4346
- function hasGlobalIpv6() {
4347
- for (const addrs of Object.values(os2.networkInterfaces())) {
4348
- for (const addr of addrs ?? []) {
4349
- if (addr.family !== "IPv6" || addr.internal) continue;
4350
- if (/^(fe80|f[c-d])/i.test(addr.address)) continue;
4351
- return true;
4352
- }
4353
- }
4354
- return false;
4355
- }
4356
- function getDefaultMirror() {
4357
- return hasGlobalIpv6() ? MIRROR_ALIASES.v6 : MIRROR_BARE;
4358
- }
4359
4382
  function normalizeMirrorUrl(val) {
4360
4383
  if (!val) return null;
4361
4384
  if (val === "direct") return null;
@@ -4401,7 +4424,7 @@ function parseMirrorArg(args) {
4401
4424
  const inline = mirrorEq?.slice("--mirror=".length);
4402
4425
  const nextArg = inline ?? args[mirrorIdx + 1];
4403
4426
  if (!nextArg || nextArg.startsWith("-")) {
4404
- return { mirror: getDefaultMirror(), isOverride: true };
4427
+ return { mirror: MIRROR_BARE, isOverride: true };
4405
4428
  }
4406
4429
  const normalized = normalizeMirrorUrl(nextArg);
4407
4430
  return { mirror: normalized, isOverride: true };
@@ -4665,7 +4688,13 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4665
4688
  for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
4666
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`);
4667
4690
  }
4668
- 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
+ );
4669
4698
  return hint;
4670
4699
  }
4671
4700
  async function validateConfigWithKernel(config, overwriteSummaries) {
@@ -4763,18 +4792,19 @@ import path7 from "path";
4763
4792
  import fs5 from "fs";
4764
4793
  import path5 from "path";
4765
4794
  var DEFAULT_LOG_RETENTION_DAYS = 7;
4795
+ var LOG_TAIL_LINES = 15;
4766
4796
  var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
4767
4797
  function isArchiveLogFilename(filename) {
4768
4798
  return ARCHIVE_LOG_RE.test(filename);
4769
4799
  }
4770
4800
  function rotateAndCleanupLogs() {
4771
4801
  rotateLog();
4772
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4802
+ cleanupOldLogs();
4773
4803
  }
4774
4804
  function getLogPath() {
4775
4805
  return PATHS.logFile;
4776
4806
  }
4777
- function readLogTail(maxLines = 15) {
4807
+ function readLogTail() {
4778
4808
  const TAIL_BYTES = 64 * 1024;
4779
4809
  let fd = null;
4780
4810
  try {
@@ -4785,7 +4815,7 @@ function readLogTail(maxLines = 15) {
4785
4815
  const buf = Buffer.alloc(length);
4786
4816
  fd = fs5.openSync(PATHS.logFile, "r");
4787
4817
  fs5.readSync(fd, buf, 0, length, start);
4788
- 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);
4789
4819
  } catch {
4790
4820
  return [];
4791
4821
  } finally {
@@ -4844,12 +4874,12 @@ function rotateLog() {
4844
4874
  }
4845
4875
  return rotatedPath;
4846
4876
  }
4847
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4877
+ function cleanupOldLogs() {
4848
4878
  const logsDir = DIRS.logs;
4849
4879
  if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4850
4880
  const files = fs5.readdirSync(logsDir);
4851
4881
  const now = Date.now();
4852
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4882
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
4853
4883
  let deleted = 0;
4854
4884
  let errors = 0;
4855
4885
  for (const file of files) {
@@ -5635,6 +5665,38 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
5635
5665
  );
5636
5666
  console.log(lines.join("\n"));
5637
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
+ }
5638
5700
  function printVersion() {
5639
5701
  const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5640
5702
  console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
@@ -5642,322 +5704,111 @@ function printVersion() {
5642
5704
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5643
5705
  }
5644
5706
 
5645
- // src/commands/completion.ts
5646
- import fs12 from "fs";
5647
- import os3 from "os";
5648
- import path9 from "path";
5649
-
5650
- // src/open.ts
5651
- import { spawn } from "child_process";
5652
-
5653
- // src/lifecycle.ts
5654
- var silentSigint = false;
5655
- function setSilentSigint(value) {
5656
- 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;
5657
5731
  }
5658
- function isSilentSigint() {
5659
- return silentSigint;
5732
+ function redactConfigSecrets(config) {
5733
+ const state = { changed: false };
5734
+ return { config: walk(config, false, state), changed: state.changed };
5660
5735
  }
5661
5736
 
5662
- // src/open.ts
5663
- 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) {
5664
5741
  try {
5665
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5666
- child.unref();
5667
- child.on("error", () => {
5668
- });
5742
+ return new URL(url).protocol === "https:";
5669
5743
  } catch {
5744
+ return false;
5670
5745
  }
5671
5746
  }
5672
- function openLogFile(logPath, label) {
5673
- const displayLabel = label || logPath;
5674
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
5675
- openUrl(logPath);
5676
- }
5677
- function viewLogWithTail(logPath, options) {
5678
- const follow = options?.follow;
5679
- const lines = options?.lines || 100;
5680
- console.log(`\u65E5\u5FD7: ${logPath}`);
5681
- if (follow) {
5682
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5683
- } else {
5684
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5685
- `);
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 {
5686
5753
  }
5687
- const tailArgs = [];
5688
- if (follow) tailArgs.push("-f");
5689
- tailArgs.push("-n", lines.toString());
5690
- tailArgs.push(logPath);
5691
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5692
- if (follow) setSilentSigint(true);
5693
- tail.on("close", (code) => process.exit(code ?? 0));
5694
- tail.on("error", (e) => {
5695
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5696
- process.exit(1);
5697
- });
5698
- }
5699
-
5700
- // src/commands/shared.ts
5701
- import readline from "readline";
5702
-
5703
- // src/process-start.ts
5704
- import fs9 from "fs";
5705
- var TUN_MODE_POST_WAIT_MS = 500;
5706
- function buildTunLaunchScript() {
5707
- const binary = shellQuote(PATHS.mihomoBinary);
5708
- const configFile = shellQuote(PATHS.configFile);
5709
- const logFile = shellQuote(PATHS.logFile);
5710
- const pidFile = shellQuote(PATHS.pidFile);
5711
- const dataDir = shellQuote(DIRS.data);
5712
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5713
- return `#!/bin/bash
5714
- BINARY=${binary}
5715
- CONFIG_FILE=${configFile}
5716
- LOG_FILE=${logFile}
5717
- PID_FILE=${pidFile}
5718
- DATA_DIR=${dataDir}
5719
- KILL_PATTERN=${killPattern}
5720
-
5721
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5722
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5723
- sleep 0.2
5724
- rm -f "\${PID_FILE}" 2>/dev/null || true
5725
-
5726
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5727
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5728
-
5729
- # \u542F\u52A8
5730
- cd /tmp
5731
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5732
- NEW_PID=$!
5733
- echo \${NEW_PID} > "\${PID_FILE}"
5734
-
5735
- # \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
5736
- #\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
5737
- # 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
5738
- is_alive() {
5739
- local stat
5740
- stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
5741
- case "\${stat}" in
5742
- Z*|'') return 1 ;;
5743
- *) return 0 ;;
5744
- esac
5745
- }
5746
-
5747
- # \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
5748
- # \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
5749
- # \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
5750
- i=0
5751
- while [ $i -lt 12 ]; do
5752
- sleep 0.1
5753
- is_alive \${NEW_PID} || break
5754
- i=$((i+1))
5755
- done
5756
- if is_alive \${NEW_PID}; then
5757
- exit 0
5758
- fi
5759
-
5760
- # \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
5761
- rm -f "\${PID_FILE}" 2>/dev/null || true
5762
- echo "TUN \u542F\u52A8\u5931\u8D25"
5763
- echo ""
5764
- echo "--- \u65E5\u5FD7 ---"
5765
- tail -25 "\${LOG_FILE}" 2>/dev/null
5766
- exit 2
5767
- `;
5754
+ return error;
5768
5755
  }
5769
- async function startTun() {
5770
- ensureDirs();
5771
- rotateAndCleanupLogs();
5772
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
5773
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5774
- }
5775
- if (!fs9.existsSync(PATHS.configFile)) {
5776
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5777
- }
5778
- const logFile = PATHS.logFile;
5779
- if (fs9.existsSync(logFile)) {
5780
- try {
5781
- fs9.accessSync(logFile, fs9.constants.W_OK);
5782
- } 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;
5783
5763
  try {
5784
- fs9.unlinkSync(logFile);
5785
- } 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);
5786
5788
  }
5787
5789
  }
5788
- }
5789
- const staleState = checkStaleState();
5790
- if (staleState.needsCleanup) {
5791
- if (staleState.allPids.length > 0) {
5792
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5793
- } else {
5794
- 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
+ }
5795
5809
  }
5796
- }
5797
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5798
- runSudoScript(buildTunLaunchScript(), {
5799
- action: "TUN \u542F\u52A8",
5800
- file: "launch-tun.sh",
5801
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5802
- });
5803
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5804
- const finalPid = getPid();
5805
- if (!finalPid || !isRunning()) {
5806
- const tail = readLogTail();
5807
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
5808
- hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
5809
- });
5810
- }
5811
- return { success: true, pid: finalPid, mode: "tun" };
5812
- }
5813
-
5814
- // src/runtime.ts
5815
- function getRuntimeMode() {
5816
- if (isServiceInstalled()) return "mixed";
5817
- return getConfigInfo()?.tun ? "tun" : "mixed";
5818
- }
5819
- function getRunningState(serviceStatus) {
5820
- const service = serviceStatus ?? getServiceStatus();
5821
- if (service.running) {
5822
- return { running: true, pid: service.pid, kind: "service", processInfo: null };
5823
- }
5824
- const status = getStatus();
5825
- if (status.running) {
5826
- return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
5827
- }
5828
- return { running: false, pid: null, kind: null, processInfo: null };
5829
- }
5830
- function restartModeFor(state, fallbackMode) {
5831
- return state.kind === "tun" ? "tun" : fallbackMode;
5832
- }
5833
- function restartModeOnChange() {
5834
- const state = getRunningState();
5835
- return state.running ? restartModeFor(state, getRuntimeMode()) : null;
5836
- }
5837
- async function launchOrRestart(mode, stopEpochBefore) {
5838
- if (mode === "tun") {
5839
- const result = await startTun();
5840
- return result.pid;
5841
- }
5842
- const status = getServiceStatus();
5843
- let hotReloaded = false;
5844
- let started;
5845
- if (status.running && !status.disabled) {
5846
- ({ hotReloaded, started } = await restartService(stopEpochBefore));
5847
- } else {
5848
- ({ started } = await startService(stopEpochBefore));
5849
- }
5850
- if (!started) throw cancelledByConcurrentStop();
5851
- if (hotReloaded) return getServiceStatus().pid;
5852
- try {
5853
- return await assertServiceHealthy();
5854
- } catch (e) {
5855
- if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) throw cancelledByConcurrentStop();
5856
- throw e;
5857
- }
5858
- }
5859
- function cancelledByConcurrentStop() {
5860
- return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
5861
- label: "\u542F\u52A8\u5931\u8D25",
5862
- hint: [
5863
- "\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",
5864
- "",
5865
- "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
5866
- ]
5867
- });
5868
- }
5869
- async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
5870
- const health = await waitServiceHealthy();
5871
- if (health.healthy) return health.pid;
5872
- const tail = readLogTail();
5873
- const cause = describeExitCause(health.exitCode, health.terminatingSignal);
5874
- 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";
5875
- throw new CliError(reason, {
5876
- label,
5877
- hint: [
5878
- ...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"] : [],
5879
- ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
5880
- "",
5881
- "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"
5882
- ]
5883
- });
5884
- }
5885
-
5886
- // src/http.ts
5887
- var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5888
- var MAX_ERROR_BODY_BYTES = 64 * 1024;
5889
- function isHttpsUrl(url) {
5890
- try {
5891
- return new URL(url).protocol === "https:";
5892
- } catch {
5893
- return false;
5894
- }
5895
- }
5896
- function createHttpError(status, bodyText) {
5897
- const error = new Error(`HTTP ${status}`);
5898
- error.response = { status };
5899
- try {
5900
- error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
5901
- } catch {
5902
- }
5903
- return error;
5904
- }
5905
- function createHttpClient(options = {}) {
5906
- const { timeout = 6e4 } = options;
5907
- return {
5908
- async get(url, config) {
5909
- const controller = new AbortController();
5910
- const timer = setTimeout(() => controller.abort(), timeout);
5911
- const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
5912
- try {
5913
- const response = await fetch(url, {
5914
- signal,
5915
- headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5916
- });
5917
- if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
5918
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5919
- }
5920
- if (!response.ok) {
5921
- let text2 = "";
5922
- try {
5923
- text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
5924
- } catch {
5925
- }
5926
- throw createHttpError(response.status, text2);
5927
- }
5928
- const declaredLen = Number(response.headers.get("content-length"));
5929
- if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
5930
- throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
5931
- }
5932
- const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
5933
- const data = config?.responseType === "json" ? JSON.parse(text) : text;
5934
- return { data, headers: response.headers, status: response.status };
5935
- } finally {
5936
- clearTimeout(timer);
5937
- }
5938
- }
5939
- };
5940
- }
5941
- async function readBodyWithLimit(response, controller, limit) {
5942
- if (!response.body) return response.text();
5943
- const reader = response.body.getReader();
5944
- const chunks = [];
5945
- let total = 0;
5946
- try {
5947
- while (true) {
5948
- const { done, value } = await reader.read();
5949
- if (done) break;
5950
- if (value) {
5951
- total += value.byteLength;
5952
- if (total > limit) {
5953
- controller.abort();
5954
- throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5955
- }
5956
- chunks.push(value);
5957
- }
5958
- }
5959
- } finally {
5960
- reader.releaseLock();
5810
+ } finally {
5811
+ reader.releaseLock();
5961
5812
  }
5962
5813
  return Buffer.concat(chunks).toString("utf8");
5963
5814
  }
@@ -6076,10 +5927,10 @@ function getActiveSubscription() {
6076
5927
  }
6077
5928
  return subs[0];
6078
5929
  }
6079
- function requireActiveSubscription(emptyMsg = "\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605") {
5930
+ function requireActiveSubscription() {
6080
5931
  const sub = getActiveSubscription();
6081
5932
  if (!sub) {
6082
- 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>" });
6083
5934
  }
6084
5935
  return sub;
6085
5936
  }
@@ -6171,7 +6022,9 @@ async function downloadSubscription(url, subName = "default", signal) {
6171
6022
  async function prepareConfigForStart(mode, subName = "default") {
6172
6023
  const rawContent = readSubscriptionRawConfig(subName);
6173
6024
  if (!rawContent) {
6174
- 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
+ });
6175
6028
  }
6176
6029
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6177
6030
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
@@ -6262,1718 +6115,781 @@ async function autoUpdateStaleSubscription(options = {}) {
6262
6115
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
6263
6116
  }
6264
6117
 
6265
- // src/proxy-probe.ts
6266
- import { execFile as execFile2 } from "child_process";
6267
- import { promisify as promisify2 } from "util";
6268
- var execFileAsync = promisify2(execFile2);
6269
- var PROBE_URL = "https://www.gstatic.com/generate_204";
6270
- function isProbeSuccessStatus(code) {
6271
- return code !== null && code >= 200 && code < 300;
6272
- }
6273
- async function probeProxyConnectivity(port, timeoutMs = 2e3) {
6274
- const start = Date.now();
6275
- try {
6276
- const { stdout } = await execFileAsync(
6277
- "curl",
6278
- [
6279
- "-x",
6280
- `http://127.0.0.1:${port}`,
6281
- "-s",
6282
- "-o",
6283
- "/dev/null",
6284
- "-w",
6285
- "%{http_code}",
6286
- "--connect-timeout",
6287
- "3",
6288
- "--max-time",
6289
- String(Math.ceil(timeoutMs / 1e3)),
6290
- PROBE_URL
6291
- ],
6292
- { timeout: timeoutMs + 2e3 }
6293
- );
6294
- const code = Number.parseInt(stdout.trim(), 10);
6295
- const statusCode = Number.isFinite(code) ? code : null;
6296
- const ok = isProbeSuccessStatus(statusCode);
6297
- return {
6298
- ok,
6299
- statusCode,
6300
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6301
- durationMs: Date.now() - start
6302
- };
6303
- } catch (e) {
6304
- const err = e;
6305
- const stderr = err.stderr?.toString().trim();
6306
- const lastLine = stderr ? stderr.split("\n").pop() : void 0;
6307
- const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6308
- 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}`));
6309
6150
  }
6310
6151
  }
6311
6152
 
6312
- // src/commands/status.ts
6313
- function connectivityHint(urgency) {
6314
- if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6315
- if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6316
- return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
6317
- }
6318
- function trafficColor(line, urgency, total, upload, download) {
6319
- if (urgency === "traffic-exhausted") return colors.red(line);
6320
- if (total && total > 0) {
6321
- const used = (upload || 0) + (download || 0);
6322
- if (used / total >= 0.9) return colors.yellow(line);
6323
- }
6324
- 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;
6325
6160
  }
6326
- function expireColor(line, urgency) {
6327
- if (urgency === "expired") return colors.red(line);
6328
- if (urgency === "expiring") return colors.yellow(line);
6329
- return line;
6161
+ function isSilentSigint() {
6162
+ return silentSigint;
6330
6163
  }
6331
- function buildStatusJson(args) {
6332
- const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
6333
- return {
6334
- version: VERSION,
6335
- running: args.running,
6336
- connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
6337
- mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
6338
- carrier: args.kind,
6339
- pid: args.pid,
6340
- kernel: getKernelVersion(),
6341
- kernelInstalled: hasKernel(),
6342
- ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
6343
- ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {}
6344
- } : {},
6345
- subscription: args.activeSub ? {
6346
- name: args.activeSub.name,
6347
- proxies: args.info?.proxies ?? 0,
6348
- proxyGroups: args.info?.proxyGroups ?? 0,
6349
- ...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
6350
- ...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
6351
- ...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
6352
- ...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
6353
- ...args.cached?.updated_at !== void 0 ? { updatedAt: args.cached.updated_at } : {},
6354
- stale: args.cached ? isSubscriptionStale(args.cached) : false,
6355
- urgency
6356
- } : null,
6357
- overwrite: {
6358
- enabled: args.overwriteEnabled,
6359
- files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6360
- // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6361
- // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6362
- applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : []
6363
- },
6364
- service: {
6365
- installed: args.service.installed,
6366
- loaded: args.service.loaded,
6367
- running: args.service.running,
6368
- disabled: args.service.disabled,
6369
- lastExitCode: args.service.lastExitCode,
6370
- lastTerminatingSignal: args.service.lastTerminatingSignal,
6371
- legacySystemInstall: args.legacy
6372
- }
6373
- };
6374
- }
6375
- async function printStatus(args = []) {
6376
- assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
6377
- assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
6378
- const asJson = hasFlag(args, "-j", "--json");
6379
- const skipProbe = hasFlag(args, "--no-probe");
6380
- const service = getServiceStatus();
6381
- const state = getRunningState(service);
6382
- const info = getConfigInfo();
6383
- const activeSub = getActiveSubscription();
6384
- const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6385
- const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6386
- const legacy = detectLegacySystemInstall();
6387
- const { running, pid, kind } = state;
6388
- let probe = null;
6389
- if (running && info?.mixedPort && !skipProbe) {
6390
- probe = await probeProxyConnectivity(info.mixedPort);
6391
- }
6392
- if (asJson) {
6393
- console.log(
6394
- JSON.stringify(
6395
- buildStatusJson({
6396
- running,
6397
- kind,
6398
- pid,
6399
- probe,
6400
- info,
6401
- activeSub,
6402
- cached,
6403
- overwriteEnabled,
6404
- // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
6405
- // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
6406
- overwriteFiles,
6407
- service,
6408
- legacy
6409
- }),
6410
- null,
6411
- 2
6412
- )
6413
- );
6414
- return;
6415
- }
6416
- const urgency = cached ? subscriptionUrgency(cached) : null;
6417
- console.log("");
6418
- let modeLabel = "";
6419
- if (info) {
6420
- const mode = info.tun ? "TUN" : "Mixed";
6421
- const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
6422
- modeLabel = colors.cyan(` (${mode}${carrier})`);
6423
- }
6424
- let statusText;
6425
- if (!running) {
6426
- statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
6427
- } else if (probe && !probe.ok) {
6428
- statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
6429
- } else {
6430
- statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
6431
- }
6432
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
6433
- if (running && probe && !probe.ok) {
6434
- console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
6435
- }
6436
- const abnormalExit = describeAbnormalExit(service);
6437
- if (!running && service.installed && !service.disabled && abnormalExit) {
6438
- console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
6439
- console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
6440
- }
6441
- const kernelVersion = getKernelVersion();
6442
- console.log(
6443
- kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
6444
- );
6445
- if (pid) {
6446
- console.log(`${colors.gray("PID: ")}${pid}`);
6447
- if (kind === "tun" && state.processInfo) {
6448
- console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
6449
- }
6450
- }
6451
- if (info) {
6452
- if (info.tun) {
6453
- const extra = info.mixedPort ? `\uFF0C\u53E6\u76D1\u542C ${info.mixedPort}` : "";
6454
- console.log(`${colors.gray("\u7AEF\u53E3: ")}TUN \u63A5\u7BA1${extra}`);
6455
- } else if (info.mixedPort) {
6456
- console.log(`${colors.gray("\u7AEF\u53E3: ")}${info.mixedPort}`);
6457
- } else {
6458
- console.log(`${colors.gray("\u7AEF\u53E3: ")}\u672A\u77E5`);
6459
- }
6460
- }
6461
- if (activeSub) {
6462
- let subLine = `${colors.gray("\u8BA2\u9605: ")}${activeSub.name}`;
6463
- if (info) {
6464
- subLine += ` (${formatProxySummary(info)})`;
6465
- }
6466
- console.log(subLine);
6467
- if (cached?.updated_at) {
6468
- const rel = formatRelativeTime(cached.updated_at) || formatDate(cached.updated_at);
6469
- if (isSubscriptionStale(cached)) {
6470
- 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`));
6471
- } else {
6472
- console.log(`${colors.gray("\u66F4\u65B0: ")}${rel}`);
6473
- }
6474
- }
6475
- const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
6476
- if (traffic) {
6477
- console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
6478
- }
6479
- if (cached?.expire !== void 0) {
6480
- console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
6481
- }
6482
- } else {
6483
- console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
6484
- }
6485
- printOverwriteLines(overwriteEnabled, overwriteFiles, activeSub);
6486
- printServiceLines(service, legacy);
6487
- console.log("");
6488
- }
6489
- function shortOverwriteName(name) {
6490
- return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6491
- }
6492
- function printOverwriteLines(enabled, files, activeSub) {
6493
- if (!enabled) {
6494
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
6495
- return;
6496
- }
6497
- const active = files.filter((f) => f.enabled && f.matched !== false);
6498
- const unmatched = files.filter((f) => f.enabled && f.matched === false);
6499
- const disabledCount = files.filter((f) => !f.enabled).length;
6500
- const suffixes = [];
6501
- if (unmatched.length > 0) suffixes.push(`${unmatched.length} \u4E2A\u4E0D\u9002\u7528`);
6502
- if (disabledCount > 0) suffixes.push(`${disabledCount} \u4E2A\u5DF2\u7981\u7528`);
6503
- const suffix = suffixes.length > 0 ? `\uFF0C${suffixes.join("\uFF0C")}` : "";
6504
- if (active.length > 0) {
6505
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
6506
- } else {
6507
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
6508
- }
6509
- for (const f of unmatched) {
6510
- const scope = f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
6511
- console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${scope}\uFF09`));
6512
- }
6513
- }
6514
- function printServiceLines(service, legacy) {
6515
- if (!service.installed && !service.loaded) {
6516
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
6517
- } else if (!service.installed) {
6518
- 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)")}`);
6519
- console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
6520
- printAutoStart(service);
6521
- } else {
6522
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
6523
- printAutoStart(service);
6524
- }
6525
- if (legacy) {
6526
- console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
6527
- 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"));
6528
- }
6529
- }
6530
- function printAutoStart(service) {
6531
- const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
6532
- console.log(`${colors.gray("\u81EA\u542F: ")}${autoStart}`);
6533
- }
6534
-
6535
- // src/commands/start.ts
6536
- function resolveStartMode(args) {
6537
- const modeArg = getNonFlagArg(args, 1);
6538
- const modeToken = modeArg?.toLowerCase();
6539
- if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
6540
- throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
6541
- }
6542
- return modeToken === "tun" ? "tun" : "mixed";
6543
- }
6544
- async function cmdStart(args) {
6545
- assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
6546
- assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
6547
- const targetMode = resolveStartMode(args);
6548
- if (!hasKernel()) {
6549
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
6550
- }
6551
- const skipUpdate = hasFlag(args, "-s", "--no-update");
6552
- const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6553
- const stopEpochBefore = readStopEpoch();
6554
- const serviceBefore = getServiceStatus();
6555
- if (targetMode === "tun") {
6556
- if (detectLegacySystemInstall()) {
6557
- 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"));
6558
- 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"));
6559
- cleanupLegacyInstallOrThrow();
6560
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6561
- console.log("");
6562
- }
6563
- if (serviceBefore.loaded) {
6564
- throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6565
- 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"]
6566
- });
6567
- }
6568
- if (serviceBefore.installed && !serviceBefore.disabled) {
6569
- disableServiceAutoStart();
6570
- 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"));
6571
- console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D"));
6572
- console.log("");
6573
- }
6574
- } else if (!serviceBefore.installed) {
6575
- if (serviceBefore.loaded) {
6576
- throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
6577
- hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
6578
- });
6579
- }
6580
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
6581
- 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"]
6582
- });
6583
- }
6584
- const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6585
- if (!skipUpdate) {
6586
- await autoUpdateStaleSubscription({ timeout: updateTimeout });
6587
- }
6588
- let prepared;
6589
- try {
6590
- prepared = await prepareConfigForStart(targetMode, sub.name);
6591
- } catch (e) {
6592
- if (e instanceof CliError) throw e;
6593
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
6594
- }
6595
- const configInfo = commitPreparedConfig(prepared);
6596
- const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6597
- console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6598
- try {
6599
- const pid = await launchOrRestart(targetMode, stopEpochBefore);
6600
- console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
6601
- } catch (e) {
6602
- if (e instanceof CliError) throw e;
6603
- const lines = e.message.split("\n");
6604
- throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
6605
- }
6606
- await printStatus();
6607
- if (targetMode === "mixed") {
6608
- 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`));
6609
- console.log("");
6610
- }
6611
- }
6612
-
6613
- // src/commands/shared.ts
6614
- var validatedTables = /* @__PURE__ */ new WeakSet();
6615
- function assertUniqueTokens(table) {
6616
- if (validatedTables.has(table)) return;
6617
- const owner = /* @__PURE__ */ new Map();
6618
- for (const cmd of table) {
6619
- for (const token of [cmd.name, ...cmd.aliases ?? []]) {
6620
- const prev = owner.get(token);
6621
- if (prev !== void 0) {
6622
- throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
6623
- }
6624
- owner.set(token, cmd.name);
6625
- }
6626
- }
6627
- validatedTables.add(table);
6628
- }
6629
- async function dispatchSubcommand(args, table, options) {
6630
- assertUniqueTokens(table);
6631
- const action = args[1];
6632
- if (action) {
6633
- const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
6634
- if (cmd) return cmd.handler(args);
6635
- return options.onUnknown(action);
6636
- }
6637
- return options.fallback(args);
6638
- }
6639
- async function confirmPrompt(question) {
6640
- if (!process.stdin.isTTY) return false;
6641
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
6642
- const answer = await new Promise((resolve) => {
6643
- rl.question(`${question} (y/N) `, (a) => {
6644
- rl.close();
6645
- resolve(a);
6646
- });
6647
- });
6648
- return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6649
- }
6650
- async function confirmOrThrow(question, opts) {
6651
- if (!process.stdin.isTTY) {
6652
- throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6653
- }
6654
- return confirmPrompt(question);
6655
- }
6656
- async function restartToApply(args) {
6657
- const currentMode = restartModeOnChange();
6658
- if (!currentMode) return false;
6659
- console.log("");
6660
- await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6661
- return true;
6662
- }
6663
-
6664
- // src/commands/directory.ts
6665
- function openDirectory(args) {
6666
- assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
6667
- const target = args[2];
6668
- if (target === void 0 || target === "root") {
6669
- console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
6670
- openUrl(USER_DATA_DIR);
6671
- return;
6672
- }
6673
- const key = target.toLowerCase();
6674
- const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
6675
- if (targetInfo) {
6676
- const targetPath = targetInfo.path || USER_DATA_DIR;
6677
- console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetPath})`);
6678
- openUrl(targetPath);
6679
- return;
6680
- }
6681
- const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
6682
- for (const [k, val] of Object.entries(DIRECTORY_TARGETS)) {
6683
- if (k !== "root") {
6684
- hint.push(` ${k.padEnd(14)}${val.label}`);
6685
- }
6686
- }
6687
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u76EE\u6807 "${target}"`, { hint });
6688
- }
6689
- function printDirectoryInfo() {
6690
- const entries = Object.entries(DIRECTORY_TARGETS).filter(([key]) => key !== "root");
6691
- const pathWidth = Math.max(...entries.map(([, val]) => val.path.replace(USER_DATA_DIR, ".").length));
6692
- console.log("");
6693
- console.log(`\u6570\u636E\u76EE\u5F55: ${USER_DATA_DIR}`);
6694
- console.log("");
6695
- for (const [key, val] of entries) {
6696
- const rel = val.path.replace(USER_DATA_DIR, ".");
6697
- console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
6698
- }
6699
- console.log("");
6700
- console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
6701
- console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6702
- console.log("");
6703
- }
6704
- var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
6705
- async function cmdDirectory(args) {
6706
- assertKnownFlags(args.slice(1), [], "dir");
6707
- await dispatchSubcommand(args, SUBCOMMANDS, {
6708
- fallback: printDirectoryInfo,
6709
- onUnknown: (action) => {
6710
- if (action.startsWith("-")) {
6711
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
6712
- label: "\u53C2\u6570\u9519\u8BEF",
6713
- 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]"]
6714
- });
6715
- }
6716
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6717
- const suggestion = suggestSimilar(action, names);
6718
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6719
- 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>"]
6720
- });
6721
- }
6722
- });
6723
- }
6724
-
6725
- // src/commands/overwrite.ts
6726
- import path8 from "path";
6727
- function printOverwriteList() {
6728
- const info = listOverwriteFile();
6729
- const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6730
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6731
- console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6732
- console.log("");
6733
- if (info.files.length === 0) {
6734
- console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6735
- console.log("");
6736
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6737
- console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6738
- console.log("");
6739
- } else {
6740
- const disabledCount = info.files.filter((f) => !f.enabled).length;
6741
- 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`;
6742
- console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${countText}):`);
6743
- console.log("");
6744
- info.files.forEach((f, i) => {
6745
- const num = i < 10 ? ` ${i}` : `${i}`;
6746
- const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
6747
- console.log(` ${num}. ${f.name}${mark}`);
6748
- if (f.scope) {
6749
- console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6750
- }
6751
- if (f.keys.length > 0) {
6752
- console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6753
- }
6754
- });
6755
- console.log("");
6756
- }
6757
- console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6758
- console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6759
- console.log("\u505C\u7528\u5355\u4E2A\u6587\u4EF6: \u5728\u8BE5\u6587\u4EF6\u9876\u90E8\u5199 enabled: false");
6760
- console.log("");
6761
- }
6762
- async function setOverwrite(enabled, args) {
6763
- assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
6764
- assertRestartOptionValues(args);
6765
- if (isOverwriteEnabled() === enabled) {
6766
- console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
6767
- console.log("");
6768
- printOverwriteList();
6769
- return;
6770
- }
6771
- setOverwriteEnabled(enabled);
6772
- console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
6773
- if (await restartToApply(args)) return;
6774
- console.log("");
6775
- printOverwriteList();
6776
- }
6777
- var SUBCOMMANDS2 = [
6778
- { name: "on", aliases: ["enable"], description: "\u542F\u7528\u8986\u5199", handler: (args) => setOverwrite(true, args) },
6779
- { name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
6780
- ];
6781
- async function cmdOverwrite(args) {
6782
- assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
6783
- await dispatchSubcommand(args, SUBCOMMANDS2, {
6784
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6785
- fallback: () => {
6786
- console.log("");
6787
- printOverwriteList();
6788
- },
6789
- onUnknown: (action) => {
6790
- if (action.startsWith("-")) {
6791
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
6792
- label: "\u53C2\u6570\u9519\u8BEF",
6793
- 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]"]
6794
- });
6795
- }
6796
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6797
- const suggestion = suggestSimilar(action, names);
6798
- throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6799
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6800
- });
6801
- }
6802
- });
6803
- }
6804
-
6805
- // src/commands/reset.ts
6806
- import fs11 from "fs";
6807
-
6808
- // src/process-stop.ts
6809
- import { spawnSync as spawnSync5 } from "child_process";
6810
- import fs10 from "fs";
6811
- var PROCESS_WAIT_ATTEMPTS = 50;
6812
- var PROCESS_WAIT_INTERVAL = 100;
6813
- var BATCH_KILL_THRESHOLD = 3;
6814
- function clearRuntime() {
6815
- if (fs10.existsSync(DIRS.runtime)) {
6816
- rmrf(DIRS.runtime);
6817
- }
6818
- ensureDirs();
6819
- }
6820
- function clearPid() {
6821
- if (!fs10.existsSync(PATHS.pidFile)) return;
6822
- if (isPidFileOwnedByRoot()) {
6823
- try {
6824
- spawnSync5("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
6825
- } catch {
6826
- }
6827
- } else {
6828
- try {
6829
- fs10.unlinkSync(PATHS.pidFile);
6830
- } catch {
6831
- }
6832
- }
6833
- }
6834
- function killProcess(pid) {
6835
- try {
6836
- process.kill(pid, "SIGKILL");
6837
- return true;
6838
- } catch {
6839
- return false;
6840
- }
6841
- }
6842
- function killAllMihomo(forceSudo = false) {
6843
- const pattern = MAIN_INSTANCE_PATTERN;
6844
- const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
6845
- const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
6164
+
6165
+ // src/open.ts
6166
+ function openUrl(url) {
6846
6167
  try {
6847
- const result = spawnSync5(argv[0], argv[1], options);
6848
- if (result.error) return false;
6849
- 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
+ });
6850
6172
  } catch {
6851
- return false;
6852
6173
  }
6853
6174
  }
6854
- async function cleanupAll(forceSudo = false) {
6855
- const pids = getMihomoPids();
6856
- if (pids.length === 0) {
6857
- clearPid();
6858
- return { killed: 0, failed: 0, remaining: [] };
6859
- }
6860
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
6861
- const needsSudo = forceSudo || hasRootProcess;
6862
- let killedCount = 0;
6863
- const failedPids = [];
6864
- if (needsSudo) {
6865
- const success = killAllMihomo(true);
6866
- if (success) {
6867
- killedCount = pids.length;
6868
- } else {
6869
- failedPids.push(...pids);
6870
- }
6871
- } else {
6872
- if (pids.length > BATCH_KILL_THRESHOLD) {
6873
- if (killAllMihomo(false)) {
6874
- killedCount = pids.length;
6875
- } else {
6876
- failedPids.push(...pids);
6877
- }
6878
- } else {
6879
- for (const pid of pids) {
6880
- if (killProcess(pid)) {
6881
- killedCount++;
6882
- } else {
6883
- failedPids.push(pid);
6884
- }
6885
- }
6886
- }
6887
- }
6888
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6889
- if (getMihomoPids().length === 0) break;
6890
- await sleep(PROCESS_WAIT_INTERVAL);
6891
- }
6892
- clearPid();
6893
- 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);
6894
6178
  }
6895
- async function stop(forceSudo = false) {
6896
- const allPids = getMihomoPids();
6897
- if (allPids.length === 0) {
6898
- clearPid();
6899
- clearRuntime();
6900
- return { success: true, notRunning: true };
6901
- }
6902
- const result = await cleanupAll(forceSudo);
6903
- const remaining = getMihomoPids();
6904
- if (remaining.length > 0) {
6905
- console.log("");
6906
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6907
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6908
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
6909
- console.log("");
6910
- 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
+ `);
6911
6188
  }
6912
- clearRuntime();
6913
- 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
+ });
6914
6200
  }
6915
6201
 
6916
- // src/commands/reset.ts
6917
- var RESET_TARGETS = [
6918
- { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
6919
- { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
6920
- { id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
6921
- { id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
6922
- {
6923
- id: "overwrites",
6924
- aliases: ["overwrite", "overwrites", "ow"],
6925
- label: "\u8986\u5199",
6926
- needsStop: false,
6927
- preserveOnBare: true,
6928
- paths: () => fs11.existsSync(USER_DATA_DIR) ? fs11.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
6929
- },
6930
- {
6931
- id: "settings",
6932
- aliases: ["setting", "settings", "config"],
6933
- label: "\u8BBE\u7F6E",
6934
- needsStop: false,
6935
- preserveOnBare: true,
6936
- // 损坏备份也包含订阅凭据,需要一起删除
6937
- paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
6938
- },
6939
- { id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
6940
- { id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
6941
- ];
6942
- function resolveResetTargets(names) {
6943
- const matched = /* @__PURE__ */ new Set();
6944
- for (const name of names) {
6945
- const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
6946
- if (!target) {
6947
- throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
6948
- }
6949
- matched.add(target);
6950
- }
6951
- return [...matched];
6952
- }
6953
- async function cmdReset(args) {
6954
- assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
6955
- const names = args.slice(1).filter((a) => !a.startsWith("-"));
6956
- const namedTargets = resolveResetTargets(names);
6957
- const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
6958
- const ids = new Set(targets.map((t) => t.id));
6959
- const needsStop = targets.some((t) => t.needsStop);
6960
- const serviceTargeted = ids.has("service");
6961
- const service = getServiceStatus();
6962
- const serviceActive = service.installed || service.loaded;
6963
- const legacy = detectLegacySystemInstall();
6964
- if (targets.length === 1) {
6965
- if (serviceTargeted && !serviceActive && !legacy) {
6966
- console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
6967
- return;
6968
- }
6969
- }
6970
- if (ids.has("kernel") && getMihomoPids().length > 0) {
6971
- 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"));
6972
- }
6973
- if (serviceTargeted && serviceActive) {
6974
- console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
6975
- } else if (needsStop && serviceActive) {
6976
- 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"));
6977
- }
6978
- if ((needsStop || serviceTargeted) && legacy) {
6979
- 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"));
6980
- }
6981
- console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6982
- if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
6983
- nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
6984
- hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
6985
- })) {
6986
- console.log("\u5DF2\u53D6\u6D88");
6987
- return;
6988
- }
6989
- if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
6990
- if (serviceActive) {
6991
- if (serviceTargeted) await uninstallService();
6992
- else if (needsStop) await stopService();
6993
- }
6994
- if (needsStop) {
6995
- const cleanup = await cleanupAll();
6996
- if (cleanup.remaining.length > 0) {
6997
- throw new CliError(cleanup.remaining.join(", "), {
6998
- label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
6999
- hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
7000
- });
7001
- }
7002
- recordServiceStopped();
7003
- }
7004
- const deleted = /* @__PURE__ */ new Set();
7005
- for (const target of targets) {
7006
- let hadContent = target.id === "service" && (serviceActive || legacy);
7007
- for (const filePath of target.paths()) {
7008
- if (!fs11.existsSync(filePath)) continue;
7009
- try {
7010
- rmrf(filePath);
7011
- } catch (e) {
7012
- throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
7013
- }
7014
- hadContent = true;
7015
- }
7016
- if (hadContent) deleted.add(target.id);
7017
- }
7018
- if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
7019
- updateSettings((settings) => {
7020
- const patch = {};
7021
- if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
7022
- patch.subscriptions = void 0;
7023
- patch.active_subscription = void 0;
7024
- deleted.add("subs");
7025
- }
7026
- if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
7027
- patch.overwrite_enabled = void 0;
7028
- deleted.add("overwrites");
7029
- }
7030
- return patch;
7031
- });
7032
- }
7033
- if (ids.has("kernel")) clearKernelVersionCache();
7034
- ensureDirs();
7035
- const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
7036
- 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
7037
6247
  }
7038
6248
 
7039
- // src/commands/subscription.ts
7040
- import { spawnSync as spawnSync6 } from "child_process";
7041
- function printRestartHintIfRunning() {
7042
- const state = getRunningState();
7043
- if (state.running) {
7044
- const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
7045
- 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`));
7046
- console.log("");
7047
- }
7048
- }
7049
- function printSubscriptionList() {
7050
- const subs = getSubscriptionsWithCache();
7051
- if (subs.length === 0) {
7052
- console.log("\u6CA1\u6709\u8BA2\u9605");
7053
- console.log("");
7054
- console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
7055
- console.log("");
7056
- return;
7057
- }
7058
- const activeSub = getActiveSubscription();
7059
- console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
7060
- subs.forEach((s, i) => {
7061
- const rel = formatRelativeTime(s.updated_at);
7062
- const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
7063
- const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
7064
- const interval = resolveUpdateInterval(s.update_interval);
7065
- console.log(` ${i + 1}. ${s.name}${defaultMark}`);
7066
- console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
7067
- if (s.username) {
7068
- console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
7069
- }
7070
- const traffic = formatTraffic(s.upload, s.download, s.total);
7071
- if (traffic) {
7072
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
7073
- }
7074
- if (s.expire !== void 0) {
7075
- console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
7076
- }
7077
- if (s.web_page_url) {
7078
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
7079
- }
7080
- });
7081
- console.log("");
7082
- console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
7083
- console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
7084
- console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
7085
- console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
7086
- 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
+ `;
7087
6270
  }
7088
- function assertNotFlagLike(name, usage) {
7089
- if (name.startsWith("-")) {
7090
- throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
7091
- label: "\u53C2\u6570\u9519\u8BEF",
7092
- 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}`]
7093
- });
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" });
7094
6276
  }
7095
- }
7096
- function readUrlFromClipboard() {
7097
- if (!process.stdin.isTTY) return null;
7098
- try {
7099
- const r = spawnSync6("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
7100
- if (r.status !== 0) return null;
7101
- const text = (r.stdout || "").trim();
7102
- return isValidHttpUrl(text) ? text : null;
7103
- } catch {
7104
- 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");
7105
6279
  }
7106
- }
7107
- async function subAdd(args) {
7108
- assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
7109
- let url = args[2]?.trim();
7110
- const name = args[3] || "default";
7111
- if (!url) {
7112
- const clipped = readUrlFromClipboard();
7113
- if (clipped) {
7114
- console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
7115
- console.log(` ${maskUrl(clipped)}`);
7116
- if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
7117
- console.log("\u5DF2\u53D6\u6D88");
7118
- 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 {
7119
6288
  }
7120
- url = clipped;
7121
- } else if (process.stdin.isTTY) {
7122
- throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
7123
- hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
7124
- });
7125
- } else {
7126
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
7127
6289
  }
7128
6290
  }
7129
- if (!isValidHttpUrl(url)) {
7130
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
7131
- }
7132
- assertNotFlagLike(name, "mihomo sub add <url> [name]");
7133
- console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
7134
- addSubscription(url, name);
7135
- try {
7136
- const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
7137
- setDefaultSubscription(name);
7138
- console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
7139
- } catch (e) {
7140
- removeSubscription(name);
7141
- if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
7142
- throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
7143
- }
7144
- console.log("");
7145
- printRestartHintIfRunning();
7146
- printSubscriptionList();
7147
- }
7148
- async function subUpdate(args) {
7149
- assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
7150
- const nameArg = getNonFlagArg(args, 2);
7151
- const subs = getSubscriptions();
7152
- if (subs.length === 0) {
7153
- throw new CliError("\u6CA1\u6709\u8BA2\u9605");
7154
- }
7155
- if (nameArg === "") {
7156
- 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>`] });
7157
- }
7158
- if (nameArg === null) {
7159
- console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
7160
- const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
7161
- let ok = 0;
7162
- for (const r of results) {
7163
- if (r.success) ok++;
7164
- 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...");
7165
6297
  }
7166
- if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
7167
- console.log("");
7168
- printRestartHintIfRunning();
7169
- printSubscriptionList();
7170
- return;
7171
- }
7172
- const target = resolveSubscription(subs, nameArg);
7173
- console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
7174
- const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
7175
- if (!result.success) {
7176
- throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
7177
- }
7178
- console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
7179
- console.log("");
7180
- printRestartHintIfRunning();
7181
- printSubscriptionList();
7182
- }
7183
- async function subUse(args) {
7184
- assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
7185
- assertRestartOptionValues(args);
7186
- const name = getNonFlagArg(args, 2);
7187
- const subs = getSubscriptions();
7188
- if (subs.length === 0) {
7189
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
7190
6298
  }
7191
- if (!name) {
7192
- throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
7193
- 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"]
7194
6311
  });
7195
6312
  }
7196
- const target = resolveSubscription(subs, name);
7197
- const currentDefault = getActiveSubscription();
7198
- const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
7199
- if (isAlreadyDefault) {
7200
- console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
7201
- console.log("");
7202
- printSubscriptionList();
7203
- 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 };
7204
6325
  }
7205
- const success = setDefaultSubscription(target.name);
7206
- if (!success) {
7207
- 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 };
7208
6329
  }
7209
- console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
7210
- if (await restartToApply(args)) return;
7211
- console.log("");
7212
- printSubscriptionList();
6330
+ return { running: false, pid: null, kind: null, processInfo: null };
7213
6331
  }
7214
- async function subRemove(args) {
7215
- assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
7216
- const name = getNonFlagArg(args, 2);
7217
- const subs = getSubscriptions();
7218
- if (!name) {
7219
- throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
7220
- hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
7221
- });
7222
- }
7223
- const target = resolveSubscription(subs, name);
7224
- const isExact = target.name === name;
7225
- const skipConfirm = hasFlag(args, "-y", "--yes");
7226
- if (!isExact && !skipConfirm) {
7227
- console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7228
- if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7229
- nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7230
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7231
- })) {
7232
- console.log("\u5DF2\u53D6\u6D88");
7233
- return;
7234
- }
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;
7235
6343
  }
7236
- const switchedTo = removeSubscription(target.name);
7237
- console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
7238
- if (switchedTo) {
7239
- 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;
7240
6359
  }
7241
- console.log("");
7242
- printSubscriptionList();
7243
6360
  }
7244
- var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
7245
- var REMOVE_FLAGS = ["-y", "--yes"];
7246
- function withKnownFlags(usage, known, handler) {
7247
- return async (args) => {
7248
- assertKnownFlags(args, known, usage);
7249
- await handler(args);
7250
- };
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
+ });
7251
6370
  }
7252
- var SUBCOMMANDS3 = [
7253
- { name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
7254
- { name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: withKnownFlags("sub update [name]", [], subUpdate) },
7255
- { name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
7256
- { name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
7257
- ];
7258
- async function cmdSubscription(args) {
7259
- await dispatchSubcommand(args, SUBCOMMANDS3, {
7260
- // 无子命令 → 列表;未知子命令 → 报错
7261
- fallback: printSubscriptionList,
7262
- onUnknown: (action) => {
7263
- if (action.startsWith("-")) {
7264
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
7265
- label: "\u53C2\u6570\u9519\u8BEF",
7266
- 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"]
7267
- });
7268
- }
7269
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7270
- const suggestion = suggestSimilar(action, names);
7271
- throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7272
- 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"]
7273
- });
7274
- }
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
+ ]
7275
6385
  });
7276
6386
  }
7277
6387
 
7278
- // src/commands/completion.ts
7279
- function commandWords(commands) {
7280
- return commands.flatMap((c) => [
7281
- { word: c.name, desc: c.usage[0]?.description ?? "" },
7282
- ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))
7283
- ]);
7284
- }
7285
- function subWords(subs) {
7286
- return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
7287
- }
7288
- function subGroups(commands) {
7289
- const groupOf = (name, subs) => {
7290
- const cmd = commands.find((c) => c.name === name);
7291
- return { tokens: cmd ? [cmd.name, ...cmd.aliases] : [name], words: subWords(subs) };
7292
- };
7293
- return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
7294
- }
7295
- var DIR_TARGETS = Object.keys(DIRECTORY_TARGETS);
7296
- var UI_NAMES = Object.keys(UI_URLS);
7297
- var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
7298
- var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
7299
- var SHELLS = ["zsh", "bash", "fish"];
7300
- function zshSingleQuote(s) {
7301
- return s.replace(/'/g, "'\\''");
7302
- }
7303
- function buildZsh(commands, groups) {
7304
- const lines = [
7305
- "#compdef mihomo mhm mh mihomo-cli",
7306
- "",
7307
- '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install zsh\uFF0C\u6216 eval "$(mihomo completion zsh)"\uFF09',
7308
- "",
7309
- "_mihomo() {",
7310
- " local -a commands subcmds",
7311
- " commands=(",
7312
- ...commandWords(commands).map((c) => ` '${c.word}:${zshSingleQuote(c.desc)}'`),
7313
- " )",
7314
- "",
7315
- " _arguments -C \\",
7316
- " '1: :->cmd' \\",
7317
- " '*::arg:->args'",
7318
- "",
7319
- " case $state in",
7320
- " cmd)",
7321
- " _describe 'command' commands",
7322
- " ;;",
7323
- " args)",
7324
- " case ${words[1]} in"
7325
- ];
7326
- for (const group of groups) {
7327
- const aliases = group.tokens.join("|");
7328
- const isDirectory = group.tokens.includes("directory");
7329
- lines.push(` ${aliases})`);
7330
- lines.push(" subcmds=(");
7331
- for (const s of group.words) lines.push(` '${s.word}:${zshSingleQuote(s.desc)}'`);
7332
- lines.push(" )");
7333
- lines.push(" if (( CURRENT == 2 )); then");
7334
- lines.push(" _describe 'subcommand' subcmds");
7335
- if (isDirectory) {
7336
- lines.push(" elif (( CURRENT == 3 )) && [[ ${words[2]} == open ]]; then");
7337
- lines.push(` _values 'target' ${DIR_TARGETS.join(" ")}`);
7338
- lines.push(" else");
7339
- lines.push(" _files");
7340
- } else {
7341
- lines.push(" else");
7342
- lines.push(" _files");
7343
- }
7344
- lines.push(" fi");
7345
- lines.push(" ;;");
7346
- }
7347
- lines.push(
7348
- " logs)",
7349
- " _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:'",
7350
- " ;;",
7351
- " ui)",
7352
- ` _values 'ui' ${UI_NAMES.join(" ")}`,
7353
- " ;;",
7354
- " kernel)",
7355
- ` _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(${MIRROR_NAMES.join(" ")})'`,
7356
- " ;;",
7357
- " reset)",
7358
- ` _values 'target' ${RESET_TARGET_NAMES.join(" ")}`,
7359
- " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--yes[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
7360
- " ;;",
7361
- " completion)",
7362
- " if (( CURRENT == 2 )); then",
7363
- ` _values 'action' install uninstall ${SHELLS.join(" ")}`,
7364
- " elif (( CURRENT == 3 )) && [[ ${words[2]} == (install|uninstall) ]]; then",
7365
- ` _values 'shell' ${SHELLS.join(" ")}`,
7366
- " fi",
7367
- " ;;",
7368
- " *)",
7369
- " _files",
7370
- " ;;",
7371
- " esac",
7372
- " ;;",
7373
- " esac",
7374
- "}",
7375
- "",
7376
- // 结尾必须是 compdef 注册,**不能是裸调用 `_mihomo "$@"`**。
7377
- //
7378
- // 两条安装路径对结尾行的要求不同,而裸调用只满足其中一条:
7379
- // - 放进 fpath(`completion install zsh`):compinit 按 `#compdef` 首行自动注册,
7380
- // 函数体被 autoload,结尾写什么都行——两种写法实测都能注册全部四个别名
7381
- // - `eval "$(mihomo completion zsh)"`(README 与下方 CLI 提示都推荐):`#compdef`
7382
- // 只是条注释、不起作用,而裸调用会在补全上下文之外执行 `_arguments`,实测报
7383
- // `_arguments:comparguments:327: can only be called from completion function`,
7384
- // 且 `_comps[mihomo]` 前后都是 0 —— 补全完全没注册,eval 却返回 0。
7385
- // 用户照文档做了、看到没报错(错误在 stderr 一闪而过)、补全就是不工作。
7386
- //
7387
- // compdef 同时满足两条:实测 eval 后四个别名 `_comps` 全部为 1,fpath 安装不受影响。
7388
- "compdef _mihomo mihomo mhm mh mihomo-cli"
7389
- );
7390
- return lines.join("\n");
7391
- }
7392
- function buildBash(commands, groups) {
7393
- const top = commandWords(commands).map((c) => c.word).join(" ");
7394
- const subCase = groups.map((group) => {
7395
- const aliases = group.tokens.join("|");
7396
- const words = group.words.map((w) => w.word).join(" ");
7397
- if (group.tokens[0] === "directory") {
7398
- return ` ${aliases})
7399
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7400
- COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7401
- elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
7402
- COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
7403
- fi
7404
- ;;`;
7405
- }
7406
- return ` ${aliases})
7407
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7408
- COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7409
- fi
7410
- ;;`;
7411
- }).join("\n");
7412
- 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
7413
-
7414
- _mihomo_completions() {
7415
- local cur prev
7416
- COMPREPLY=()
7417
- cur="\${COMP_WORDS[COMP_CWORD]}"
7418
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
7419
-
7420
- if [[ \${COMP_CWORD} -eq 1 ]]; then
7421
- COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
7422
- return 0
7423
- fi
7424
-
7425
- case "\${COMP_WORDS[1]}" in
7426
- ${subCase}
7427
- logs)
7428
- COMPREPLY=( $(compgen -W "-f -n -o --lines --follow --open" -- "\${cur}") )
7429
- ;;
7430
- ui)
7431
- COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
7432
- ;;
7433
- kernel)
7434
- if [[ "\${prev}" == "--mirror" ]]; then
7435
- COMPREPLY=( $(compgen -W "${MIRROR_NAMES.join(" ")}" -- "\${cur}") )
7436
- else
7437
- COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
7438
- fi
7439
- ;;
7440
- reset)
7441
- COMPREPLY=( $(compgen -W "${RESET_TARGET_NAMES.join(" ")} --full -y --yes" -- "\${cur}") )
7442
- ;;
7443
- completion)
7444
- if [[ \${COMP_CWORD} -eq 2 ]]; then
7445
- COMPREPLY=( $(compgen -W "install uninstall ${SHELLS.join(" ")}" -- "\${cur}") )
7446
- elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install || "\${COMP_WORDS[2]}" == uninstall ]]; then
7447
- COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
7448
- fi
7449
- ;;
7450
- 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;
7451
6395
  }
7452
- complete -F _mihomo_completions mihomo mhm mh mihomo-cli
7453
- `;
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
+ }
7454
6434
  }
7455
- function fishSingleQuote(s) {
7456
- 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)";
7457
6441
  }
7458
- function buildFish(commands, groups) {
7459
- const lines = [
7460
- "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install fish\uFF0C\u6216 mihomo completion fish | source\uFF09",
7461
- "",
7462
- "for cmd in mihomo mhm mh mihomo-cli"
7463
- ];
7464
- for (const c of commandWords(commands)) {
7465
- lines.push(` complete -c $cmd -f -a '${c.word}' -d '${fishSingleQuote(c.desc)}'`);
7466
- }
7467
- for (const group of groups) {
7468
- const seen = group.tokens.join(" ");
7469
- const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
7470
- for (const s of group.words) {
7471
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${fishSingleQuote(s.desc)}'`);
7472
- }
7473
- }
7474
- const directoryTokens = groups.find((g) => g.tokens.includes("directory"))?.tokens.join(" ") ?? "directory";
7475
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${directoryTokens}; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`);
7476
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
7477
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
7478
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
7479
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -l mirror -d '\u8D70\u955C\u50CF\u4E0B\u8F7D' -a '${MIRROR_NAMES.join(" ")}'`);
7480
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -a '${RESET_TARGET_NAMES.join(" ")}'`);
7481
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -s y -l yes -d '\u8DF3\u8FC7\u786E\u8BA4'`);
7482
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -l full -d '\u5220\u5168\u90E8'`);
7483
- lines.push("end");
7484
- return lines.join("\n");
7485
- }
7486
- function buildCompletionScript(shell, commands, usageVerb = "") {
7487
- const groups = subGroups(commands);
7488
- switch (shell) {
7489
- case "zsh":
7490
- return buildZsh(commands, groups);
7491
- case "bash":
7492
- return buildBash(commands, groups);
7493
- case "fish":
7494
- return buildFish(commands, groups);
7495
- default: {
7496
- const suggestion = suggestSimilar(shell, [...SHELLS]);
7497
- const usage = `\u7528\u6CD5: mihomo completion ${usageVerb ? `${usageVerb} ` : ""}<${SHELLS.join("|")}>`;
7498
- throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
7499
- label: "\u53C2\u6570\u9519\u8BEF",
7500
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], usage]
7501
- });
7502
- }
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);
7503
6447
  }
6448
+ return line;
7504
6449
  }
7505
- var BASH_MARKER = "# >>> mihomo-cli completion (append)";
7506
- var BASH_END_MARKER = BASH_MARKER.replace(">>>", "<<<");
7507
- function hasBashMarkerBlock(content) {
7508
- const start = content.indexOf(BASH_MARKER);
7509
- const end = content.indexOf(BASH_END_MARKER);
7510
- return start !== -1 && end !== -1 && end > start;
7511
- }
7512
- function productFingerprint(shell) {
7513
- if (shell === "zsh") return "#compdef mihomo mhm mh mihomo-cli";
7514
- if (shell === "fish") return "for cmd in mihomo mhm mh mihomo-cli";
7515
- 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;
7516
6454
  }
7517
- function completionInstallPath(shell) {
7518
- const home = os3.homedir();
7519
- switch (shell) {
7520
- case "zsh":
7521
- return path9.join(home, ".zsh", "completions", "_mihomo");
7522
- case "bash":
7523
- return path9.join(home, ".bash_completion");
7524
- case "fish": {
7525
- const fishConfigDir = process.env.XDG_CONFIG_HOME ? path9.join(process.env.XDG_CONFIG_HOME, "fish") : path9.join(home, ".config", "fish");
7526
- 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
7527
6500
  }
7528
- default:
7529
- 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");
7530
6571
  }
7531
- }
7532
- function installCompletion(shell, commands) {
7533
- if (!shell) {
7534
- 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)}`));
7535
6575
  }
7536
- const target = completionInstallPath(shell);
7537
- if (!target) {
7538
- buildCompletionScript(shell, commands, "install");
7539
- 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"));
7540
6580
  }
7541
- const script = buildCompletionScript(shell, commands);
7542
- console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
7543
- try {
7544
- if (shell === "bash") {
7545
- const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
7546
- if (hasBashMarkerBlock(existing)) {
7547
- console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
7548
- return;
7549
- }
7550
- fs12.mkdirSync(path9.dirname(target), { recursive: true });
7551
- fs12.appendFileSync(target, `
7552
- ${BASH_MARKER}
7553
- ${script}${BASH_END_MARKER}
7554
- `);
7555
- console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7556
- return;
7557
- }
7558
- const fingerprint = productFingerprint(shell);
7559
- if (fingerprint && fs12.existsSync(target)) {
7560
- const existing = fs12.readFileSync(target, "utf8");
7561
- if (!existing.includes(fingerprint)) {
7562
- throw new CliError(`${target} \u5DF2\u5B58\u5728\u4E14\u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5B89\u88C5`, {
7563
- label: "\u5B89\u88C5\u4E2D\u6B62",
7564
- hint: [
7565
- "\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",
7566
- "\u786E\u8BA4\u65E0\u7528\u540E\u5148\u624B\u52A8\u5220\u9664\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:",
7567
- ` rm ${target}`,
7568
- ` mihomo completion install ${shell}`,
7569
- "",
7570
- "\u6216\u6539\u4E3A\u624B\u52A8\u8F93\u51FA\u5230\u522B\u5904:",
7571
- ` mihomo completion ${shell} > <\u4F60\u9009\u62E9\u7684\u8DEF\u5F84>`
7572
- ]
7573
- });
7574
- }
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}`);
7575
6589
  }
7576
- fs12.mkdirSync(path9.dirname(target), { recursive: true });
7577
- fs12.writeFileSync(target, script, { mode: 420 });
7578
- console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7579
- } catch (e) {
7580
- throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
7581
- label: "\u5B89\u88C5\u5931\u8D25",
7582
- 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}`]
7583
- });
7584
- }
7585
- if (shell === "zsh") {
7586
- console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
7587
- }
7588
- }
7589
- function uninstallCompletion(shell, commands) {
7590
- if (!shell) {
7591
- throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion uninstall <${SHELLS.join("|")}>`] });
7592
- }
7593
- const target = completionInstallPath(shell);
7594
- if (!target) {
7595
- buildCompletionScript(shell, commands, "uninstall");
7596
- return;
7597
6590
  }
7598
- if (!fs12.existsSync(target)) {
7599
- console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
7600
- 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
+ }
7601
6601
  }
7602
- console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
7603
- try {
7604
- if (shell === "bash") {
7605
- const existing2 = fs12.readFileSync(target, "utf8");
7606
- if (!hasBashMarkerBlock(existing2)) {
7607
- console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
7608
- console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
7609
- return;
7610
- }
7611
- let rest = existing2;
7612
- let removed = 0;
7613
- while (hasBashMarkerBlock(rest)) {
7614
- const start = rest.indexOf(BASH_MARKER);
7615
- const end = rest.indexOf(BASH_END_MARKER);
7616
- const before = rest.slice(0, start).replace(/\n+$/, "\n");
7617
- const after = rest.slice(end + BASH_END_MARKER.length).replace(/^\n/, "");
7618
- rest = `${before}${after}`;
7619
- removed++;
7620
- }
7621
- if (rest.trim() === "") {
7622
- fs12.rmSync(target);
7623
- 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"));
7624
- return;
7625
- }
7626
- fs12.writeFileSync(target, rest);
7627
- if (removed > 1) {
7628
- 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}`);
7629
6614
  }
7630
- 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"));
7631
- return;
7632
6615
  }
7633
- const existing = fs12.readFileSync(target, "utf8");
7634
- const fingerprint = productFingerprint(shell);
7635
- if (!fingerprint || !existing.includes(fingerprint)) {
7636
- throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
7637
- label: "\u5378\u8F7D\u4E2D\u6B62",
7638
- 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}`]
7639
- });
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)}`);
7640
6619
  }
7641
- fs12.rmSync(target);
7642
- console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7643
- } catch (e) {
7644
- if (e instanceof CliError) throw e;
7645
- throw new CliError(`\u8865\u5168\u5378\u8F7D\u5931\u8D25: ${e.message}`, {
7646
- label: "\u5378\u8F7D\u5931\u8D25",
7647
- hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u6587\u4EF6\u7684\u6743\u9650\uFF0C\u6216\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
7648
- });
7649
- }
7650
- }
7651
- function cmdCompletion(args, commands) {
7652
- assertKnownFlags(args.slice(1), [], "completion");
7653
- if (args[1] === "install") {
7654
- assertPositionalCount(args, 1, 2, `mihomo completion install <${SHELLS.join("|")}>`);
7655
- installCompletion(args[2], commands);
7656
- return;
7657
- }
7658
- if (args[1] === "uninstall") {
7659
- assertPositionalCount(args, 1, 2, `mihomo completion uninstall <${SHELLS.join("|")}>`);
7660
- uninstallCompletion(args[2], commands);
7661
- 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>)")}`);
7662
6625
  }
7663
- assertPositionalCount(args, 1, 1, `mihomo completion <${SHELLS.join("|")}>`);
7664
- const shell = args[1];
7665
- if (!shell) {
7666
- throw new CliError("\u8BF7\u6307\u5B9A shell", {
7667
- hint: [
7668
- `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`,
7669
- `\u5B89\u88C5\u5230\u9ED8\u8BA4\u4F4D\u7F6E: mihomo completion install <${SHELLS.join("|")}>`,
7670
- `\u5378\u8F7D: mihomo completion uninstall <${SHELLS.join("|")}>`,
7671
- '\u4E34\u65F6\u542F\u7528: eval "$(mihomo completion zsh)"'
7672
- ]
7673
- });
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"));
7674
6630
  }
7675
- console.log(buildCompletionScript(shell, commands));
6631
+ console.log("");
7676
6632
  }
7677
-
7678
- // src/commands/config.ts
7679
- function cmdConfig(args = []) {
7680
- assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
7681
- assertPositionalCount(args, 0, 1, "mihomo config [--json]");
7682
- const asJson = hasFlag(args, "-j", "--json");
7683
- const active = getActiveSubscription();
7684
- if (!active) {
7685
- throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
7686
- }
7687
- const rawContent = readSubscriptionRawConfig(active.name);
7688
- if (!rawContent) {
7689
- 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}` });
7690
- }
7691
- const mode = getConfigInfo()?.tun ? "tun" : "mixed";
7692
- const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
7693
- const shown = { ...config };
7694
- if ("secret" in shown) shown.secret = "***";
7695
- if (asJson) {
7696
- 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")}`);
7697
6639
  return;
7698
6640
  }
7699
- console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
7700
- 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"));
7701
- if ("secret" in config) {
7702
- 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"})`);
7703
6652
  }
7704
- console.log("");
7705
- console.log(dumpYaml(shown).trimEnd());
7706
- if (warnings.length > 0) {
7707
- console.log("");
7708
- 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`));
7709
6656
  }
7710
- }
7711
-
7712
- // src/commands/doctor.ts
7713
- import { spawnSync as spawnSync7 } from "child_process";
7714
- import fs13 from "fs";
7715
-
7716
- // src/commands/update.ts
7717
- import { execFile as execFile3, spawn as spawn2 } from "child_process";
7718
- import { promisify as promisify3 } from "util";
7719
- var execFileAsync2 = promisify3(execFile3);
7720
- var NPM_VIEW_TIMEOUT_MS = 15e3;
7721
- async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
7722
- try {
7723
- const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs });
7724
- const version = stdout.trim().split("\n").pop()?.trim();
7725
- return version || null;
7726
- } catch {
7727
- return null;
6657
+ for (const b of broken) {
6658
+ console.log(colors.red(` ${b.message}`));
7728
6659
  }
7729
6660
  }
7730
- async function cmdUpdate(args = []) {
7731
- assertKnownFlags(args.slice(1), [], "update");
7732
- assertPositionalCount(args, 0, 1, "mihomo update");
7733
- console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7734
- console.log("");
7735
- const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7736
- if (latest) {
7737
- try {
7738
- const cmp = compareVersions(VERSION, latest);
7739
- if (cmp > 0) {
7740
- 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`));
7741
- console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
7742
- return;
7743
- }
7744
- if (cmp === 0) {
7745
- console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7746
- return;
7747
- }
7748
- } catch {
7749
- }
7750
- 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);
7751
6668
  } else {
7752
- 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);
7753
6671
  }
7754
- console.log("");
7755
- console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7756
- console.log("");
7757
- await new Promise((resolve, reject) => {
7758
- const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7759
- npm.on("close", (code) => {
7760
- if (code === 0) {
7761
- resolve();
7762
- } else {
7763
- 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 }));
7764
- }
7765
- });
7766
- npm.on("error", (e) => {
7767
- const perm = e.message.includes("EACCES") || e.message.includes("permission");
7768
- 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}`));
7769
- });
7770
- });
7771
- try {
7772
- const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7773
- const result = JSON.parse(stdout);
7774
- const newVersion = result.dependencies?.[PKG_NAME]?.version;
7775
- console.log("");
7776
- if (newVersion) {
7777
- console.log(`\u66F4\u65B0\u5B8C\u6210\uFF0C\u6700\u65B0\u7248\u672C: ${colors.green(newVersion)}`);
7778
- } else {
7779
- console.log("\u66F4\u65B0\u5B8C\u6210");
7780
- }
7781
- } catch {
7782
- console.log("");
7783
- 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"));
7784
6675
  }
7785
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
+ }
7786
6681
 
7787
- // src/commands/doctor.ts
7788
- function isPortListening(port) {
7789
- try {
7790
- const r = spawnSync7("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7791
- return r.status === 0 && (r.stdout || "").trim().length > 0;
7792
- } catch {
7793
- 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" });
7794
6688
  }
6689
+ return modeToken === "tun" ? "tun" : "mixed";
7795
6690
  }
7796
- async function collectChecks() {
7797
- const checks = [];
7798
- const push = (name, status, detail, fix, notes) => {
7799
- checks.push({ name, status, detail, fix, notes });
7800
- };
7801
- 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;
7802
6696
  if (!hasKernel()) {
7803
- push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7804
- } else {
7805
- const v = getKernelVersion();
7806
- const r = spawnSync7(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7807
- if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7808
- push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7809
- } else if (r.error) {
7810
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7811
- } else {
7812
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7813
- }
7814
- }
7815
- try {
7816
- fs13.accessSync(USER_DATA_DIR, fs13.constants.W_OK);
7817
- push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7818
- } catch {
7819
- 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" });
7820
6698
  }
7821
- if (fs13.existsSync(PATHS.settingsFile)) {
7822
- if (isValidSettingsContent(fs13.readFileSync(PATHS.settingsFile, "utf8"))) {
7823
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7824
- } else {
7825
- 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("");
7826
6710
  }
7827
- } else {
7828
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
7829
- }
7830
- const subs = getSubscriptionsWithCache();
7831
- const active = getActiveSubscription();
7832
- if (subs.length === 0) {
7833
- push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
7834
- } else {
7835
- push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7836
- if (active) {
7837
- if (!readSubscriptionRawConfig(active.name)) {
7838
- 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}`);
7839
- } else {
7840
- push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
7841
- }
7842
- const cached = subs.find((s) => s.name === active.name);
7843
- if (cached?.updated_at) {
7844
- const rel = formatRelativeTime(cached.updated_at);
7845
- if (isSubscriptionStale(cached)) {
7846
- 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");
7847
- } else {
7848
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
7849
- }
7850
- }
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
+ });
7851
6715
  }
7852
- }
7853
- const service = getServiceStatus();
7854
- const legacy = detectLegacySystemInstall();
7855
- if (legacy) {
7856
- 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");
7857
- } else if (!service.installed && !service.loaded) {
7858
- push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
7859
- } else if (!service.installed) {
7860
- push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
7861
- } else if (service.running) {
7862
- const abnormalExit = describeAbnormalExit(service);
7863
- 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` : ""}`);
7864
- if (abnormalExit) {
7865
- 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("");
7866
6722
  }
7867
- } else {
7868
- const abnormalExit = describeAbnormalExit(service);
7869
- if (!service.disabled && abnormalExit) {
7870
- 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");
7871
- } else {
7872
- 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
+ });
7873
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
+ });
7874
6732
  }
7875
- const state = getRunningState();
7876
- const info = getConfigInfo();
7877
- let mixedPortDefault = DEFAULT_MIXED_PORT;
6733
+ const sub = requireActiveSubscription();
6734
+ if (!skipUpdate) {
6735
+ await autoUpdateStaleSubscription({ timeout: updateTimeout });
6736
+ }
6737
+ let prepared;
7878
6738
  try {
7879
- const ports = getPorts();
7880
- mixedPortDefault = ports.mixed;
6739
+ prepared = await prepareConfigForStart(targetMode, sub.name);
7881
6740
  } catch (e) {
7882
- 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" });
7883
6743
  }
7884
- const mixedPort = info?.mixedPort ?? mixedPortDefault;
7885
- if (state.running) {
7886
- if (isPortListening(mixedPort)) {
7887
- push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
7888
- } else {
7889
- 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");
7890
6755
  }
7891
- } else if (isPortListening(mixedPort)) {
7892
- 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`));
7893
6764
  } else {
7894
- 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"));
7895
6766
  }
7896
- if (active && hasKernel()) {
7897
- try {
7898
- const mode = info?.tun ? "tun" : "mixed";
7899
- const prepared = await prepareConfigForStart(mode, active.name);
7900
- const warnings = prepared.buildResult.warnings;
7901
- if (warnings.length > 0) {
7902
- push(
7903
- "\u914D\u7F6E\u6784\u5EFA",
7904
- "warn",
7905
- `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
7906
- void 0,
7907
- warnings.map((w) => ` ${w}`)
7908
- );
7909
- } else {
7910
- 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`);
7911
6778
  }
7912
- } catch (e) {
7913
- const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
7914
- 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);
7915
6780
  }
7916
- } else {
7917
- push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
7918
6781
  }
7919
- if (state.running && info?.mixedPort) {
7920
- const probe = await probeProxyConnectivity(info.mixedPort);
7921
- if (probe.ok) {
7922
- push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
7923
- } else {
7924
- push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
7925
- }
7926
- } else {
7927
- 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);
7928
6790
  }
7929
- const latest = await latestVersionPromise;
7930
- if (latest === null) {
7931
- push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7932
- } else if (compareVersions(latest, VERSION) > 0) {
7933
- push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo update");
7934
- } else {
7935
- 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 });
7936
6807
  }
7937
- return checks;
6808
+ return confirmPrompt(question);
7938
6809
  }
7939
- async function cmdDoctor(args = []) {
7940
- assertKnownFlags(args.slice(1), [], "doctor");
7941
- assertPositionalCount(args, 0, 1, "mihomo doctor");
7942
- const checks = await collectChecks();
6810
+ async function restartToApply(args) {
6811
+ const currentMode = restartModeOnChange();
6812
+ if (!currentMode) return false;
7943
6813
  console.log("");
7944
- for (const c of checks) {
7945
- const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
7946
- console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
7947
- if (c.status !== "ok" && c.status !== "skip") {
7948
- for (const line of c.notes ?? []) console.log(colors.gray(line));
7949
- 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}`);
7950
6839
  }
7951
6840
  }
7952
- const ok = checks.filter((c) => c.status === "ok").length;
7953
- const warn = checks.filter((c) => c.status === "warn").length;
7954
- const fail = checks.filter((c) => c.status === "fail").length;
7955
- 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));
7956
6846
  console.log("");
7957
- 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}`);
7958
6848
  console.log("");
7959
- if (fail > 0) {
7960
- throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
7961
- label: "\u4F53\u68C0\u672A\u901A\u8FC7",
7962
- hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
7963
- });
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)}`);
7964
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
+ });
7965
6877
  }
7966
6878
 
6879
+ // src/commands/doctor.ts
6880
+ import { spawnSync as spawnSync6 } from "child_process";
6881
+ import fs11 from "fs";
6882
+
7967
6883
  // src/kernel.ts
7968
- import { execFile as execFile4, spawnSync as spawnSync8 } from "child_process";
7969
- import fs14 from "fs";
7970
- import path10 from "path";
7971
- 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";
7972
6888
  var GITHUB_REPO = "MetaCubeX/mihomo";
7973
6889
  var KERNEL_HTTP_TIMEOUT = 12e4;
7974
6890
  var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
7975
6891
  var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
7976
- var execFileAsync3 = promisify4(execFile4);
6892
+ var execFileAsync2 = promisify3(execFile3);
7977
6893
  function withMirror(url, mirror) {
7978
6894
  if (mirror && url.startsWith("https://github.com/")) {
7979
6895
  return mirror + url;
@@ -8005,7 +6921,7 @@ function resolveDownloadChannel(input) {
8005
6921
  return { kind: "direct" };
8006
6922
  }
8007
6923
  function hasGh() {
8008
- const result = spawnSync8("gh", ["--version"], { stdio: "ignore" });
6924
+ const result = spawnSync5("gh", ["--version"], { stdio: "ignore" });
8009
6925
  return !result.error && result.status === 0;
8010
6926
  }
8011
6927
  function getArch() {
@@ -8016,9 +6932,7 @@ function getArch() {
8016
6932
  }
8017
6933
  function findMatchingAsset(assets, platform, arch) {
8018
6934
  const prefix = `mihomo-${platform}-${arch}`;
8019
- const matchingAssets = assets.filter(
8020
- (a) => a.name.startsWith(prefix) && a.name.endsWith(".gz") || a.name.startsWith(`${prefix}-`) && a.name.endsWith(".gz")
8021
- );
6935
+ const matchingAssets = assets.filter((a) => a.name.startsWith(prefix) && a.name.endsWith(".gz"));
8022
6936
  if (matchingAssets.length === 0) return null;
8023
6937
  if (matchingAssets.length === 1) return matchingAssets[0];
8024
6938
  const standardAsset = matchingAssets.find((a) => new RegExp(`^${escapeRegExp(prefix)}-v?\\d+\\.\\d+\\.\\d+$`).test(a.name.slice(0, -3)));
@@ -8087,7 +7001,7 @@ async function getLatestRelease(repo, proxyPort) {
8087
7001
  if (proxyPort) {
8088
7002
  let stdout;
8089
7003
  try {
8090
- const result = await execFileAsync3("curl", buildReleaseApiCurlArgs(proxyPort, url), {
7004
+ const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(proxyPort, url), {
8091
7005
  encoding: "utf8",
8092
7006
  maxBuffer: 50 * 1024 * 1024,
8093
7007
  timeout: KERNEL_HTTP_TIMEOUT + 1e4
@@ -8134,32 +7048,6 @@ async function checkUpdate(proxyPort) {
8134
7048
  release: latest
8135
7049
  };
8136
7050
  }
8137
- function findBinaryInDir(dir, maxDepth = 4) {
8138
- if (maxDepth <= 0) return null;
8139
- const files = fs14.readdirSync(dir);
8140
- for (const f of files) {
8141
- const fullPath = path10.join(dir, f);
8142
- const stat = fs14.lstatSync(fullPath);
8143
- if (stat.isDirectory()) {
8144
- const found = findBinaryInDir(fullPath, maxDepth - 1);
8145
- if (found) return found;
8146
- continue;
8147
- }
8148
- if (!stat.isFile()) continue;
8149
- if (f === "mihomo") return fullPath;
8150
- if (f.includes("mihomo") && !f.endsWith(".gz")) return fullPath;
8151
- }
8152
- return null;
8153
- }
8154
- var MAX_EXTRACTED_BYTES = 512 * 1024 * 1024;
8155
- function parseTarEntrySize(line) {
8156
- const tokens = line.trim().split(/\s+/);
8157
- if (tokens.length < 5) return null;
8158
- const sizeToken = tokens[1].includes("/") ? tokens[2] : tokens[4];
8159
- if (!/^\d+$/.test(sizeToken)) return null;
8160
- const size = Number(sizeToken);
8161
- return Number.isSafeInteger(size) ? size : null;
8162
- }
8163
7051
  function buildKernelCurlArgs(args) {
8164
7052
  const argv = [
8165
7053
  "-L",
@@ -8204,8 +7092,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8204
7092
  }
8205
7093
  assertTrustedAssetUrl(asset.browser_download_url);
8206
7094
  const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
8207
- const tempDir = fs14.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
8208
- 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));
8209
7097
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
8210
7098
  try {
8211
7099
  if (channel.kind === "mirror" && progressCallback) {
@@ -8215,10 +7103,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8215
7103
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
8216
7104
  }
8217
7105
  if (channel.kind === "gh") {
8218
- if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
7106
+ if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
8219
7107
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
8220
7108
  }
8221
- const ghResult = spawnSync8("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7109
+ const ghResult = spawnSync5("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
8222
7110
  stdio: "inherit",
8223
7111
  timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
8224
7112
  });
@@ -8236,7 +7124,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8236
7124
  }
8237
7125
  } else {
8238
7126
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
8239
- const curlResult = spawnSync8(
7127
+ const curlResult = spawnSync5(
8240
7128
  "curl",
8241
7129
  buildKernelCurlArgs({
8242
7130
  url: downloadUrl,
@@ -8259,11 +7147,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8259
7147
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
8260
7148
  }
8261
7149
  }
8262
- if (!fs14.existsSync(tempPath)) {
7150
+ if (!fs10.existsSync(tempPath)) {
8263
7151
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
8264
7152
  }
8265
7153
  if (Number.isFinite(asset.size) && asset.size > 0) {
8266
- const actual = fs14.statSync(tempPath).size;
7154
+ const actual = fs10.statSync(tempPath).size;
8267
7155
  if (actual !== asset.size) {
8268
7156
  throw new Error(
8269
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
@@ -8274,57 +7162,19 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8274
7162
  if (progressCallback) {
8275
7163
  progressCallback("\u89E3\u538B\u5185\u6838...");
8276
7164
  }
8277
- let extractedBinary = null;
8278
- if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
8279
- const listResult = spawnSync8("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
8280
- if (listResult.error) throw listResult.error;
8281
- if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
8282
- for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
8283
- if (entry.startsWith("/") || entry.split("/").includes("..")) {
8284
- throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
8285
- }
8286
- }
8287
- const typeResult = spawnSync8("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
8288
- if (typeResult.error) throw typeResult.error;
8289
- if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
8290
- let extractedBytes = 0;
8291
- for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
8292
- const typeChar = line[0];
8293
- if (typeChar !== "-" && typeChar !== "d") {
8294
- throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
8295
- }
8296
- const entrySize = parseTarEntrySize(line);
8297
- if (entrySize !== null) extractedBytes += entrySize;
8298
- }
8299
- if (extractedBytes > MAX_EXTRACTED_BYTES) {
8300
- throw new Error(
8301
- `\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`
8302
- );
8303
- }
8304
- const tarResult = spawnSync8("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
8305
- stdio: ["ignore", "ignore", "inherit"],
8306
- timeout: 6e4
8307
- });
8308
- if (tarResult.error) throw tarResult.error;
8309
- if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
8310
- } else if (tempPath.endsWith(".gz")) {
8311
- const baseName = path10.basename(tempPath, ".gz");
8312
- const outputPath = path10.join(tempDir, baseName);
8313
- const gzipResult = spawnSync8("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
8314
- if (gzipResult.error) throw gzipResult.error;
8315
- if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
8316
- fs14.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
8317
- extractedBinary = outputPath;
8318
- }
8319
- const foundBinary = extractedBinary || findBinaryInDir(tempDir);
8320
- if (!foundBinary) {
8321
- 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`);
8322
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 });
8323
7173
  if (progressCallback) {
8324
7174
  progressCallback("\u6821\u9A8C\u5185\u6838...");
8325
7175
  }
8326
- fs14.chmodSync(foundBinary, 493);
8327
- const check = spawnSync8(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7176
+ fs10.chmodSync(foundBinary, 493);
7177
+ const check = spawnSync5(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
8328
7178
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
8329
7179
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
8330
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
@@ -8340,15 +7190,300 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
8340
7190
  }
8341
7191
  }
8342
7192
  const targetPath = PATHS.mihomoBinary;
8343
- fs14.renameSync(foundBinary, targetPath);
8344
- fs14.chmodSync(targetPath, 493);
7193
+ fs10.renameSync(foundBinary, targetPath);
7194
+ fs10.chmodSync(targetPath, 493);
8345
7195
  clearKernelVersionCache();
8346
7196
  return { version: latest.tag_name, path: targetPath };
8347
7197
  } finally {
8348
7198
  try {
8349
- 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
+ }
8350
7237
  } catch {
8351
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
+ });
8352
7487
  }
8353
7488
  }
8354
7489
 
@@ -8394,120 +7529,448 @@ async function cmdKernel(args) {
8394
7529
  if (err.response?.data?.documentation_url) {
8395
7530
  hint.push(`\u6587\u6863: ${err.response.data.documentation_url}`);
8396
7531
  }
8397
- if (!effectiveMirror) {
8398
- if (proxyRunning && !forceDirect) {
8399
- 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;
8400
7805
  } else {
8401
- hint.push(
8402
- "",
8403
- "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
8404
- " mihomo kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
8405
- ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
8406
- );
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
+ }
8407
7815
  }
8408
7816
  }
8409
- throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
8410
7817
  }
8411
- console.log(`\u5F53\u524D: ${info.current}`);
8412
- console.log(`\u6700\u65B0: ${info.latest}`);
8413
- if (!info.needsUpdate) {
8414
- console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
8415
- } else {
8416
- console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
8417
- let result;
8418
- try {
8419
- result = await downloadKernel((msg) => console.log(msg), channel, info.release);
8420
- } catch (e) {
8421
- if (e instanceof CliError) throw e;
8422
- throw new CliError(e.message, {
8423
- label: "\u4E0B\u8F7D\u5931\u8D25",
8424
- hint: [
8425
- "",
8426
- "\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
8427
- "\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"
8428
- ]
8429
- });
8430
- }
8431
- console.log(`
8432
- \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8433
- if (getRunningState().running) {
8434
- 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"));
8435
- }
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 };
8436
7841
  }
7842
+ clearRuntime();
7843
+ return { success: true, killed: result.killed };
8437
7844
  }
8438
7845
 
8439
- // src/commands/log.ts
8440
- function cmdLogs(args) {
8441
- assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8442
- assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
8443
- const lines = parseIntArg(args, "-n", "--lines", 100);
8444
- const openInViewer = hasFlag(args, "-o", "--open");
8445
- const follow = hasFlag(args, "-f", "--follow");
8446
- const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8447
- const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8448
- if (targetName) {
8449
- let logPath;
8450
- if (targetName === "0") {
8451
- logPath = getLogPath();
8452
- } else {
8453
- const parsedIdx = parseInt(targetName, 10);
8454
- if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
8455
- 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" });
8456
- }
8457
- const archive = listLogs().archives[parsedIdx - 1];
8458
- if (!archive) {
8459
- throw new CliError(`\u672A\u627E\u5230\u65E5\u5FD7 "${targetName}"`, { hint: '\u4F7F\u7528 "mihomo logs" \u67E5\u770B\u53EF\u7528\u65E5\u5FD7\u5217\u8868' });
8460
- }
8461
- 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(", ")}`] });
8462
7878
  }
8463
- if (openInViewer) {
8464
- 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");
8465
7897
  return;
8466
7898
  }
8467
- viewLogWithTail(logPath, { follow, lines });
8468
- return;
8469
7899
  }
8470
- const logs = listLogs();
8471
- const all = [];
8472
- if (logs.current) all.push(logs.current);
8473
- all.push(...logs.archives);
8474
- if (all.length === 0) {
8475
- 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");
8476
7920
  return;
8477
7921
  }
8478
- console.log("");
8479
- console.log("\u65E5\u5FD7\u5217\u8868:");
8480
- console.log("");
8481
- let archiveCounter = 0;
8482
- for (const log of all) {
8483
- let num;
8484
- if (log.isCurrent) {
8485
- num = " 0";
8486
- } else {
8487
- archiveCounter++;
8488
- 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
+ });
8489
7934
  }
8490
- const time = formatDate(log.mtime);
8491
- const size = formatBytes(log.size);
8492
- const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8493
- console.log(` ${num}. ${name}`);
8494
- console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
8495
- if (!log.isCurrent) {
8496
- 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;
8497
7948
  }
8498
- console.log("");
7949
+ if (hadContent) deleted.add(target.id);
8499
7950
  }
8500
- console.log("\u7528\u6CD5:");
8501
- console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8502
- console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
8503
- console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
8504
- console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8505
- console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8506
- 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");
8507
7970
  }
8508
7971
 
8509
7972
  // src/commands/service.ts
8510
- import fs15 from "fs";
7973
+ import fs14 from "fs";
8511
7974
  async function handleLegacyInstall() {
8512
7975
  if (!detectLegacySystemInstall()) return;
8513
7976
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -8559,7 +8022,7 @@ async function cmdInstall(args) {
8559
8022
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8560
8023
  } else {
8561
8024
  console.log("\u542F\u52A8: mihomo start");
8562
- if (!fs15.existsSync(PATHS.configFile)) {
8025
+ if (!fs14.existsSync(PATHS.configFile)) {
8563
8026
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8564
8027
  }
8565
8028
  }
@@ -8643,12 +8106,261 @@ async function cmdStop(args) {
8643
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")}`);
8644
8107
  }
8645
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
+
8646
8357
  // src/commands/ui.ts
8647
8358
  import { spawnSync as spawnSync9 } from "child_process";
8648
8359
  function resolveUiName(args) {
8649
- const name = (args[1] ?? "zash").toLowerCase();
8360
+ const raw = getNonFlagArg(args, 1);
8361
+ const name = (raw ?? "zash").toLowerCase();
8650
8362
  if (name === "" || !Object.hasOwn(UI_URLS, name)) {
8651
- 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" });
8652
8364
  }
8653
8365
  return name;
8654
8366
  }
@@ -8660,22 +8372,30 @@ function copyToClipboard(text) {
8660
8372
  }
8661
8373
  }
8662
8374
  function cmdUI(args) {
8663
- assertKnownFlags(args.slice(1), [], "ui");
8664
- 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]");
8665
8377
  const uiName = resolveUiName(args);
8378
+ const copySecret = hasFlag(args, "-c", "--copy-secret");
8666
8379
  if (!getRunningState().running) {
8667
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"));
8668
8381
  console.log("");
8669
8382
  }
8670
8383
  const url = UI_URLS[uiName];
8384
+ const controllerPort = getPorts().controller;
8671
8385
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
8672
- console.log(`\u5730\u5740: ${url}`);
8386
+ console.log(`\u9875\u9762: ${url}`);
8387
+ console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${controllerPort}`);
8673
8388
  const secret = readSettings().controller_secret;
8674
8389
  if (typeof secret === "string" && secret) {
8675
- console.log(
8676
- 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`
8677
- );
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
+ }
8678
8397
  }
8398
+ console.log("");
8679
8399
  openUrl(url);
8680
8400
  }
8681
8401
 
@@ -8731,7 +8451,7 @@ var COMMANDS = [
8731
8451
  aliases: [],
8732
8452
  handler: cmdUI,
8733
8453
  group: "interface",
8734
- 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" }]
8735
8455
  },
8736
8456
  {
8737
8457
  name: "logs",
@@ -8769,7 +8489,7 @@ var COMMANDS = [
8769
8489
  aliases: [],
8770
8490
  handler: cmdConfig,
8771
8491
  group: "config",
8772
- 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" }]
8773
8493
  },
8774
8494
  {
8775
8495
  name: "overwrite",
@@ -8818,26 +8538,15 @@ var COMMANDS = [
8818
8538
  aliases: [],
8819
8539
  handler: cmdDoctor,
8820
8540
  group: "system",
8821
- 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" }]
8822
- },
8823
- {
8824
- name: "completion",
8825
- aliases: [],
8826
- handler: (args) => cmdCompletion(args, COMMANDS),
8827
- group: "system",
8828
- usage: [
8829
- { signature: "completion install <zsh|bash|fish>", description: "\u5B89\u88C5\u8865\u5168\u5230\u5BF9\u5E94 shell \u7684\u9ED8\u8BA4\u4F4D\u7F6E" },
8830
- { signature: "completion uninstall <zsh|bash|fish>", description: "\u79FB\u9664\u5DF2\u5B89\u88C5\u7684\u8865\u5168" },
8831
- { signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA\u8865\u5168\u811A\u672C\uFF08\u91CD\u5B9A\u5411\u6216 eval \u4F7F\u7528\uFF09" }
8832
- ]
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" }]
8833
8542
  },
8834
8543
  // === meta(不在分组清单展示,help 末尾单列) ===
8835
8544
  {
8836
8545
  name: "help",
8837
8546
  aliases: ["-h", "--help"],
8838
- handler: () => printHelp(COMMANDS),
8547
+ handler: (args) => printHelpEntry(args, COMMANDS, findCommand),
8839
8548
  group: "meta",
8840
- 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" }]
8841
8550
  },
8842
8551
  {
8843
8552
  name: "version",
@@ -8889,13 +8598,24 @@ process.on("unhandledRejection", (reason) => {
8889
8598
  \u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
8890
8599
  process.exit(1);
8891
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
+ }
8892
8611
  function clearProxyEnv() {
8893
- delete process.env.http_proxy;
8894
- delete process.env.https_proxy;
8895
- delete process.env.HTTP_PROXY;
8896
- delete process.env.HTTPS_PROXY;
8897
- delete process.env.all_proxy;
8898
- 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
+ }
8899
8619
  }
8900
8620
  var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
8901
8621
  function assertNotRoot(commandName) {
@@ -8966,7 +8686,11 @@ async function main() {
8966
8686
  }
8967
8687
  if (command.group === "meta") {
8968
8688
  assertKnownFlags(args.slice(1), [], command.name);
8969
- 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;
8970
8694
  }
8971
8695
  await command.handler(command.rewrite ? command.rewrite(args) : args);
8972
8696
  }