mihomo-cli 4.2.4 → 4.3.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
@@ -3858,6 +3858,35 @@ function formatDate(dateOrIso) {
3858
3858
  return "\u672A\u77E5";
3859
3859
  }
3860
3860
  }
3861
+ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
3862
+ if (dateOrIso === void 0 || dateOrIso === null) return null;
3863
+ let t;
3864
+ try {
3865
+ const d = dateOrIso instanceof Date ? dateOrIso : new Date(dateOrIso);
3866
+ t = d.getTime();
3867
+ } catch {
3868
+ return null;
3869
+ }
3870
+ if (Number.isNaN(t) || t > nowMs) return null;
3871
+ const sec = Math.floor((nowMs - t) / 1e3);
3872
+ if (sec < 60) return "\u521A\u521A";
3873
+ const min = Math.floor(sec / 60);
3874
+ if (min < 60) return `${min} \u5206\u949F\u524D`;
3875
+ const hour = Math.floor(min / 60);
3876
+ if (hour < 24) return `${hour} \u5C0F\u65F6\u524D`;
3877
+ const day = Math.floor(hour / 24);
3878
+ if (day < 30) return `${day} \u5929\u524D`;
3879
+ const month = Math.floor(day / 30);
3880
+ if (month < 12) return `${month} \u4E2A\u6708\u524D`;
3881
+ return `${Math.floor(month / 12)} \u5E74\u524D`;
3882
+ }
3883
+ function subscriptionUrgency(entry, nowMs = Date.now()) {
3884
+ if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 < nowMs) return "expired";
3885
+ const used = (entry.upload || 0) + (entry.download || 0);
3886
+ if (entry.total !== void 0 && entry.total > 0 && used >= entry.total) return "traffic-exhausted";
3887
+ if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 - nowMs < 7 * 864e5) return "expiring";
3888
+ return null;
3889
+ }
3861
3890
  function hasFlag(args, short, long) {
3862
3891
  return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
3863
3892
  }
@@ -3975,9 +4004,9 @@ function normalizeMirrorUrl(val) {
3975
4004
  const url = parsed.toString();
3976
4005
  return url.endsWith("/") ? url : `${url}/`;
3977
4006
  }
3978
- function parseMirrorArg(args) {
4007
+ function parseMirrorArg(args, savedMirror) {
3979
4008
  if (!args || args.length < 2) {
3980
- return { mirror: null, isOverride: false };
4009
+ return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
3981
4010
  }
3982
4011
  if (args.some((a) => a === "--mirror-all" || a.startsWith("--mirror-all="))) {
3983
4012
  throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
@@ -3991,7 +4020,7 @@ function parseMirrorArg(args) {
3991
4020
  });
3992
4021
  }
3993
4022
  if (args.includes("--no-mirror") || args.includes("--direct")) {
3994
- return { mirror: null, isOverride: true };
4023
+ return { mirror: null, isOverride: true, clearSaved: true };
3995
4024
  }
3996
4025
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
3997
4026
  const mirrorIdx = args.indexOf("--mirror");
@@ -3999,11 +4028,12 @@ function parseMirrorArg(args) {
3999
4028
  const inline = mirrorEq?.slice("--mirror=".length);
4000
4029
  const nextArg = inline ?? args[mirrorIdx + 1];
4001
4030
  if (!nextArg || nextArg.startsWith("-")) {
4002
- return { mirror: DEFAULT_MIRROR, isOverride: true };
4031
+ return { mirror: DEFAULT_MIRROR, isOverride: true, remember: true };
4003
4032
  }
4004
- return { mirror: normalizeMirrorUrl(nextArg), isOverride: true };
4033
+ const normalized = normalizeMirrorUrl(nextArg);
4034
+ return normalized ? { mirror: normalized, isOverride: true, remember: true } : { mirror: null, isOverride: true, clearSaved: true };
4005
4035
  }
4006
- return { mirror: null, isOverride: false };
4036
+ return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
4007
4037
  }
4008
4038
 
4009
4039
  // src/config.ts
@@ -4369,132 +4399,10 @@ function clearKernelVersionCache() {
4369
4399
  kernelVersionCached = false;
4370
4400
  }
4371
4401
 
4372
- // src/commands/help.ts
4373
- function printShortHelp() {
4374
- console.log(`
4375
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
4376
- `);
4377
- console.log(
4378
- `\u5E38\u7528\u547D\u4EE4:
4379
- ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
4380
- ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
4381
- ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
4382
- ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
4383
- `
4384
- );
4385
- }
4386
- var GROUP_TITLES = [
4387
- ["control", "\u63A7\u5236:"],
4388
- ["interface", "\u754C\u9762:"],
4389
- ["subscription", "\u8BA2\u9605:"],
4390
- ["config", "\u914D\u7F6E:"],
4391
- ["system", "\u7CFB\u7EDF:"]
4392
- ];
4393
- function printHelp(commands) {
4394
- const lines = [`
4395
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
4396
- const allUsage = commands.flatMap((c) => c.usage);
4397
- const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
4398
- const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
4399
- for (const [group, title] of GROUP_TITLES) {
4400
- const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
4401
- if (usageLines.length === 0) continue;
4402
- lines.push("", colors.cyan(title));
4403
- for (const u of usageLines) lines.push(formatUsage(u));
4404
- }
4405
- const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
4406
- if (meta.length > 0) {
4407
- lines.push("", colors.cyan("\u5143:"));
4408
- for (const u of meta) lines.push(formatUsage(u));
4409
- }
4410
- lines.push(
4411
- "",
4412
- `${colors.cyan("\u793A\u4F8B:")}`,
4413
- " mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
4414
- " mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
4415
- " mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
4416
- " mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
4417
- " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
4418
- " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
4419
- " mihomo ui # \u6253\u5F00 Web UI",
4420
- "",
4421
- `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
4422
- " tun = start tun",
4423
- "",
4424
- `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
4425
- " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
4426
- " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
4427
- "",
4428
- `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
4429
- " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
4430
- ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
4431
- );
4432
- console.log(lines.join("\n"));
4433
- }
4434
- function printVersion() {
4435
- const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
4436
- console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
4437
- console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
4438
- console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
4439
- }
4440
-
4441
- // src/open.ts
4442
- import { spawn } from "child_process";
4443
-
4444
- // src/lifecycle.ts
4445
- var silentSigint = false;
4446
- function setSilentSigint(value) {
4447
- silentSigint = value;
4448
- }
4449
- function isSilentSigint() {
4450
- return silentSigint;
4451
- }
4452
-
4453
- // src/open.ts
4454
- function openUrl(url) {
4455
- try {
4456
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
4457
- child.unref();
4458
- child.on("error", () => {
4459
- });
4460
- return true;
4461
- } catch {
4462
- return false;
4463
- }
4464
- }
4465
- function openLogFile(logPath, label) {
4466
- const displayLabel = label || logPath;
4467
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
4468
- const success = openUrl(logPath);
4469
- if (!success) {
4470
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
4471
- }
4472
- }
4473
- function viewLogWithTail(logPath, options) {
4474
- const follow = options?.follow;
4475
- const lines = options?.lines || 100;
4476
- console.log(`\u65E5\u5FD7: ${logPath}`);
4477
- if (follow) {
4478
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
4479
- } else {
4480
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
4481
- `);
4482
- }
4483
- const tailArgs = [];
4484
- if (follow) tailArgs.push("-f");
4485
- tailArgs.push("-n", lines.toString());
4486
- tailArgs.push(logPath);
4487
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
4488
- if (follow) setSilentSigint(true);
4489
- tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
4490
- tail.on("error", (e) => {
4491
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
4492
- process.exit(1);
4493
- });
4494
- }
4495
-
4496
- // src/commands/shared.ts
4497
- import readline from "readline";
4402
+ // src/service.ts
4403
+ import { spawnSync as spawnSync4 } from "child_process";
4404
+ import fs8 from "fs";
4405
+ import path6 from "path";
4498
4406
 
4499
4407
  // src/log-files.ts
4500
4408
  import fs5 from "fs";
@@ -4711,9 +4619,6 @@ function getStatus() {
4711
4619
  };
4712
4620
  }
4713
4621
 
4714
- // src/process-start.ts
4715
- import fs8 from "fs";
4716
-
4717
4622
  // src/sudo.ts
4718
4623
  import { spawnSync as spawnSync3 } from "child_process";
4719
4624
  import fs7 from "fs";
@@ -4748,116 +4653,7 @@ function runSudoScript(scriptBody, opts) {
4748
4653
  }
4749
4654
  }
4750
4655
 
4751
- // src/process-start.ts
4752
- var TUN_MODE_POST_WAIT_MS = 500;
4753
- function buildTunLaunchScript() {
4754
- const binary = shellQuote(PATHS.mihomoBinary);
4755
- const configFile = shellQuote(PATHS.configFile);
4756
- const logFile = shellQuote(PATHS.logFile);
4757
- const pidFile = shellQuote(PATHS.pidFile);
4758
- const dataDir = shellQuote(DIRS.data);
4759
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
4760
- return `#!/bin/bash
4761
- BINARY=${binary}
4762
- CONFIG_FILE=${configFile}
4763
- LOG_FILE=${logFile}
4764
- PID_FILE=${pidFile}
4765
- DATA_DIR=${dataDir}
4766
- KILL_PATTERN=${killPattern}
4767
-
4768
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
4769
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
4770
- sleep 0.2
4771
- rm -f "\${PID_FILE}" 2>/dev/null || true
4772
-
4773
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
4774
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
4775
-
4776
- # \u542F\u52A8
4777
- cd /tmp
4778
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
4779
- NEW_PID=$!
4780
- echo \${NEW_PID} > "\${PID_FILE}"
4781
-
4782
- # \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
4783
- #\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
4784
- # 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
4785
- is_alive() {
4786
- local stat
4787
- stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
4788
- case "\${stat}" in
4789
- Z*|'') return 1 ;;
4790
- *) return 0 ;;
4791
- esac
4792
- }
4793
-
4794
- # \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
4795
- # \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
4796
- # \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
4797
- i=0
4798
- while [ $i -lt 12 ]; do
4799
- sleep 0.1
4800
- is_alive \${NEW_PID} || break
4801
- i=$((i+1))
4802
- done
4803
- if is_alive \${NEW_PID}; then
4804
- exit 0
4805
- fi
4806
-
4807
- # \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
4808
- rm -f "\${PID_FILE}" 2>/dev/null || true
4809
- echo "TUN \u542F\u52A8\u5931\u8D25"
4810
- echo ""
4811
- echo "--- \u65E5\u5FD7 ---"
4812
- tail -25 "\${LOG_FILE}" 2>/dev/null
4813
- exit 2
4814
- `;
4815
- }
4816
- async function startTun() {
4817
- ensureDirs();
4818
- rotateAndCleanupLogs();
4819
- if (!fs8.existsSync(PATHS.mihomoBinary)) {
4820
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4821
- }
4822
- if (!fs8.existsSync(PATHS.configFile)) {
4823
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4824
- }
4825
- const logFile = PATHS.logFile;
4826
- if (fs8.existsSync(logFile)) {
4827
- try {
4828
- fs8.accessSync(logFile, fs8.constants.W_OK);
4829
- } catch {
4830
- try {
4831
- fs8.unlinkSync(logFile);
4832
- } catch {
4833
- }
4834
- }
4835
- }
4836
- const staleState = checkStaleState();
4837
- if (staleState.needsCleanup) {
4838
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
4839
- }
4840
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
4841
- runSudoScript(buildTunLaunchScript(), {
4842
- action: "TUN \u542F\u52A8",
4843
- file: "launch-tun.sh",
4844
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
4845
- });
4846
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4847
- const finalPid = getPid();
4848
- if (!finalPid || !isRunning()) {
4849
- const tail = readLogTail();
4850
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
4851
- hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
4852
- });
4853
- }
4854
- return { success: true, pid: finalPid, mode: "tun" };
4855
- }
4856
-
4857
4656
  // src/service.ts
4858
- import { spawnSync as spawnSync4 } from "child_process";
4859
- import fs9 from "fs";
4860
- import path6 from "path";
4861
4657
  function assertServiceLabelSafe() {
4862
4658
  if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
4863
4659
  throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
@@ -4879,10 +4675,10 @@ function bootstrapDomain() {
4879
4675
  return `gui/${process.getuid?.() ?? 0}`;
4880
4676
  }
4881
4677
  function isServiceInstalled() {
4882
- return fs9.existsSync(PATHS.userAgentPlist);
4678
+ return fs8.existsSync(PATHS.userAgentPlist);
4883
4679
  }
4884
4680
  function detectLegacySystemInstall() {
4885
- return fs9.existsSync(PATHS.systemDaemonPlist);
4681
+ return fs8.existsSync(PATHS.systemDaemonPlist);
4886
4682
  }
4887
4683
  function parseServicePrint(output) {
4888
4684
  const stateMatch = output.match(/^\tstate = (.+)$/m);
@@ -4997,25 +4793,25 @@ ${argsXml}
4997
4793
  `;
4998
4794
  }
4999
4795
  function ensureServiceSymlink() {
5000
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
4796
+ if (!fs8.existsSync(PATHS.mihomoBinary)) {
5001
4797
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5002
4798
  }
5003
4799
  try {
5004
- const current = fs9.readlinkSync(PATHS.serviceBinary);
4800
+ const current = fs8.readlinkSync(PATHS.serviceBinary);
5005
4801
  if (current === "mihomo") return;
5006
- fs9.unlinkSync(PATHS.serviceBinary);
4802
+ fs8.unlinkSync(PATHS.serviceBinary);
5007
4803
  } catch (e) {
5008
4804
  const code = e.code;
5009
4805
  if (code === "EINVAL") {
5010
4806
  try {
5011
- fs9.unlinkSync(PATHS.serviceBinary);
4807
+ fs8.unlinkSync(PATHS.serviceBinary);
5012
4808
  } catch {
5013
4809
  }
5014
4810
  } else if (code !== "ENOENT") {
5015
4811
  throw e;
5016
4812
  }
5017
4813
  }
5018
- fs9.symlinkSync("mihomo", PATHS.serviceBinary);
4814
+ fs8.symlinkSync("mihomo", PATHS.serviceBinary);
5019
4815
  }
5020
4816
  function runLaunchctlOrThrow(args, what) {
5021
4817
  const result = runLaunchctl(args);
@@ -5094,16 +4890,16 @@ async function installService(wasRunning) {
5094
4890
  }
5095
4891
  await bootoutService();
5096
4892
  await waitUntilUnloaded();
5097
- fs9.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
5098
- fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5099
- fs9.chmodSync(PATHS.userAgentPlist, 420);
4893
+ fs8.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
4894
+ fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
4895
+ fs8.chmodSync(PATHS.userAgentPlist, 420);
5100
4896
  if (wasRunning) {
5101
4897
  runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5102
4898
  runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
5103
4899
  }
5104
4900
  } finally {
5105
4901
  try {
5106
- fs9.unlinkSync(stagePath);
4902
+ fs8.unlinkSync(stagePath);
5107
4903
  } catch {
5108
4904
  }
5109
4905
  }
@@ -5117,7 +4913,7 @@ async function startService() {
5117
4913
  if (!isServiceInstalled()) {
5118
4914
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5119
4915
  }
5120
- if (!fs9.existsSync(PATHS.configFile)) {
4916
+ if (!fs8.existsSync(PATHS.configFile)) {
5121
4917
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
5122
4918
  }
5123
4919
  if (getConfigInfo()?.tun) {
@@ -5159,14 +4955,14 @@ async function uninstallService() {
5159
4955
  await bootoutService();
5160
4956
  await waitUntilUnloaded();
5161
4957
  try {
5162
- fs9.rmSync(PATHS.userAgentPlist, { force: true });
4958
+ fs8.rmSync(PATHS.userAgentPlist, { force: true });
5163
4959
  } catch (e) {
5164
4960
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5165
4961
  }
5166
4962
  disableServiceAutoStart();
5167
4963
  killResidualKernels();
5168
4964
  try {
5169
- fs9.rmSync(PATHS.serviceBinary, { force: true });
4965
+ fs8.rmSync(PATHS.serviceBinary, { force: true });
5170
4966
  } catch {
5171
4967
  }
5172
4968
  }
@@ -5184,59 +4980,526 @@ function cleanupLegacySystemInstall() {
5184
4980
  ].join("\n");
5185
4981
  runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
5186
4982
  }
5187
- function logOversized() {
5188
- try {
5189
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5190
- } catch {
5191
- return false;
5192
- }
4983
+ function logOversized() {
4984
+ try {
4985
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4986
+ } catch {
4987
+ return false;
4988
+ }
4989
+ }
4990
+ async function tryHotReload() {
4991
+ const status = getServiceStatus();
4992
+ if (!status.running || status.pid === null) return false;
4993
+ const controller = new AbortController();
4994
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
4995
+ const secret = readSettings().controller_secret;
4996
+ const headers = { "Content-Type": "application/json" };
4997
+ if (secret) headers.Authorization = `Bearer ${secret}`;
4998
+ try {
4999
+ const probe = await fetch(`${CONTROLLER_BASE_URL}/version`, { headers, signal: controller.signal });
5000
+ if (!probe.ok) return false;
5001
+ const info = await probe.json();
5002
+ if (typeof info?.version !== "string") return false;
5003
+ const res = await fetch(`${CONTROLLER_BASE_URL}/configs?force=true`, {
5004
+ method: "PUT",
5005
+ headers,
5006
+ body: "{}",
5007
+ signal: controller.signal
5008
+ });
5009
+ return res.status === 204 || res.ok;
5010
+ } catch {
5011
+ return false;
5012
+ } finally {
5013
+ clearTimeout(timer);
5014
+ }
5015
+ }
5016
+ async function restartService() {
5017
+ if (!isServiceInstalled()) {
5018
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5019
+ }
5020
+ if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
5021
+ if (logOversized()) {
5022
+ const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
5023
+ try {
5024
+ fs8.copyFileSync(PATHS.logFile, archiveFile);
5025
+ fs8.writeFileSync(PATHS.logFile, "");
5026
+ } catch {
5027
+ }
5028
+ }
5029
+ const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5030
+ if (kick.status !== 0) {
5031
+ runLaunchctl(["enable", serviceTarget()]);
5032
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
5033
+ }
5034
+ cleanupOldLogs();
5035
+ return { hotReloaded: false };
5036
+ }
5037
+
5038
+ // src/commands/help.ts
5039
+ function printShortHelp() {
5040
+ console.log(`
5041
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5042
+ `);
5043
+ const steps = [];
5044
+ if (!hasKernel()) steps.push(["mihomo kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5045
+ if (getSubscriptions().length === 0) steps.push(["mihomo sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5046
+ if (!getServiceStatus().installed) steps.push(["mihomo install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5047
+ if (steps.length > 0) {
5048
+ steps.push(["mihomo start", "\u542F\u52A8\u4EE3\u7406"]);
5049
+ const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
5050
+ console.log("\u5F00\u59CB\u4F7F\u7528:");
5051
+ steps.forEach(([cmd, desc], i) => {
5052
+ console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
5053
+ });
5054
+ console.log("");
5055
+ return;
5056
+ }
5057
+ console.log(
5058
+ `\u5E38\u7528\u547D\u4EE4:
5059
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
5060
+ ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
5061
+ ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
5062
+ ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
5063
+ `
5064
+ );
5065
+ }
5066
+ var GROUP_TITLES = [
5067
+ ["control", "\u63A7\u5236:"],
5068
+ ["interface", "\u754C\u9762:"],
5069
+ ["subscription", "\u8BA2\u9605:"],
5070
+ ["config", "\u914D\u7F6E:"],
5071
+ ["system", "\u7CFB\u7EDF:"]
5072
+ ];
5073
+ function printHelp(commands) {
5074
+ const lines = [`
5075
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
5076
+ const allUsage = commands.flatMap((c) => c.usage);
5077
+ const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5078
+ const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
5079
+ for (const [group, title] of GROUP_TITLES) {
5080
+ const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
5081
+ if (usageLines.length === 0) continue;
5082
+ lines.push("", colors.cyan(title));
5083
+ for (const u of usageLines) lines.push(formatUsage(u));
5084
+ }
5085
+ const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
5086
+ if (meta.length > 0) {
5087
+ lines.push("", colors.cyan("\u5143:"));
5088
+ for (const u of meta) lines.push(formatUsage(u));
5089
+ }
5090
+ lines.push(
5091
+ "",
5092
+ `${colors.cyan("\u793A\u4F8B:")}`,
5093
+ " mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5094
+ " mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5095
+ " mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5096
+ " mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5097
+ " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5098
+ " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5099
+ " mihomo ui # \u6253\u5F00 Web UI",
5100
+ "",
5101
+ `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
5102
+ " tun = start tun",
5103
+ "",
5104
+ `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
5105
+ " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
5106
+ " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
5107
+ "",
5108
+ `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
5109
+ " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
5110
+ ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
5111
+ );
5112
+ console.log(lines.join("\n"));
5113
+ }
5114
+ function printVersion() {
5115
+ const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5116
+ console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
5117
+ console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
5118
+ console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5119
+ }
5120
+
5121
+ // src/commands/completion.ts
5122
+ var COMMAND_WORDS = [
5123
+ { word: "install", desc: "\u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09" },
5124
+ { word: "start", desc: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F" },
5125
+ { word: "stop", desc: "\u505C\u6B62\u4EE3\u7406\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F" },
5126
+ { word: "uninstall", desc: "\u5378\u8F7D\u670D\u52A1" },
5127
+ { word: "status", desc: "\u67E5\u770B\u72B6\u6001\uFF08--json \u673A\u5668\u53EF\u8BFB\uFF09" },
5128
+ { word: "logs", desc: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B" },
5129
+ { word: "ui", desc: "\u6253\u5F00 Web UI" },
5130
+ { word: "subscription", desc: "\u8BA2\u9605\u7BA1\u7406" },
5131
+ { word: "overwrite", desc: "\u8986\u5199\u914D\u7F6E" },
5132
+ { word: "directory", desc: "\u6570\u636E\u76EE\u5F55" },
5133
+ { word: "kernel", desc: "\u66F4\u65B0\u5185\u6838" },
5134
+ { word: "update", desc: "\u66F4\u65B0 mihomo-cli" },
5135
+ { word: "reset", desc: "\u91CD\u7F6E\u7528\u6237\u6570\u636E" },
5136
+ { word: "doctor", desc: "\u4F53\u68C0\u8BCA\u65AD" },
5137
+ { word: "completion", desc: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C" },
5138
+ { word: "use", desc: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF09" },
5139
+ { word: "tun", desc: "\u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08= start tun\uFF09" },
5140
+ { word: "help", desc: "\u663E\u793A\u5E2E\u52A9" },
5141
+ { word: "version", desc: "\u663E\u793A\u7248\u672C" }
5142
+ ];
5143
+ var SUBCOMMANDS = {
5144
+ subscription: [
5145
+ { word: "use", desc: "\u5207\u6362\u8BA2\u9605" },
5146
+ { word: "add", desc: "\u6DFB\u52A0\u8BA2\u9605" },
5147
+ { word: "update", desc: "\u66F4\u65B0\u8BA2\u9605" },
5148
+ { word: "remove", desc: "\u5220\u9664\u8BA2\u9605" },
5149
+ { word: "rm", desc: "\u5220\u9664\u8BA2\u9605" },
5150
+ { word: "delete", desc: "\u5220\u9664\u8BA2\u9605" }
5151
+ ],
5152
+ overwrite: [
5153
+ { word: "on", desc: "\u542F\u7528\u8986\u5199" },
5154
+ { word: "off", desc: "\u7981\u7528\u8986\u5199" },
5155
+ { word: "enable", desc: "\u542F\u7528\u8986\u5199" },
5156
+ { word: "disable", desc: "\u7981\u7528\u8986\u5199" }
5157
+ ],
5158
+ directory: [{ word: "open", desc: "\u6253\u5F00\u76EE\u5F55" }]
5159
+ };
5160
+ var DIR_TARGETS = ["root", "subs", "logs", "data", "runtime", "kernel"];
5161
+ var UI_NAMES = ["zash", "dash", "yacd"];
5162
+ var SHELLS = ["zsh", "bash", "fish"];
5163
+ function buildZsh() {
5164
+ const lines = [
5165
+ "#compdef mihomo mhm mh mihomo-cli",
5166
+ "",
5167
+ '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: \u5199\u5165 ~/.zsh/completions/_mihomo \u6216 eval "$(mihomo completion zsh)"\uFF09',
5168
+ "",
5169
+ "_mihomo() {",
5170
+ " local -a commands subcmds",
5171
+ " commands=(",
5172
+ ...COMMAND_WORDS.map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
5173
+ " )",
5174
+ "",
5175
+ " _arguments -C \\",
5176
+ " '1: :->cmd' \\",
5177
+ " '*::arg:->args'",
5178
+ "",
5179
+ " case $state in",
5180
+ " cmd)",
5181
+ " _describe 'command' commands",
5182
+ " ;;",
5183
+ " args)",
5184
+ " case ${words[1]} in"
5185
+ ];
5186
+ for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
5187
+ const aliases = group === "subscription" ? "subscription|sub|subs|subscriptions" : group === "overwrite" ? "overwrite|ow" : "directory|dir|dirs|directories";
5188
+ lines.push(` ${aliases})`);
5189
+ lines.push(" subcmds=(");
5190
+ for (const s of subs) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
5191
+ lines.push(" )");
5192
+ lines.push(" if (( CURRENT == 2 )); then");
5193
+ lines.push(" _describe 'subcommand' subcmds");
5194
+ lines.push(" else");
5195
+ lines.push(" _files");
5196
+ lines.push(" fi");
5197
+ lines.push(" ;;");
5198
+ }
5199
+ lines.push(
5200
+ " directory|dir|dirs|directories)",
5201
+ " if (( CURRENT == 3 )); then",
5202
+ ` _values 'target' ${DIR_TARGETS.join(" ")}`,
5203
+ " fi",
5204
+ " ;;",
5205
+ " logs)",
5206
+ " _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:'",
5207
+ " ;;",
5208
+ " ui)",
5209
+ ` _values 'ui' ${UI_NAMES.join(" ")}`,
5210
+ " ;;",
5211
+ " kernel)",
5212
+ " _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:' '--no-mirror[\u76F4\u8FDE\u4E0B\u8F7D]'",
5213
+ " ;;",
5214
+ " reset)",
5215
+ ` _values 'target' subs logs data runtime settings kernel overwrites service`,
5216
+ " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
5217
+ " ;;",
5218
+ " completion)",
5219
+ ` _values 'shell' ${SHELLS.join(" ")}`,
5220
+ " ;;",
5221
+ " *)",
5222
+ " _files",
5223
+ " ;;",
5224
+ " esac",
5225
+ " ;;",
5226
+ " esac",
5227
+ "}",
5228
+ "",
5229
+ '_mihomo "$@"'
5230
+ );
5231
+ return lines.join("\n");
5232
+ }
5233
+ function buildBash() {
5234
+ const top = COMMAND_WORDS.map((c) => c.word).join(" ");
5235
+ return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
5236
+
5237
+ _mihomo_completions() {
5238
+ local cur prev
5239
+ COMPREPLY=()
5240
+ cur="\${COMP_WORDS[COMP_CWORD]}"
5241
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
5242
+
5243
+ if [[ \${COMP_CWORD} -eq 1 ]]; then
5244
+ COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
5245
+ return 0
5246
+ fi
5247
+
5248
+ case "\${COMP_WORDS[1]}" in
5249
+ subscription|sub|subs|subscriptions)
5250
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
5251
+ COMPREPLY=( $(compgen -W "use add update remove rm delete" -- "\${cur}") )
5252
+ fi
5253
+ ;;
5254
+ overwrite|ow)
5255
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
5256
+ COMPREPLY=( $(compgen -W "on off enable disable" -- "\${cur}") )
5257
+ fi
5258
+ ;;
5259
+ directory|dir|dirs|directories)
5260
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
5261
+ COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
5262
+ elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
5263
+ COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
5264
+ fi
5265
+ ;;
5266
+ logs)
5267
+ COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
5268
+ ;;
5269
+ ui)
5270
+ COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
5271
+ ;;
5272
+ kernel)
5273
+ COMPREPLY=( $(compgen -W "--mirror --no-mirror" -- "\${cur}") )
5274
+ ;;
5275
+ reset)
5276
+ COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
5277
+ ;;
5278
+ completion)
5279
+ COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
5280
+ ;;
5281
+ esac
5282
+ }
5283
+ complete -F _mihomo_completions mihomo mhm mh mihomo-cli
5284
+ `;
5285
+ }
5286
+ function buildFish() {
5287
+ const lines = [
5288
+ "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
5289
+ "",
5290
+ "for cmd in mihomo mhm mh mihomo-cli"
5291
+ ];
5292
+ for (const c of COMMAND_WORDS) {
5293
+ lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
5294
+ }
5295
+ const subAliases = {
5296
+ subscription: "subscription sub subs subscriptions",
5297
+ overwrite: "overwrite ow",
5298
+ directory: "directory dir dirs directories"
5299
+ };
5300
+ for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
5301
+ for (const s of subs) {
5302
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${subAliases[group]}" -a '${s.word}' -d '${s.desc}'`);
5303
+ }
5304
+ }
5305
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
5306
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
5307
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
5308
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
5309
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
5310
+ lines.push("end");
5311
+ return lines.join("\n");
5312
+ }
5313
+ function buildCompletionScript(shell) {
5314
+ switch (shell) {
5315
+ case "zsh":
5316
+ return buildZsh();
5317
+ case "bash":
5318
+ return buildBash();
5319
+ case "fish":
5320
+ return buildFish();
5321
+ default: {
5322
+ const suggestion = suggestSimilar(shell, [...SHELLS]);
5323
+ throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
5324
+ label: "\u53C2\u6570\u9519\u8BEF",
5325
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
5326
+ });
5327
+ }
5328
+ }
5329
+ }
5330
+ function cmdCompletion(args) {
5331
+ const shell = args[1];
5332
+ if (!shell) {
5333
+ throw new CliError("\u8BF7\u6307\u5B9A shell", {
5334
+ hint: [`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`, '\u5B89\u88C5: eval "$(mihomo completion zsh)"\uFF0C\u6216\u5199\u5165\u5BF9\u5E94 shell \u7684\u8865\u5168\u76EE\u5F55']
5335
+ });
5336
+ }
5337
+ console.log(buildCompletionScript(shell));
5338
+ }
5339
+
5340
+ // src/open.ts
5341
+ import { spawn } from "child_process";
5342
+
5343
+ // src/lifecycle.ts
5344
+ var silentSigint = false;
5345
+ function setSilentSigint(value) {
5346
+ silentSigint = value;
5347
+ }
5348
+ function isSilentSigint() {
5349
+ return silentSigint;
5350
+ }
5351
+
5352
+ // src/open.ts
5353
+ function openUrl(url) {
5354
+ try {
5355
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5356
+ child.unref();
5357
+ child.on("error", () => {
5358
+ });
5359
+ return true;
5360
+ } catch {
5361
+ return false;
5362
+ }
5363
+ }
5364
+ function openLogFile(logPath, label) {
5365
+ const displayLabel = label || logPath;
5366
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
5367
+ const success = openUrl(logPath);
5368
+ if (!success) {
5369
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
5370
+ }
5371
+ }
5372
+ function viewLogWithTail(logPath, options) {
5373
+ const follow = options?.follow;
5374
+ const lines = options?.lines || 100;
5375
+ console.log(`\u65E5\u5FD7: ${logPath}`);
5376
+ if (follow) {
5377
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5378
+ } else {
5379
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5380
+ `);
5381
+ }
5382
+ const tailArgs = [];
5383
+ if (follow) tailArgs.push("-f");
5384
+ tailArgs.push("-n", lines.toString());
5385
+ tailArgs.push(logPath);
5386
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5387
+ if (follow) setSilentSigint(true);
5388
+ tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
5389
+ tail.on("error", (e) => {
5390
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5391
+ process.exit(1);
5392
+ });
5393
+ }
5394
+
5395
+ // src/commands/shared.ts
5396
+ import readline from "readline";
5397
+
5398
+ // src/process-start.ts
5399
+ import fs9 from "fs";
5400
+ var TUN_MODE_POST_WAIT_MS = 500;
5401
+ function buildTunLaunchScript() {
5402
+ const binary = shellQuote(PATHS.mihomoBinary);
5403
+ const configFile = shellQuote(PATHS.configFile);
5404
+ const logFile = shellQuote(PATHS.logFile);
5405
+ const pidFile = shellQuote(PATHS.pidFile);
5406
+ const dataDir = shellQuote(DIRS.data);
5407
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5408
+ return `#!/bin/bash
5409
+ BINARY=${binary}
5410
+ CONFIG_FILE=${configFile}
5411
+ LOG_FILE=${logFile}
5412
+ PID_FILE=${pidFile}
5413
+ DATA_DIR=${dataDir}
5414
+ KILL_PATTERN=${killPattern}
5415
+
5416
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5417
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5418
+ sleep 0.2
5419
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5420
+
5421
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5422
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5423
+
5424
+ # \u542F\u52A8
5425
+ cd /tmp
5426
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5427
+ NEW_PID=$!
5428
+ echo \${NEW_PID} > "\${PID_FILE}"
5429
+
5430
+ # \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
5431
+ #\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
5432
+ # 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
5433
+ is_alive() {
5434
+ local stat
5435
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
5436
+ case "\${stat}" in
5437
+ Z*|'') return 1 ;;
5438
+ *) return 0 ;;
5439
+ esac
5440
+ }
5441
+
5442
+ # \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
5443
+ # \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
5444
+ # \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
5445
+ i=0
5446
+ while [ $i -lt 12 ]; do
5447
+ sleep 0.1
5448
+ is_alive \${NEW_PID} || break
5449
+ i=$((i+1))
5450
+ done
5451
+ if is_alive \${NEW_PID}; then
5452
+ exit 0
5453
+ fi
5454
+
5455
+ # \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
5456
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5457
+ echo "TUN \u542F\u52A8\u5931\u8D25"
5458
+ echo ""
5459
+ echo "--- \u65E5\u5FD7 ---"
5460
+ tail -25 "\${LOG_FILE}" 2>/dev/null
5461
+ exit 2
5462
+ `;
5193
5463
  }
5194
- async function tryHotReload() {
5195
- const status = getServiceStatus();
5196
- if (!status.running || status.pid === null) return false;
5197
- const controller = new AbortController();
5198
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5199
- const secret = readSettings().controller_secret;
5200
- const headers = { "Content-Type": "application/json" };
5201
- if (secret) headers.Authorization = `Bearer ${secret}`;
5202
- try {
5203
- const probe = await fetch(`${CONTROLLER_BASE_URL}/version`, { headers, signal: controller.signal });
5204
- if (!probe.ok) return false;
5205
- const info = await probe.json();
5206
- if (typeof info?.version !== "string") return false;
5207
- const res = await fetch(`${CONTROLLER_BASE_URL}/configs?force=true`, {
5208
- method: "PUT",
5209
- headers,
5210
- body: "{}",
5211
- signal: controller.signal
5212
- });
5213
- return res.status === 204 || res.ok;
5214
- } catch {
5215
- return false;
5216
- } finally {
5217
- clearTimeout(timer);
5464
+ async function startTun() {
5465
+ ensureDirs();
5466
+ rotateAndCleanupLogs();
5467
+ if (!fs9.existsSync(PATHS.mihomoBinary)) {
5468
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5218
5469
  }
5219
- }
5220
- async function restartService() {
5221
- if (!isServiceInstalled()) {
5222
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5470
+ if (!fs9.existsSync(PATHS.configFile)) {
5471
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5223
5472
  }
5224
- if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
5225
- if (logOversized()) {
5226
- const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
5473
+ const logFile = PATHS.logFile;
5474
+ if (fs9.existsSync(logFile)) {
5227
5475
  try {
5228
- fs9.copyFileSync(PATHS.logFile, archiveFile);
5229
- fs9.writeFileSync(PATHS.logFile, "");
5476
+ fs9.accessSync(logFile, fs9.constants.W_OK);
5230
5477
  } catch {
5478
+ try {
5479
+ fs9.unlinkSync(logFile);
5480
+ } catch {
5481
+ }
5231
5482
  }
5232
5483
  }
5233
- const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5234
- if (kick.status !== 0) {
5235
- runLaunchctl(["enable", serviceTarget()]);
5236
- runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
5484
+ const staleState = checkStaleState();
5485
+ if (staleState.needsCleanup) {
5486
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5237
5487
  }
5238
- cleanupOldLogs();
5239
- return { hotReloaded: false };
5488
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5489
+ runSudoScript(buildTunLaunchScript(), {
5490
+ action: "TUN \u542F\u52A8",
5491
+ file: "launch-tun.sh",
5492
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5493
+ });
5494
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5495
+ const finalPid = getPid();
5496
+ if (!finalPid || !isRunning()) {
5497
+ const tail = readLogTail();
5498
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
5499
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
5500
+ });
5501
+ }
5502
+ return { success: true, pid: finalPid, mode: "tun" };
5240
5503
  }
5241
5504
 
5242
5505
  // src/runtime.ts
@@ -5350,6 +5613,31 @@ async function readBodyWithLimit(response, controller, limit) {
5350
5613
  return Buffer.concat(chunks).toString("utf8");
5351
5614
  }
5352
5615
 
5616
+ // src/spinner.ts
5617
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
5618
+ var INTERVAL_MS = 80;
5619
+ async function withSpinner(label, fn) {
5620
+ if (!process.stdout.isTTY) {
5621
+ console.log(label);
5622
+ return fn();
5623
+ }
5624
+ const start = Date.now();
5625
+ let frame = 0;
5626
+ const render = () => {
5627
+ const secs = ((Date.now() - start) / 1e3).toFixed(0);
5628
+ process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
5629
+ frame = (frame + 1) % FRAMES.length;
5630
+ };
5631
+ render();
5632
+ const timer = setInterval(render, INTERVAL_MS);
5633
+ try {
5634
+ return await fn();
5635
+ } finally {
5636
+ clearInterval(timer);
5637
+ process.stdout.write("\r\x1B[K");
5638
+ }
5639
+ }
5640
+
5353
5641
  // src/subscription.ts
5354
5642
  function isGithubUrl(url) {
5355
5643
  return /github\.com|raw\.githubusercontent\.com/i.test(url);
@@ -5606,7 +5894,7 @@ async function autoUpdateStaleSubscription(options = {}) {
5606
5894
  )
5607
5895
  );
5608
5896
  try {
5609
- await withTimeout(updatePromise, timeoutMs);
5897
+ await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
5610
5898
  } catch (e) {
5611
5899
  if (!(e instanceof TimeoutError)) throw e;
5612
5900
  controller.abort();
@@ -5622,15 +5910,147 @@ async function autoUpdateStaleSubscription(options = {}) {
5622
5910
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5623
5911
  }
5624
5912
 
5913
+ // src/proxy-probe.ts
5914
+ import { execFile } from "child_process";
5915
+ import { promisify } from "util";
5916
+ var execFileAsync = promisify(execFile);
5917
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
5918
+ function isProbeSuccessStatus(code) {
5919
+ return code !== null && code >= 200 && code < 300;
5920
+ }
5921
+ async function probeProxyConnectivity(port, timeoutMs = 5e3) {
5922
+ const start = Date.now();
5923
+ try {
5924
+ const { stdout } = await execFileAsync(
5925
+ "curl",
5926
+ [
5927
+ "-x",
5928
+ `http://127.0.0.1:${port}`,
5929
+ "-s",
5930
+ "-o",
5931
+ "/dev/null",
5932
+ "-w",
5933
+ "%{http_code}",
5934
+ "--connect-timeout",
5935
+ "3",
5936
+ "--max-time",
5937
+ String(Math.ceil(timeoutMs / 1e3)),
5938
+ PROBE_URL
5939
+ ],
5940
+ { timeout: timeoutMs + 2e3 }
5941
+ );
5942
+ const code = Number.parseInt(stdout.trim(), 10);
5943
+ const statusCode = Number.isFinite(code) ? code : null;
5944
+ const ok = isProbeSuccessStatus(statusCode);
5945
+ return {
5946
+ ok,
5947
+ statusCode,
5948
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
5949
+ durationMs: Date.now() - start
5950
+ };
5951
+ } catch (e) {
5952
+ const err = e;
5953
+ const stderr = err.stderr?.toString().trim();
5954
+ const lastLine = stderr ? stderr.split("\n").pop() : void 0;
5955
+ const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5956
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5957
+ }
5958
+ }
5959
+
5625
5960
  // src/commands/status.ts
5626
- async function printStatus() {
5961
+ function connectivityHint(urgency) {
5962
+ if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
5963
+ if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
5964
+ return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
5965
+ }
5966
+ function trafficColor(line, urgency, total, upload, download) {
5967
+ if (urgency === "traffic-exhausted") return colors.red(line);
5968
+ if (total && total > 0) {
5969
+ const used = (upload || 0) + (download || 0);
5970
+ if (used / total >= 0.9) return colors.yellow(line);
5971
+ }
5972
+ return line;
5973
+ }
5974
+ function expireColor(line, urgency) {
5975
+ if (urgency === "expired") return colors.red(line);
5976
+ if (urgency === "expiring") return colors.yellow(line);
5977
+ return line;
5978
+ }
5979
+ function buildStatusJson(args) {
5980
+ const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
5981
+ return {
5982
+ version: VERSION,
5983
+ running: args.running,
5984
+ connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
5985
+ mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
5986
+ carrier: args.kind,
5987
+ pid: args.pid,
5988
+ kernel: getKernelVersion(),
5989
+ kernelInstalled: hasKernel(),
5990
+ ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
5991
+ ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {},
5992
+ ...args.info.httpPort ? { http: args.info.httpPort } : {},
5993
+ ...args.info.socksPort ? { socks: args.info.socksPort } : {}
5994
+ } : {},
5995
+ subscription: args.activeSub ? {
5996
+ name: args.activeSub.name,
5997
+ proxies: args.info?.proxies ?? 0,
5998
+ proxyGroups: args.info?.proxyGroups ?? 0,
5999
+ ...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
6000
+ ...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
6001
+ ...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
6002
+ ...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
6003
+ urgency
6004
+ } : null,
6005
+ overwrite: { enabled: args.overwriteEnabled, files: args.overwriteFiles },
6006
+ service: {
6007
+ installed: args.service.installed,
6008
+ loaded: args.service.loaded,
6009
+ running: args.service.running,
6010
+ disabled: args.service.disabled,
6011
+ lastExitCode: args.service.lastExitCode,
6012
+ legacySystemInstall: args.legacy
6013
+ }
6014
+ };
6015
+ }
6016
+ async function printStatus(args = []) {
6017
+ const asJson = hasFlag(args, "-j", "--json");
5627
6018
  const state = getRunningState();
5628
6019
  const service = getServiceStatus();
5629
6020
  const info = getConfigInfo();
5630
6021
  const overwriteEnabled = isOverwriteEnabled();
5631
6022
  const overwriteFiles = listOverwriteFile().files;
5632
6023
  const activeSub = getActiveSubscription();
5633
- const { running, pid, kind, processInfo } = state;
6024
+ const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6025
+ const legacy = detectLegacySystemInstall();
6026
+ const { running, pid, kind } = state;
6027
+ let probe = null;
6028
+ if (running && info?.mixedPort) {
6029
+ probe = await probeProxyConnectivity(info.mixedPort);
6030
+ }
6031
+ if (asJson) {
6032
+ console.log(
6033
+ JSON.stringify(
6034
+ buildStatusJson({
6035
+ running,
6036
+ kind,
6037
+ pid,
6038
+ probe,
6039
+ info,
6040
+ activeSub,
6041
+ cached,
6042
+ overwriteEnabled,
6043
+ overwriteFiles: overwriteFiles.map((f) => f.name),
6044
+ service,
6045
+ legacy
6046
+ }),
6047
+ null,
6048
+ 2
6049
+ )
6050
+ );
6051
+ return;
6052
+ }
6053
+ const urgency = cached ? subscriptionUrgency(cached) : null;
5634
6054
  console.log("");
5635
6055
  let modeLabel = "";
5636
6056
  if (info) {
@@ -5638,17 +6058,30 @@ async function printStatus() {
5638
6058
  const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
5639
6059
  modeLabel = colors.cyan(` (${mode}${carrier})`);
5640
6060
  }
5641
- const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
6061
+ let statusText;
6062
+ if (!running) {
6063
+ statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
6064
+ } else if (probe && !probe.ok) {
6065
+ statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
6066
+ } else {
6067
+ statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
6068
+ }
5642
6069
  console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
6070
+ if (running && probe && !probe.ok) {
6071
+ console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
6072
+ }
5643
6073
  if (!running && service.installed && !service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
5644
6074
  console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
5645
6075
  console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
5646
6076
  }
5647
- console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
6077
+ const kernelVersion = getKernelVersion();
6078
+ console.log(
6079
+ kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
6080
+ );
5648
6081
  if (pid) {
5649
6082
  console.log(`${colors.gray("PID: ")}${pid}`);
5650
- if (kind === "tun" && processInfo) {
5651
- console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
6083
+ if (kind === "tun" && state.processInfo) {
6084
+ console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
5652
6085
  }
5653
6086
  }
5654
6087
  if (info) {
@@ -5670,16 +6103,15 @@ async function printStatus() {
5670
6103
  subLine += ` (${formatProxySummary(info)})`;
5671
6104
  }
5672
6105
  console.log(subLine);
5673
- const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
5674
6106
  const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
5675
6107
  if (traffic) {
5676
- console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
6108
+ console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
5677
6109
  }
5678
6110
  if (cached?.expire !== void 0) {
5679
- console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
6111
+ console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
5680
6112
  }
5681
6113
  } else {
5682
- console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E`);
6114
+ console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
5683
6115
  }
5684
6116
  if (overwriteEnabled && overwriteFiles.length > 0) {
5685
6117
  const names = overwriteFiles.map((f) => f.name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6").join(", ");
@@ -5689,11 +6121,10 @@ async function printStatus() {
5689
6121
  } else {
5690
6122
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
5691
6123
  }
5692
- printServiceLines(service);
6124
+ printServiceLines(service, legacy);
5693
6125
  console.log("");
5694
6126
  }
5695
- function printServiceLines(service) {
5696
- const legacy = detectLegacySystemInstall();
6127
+ function printServiceLines(service, legacy) {
5697
6128
  if (!service.installed && !service.loaded) {
5698
6129
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
5699
6130
  } else if (!service.installed) {
@@ -5877,12 +6308,12 @@ function printDirectoryInfo() {
5877
6308
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
5878
6309
  console.log("");
5879
6310
  }
5880
- var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
6311
+ var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
5881
6312
  async function cmdDirectory(args) {
5882
- await dispatchSubcommand(args, SUBCOMMANDS, {
6313
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
5883
6314
  fallback: printDirectoryInfo,
5884
6315
  onUnknown: (action) => {
5885
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6316
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
5886
6317
  const suggestion = suggestSimilar(action, names);
5887
6318
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
5888
6319
  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>"]
@@ -5891,9 +6322,188 @@ async function cmdDirectory(args) {
5891
6322
  });
5892
6323
  }
5893
6324
 
5894
- // src/kernel.ts
6325
+ // src/commands/doctor.ts
5895
6326
  import { spawnSync as spawnSync5 } from "child_process";
5896
6327
  import fs10 from "fs";
6328
+ function isPortListening(port) {
6329
+ try {
6330
+ const r = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
6331
+ return r.status === 0 && (r.stdout || "").trim().length > 0;
6332
+ } catch {
6333
+ return false;
6334
+ }
6335
+ }
6336
+ function collectChecks() {
6337
+ const checks = [];
6338
+ const push = (name, status, detail, fix) => {
6339
+ checks.push({ name, status, detail, fix });
6340
+ };
6341
+ if (!hasKernel()) {
6342
+ push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
6343
+ } else {
6344
+ const v = getKernelVersion();
6345
+ const r = spawnSync5(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
6346
+ if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
6347
+ push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
6348
+ } else {
6349
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
6350
+ }
6351
+ }
6352
+ try {
6353
+ fs10.accessSync(USER_DATA_DIR, fs10.constants.W_OK);
6354
+ push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
6355
+ } catch {
6356
+ push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
6357
+ }
6358
+ if (fs10.existsSync(PATHS.settingsFile)) {
6359
+ try {
6360
+ const parsed = JSON.parse(fs10.readFileSync(PATHS.settingsFile, "utf8"));
6361
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
6362
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
6363
+ } else {
6364
+ push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6365
+ }
6366
+ } catch {
6367
+ push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "JSON \u635F\u574F\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6368
+ }
6369
+ } else {
6370
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
6371
+ }
6372
+ const subs = getSubscriptionsWithCache();
6373
+ const active = getActiveSubscription();
6374
+ if (subs.length === 0) {
6375
+ push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
6376
+ } else {
6377
+ push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
6378
+ if (active) {
6379
+ if (!readSubscriptionRawConfig(active.name)) {
6380
+ 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}`);
6381
+ } else {
6382
+ push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
6383
+ }
6384
+ const cached = subs.find((s) => s.name === active.name);
6385
+ if (cached?.updated_at) {
6386
+ const rel = formatRelativeTime(cached.updated_at);
6387
+ const intervalH = resolveUpdateInterval(cached.url, cached.update_interval);
6388
+ const ageH = (Date.now() - new Date(cached.updated_at).getTime()) / 36e5;
6389
+ if (ageH > intervalH) {
6390
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${intervalH} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
6391
+ } else {
6392
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
6393
+ }
6394
+ }
6395
+ }
6396
+ }
6397
+ const service = getServiceStatus();
6398
+ const legacy = detectLegacySystemInstall();
6399
+ if (legacy) {
6400
+ 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");
6401
+ } else if (!service.installed && !service.loaded) {
6402
+ push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
6403
+ } else if (!service.installed) {
6404
+ push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
6405
+ } else if (service.running) {
6406
+ const exitNote = service.lastExitCode !== null && service.lastExitCode !== 0 ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${service.lastExitCode}\uFF09` : "";
6407
+ push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${exitNote}`);
6408
+ if (service.lastExitCode !== null && service.lastExitCode !== 0) {
6409
+ push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6410
+ }
6411
+ } else {
6412
+ push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
6413
+ }
6414
+ const state = getRunningState();
6415
+ const info = getConfigInfo();
6416
+ const mixedPort = info?.mixedPort ?? 7890;
6417
+ if (state.running) {
6418
+ if (isPortListening(mixedPort)) {
6419
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
6420
+ } else {
6421
+ push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6422
+ }
6423
+ } else if (isPortListening(mixedPort)) {
6424
+ 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`);
6425
+ } else {
6426
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
6427
+ }
6428
+ if (active) {
6429
+ try {
6430
+ const mode = info?.tun ? "tun" : "mixed";
6431
+ prepareConfigForStart(mode, active.name);
6432
+ push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u53EF\u6B63\u5E38\u6784\u5EFA\uFF08${mode}\uFF09`);
6433
+ } catch (e) {
6434
+ push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start");
6435
+ }
6436
+ } else {
6437
+ push("\u914D\u7F6E\u6784\u5EFA", "warn", "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
6438
+ }
6439
+ if (state.running && info?.mixedPort) {
6440
+ const probe = probeProxyConnectivitySyncShim(info.mixedPort);
6441
+ if (probe.ok) {
6442
+ push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
6443
+ } else {
6444
+ push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
6445
+ }
6446
+ } else {
6447
+ push("\u4EE3\u7406\u8FDE\u901A", "ok", "\u672A\u8FD0\u884C\uFF0C\u8DF3\u8FC7");
6448
+ }
6449
+ return checks;
6450
+ }
6451
+ function probeProxyConnectivitySyncShim(port) {
6452
+ const start = Date.now();
6453
+ try {
6454
+ const r = spawnSync5(
6455
+ "curl",
6456
+ [
6457
+ "-x",
6458
+ `http://127.0.0.1:${port}`,
6459
+ "-s",
6460
+ "-o",
6461
+ "/dev/null",
6462
+ "-w",
6463
+ "%{http_code}",
6464
+ "--connect-timeout",
6465
+ "3",
6466
+ "--max-time",
6467
+ "5",
6468
+ "https://www.gstatic.com/generate_204"
6469
+ ],
6470
+ { encoding: "utf8", timeout: 8e3 }
6471
+ );
6472
+ const code = Number.parseInt((r.stdout || "").trim(), 10);
6473
+ const statusCode = Number.isFinite(code) ? code : null;
6474
+ const ok = statusCode !== null && statusCode >= 200 && statusCode < 300;
6475
+ return { ok, statusCode, error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`, durationMs: Date.now() - start };
6476
+ } catch (e) {
6477
+ return { ok: false, statusCode: null, error: e.message, durationMs: Date.now() - start };
6478
+ }
6479
+ }
6480
+ async function cmdDoctor() {
6481
+ const checks = collectChecks();
6482
+ console.log("");
6483
+ for (const c of checks) {
6484
+ const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : colors.red("\u2717");
6485
+ console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
6486
+ if (c.status !== "ok" && c.fix) {
6487
+ console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
6488
+ }
6489
+ }
6490
+ const ok = checks.filter((c) => c.status === "ok").length;
6491
+ const warn = checks.filter((c) => c.status === "warn").length;
6492
+ const fail = checks.filter((c) => c.status === "fail").length;
6493
+ console.log("");
6494
+ console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38`);
6495
+ console.log("");
6496
+ if (fail > 0) {
6497
+ throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
6498
+ label: "\u4F53\u68C0\u672A\u901A\u8FC7",
6499
+ hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
6500
+ });
6501
+ }
6502
+ }
6503
+
6504
+ // src/kernel.ts
6505
+ import { spawnSync as spawnSync6 } from "child_process";
6506
+ import fs11 from "fs";
5897
6507
  import path7 from "path";
5898
6508
 
5899
6509
  // node_modules/compare-versions/lib/esm/utils.js
@@ -6032,10 +6642,10 @@ async function checkUpdate() {
6032
6642
  }
6033
6643
  function findBinaryInDir(dir, maxDepth = 4) {
6034
6644
  if (maxDepth <= 0) return null;
6035
- const files = fs10.readdirSync(dir);
6645
+ const files = fs11.readdirSync(dir);
6036
6646
  for (const f of files) {
6037
6647
  const fullPath = path7.join(dir, f);
6038
- const stat = fs10.lstatSync(fullPath);
6648
+ const stat = fs11.lstatSync(fullPath);
6039
6649
  if (stat.isDirectory()) {
6040
6650
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6041
6651
  if (found) return found;
@@ -6072,7 +6682,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6072
6682
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
6073
6683
  }
6074
6684
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
6075
- const curlResult = spawnSync5(
6685
+ const curlResult = spawnSync6(
6076
6686
  "curl",
6077
6687
  [
6078
6688
  "-L",
@@ -6101,19 +6711,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6101
6711
  }
6102
6712
  if (curlResult.status !== 0) {
6103
6713
  try {
6104
- fs10.unlinkSync(tempPath);
6714
+ fs11.unlinkSync(tempPath);
6105
6715
  } catch {
6106
6716
  }
6107
6717
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6108
6718
  }
6109
- if (!fs10.existsSync(tempPath)) {
6719
+ if (!fs11.existsSync(tempPath)) {
6110
6720
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6111
6721
  }
6112
6722
  if (Number.isFinite(asset.size) && asset.size > 0) {
6113
- const actual = fs10.statSync(tempPath).size;
6723
+ const actual = fs11.statSync(tempPath).size;
6114
6724
  if (actual !== asset.size) {
6115
6725
  try {
6116
- fs10.unlinkSync(tempPath);
6726
+ fs11.unlinkSync(tempPath);
6117
6727
  } catch {
6118
6728
  }
6119
6729
  throw new Error(
@@ -6129,7 +6739,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6129
6739
  let extractedBinary = null;
6130
6740
  try {
6131
6741
  if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
6132
- const listResult = spawnSync5("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6742
+ const listResult = spawnSync6("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6133
6743
  if (listResult.error) throw listResult.error;
6134
6744
  if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
6135
6745
  for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6137,7 +6747,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6137
6747
  throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
6138
6748
  }
6139
6749
  }
6140
- const typeResult = spawnSync5("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6750
+ const typeResult = spawnSync6("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6141
6751
  if (typeResult.error) throw typeResult.error;
6142
6752
  if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
6143
6753
  for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6146,7 +6756,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6146
6756
  throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
6147
6757
  }
6148
6758
  }
6149
- const tarResult = spawnSync5("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6759
+ const tarResult = spawnSync6("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6150
6760
  stdio: ["ignore", "ignore", "inherit"],
6151
6761
  timeout: 6e4
6152
6762
  });
@@ -6155,15 +6765,15 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6155
6765
  } else if (tempPath.endsWith(".gz")) {
6156
6766
  const baseName = path7.basename(tempPath, ".gz");
6157
6767
  const outputPath = path7.join(extractPath, baseName);
6158
- const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6768
+ const gzipResult = spawnSync6("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6159
6769
  if (gzipResult.error) throw gzipResult.error;
6160
6770
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6161
- fs10.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6771
+ fs11.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6162
6772
  extractedBinary = outputPath;
6163
6773
  }
6164
6774
  } catch (e) {
6165
6775
  try {
6166
- fs10.unlinkSync(tempPath);
6776
+ fs11.unlinkSync(tempPath);
6167
6777
  } catch {
6168
6778
  }
6169
6779
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6171,35 +6781,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6171
6781
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6172
6782
  if (!foundBinary) {
6173
6783
  try {
6174
- fs10.unlinkSync(tempPath);
6784
+ fs11.unlinkSync(tempPath);
6175
6785
  } catch {
6176
6786
  }
6177
6787
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6178
6788
  }
6179
6789
  const targetPath = PATHS.mihomoBinary;
6180
6790
  if (foundBinary !== targetPath) {
6181
- if (fs10.existsSync(targetPath)) {
6182
- fs10.chmodSync(targetPath, 493);
6791
+ if (fs11.existsSync(targetPath)) {
6792
+ fs11.chmodSync(targetPath, 493);
6183
6793
  try {
6184
- fs10.unlinkSync(targetPath);
6794
+ fs11.unlinkSync(targetPath);
6185
6795
  } catch {
6186
6796
  }
6187
6797
  }
6188
- fs10.renameSync(foundBinary, targetPath);
6798
+ fs11.renameSync(foundBinary, targetPath);
6189
6799
  }
6190
- fs10.chmodSync(targetPath, 493);
6800
+ fs11.chmodSync(targetPath, 493);
6191
6801
  if (progressCallback) {
6192
6802
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6193
6803
  }
6194
- const check = spawnSync5(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6804
+ const check = spawnSync6(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6195
6805
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6196
6806
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6197
6807
  try {
6198
- fs10.unlinkSync(targetPath);
6808
+ fs11.unlinkSync(targetPath);
6199
6809
  } catch {
6200
6810
  }
6201
6811
  try {
6202
- fs10.unlinkSync(tempPath);
6812
+ fs11.unlinkSync(tempPath);
6203
6813
  } catch {
6204
6814
  }
6205
6815
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
@@ -6207,7 +6817,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6207
6817
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6208
6818
  }
6209
6819
  try {
6210
- fs10.unlinkSync(tempPath);
6820
+ fs11.unlinkSync(tempPath);
6211
6821
  } catch {
6212
6822
  }
6213
6823
  clearKernelVersionCache();
@@ -6234,28 +6844,23 @@ function assertKnownKernelFlags(args) {
6234
6844
  }
6235
6845
  async function cmdKernel(args) {
6236
6846
  assertKnownKernelFlags(args);
6237
- const mirrorInfo = parseMirrorArg(args);
6847
+ const savedMirror = readSettings().kernel_mirror ?? null;
6848
+ const mirrorInfo = parseMirrorArg(args, savedMirror);
6238
6849
  const effectiveMirror = mirrorInfo.mirror;
6850
+ if (mirrorInfo.remember) {
6851
+ writeSettings({ kernel_mirror: mirrorInfo.mirror ?? void 0 });
6852
+ } else if (mirrorInfo.clearSaved && savedMirror) {
6853
+ writeSettings({ kernel_mirror: void 0 });
6854
+ }
6239
6855
  if (effectiveMirror) {
6240
- console.log(`\u955C\u50CF: ${effectiveMirror} (\u4EC5\u4E0B\u8F7D\u8D70\u955C\u50CF\uFF0C\u7248\u672C\u67E5\u8BE2\u6052\u76F4\u8FDE)`);
6856
+ const host = effectiveMirror.replace(/^https?:\/\//, "").replace(/\/$/, "");
6857
+ const note = mirrorInfo.remember ? "\u5DF2\u8BB0\u4F4F\u504F\u597D\uFF0C\u540E\u7EED\u9ED8\u8BA4\u8D70\u955C\u50CF\uFF08--no-mirror \u76F4\u8FDE\u5E76\u6E05\u9664\u504F\u597D\uFF09" : !mirrorInfo.isOverride ? "\u5DF2\u8BB0\u4F4F\u7684\u504F\u597D\uFF08--no-mirror \u76F4\u8FDE\u5E76\u6E05\u9664\u504F\u597D\uFF09" : "\u4EC5\u4E0B\u8F7D\u8D70\u955C\u50CF\uFF0C\u7248\u672C\u67E5\u8BE2\u6052\u76F4\u8FDE";
6858
+ console.log(`\u955C\u50CF: ${host} (${note})`);
6241
6859
  console.log("");
6242
6860
  }
6243
- console.log("\u68C0\u67E5\u5185\u6838\u66F4\u65B0...");
6861
+ let info;
6244
6862
  try {
6245
- const info = await checkUpdate();
6246
- console.log(`\u5F53\u524D: ${info.current}`);
6247
- console.log(`\u6700\u65B0: ${info.latest}`);
6248
- if (!info.needsUpdate) {
6249
- console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
6250
- } else {
6251
- console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
6252
- const result = await downloadKernel((msg) => console.log(msg), mirrorInfo.mirror, info.release);
6253
- console.log(`
6254
- \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
6255
- if (getRunningState().running) {
6256
- 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"));
6257
- }
6258
- }
6863
+ info = await withSpinner("\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09", () => checkUpdate());
6259
6864
  } catch (e) {
6260
6865
  if (e instanceof CliError) throw e;
6261
6866
  const err = e;
@@ -6270,12 +6875,25 @@ async function cmdKernel(args) {
6270
6875
  hint.push(
6271
6876
  "",
6272
6877
  "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
6273
- " mihomo kernel --mirror [\u955C\u50CF] # \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09",
6878
+ " mihomo kernel --mirror [\u955C\u50CF] # \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09\uFF0C\u4E00\u6B21\u4F7F\u7528\u540E\u8BB0\u4F4F\u504F\u597D",
6274
6879
  ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
6275
6880
  );
6276
6881
  }
6277
6882
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
6278
6883
  }
6884
+ console.log(`\u5F53\u524D: ${info.current}`);
6885
+ console.log(`\u6700\u65B0: ${info.latest}`);
6886
+ if (!info.needsUpdate) {
6887
+ console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
6888
+ } else {
6889
+ console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
6890
+ const result = await downloadKernel((msg) => console.log(msg), mirrorInfo.mirror, info.release);
6891
+ console.log(`
6892
+ \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
6893
+ if (getRunningState().running) {
6894
+ 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"));
6895
+ }
6896
+ }
6279
6897
  }
6280
6898
 
6281
6899
  // src/commands/log.ts
@@ -6392,19 +7010,19 @@ async function setOverwrite(enabled, args) {
6392
7010
  console.log("");
6393
7011
  printOverwriteList();
6394
7012
  }
6395
- var SUBCOMMANDS2 = [
7013
+ var SUBCOMMANDS3 = [
6396
7014
  { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
6397
7015
  { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
6398
7016
  ];
6399
7017
  async function cmdOverwrite(args) {
6400
- await dispatchSubcommand(args, SUBCOMMANDS2, {
7018
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
6401
7019
  // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6402
7020
  fallback: () => {
6403
7021
  console.log("");
6404
7022
  printOverwriteList();
6405
7023
  },
6406
7024
  onUnknown: (action) => {
6407
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
7025
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6408
7026
  const suggestion = suggestSimilar(action, names);
6409
7027
  throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6410
7028
  hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
@@ -6421,30 +7039,30 @@ function removedCommand(name, version, hint) {
6421
7039
  }
6422
7040
 
6423
7041
  // src/commands/reset.ts
6424
- import fs12 from "fs";
7042
+ import fs13 from "fs";
6425
7043
 
6426
7044
  // src/process-stop.ts
6427
- import { spawnSync as spawnSync6 } from "child_process";
6428
- import fs11 from "fs";
7045
+ import { spawnSync as spawnSync7 } from "child_process";
7046
+ import fs12 from "fs";
6429
7047
  var PROCESS_WAIT_ATTEMPTS = 50;
6430
7048
  var PROCESS_WAIT_INTERVAL = 100;
6431
7049
  var BATCH_KILL_THRESHOLD = 3;
6432
7050
  function clearRuntime() {
6433
- if (fs11.existsSync(DIRS.runtime)) {
7051
+ if (fs12.existsSync(DIRS.runtime)) {
6434
7052
  rmrf(DIRS.runtime);
6435
7053
  }
6436
7054
  ensureDirs();
6437
7055
  }
6438
7056
  function clearPid() {
6439
- if (!fs11.existsSync(PATHS.pidFile)) return;
7057
+ if (!fs12.existsSync(PATHS.pidFile)) return;
6440
7058
  if (isPidFileOwnedByRoot()) {
6441
7059
  try {
6442
- spawnSync6("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
7060
+ spawnSync7("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
6443
7061
  } catch {
6444
7062
  }
6445
7063
  } else {
6446
7064
  try {
6447
- fs11.unlinkSync(PATHS.pidFile);
7065
+ fs12.unlinkSync(PATHS.pidFile);
6448
7066
  } catch {
6449
7067
  }
6450
7068
  }
@@ -6462,7 +7080,7 @@ function killAllMihomo(forceSudo = false) {
6462
7080
  const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
6463
7081
  const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
6464
7082
  try {
6465
- const result = spawnSync6(argv[0], argv[1], options);
7083
+ const result = spawnSync7(argv[0], argv[1], options);
6466
7084
  if (result.error) return false;
6467
7085
  return result.status === 0 || result.status === 1;
6468
7086
  } catch {
@@ -6591,8 +7209,8 @@ var RESET_TARGETS = [
6591
7209
  label: "\u8986\u5199",
6592
7210
  paths: () => {
6593
7211
  const dir = USER_DATA_DIR;
6594
- if (!fs12.existsSync(dir)) return [];
6595
- return fs12.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7212
+ if (!fs13.existsSync(dir)) return [];
7213
+ return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6596
7214
  },
6597
7215
  needsStop: false
6598
7216
  },
@@ -6733,7 +7351,7 @@ async function cmdReset(args) {
6733
7351
  }
6734
7352
  for (const t of targets) {
6735
7353
  for (const p of t.paths()) {
6736
- if (fs12.existsSync(p)) {
7354
+ if (fs13.existsSync(p)) {
6737
7355
  try {
6738
7356
  rmrf(p);
6739
7357
  } catch (e) {
@@ -6751,7 +7369,7 @@ async function cmdReset(args) {
6751
7369
  }
6752
7370
 
6753
7371
  // src/commands/service.ts
6754
- import fs13 from "fs";
7372
+ import fs14 from "fs";
6755
7373
  async function handleLegacyInstall() {
6756
7374
  if (!detectLegacySystemInstall()) return;
6757
7375
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -6786,7 +7404,7 @@ async function cmdInstall(_args) {
6786
7404
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
6787
7405
  } else {
6788
7406
  console.log("\u542F\u52A8: mihomo start");
6789
- if (!fs13.existsSync(PATHS.configFile)) {
7407
+ if (!fs14.existsSync(PATHS.configFile)) {
6790
7408
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
6791
7409
  }
6792
7410
  }
@@ -6881,7 +7499,8 @@ function printSubscriptionList() {
6881
7499
  const activeSub = getActiveSubscription();
6882
7500
  console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
6883
7501
  subs.forEach((s, i) => {
6884
- const time = formatDate(s.updated_at);
7502
+ const rel = formatRelativeTime(s.updated_at);
7503
+ const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
6885
7504
  const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
6886
7505
  const interval = resolveUpdateInterval(s.url, s.update_interval);
6887
7506
  console.log(` ${i + 1}. ${s.name}${defaultMark}`);
@@ -6928,7 +7547,7 @@ async function subAdd(args) {
6928
7547
  console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
6929
7548
  addSubscription(url, name);
6930
7549
  try {
6931
- const info = await downloadSubscription(url, name);
7550
+ const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
6932
7551
  setDefaultSubscription(name);
6933
7552
  console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
6934
7553
  } catch (e) {
@@ -6947,7 +7566,7 @@ async function subUpdate(args) {
6947
7566
  }
6948
7567
  if (!name) {
6949
7568
  console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
6950
- const results = await Promise.all(subs.map((sub) => tryUpdateOne(sub)));
7569
+ const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
6951
7570
  let ok = 0;
6952
7571
  for (const r of results) {
6953
7572
  if (r.success) ok++;
@@ -6961,7 +7580,7 @@ async function subUpdate(args) {
6961
7580
  }
6962
7581
  const target = resolveSubscription(subs, name);
6963
7582
  console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
6964
- const result = await tryUpdateOne(target);
7583
+ const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
6965
7584
  if (!result.success) {
6966
7585
  throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
6967
7586
  }
@@ -6973,9 +7592,12 @@ async function subUpdate(args) {
6973
7592
  async function subUse(args) {
6974
7593
  const name = args[2];
6975
7594
  const subs = getSubscriptions();
7595
+ if (subs.length === 0) {
7596
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
7597
+ }
6976
7598
  if (!name) {
6977
7599
  throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
6978
- hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
7600
+ hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
6979
7601
  });
6980
7602
  }
6981
7603
  const target = resolveSubscription(subs, name);
@@ -7025,18 +7647,18 @@ async function subRemove(args) {
7025
7647
  console.log("");
7026
7648
  printSubscriptionList();
7027
7649
  }
7028
- var SUBCOMMANDS3 = [
7650
+ var SUBCOMMANDS4 = [
7029
7651
  { name: "add", handler: subAdd },
7030
7652
  { name: "update", handler: subUpdate },
7031
7653
  { name: "use", handler: subUse },
7032
7654
  { name: "remove", aliases: ["rm", "delete"], handler: subRemove }
7033
7655
  ];
7034
7656
  async function cmdSubscription(args) {
7035
- await dispatchSubcommand(args, SUBCOMMANDS3, {
7657
+ await dispatchSubcommand(args, SUBCOMMANDS4, {
7036
7658
  // 无子命令 → 列表;未知子命令 → 报错
7037
7659
  fallback: printSubscriptionList,
7038
7660
  onUnknown: (action) => {
7039
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7661
+ const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7040
7662
  const suggestion = suggestSimilar(action, names);
7041
7663
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7042
7664
  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"]
@@ -7046,6 +7668,14 @@ async function cmdSubscription(args) {
7046
7668
  }
7047
7669
 
7048
7670
  // src/commands/ui.ts
7671
+ import { spawnSync as spawnSync8 } from "child_process";
7672
+ function copyToClipboard(text) {
7673
+ try {
7674
+ return spawnSync8("pbcopy", [], { input: text }).status === 0;
7675
+ } catch {
7676
+ return false;
7677
+ }
7678
+ }
7049
7679
  function cmdUI(args) {
7050
7680
  const uiName = args[1] || "zash";
7051
7681
  if (!Object.hasOwn(UI_URLS, uiName)) {
@@ -7060,7 +7690,9 @@ function cmdUI(args) {
7060
7690
  console.log(`\u5730\u5740: ${url}`);
7061
7691
  const secret = readSettings().controller_secret;
7062
7692
  if (secret) {
7063
- console.log("\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08UI \u8FDE\u63A5 127.0.0.1:9090 \u65F6\u9700\u8F93\u5165\uFF0C\u5BC6\u94A5\u89C1 settings.json\uFF09");
7693
+ console.log(
7694
+ 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:9090 \u65F6\u9700\u8F93\u5165\uFF0C\u5BC6\u94A5\u89C1 settings.json\uFF09"
7695
+ );
7064
7696
  }
7065
7697
  const success = openUrl(url);
7066
7698
  if (!success) {
@@ -7069,13 +7701,13 @@ function cmdUI(args) {
7069
7701
  }
7070
7702
 
7071
7703
  // src/commands/update.ts
7072
- import { execFile, spawn as spawn2 } from "child_process";
7073
- import { promisify } from "util";
7074
- var execFileAsync = promisify(execFile);
7704
+ import { execFile as execFile2, spawn as spawn2 } from "child_process";
7705
+ import { promisify as promisify2 } from "util";
7706
+ var execFileAsync2 = promisify2(execFile2);
7075
7707
  var NPM_VIEW_TIMEOUT_MS = 15e3;
7076
7708
  async function getLatestNpmVersion() {
7077
7709
  try {
7078
- const { stdout } = await execFileAsync("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
7710
+ const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
7079
7711
  const version = stdout.trim().split("\n").pop()?.trim();
7080
7712
  return version || null;
7081
7713
  } catch {
@@ -7085,8 +7717,7 @@ async function getLatestNpmVersion() {
7085
7717
  async function cmdUpdate() {
7086
7718
  console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7087
7719
  console.log("");
7088
- console.log("\u6B63\u5728\u68C0\u67E5\u6700\u65B0\u7248\u672C...");
7089
- const latest = await getLatestNpmVersion();
7720
+ const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7090
7721
  if (latest && latest === VERSION) {
7091
7722
  console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7092
7723
  return;
@@ -7114,7 +7745,7 @@ async function cmdUpdate() {
7114
7745
  });
7115
7746
  });
7116
7747
  try {
7117
- const { stdout } = await execFileAsync("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7748
+ const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7118
7749
  const result = JSON.parse(stdout);
7119
7750
  const newVersion = result.dependencies?.[PKG_NAME]?.version;
7120
7751
  console.log("");
@@ -7141,10 +7772,10 @@ var COMMANDS = [
7141
7772
  },
7142
7773
  {
7143
7774
  name: "start",
7144
- aliases: [],
7775
+ aliases: ["restart"],
7145
7776
  handler: cmdStart,
7146
7777
  group: "control",
7147
- usage: [{ signature: "start [tun|mixed] [-s] [-u ms]", description: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F\uFF08\u9ED8\u8BA4 mixed\uFF09" }]
7778
+ usage: [{ signature: "start [tun|mixed] [-s] [-u ms]", description: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F\uFF08\u9ED8\u8BA4 mixed\uFF1B= \u91CD\u542F\uFF09" }]
7148
7779
  },
7149
7780
  {
7150
7781
  name: "tun",
@@ -7229,6 +7860,15 @@ var COMMANDS = [
7229
7860
  usage: [{ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]", description: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF0C-f \u8DDF\u968F\uFF1B\u7701\u7565\u7F16\u53F7\u5373\u5F53\u524D\uFF09" }]
7230
7861
  },
7231
7862
  // === 订阅 ===
7863
+ {
7864
+ // 顶层快捷方式:`mihomo use <name>` = `mihomo subscription use <name>`(与 tun 同范式)
7865
+ name: "use",
7866
+ aliases: [],
7867
+ handler: cmdSubscription,
7868
+ rewrite: (args) => ["subscription", "use", ...args.slice(1)],
7869
+ group: "subscription",
7870
+ usage: [{ signature: "use <name>", description: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF0C\u81EA\u52A8\u91CD\u542F\uFF09" }]
7871
+ },
7232
7872
  {
7233
7873
  name: "subscription",
7234
7874
  aliases: ["sub", "subs", "subscriptions"],
@@ -7285,6 +7925,20 @@ var COMMANDS = [
7285
7925
  group: "system",
7286
7926
  usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
7287
7927
  },
7928
+ {
7929
+ name: "doctor",
7930
+ aliases: [],
7931
+ handler: cmdDoctor,
7932
+ group: "system",
7933
+ usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
7934
+ },
7935
+ {
7936
+ name: "completion",
7937
+ aliases: [],
7938
+ handler: cmdCompletion,
7939
+ group: "system",
7940
+ usage: [{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C\uFF08eval \u6216\u5199\u5165\u8865\u5168\u76EE\u5F55\uFF09" }]
7941
+ },
7288
7942
  // === meta(不在分组清单展示,help 末尾单列) ===
7289
7943
  {
7290
7944
  name: "help",