mihomo-cli 4.2.4 → 4.4.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
@@ -3110,7 +3110,6 @@ var BASE_CONFIG = {
3110
3110
  }
3111
3111
  };
3112
3112
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
3113
- var DEFAULT_UPDATE_INTERVAL_HOURS_GITHUB = 6;
3114
3113
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
3115
3114
 
3116
3115
  // src/errors.ts
@@ -3327,6 +3326,14 @@ function recoverCorruptedSettings() {
3327
3326
  settingsCache = {};
3328
3327
  return settingsCache;
3329
3328
  }
3329
+ function isValidSettingsContent(content) {
3330
+ try {
3331
+ const parsed = JSON.parse(content);
3332
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
3333
+ } catch {
3334
+ return false;
3335
+ }
3336
+ }
3330
3337
  function writeSettings(settings) {
3331
3338
  ensureDirs();
3332
3339
  return withFileLock(PATHS.settingsFile, () => writeSettingsUnlocked(settings));
@@ -3858,6 +3865,35 @@ function formatDate(dateOrIso) {
3858
3865
  return "\u672A\u77E5";
3859
3866
  }
3860
3867
  }
3868
+ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
3869
+ if (dateOrIso === void 0 || dateOrIso === null) return null;
3870
+ let t;
3871
+ try {
3872
+ const d = dateOrIso instanceof Date ? dateOrIso : new Date(dateOrIso);
3873
+ t = d.getTime();
3874
+ } catch {
3875
+ return null;
3876
+ }
3877
+ if (Number.isNaN(t) || t > nowMs) return null;
3878
+ const sec = Math.floor((nowMs - t) / 1e3);
3879
+ if (sec < 60) return "\u521A\u521A";
3880
+ const min = Math.floor(sec / 60);
3881
+ if (min < 60) return `${min} \u5206\u949F\u524D`;
3882
+ const hour = Math.floor(min / 60);
3883
+ if (hour < 24) return `${hour} \u5C0F\u65F6\u524D`;
3884
+ const day = Math.floor(hour / 24);
3885
+ if (day < 30) return `${day} \u5929\u524D`;
3886
+ const month = Math.floor(day / 30);
3887
+ if (month < 12) return `${month} \u4E2A\u6708\u524D`;
3888
+ return `${Math.floor(month / 12)} \u5E74\u524D`;
3889
+ }
3890
+ function subscriptionUrgency(entry, nowMs = Date.now()) {
3891
+ if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 < nowMs) return "expired";
3892
+ const used = (entry.upload || 0) + (entry.download || 0);
3893
+ if (entry.total !== void 0 && entry.total > 0 && used >= entry.total) return "traffic-exhausted";
3894
+ if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 - nowMs < 7 * 864e5) return "expiring";
3895
+ return null;
3896
+ }
3861
3897
  function hasFlag(args, short, long) {
3862
3898
  return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
3863
3899
  }
@@ -3975,9 +4011,9 @@ function normalizeMirrorUrl(val) {
3975
4011
  const url = parsed.toString();
3976
4012
  return url.endsWith("/") ? url : `${url}/`;
3977
4013
  }
3978
- function parseMirrorArg(args) {
4014
+ function parseMirrorArg(args, savedMirror) {
3979
4015
  if (!args || args.length < 2) {
3980
- return { mirror: null, isOverride: false };
4016
+ return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
3981
4017
  }
3982
4018
  if (args.some((a) => a === "--mirror-all" || a.startsWith("--mirror-all="))) {
3983
4019
  throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
@@ -3991,7 +4027,7 @@ function parseMirrorArg(args) {
3991
4027
  });
3992
4028
  }
3993
4029
  if (args.includes("--no-mirror") || args.includes("--direct")) {
3994
- return { mirror: null, isOverride: true };
4030
+ return { mirror: null, isOverride: true, clearSaved: true };
3995
4031
  }
3996
4032
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
3997
4033
  const mirrorIdx = args.indexOf("--mirror");
@@ -3999,11 +4035,12 @@ function parseMirrorArg(args) {
3999
4035
  const inline = mirrorEq?.slice("--mirror=".length);
4000
4036
  const nextArg = inline ?? args[mirrorIdx + 1];
4001
4037
  if (!nextArg || nextArg.startsWith("-")) {
4002
- return { mirror: DEFAULT_MIRROR, isOverride: true };
4038
+ return { mirror: DEFAULT_MIRROR, isOverride: true, remember: true };
4003
4039
  }
4004
- return { mirror: normalizeMirrorUrl(nextArg), isOverride: true };
4040
+ const normalized = normalizeMirrorUrl(nextArg);
4041
+ return normalized ? { mirror: normalized, isOverride: true, remember: true } : { mirror: null, isOverride: true, clearSaved: true };
4005
4042
  }
4006
- return { mirror: null, isOverride: false };
4043
+ return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
4007
4044
  }
4008
4045
 
4009
4046
  // src/config.ts
@@ -4369,132 +4406,10 @@ function clearKernelVersionCache() {
4369
4406
  kernelVersionCached = false;
4370
4407
  }
4371
4408
 
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";
4409
+ // src/service.ts
4410
+ import { spawnSync as spawnSync4 } from "child_process";
4411
+ import fs8 from "fs";
4412
+ import path6 from "path";
4498
4413
 
4499
4414
  // src/log-files.ts
4500
4415
  import fs5 from "fs";
@@ -4711,9 +4626,6 @@ function getStatus() {
4711
4626
  };
4712
4627
  }
4713
4628
 
4714
- // src/process-start.ts
4715
- import fs8 from "fs";
4716
-
4717
4629
  // src/sudo.ts
4718
4630
  import { spawnSync as spawnSync3 } from "child_process";
4719
4631
  import fs7 from "fs";
@@ -4748,116 +4660,7 @@ function runSudoScript(scriptBody, opts) {
4748
4660
  }
4749
4661
  }
4750
4662
 
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
4663
  // src/service.ts
4858
- import { spawnSync as spawnSync4 } from "child_process";
4859
- import fs9 from "fs";
4860
- import path6 from "path";
4861
4664
  function assertServiceLabelSafe() {
4862
4665
  if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
4863
4666
  throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
@@ -4879,10 +4682,10 @@ function bootstrapDomain() {
4879
4682
  return `gui/${process.getuid?.() ?? 0}`;
4880
4683
  }
4881
4684
  function isServiceInstalled() {
4882
- return fs9.existsSync(PATHS.userAgentPlist);
4685
+ return fs8.existsSync(PATHS.userAgentPlist);
4883
4686
  }
4884
4687
  function detectLegacySystemInstall() {
4885
- return fs9.existsSync(PATHS.systemDaemonPlist);
4688
+ return fs8.existsSync(PATHS.systemDaemonPlist);
4886
4689
  }
4887
4690
  function parseServicePrint(output) {
4888
4691
  const stateMatch = output.match(/^\tstate = (.+)$/m);
@@ -4997,25 +4800,25 @@ ${argsXml}
4997
4800
  `;
4998
4801
  }
4999
4802
  function ensureServiceSymlink() {
5000
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
4803
+ if (!fs8.existsSync(PATHS.mihomoBinary)) {
5001
4804
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5002
4805
  }
5003
4806
  try {
5004
- const current = fs9.readlinkSync(PATHS.serviceBinary);
4807
+ const current = fs8.readlinkSync(PATHS.serviceBinary);
5005
4808
  if (current === "mihomo") return;
5006
- fs9.unlinkSync(PATHS.serviceBinary);
4809
+ fs8.unlinkSync(PATHS.serviceBinary);
5007
4810
  } catch (e) {
5008
4811
  const code = e.code;
5009
4812
  if (code === "EINVAL") {
5010
4813
  try {
5011
- fs9.unlinkSync(PATHS.serviceBinary);
4814
+ fs8.unlinkSync(PATHS.serviceBinary);
5012
4815
  } catch {
5013
4816
  }
5014
4817
  } else if (code !== "ENOENT") {
5015
4818
  throw e;
5016
4819
  }
5017
4820
  }
5018
- fs9.symlinkSync("mihomo", PATHS.serviceBinary);
4821
+ fs8.symlinkSync("mihomo", PATHS.serviceBinary);
5019
4822
  }
5020
4823
  function runLaunchctlOrThrow(args, what) {
5021
4824
  const result = runLaunchctl(args);
@@ -5094,16 +4897,16 @@ async function installService(wasRunning) {
5094
4897
  }
5095
4898
  await bootoutService();
5096
4899
  await waitUntilUnloaded();
5097
- fs9.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
5098
- fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5099
- fs9.chmodSync(PATHS.userAgentPlist, 420);
4900
+ fs8.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
4901
+ fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
4902
+ fs8.chmodSync(PATHS.userAgentPlist, 420);
5100
4903
  if (wasRunning) {
5101
4904
  runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5102
4905
  runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
5103
4906
  }
5104
4907
  } finally {
5105
4908
  try {
5106
- fs9.unlinkSync(stagePath);
4909
+ fs8.unlinkSync(stagePath);
5107
4910
  } catch {
5108
4911
  }
5109
4912
  }
@@ -5117,7 +4920,7 @@ async function startService() {
5117
4920
  if (!isServiceInstalled()) {
5118
4921
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5119
4922
  }
5120
- if (!fs9.existsSync(PATHS.configFile)) {
4923
+ if (!fs8.existsSync(PATHS.configFile)) {
5121
4924
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
5122
4925
  }
5123
4926
  if (getConfigInfo()?.tun) {
@@ -5159,14 +4962,14 @@ async function uninstallService() {
5159
4962
  await bootoutService();
5160
4963
  await waitUntilUnloaded();
5161
4964
  try {
5162
- fs9.rmSync(PATHS.userAgentPlist, { force: true });
4965
+ fs8.rmSync(PATHS.userAgentPlist, { force: true });
5163
4966
  } catch (e) {
5164
4967
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5165
4968
  }
5166
4969
  disableServiceAutoStart();
5167
4970
  killResidualKernels();
5168
4971
  try {
5169
- fs9.rmSync(PATHS.serviceBinary, { force: true });
4972
+ fs8.rmSync(PATHS.serviceBinary, { force: true });
5170
4973
  } catch {
5171
4974
  }
5172
4975
  }
@@ -5186,7 +4989,7 @@ function cleanupLegacySystemInstall() {
5186
4989
  }
5187
4990
  function logOversized() {
5188
4991
  try {
5189
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4992
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5190
4993
  } catch {
5191
4994
  return false;
5192
4995
  }
@@ -5225,8 +5028,8 @@ async function restartService() {
5225
5028
  if (logOversized()) {
5226
5029
  const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
5227
5030
  try {
5228
- fs9.copyFileSync(PATHS.logFile, archiveFile);
5229
- fs9.writeFileSync(PATHS.logFile, "");
5031
+ fs8.copyFileSync(PATHS.logFile, archiveFile);
5032
+ fs8.writeFileSync(PATHS.logFile, "");
5230
5033
  } catch {
5231
5034
  }
5232
5035
  }
@@ -5239,13 +5042,261 @@ async function restartService() {
5239
5042
  return { hotReloaded: false };
5240
5043
  }
5241
5044
 
5242
- // src/runtime.ts
5045
+ // src/commands/help.ts
5046
+ function printShortHelp() {
5047
+ console.log(`
5048
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5049
+ `);
5050
+ const steps = [];
5051
+ if (!hasKernel()) steps.push(["mihomo kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5052
+ if (getSubscriptions().length === 0) steps.push(["mihomo sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5053
+ if (!getServiceStatus().installed) steps.push(["mihomo install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5054
+ if (steps.length > 0) {
5055
+ steps.push(["mihomo start", "\u542F\u52A8\u4EE3\u7406"]);
5056
+ const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
5057
+ console.log("\u5F00\u59CB\u4F7F\u7528:");
5058
+ steps.forEach(([cmd, desc], i) => {
5059
+ console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
5060
+ });
5061
+ console.log("");
5062
+ return;
5063
+ }
5064
+ console.log(
5065
+ `\u5E38\u7528\u547D\u4EE4:
5066
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
5067
+ ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
5068
+ ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
5069
+ ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
5070
+ `
5071
+ );
5072
+ }
5073
+ var GROUP_TITLES = [
5074
+ ["control", "\u63A7\u5236:"],
5075
+ ["interface", "\u754C\u9762:"],
5076
+ ["subscription", "\u8BA2\u9605:"],
5077
+ ["config", "\u914D\u7F6E:"],
5078
+ ["system", "\u7CFB\u7EDF:"]
5079
+ ];
5080
+ function printHelp(commands) {
5081
+ const lines = [`
5082
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
5083
+ const allUsage = commands.flatMap((c) => c.usage);
5084
+ const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5085
+ const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
5086
+ for (const [group, title] of GROUP_TITLES) {
5087
+ const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
5088
+ if (usageLines.length === 0) continue;
5089
+ lines.push("", colors.cyan(title));
5090
+ for (const u of usageLines) lines.push(formatUsage(u));
5091
+ }
5092
+ const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
5093
+ if (meta.length > 0) {
5094
+ lines.push("", colors.cyan("\u5143:"));
5095
+ for (const u of meta) lines.push(formatUsage(u));
5096
+ }
5097
+ lines.push(
5098
+ "",
5099
+ `${colors.cyan("\u793A\u4F8B:")}`,
5100
+ " mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5101
+ " mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5102
+ " mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5103
+ " mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5104
+ " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5105
+ " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5106
+ " mihomo ui # \u6253\u5F00 Web UI",
5107
+ "",
5108
+ `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
5109
+ " tun = start tun",
5110
+ "",
5111
+ `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
5112
+ " 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",
5113
+ " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
5114
+ "",
5115
+ `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
5116
+ " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
5117
+ ` \u9ED8\u8BA4: ${USER_DATA_DIR}`
5118
+ );
5119
+ console.log(lines.join("\n"));
5120
+ }
5121
+ function printVersion() {
5122
+ const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5123
+ console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
5124
+ console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
5125
+ console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5126
+ }
5127
+
5128
+ // src/open.ts
5129
+ import { spawn } from "child_process";
5130
+
5131
+ // src/lifecycle.ts
5132
+ var silentSigint = false;
5133
+ function setSilentSigint(value) {
5134
+ silentSigint = value;
5135
+ }
5136
+ function isSilentSigint() {
5137
+ return silentSigint;
5138
+ }
5139
+
5140
+ // src/open.ts
5141
+ function openUrl(url) {
5142
+ try {
5143
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
5144
+ child.unref();
5145
+ child.on("error", () => {
5146
+ });
5147
+ return true;
5148
+ } catch {
5149
+ return false;
5150
+ }
5151
+ }
5152
+ function openLogFile(logPath, label) {
5153
+ const displayLabel = label || logPath;
5154
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
5155
+ const success = openUrl(logPath);
5156
+ if (!success) {
5157
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
5158
+ }
5159
+ }
5160
+ function viewLogWithTail(logPath, options) {
5161
+ const follow = options?.follow;
5162
+ const lines = options?.lines || 100;
5163
+ console.log(`\u65E5\u5FD7: ${logPath}`);
5164
+ if (follow) {
5165
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5166
+ } else {
5167
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5168
+ `);
5169
+ }
5170
+ const tailArgs = [];
5171
+ if (follow) tailArgs.push("-f");
5172
+ tailArgs.push("-n", lines.toString());
5173
+ tailArgs.push(logPath);
5174
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5175
+ if (follow) setSilentSigint(true);
5176
+ tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
5177
+ tail.on("error", (e) => {
5178
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5179
+ process.exit(1);
5180
+ });
5181
+ }
5182
+
5183
+ // src/commands/shared.ts
5184
+ import readline from "readline";
5185
+
5186
+ // src/process-start.ts
5187
+ import fs9 from "fs";
5188
+ var TUN_MODE_POST_WAIT_MS = 500;
5189
+ function buildTunLaunchScript() {
5190
+ const binary = shellQuote(PATHS.mihomoBinary);
5191
+ const configFile = shellQuote(PATHS.configFile);
5192
+ const logFile = shellQuote(PATHS.logFile);
5193
+ const pidFile = shellQuote(PATHS.pidFile);
5194
+ const dataDir = shellQuote(DIRS.data);
5195
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5196
+ return `#!/bin/bash
5197
+ BINARY=${binary}
5198
+ CONFIG_FILE=${configFile}
5199
+ LOG_FILE=${logFile}
5200
+ PID_FILE=${pidFile}
5201
+ DATA_DIR=${dataDir}
5202
+ KILL_PATTERN=${killPattern}
5203
+
5204
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5205
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5206
+ sleep 0.2
5207
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5208
+
5209
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5210
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5211
+
5212
+ # \u542F\u52A8
5213
+ cd /tmp
5214
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5215
+ NEW_PID=$!
5216
+ echo \${NEW_PID} > "\${PID_FILE}"
5217
+
5218
+ # \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
5219
+ #\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
5220
+ # 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
5221
+ is_alive() {
5222
+ local stat
5223
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
5224
+ case "\${stat}" in
5225
+ Z*|'') return 1 ;;
5226
+ *) return 0 ;;
5227
+ esac
5228
+ }
5229
+
5230
+ # \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
5231
+ # \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
5232
+ # \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
5233
+ i=0
5234
+ while [ $i -lt 12 ]; do
5235
+ sleep 0.1
5236
+ is_alive \${NEW_PID} || break
5237
+ i=$((i+1))
5238
+ done
5239
+ if is_alive \${NEW_PID}; then
5240
+ exit 0
5241
+ fi
5242
+
5243
+ # \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
5244
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5245
+ echo "TUN \u542F\u52A8\u5931\u8D25"
5246
+ echo ""
5247
+ echo "--- \u65E5\u5FD7 ---"
5248
+ tail -25 "\${LOG_FILE}" 2>/dev/null
5249
+ exit 2
5250
+ `;
5251
+ }
5252
+ async function startTun() {
5253
+ ensureDirs();
5254
+ rotateAndCleanupLogs();
5255
+ if (!fs9.existsSync(PATHS.mihomoBinary)) {
5256
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5257
+ }
5258
+ if (!fs9.existsSync(PATHS.configFile)) {
5259
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5260
+ }
5261
+ const logFile = PATHS.logFile;
5262
+ if (fs9.existsSync(logFile)) {
5263
+ try {
5264
+ fs9.accessSync(logFile, fs9.constants.W_OK);
5265
+ } catch {
5266
+ try {
5267
+ fs9.unlinkSync(logFile);
5268
+ } catch {
5269
+ }
5270
+ }
5271
+ }
5272
+ const staleState = checkStaleState();
5273
+ if (staleState.needsCleanup) {
5274
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5275
+ }
5276
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5277
+ runSudoScript(buildTunLaunchScript(), {
5278
+ action: "TUN \u542F\u52A8",
5279
+ file: "launch-tun.sh",
5280
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5281
+ });
5282
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5283
+ const finalPid = getPid();
5284
+ if (!finalPid || !isRunning()) {
5285
+ const tail = readLogTail();
5286
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
5287
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
5288
+ });
5289
+ }
5290
+ return { success: true, pid: finalPid, mode: "tun" };
5291
+ }
5292
+
5293
+ // src/runtime.ts
5243
5294
  function getRuntimeMode() {
5244
5295
  if (isServiceInstalled()) return "mixed";
5245
5296
  return getConfigInfo()?.tun ? "tun" : "mixed";
5246
5297
  }
5247
- function getRunningState() {
5248
- const service = getServiceStatus();
5298
+ function getRunningState(serviceStatus) {
5299
+ const service = serviceStatus ?? getServiceStatus();
5249
5300
  if (service.running) {
5250
5301
  return { running: true, pid: service.pid, kind: "service", processInfo: null };
5251
5302
  }
@@ -5350,15 +5401,34 @@ async function readBodyWithLimit(response, controller, limit) {
5350
5401
  return Buffer.concat(chunks).toString("utf8");
5351
5402
  }
5352
5403
 
5353
- // src/subscription.ts
5354
- function isGithubUrl(url) {
5355
- return /github\.com|raw\.githubusercontent\.com/i.test(url);
5356
- }
5357
- function getDefaultUpdateInterval(url) {
5358
- return isGithubUrl(url) ? DEFAULT_UPDATE_INTERVAL_HOURS_GITHUB : DEFAULT_UPDATE_INTERVAL_HOURS;
5404
+ // src/spinner.ts
5405
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
5406
+ var INTERVAL_MS = 80;
5407
+ async function withSpinner(label, fn) {
5408
+ if (!process.stdout.isTTY) {
5409
+ console.log(label);
5410
+ return fn();
5411
+ }
5412
+ const start = Date.now();
5413
+ let frame = 0;
5414
+ const render = () => {
5415
+ const secs = ((Date.now() - start) / 1e3).toFixed(0);
5416
+ process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
5417
+ frame = (frame + 1) % FRAMES.length;
5418
+ };
5419
+ render();
5420
+ const timer = setInterval(render, INTERVAL_MS);
5421
+ try {
5422
+ return await fn();
5423
+ } finally {
5424
+ clearInterval(timer);
5425
+ process.stdout.write("\r\x1B[K");
5426
+ }
5359
5427
  }
5360
- function resolveUpdateInterval(url, cachedInterval) {
5361
- return cachedInterval && cachedInterval > 0 ? cachedInterval : getDefaultUpdateInterval(url);
5428
+
5429
+ // src/subscription.ts
5430
+ function resolveUpdateInterval(cachedInterval) {
5431
+ return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
5362
5432
  }
5363
5433
  var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
5364
5434
  function isValidHttpUrl(url) {
@@ -5562,7 +5632,7 @@ function needsAutoUpdate(sub) {
5562
5632
  const lastUpdate = new Date(sub.updated_at).getTime();
5563
5633
  if (Number.isNaN(lastUpdate)) return true;
5564
5634
  if (lastUpdate > Date.now()) return true;
5565
- const intervalHours = resolveUpdateInterval(sub.url, sub.update_interval);
5635
+ const intervalHours = resolveUpdateInterval(sub.update_interval);
5566
5636
  const intervalMs = intervalHours * 60 * 60 * 1e3;
5567
5637
  return Date.now() - lastUpdate > intervalMs;
5568
5638
  }
@@ -5589,7 +5659,7 @@ async function autoUpdateStaleSubscription(options = {}) {
5589
5659
  }
5590
5660
  if (staleSubs.length === 1) {
5591
5661
  const sub = staleSubs[0];
5592
- const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5662
+ const interval = resolveUpdateInterval(sub.update_interval);
5593
5663
  console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5594
5664
  } else {
5595
5665
  console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
@@ -5606,7 +5676,7 @@ async function autoUpdateStaleSubscription(options = {}) {
5606
5676
  )
5607
5677
  );
5608
5678
  try {
5609
- await withTimeout(updatePromise, timeoutMs);
5679
+ await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
5610
5680
  } catch (e) {
5611
5681
  if (!(e instanceof TimeoutError)) throw e;
5612
5682
  controller.abort();
@@ -5622,33 +5692,179 @@ async function autoUpdateStaleSubscription(options = {}) {
5622
5692
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5623
5693
  }
5624
5694
 
5625
- // src/commands/status.ts
5626
- async function printStatus() {
5627
- const state = getRunningState();
5628
- const service = getServiceStatus();
5629
- const info = getConfigInfo();
5630
- const overwriteEnabled = isOverwriteEnabled();
5631
- const overwriteFiles = listOverwriteFile().files;
5632
- const activeSub = getActiveSubscription();
5633
- const { running, pid, kind, processInfo } = state;
5634
- console.log("");
5635
- let modeLabel = "";
5695
+ // src/proxy-probe.ts
5696
+ import { execFile } from "child_process";
5697
+ import { promisify } from "util";
5698
+ var execFileAsync = promisify(execFile);
5699
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
5700
+ function isProbeSuccessStatus(code) {
5701
+ return code !== null && code >= 200 && code < 300;
5702
+ }
5703
+ async function probeProxyConnectivity(port, timeoutMs = 2e3) {
5704
+ const start = Date.now();
5705
+ try {
5706
+ const { stdout } = await execFileAsync(
5707
+ "curl",
5708
+ [
5709
+ "-x",
5710
+ `http://127.0.0.1:${port}`,
5711
+ "-s",
5712
+ "-o",
5713
+ "/dev/null",
5714
+ "-w",
5715
+ "%{http_code}",
5716
+ "--connect-timeout",
5717
+ "3",
5718
+ "--max-time",
5719
+ String(Math.ceil(timeoutMs / 1e3)),
5720
+ PROBE_URL
5721
+ ],
5722
+ { timeout: timeoutMs + 2e3 }
5723
+ );
5724
+ const code = Number.parseInt(stdout.trim(), 10);
5725
+ const statusCode = Number.isFinite(code) ? code : null;
5726
+ const ok = isProbeSuccessStatus(statusCode);
5727
+ return {
5728
+ ok,
5729
+ statusCode,
5730
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
5731
+ durationMs: Date.now() - start
5732
+ };
5733
+ } catch (e) {
5734
+ const err = e;
5735
+ const stderr = err.stderr?.toString().trim();
5736
+ const lastLine = stderr ? stderr.split("\n").pop() : void 0;
5737
+ const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5738
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5739
+ }
5740
+ }
5741
+
5742
+ // src/commands/status.ts
5743
+ function connectivityHint(urgency) {
5744
+ if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
5745
+ if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
5746
+ return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
5747
+ }
5748
+ function trafficColor(line, urgency, total, upload, download) {
5749
+ if (urgency === "traffic-exhausted") return colors.red(line);
5750
+ if (total && total > 0) {
5751
+ const used = (upload || 0) + (download || 0);
5752
+ if (used / total >= 0.9) return colors.yellow(line);
5753
+ }
5754
+ return line;
5755
+ }
5756
+ function expireColor(line, urgency) {
5757
+ if (urgency === "expired") return colors.red(line);
5758
+ if (urgency === "expiring") return colors.yellow(line);
5759
+ return line;
5760
+ }
5761
+ function buildStatusJson(args) {
5762
+ const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
5763
+ return {
5764
+ version: VERSION,
5765
+ running: args.running,
5766
+ connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
5767
+ mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
5768
+ carrier: args.kind,
5769
+ pid: args.pid,
5770
+ kernel: getKernelVersion(),
5771
+ kernelInstalled: hasKernel(),
5772
+ ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
5773
+ ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {},
5774
+ ...args.info.httpPort ? { http: args.info.httpPort } : {},
5775
+ ...args.info.socksPort ? { socks: args.info.socksPort } : {}
5776
+ } : {},
5777
+ subscription: args.activeSub ? {
5778
+ name: args.activeSub.name,
5779
+ proxies: args.info?.proxies ?? 0,
5780
+ proxyGroups: args.info?.proxyGroups ?? 0,
5781
+ ...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
5782
+ ...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
5783
+ ...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
5784
+ ...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
5785
+ urgency
5786
+ } : null,
5787
+ overwrite: { enabled: args.overwriteEnabled, files: args.overwriteFiles },
5788
+ service: {
5789
+ installed: args.service.installed,
5790
+ loaded: args.service.loaded,
5791
+ running: args.service.running,
5792
+ disabled: args.service.disabled,
5793
+ lastExitCode: args.service.lastExitCode,
5794
+ legacySystemInstall: args.legacy
5795
+ }
5796
+ };
5797
+ }
5798
+ async function printStatus(args = []) {
5799
+ const asJson = hasFlag(args, "-j", "--json");
5800
+ const skipProbe = hasFlag(args, "--no-probe");
5801
+ const service = getServiceStatus();
5802
+ const state = getRunningState(service);
5803
+ const info = getConfigInfo();
5804
+ const overwriteEnabled = isOverwriteEnabled();
5805
+ const overwriteFiles = listOverwriteFile().files;
5806
+ const activeSub = getActiveSubscription();
5807
+ const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
5808
+ const legacy = detectLegacySystemInstall();
5809
+ const { running, pid, kind } = state;
5810
+ let probe = null;
5811
+ if (running && info?.mixedPort && !skipProbe) {
5812
+ probe = await probeProxyConnectivity(info.mixedPort);
5813
+ }
5814
+ if (asJson) {
5815
+ console.log(
5816
+ JSON.stringify(
5817
+ buildStatusJson({
5818
+ running,
5819
+ kind,
5820
+ pid,
5821
+ probe,
5822
+ info,
5823
+ activeSub,
5824
+ cached,
5825
+ overwriteEnabled,
5826
+ overwriteFiles: overwriteFiles.map((f) => f.name),
5827
+ service,
5828
+ legacy
5829
+ }),
5830
+ null,
5831
+ 2
5832
+ )
5833
+ );
5834
+ return;
5835
+ }
5836
+ const urgency = cached ? subscriptionUrgency(cached) : null;
5837
+ console.log("");
5838
+ let modeLabel = "";
5636
5839
  if (info) {
5637
5840
  const mode = info.tun ? "TUN" : "Mixed";
5638
5841
  const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
5639
5842
  modeLabel = colors.cyan(` (${mode}${carrier})`);
5640
5843
  }
5641
- const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5844
+ let statusText;
5845
+ if (!running) {
5846
+ statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5847
+ } else if (probe && !probe.ok) {
5848
+ statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
5849
+ } else {
5850
+ statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
5851
+ }
5642
5852
  console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5853
+ if (running && probe && !probe.ok) {
5854
+ console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
5855
+ }
5643
5856
  if (!running && service.installed && !service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
5644
5857
  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
5858
  console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
5646
5859
  }
5647
- console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5860
+ const kernelVersion = getKernelVersion();
5861
+ console.log(
5862
+ kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
5863
+ );
5648
5864
  if (pid) {
5649
5865
  console.log(`${colors.gray("PID: ")}${pid}`);
5650
- if (kind === "tun" && processInfo) {
5651
- console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5866
+ if (kind === "tun" && state.processInfo) {
5867
+ console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
5652
5868
  }
5653
5869
  }
5654
5870
  if (info) {
@@ -5670,16 +5886,15 @@ async function printStatus() {
5670
5886
  subLine += ` (${formatProxySummary(info)})`;
5671
5887
  }
5672
5888
  console.log(subLine);
5673
- const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
5674
5889
  const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
5675
5890
  if (traffic) {
5676
- console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
5891
+ console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
5677
5892
  }
5678
5893
  if (cached?.expire !== void 0) {
5679
- console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
5894
+ console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
5680
5895
  }
5681
5896
  } else {
5682
- console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E`);
5897
+ console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
5683
5898
  }
5684
5899
  if (overwriteEnabled && overwriteFiles.length > 0) {
5685
5900
  const names = overwriteFiles.map((f) => f.name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6").join(", ");
@@ -5689,11 +5904,10 @@ async function printStatus() {
5689
5904
  } else {
5690
5905
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
5691
5906
  }
5692
- printServiceLines(service);
5907
+ printServiceLines(service, legacy);
5693
5908
  console.log("");
5694
5909
  }
5695
- function printServiceLines(service) {
5696
- const legacy = detectLegacySystemInstall();
5910
+ function printServiceLines(service, legacy) {
5697
5911
  if (!service.installed && !service.loaded) {
5698
5912
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
5699
5913
  } else if (!service.installed) {
@@ -5784,6 +5998,10 @@ async function cmdStart(args) {
5784
5998
  throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
5785
5999
  }
5786
6000
  await printStatus();
6001
+ if (targetMode === "mixed") {
6002
+ console.log(colors.gray("\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:7890\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09"));
6003
+ console.log("");
6004
+ }
5787
6005
  }
5788
6006
 
5789
6007
  // src/commands/shared.ts
@@ -5794,107 +6012,704 @@ async function dispatchSubcommand(args, table, options) {
5794
6012
  if (cmd) return cmd.handler(args);
5795
6013
  if (options.onUnknown) return options.onUnknown(action);
5796
6014
  }
5797
- return options.fallback(args);
6015
+ return options.fallback(args);
6016
+ }
6017
+ async function confirmPrompt(question) {
6018
+ if (!process.stdin.isTTY) return false;
6019
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
6020
+ const answer = await new Promise((resolve) => {
6021
+ rl.question(`${question} (y/N) `, (a) => {
6022
+ rl.close();
6023
+ resolve(a);
6024
+ });
6025
+ });
6026
+ return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6027
+ }
6028
+ async function confirmOrThrow(question, opts) {
6029
+ if (!process.stdin.isTTY) {
6030
+ throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6031
+ }
6032
+ return confirmPrompt(question);
6033
+ }
6034
+ async function restartToApply(args) {
6035
+ if (!isRestartNeededOnChange()) return false;
6036
+ const currentMode = getRuntimeMode();
6037
+ console.log("");
6038
+ await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6039
+ return true;
6040
+ }
6041
+ function cleanupLegacyInstallOrThrow() {
6042
+ try {
6043
+ cleanupLegacySystemInstall();
6044
+ } catch (e) {
6045
+ if (e instanceof CliError) throw e;
6046
+ throw new CliError(e.message, {
6047
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
6048
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
6049
+ });
6050
+ }
6051
+ }
6052
+
6053
+ // src/commands/directory.ts
6054
+ function openDirectory(args) {
6055
+ const target = args[2];
6056
+ if (!target || target === "root") {
6057
+ console.log("\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55");
6058
+ const success = openUrl(USER_DATA_DIR);
6059
+ if (!success) {
6060
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${USER_DATA_DIR}`);
6061
+ }
6062
+ return;
6063
+ }
6064
+ const key = target.toLowerCase();
6065
+ const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
6066
+ if (targetInfo) {
6067
+ const targetPath = targetInfo.path || USER_DATA_DIR;
6068
+ console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label}`);
6069
+ const success = openUrl(targetPath);
6070
+ if (!success) {
6071
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${targetPath}`);
6072
+ }
6073
+ return;
6074
+ }
6075
+ const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
6076
+ for (const [k, val] of Object.entries(DIRECTORY_TARGETS)) {
6077
+ if (k !== "root") {
6078
+ hint.push(` ${k.padEnd(14)}${val.label}`);
6079
+ }
6080
+ }
6081
+ throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u76EE\u6807 "${target}"`, { hint });
6082
+ }
6083
+ function printDirectoryInfo() {
6084
+ const entries = Object.entries(DIRECTORY_TARGETS).filter(([key]) => key !== "root");
6085
+ const pathWidth = Math.max(...entries.map(([, val]) => val.path.replace(USER_DATA_DIR, ".").length));
6086
+ console.log("");
6087
+ console.log(`\u6570\u636E\u76EE\u5F55: ${USER_DATA_DIR}`);
6088
+ console.log("");
6089
+ for (const [key, val] of entries) {
6090
+ const rel = val.path.replace(USER_DATA_DIR, ".");
6091
+ console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
6092
+ }
6093
+ console.log("");
6094
+ console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
6095
+ console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6096
+ console.log("");
6097
+ }
6098
+ var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
6099
+ async function cmdDirectory(args) {
6100
+ await dispatchSubcommand(args, SUBCOMMANDS, {
6101
+ fallback: printDirectoryInfo,
6102
+ onUnknown: (action) => {
6103
+ const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6104
+ const suggestion = suggestSimilar(action, names);
6105
+ throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6106
+ 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>"]
6107
+ });
6108
+ }
6109
+ });
6110
+ }
6111
+
6112
+ // src/commands/overwrite.ts
6113
+ import path7 from "path";
6114
+ function printOverwriteList() {
6115
+ const info = listOverwriteFile();
6116
+ const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6117
+ console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6118
+ console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6119
+ console.log("");
6120
+ if (info.files.length === 0) {
6121
+ console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6122
+ console.log("");
6123
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path7.join(info.dir, "overwrite.yaml")}`);
6124
+ console.log(` \u6216 ${path7.join(info.dir, "overwrite.dns.yaml")}`);
6125
+ console.log("");
6126
+ } else {
6127
+ console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
6128
+ console.log("");
6129
+ info.files.forEach((f, i) => {
6130
+ const num = i < 10 ? ` ${i}` : `${i}`;
6131
+ console.log(` ${num}. ${f.name}`);
6132
+ if (f.scope) {
6133
+ console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6134
+ }
6135
+ if (f.keys.length > 0) {
6136
+ console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6137
+ }
6138
+ });
6139
+ console.log("");
6140
+ }
6141
+ console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6142
+ console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6143
+ console.log("");
6144
+ }
6145
+ async function setOverwrite(enabled, args) {
6146
+ if (isOverwriteEnabled() === enabled) {
6147
+ console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
6148
+ console.log("");
6149
+ printOverwriteList();
6150
+ return;
6151
+ }
6152
+ setOverwriteEnabled(enabled);
6153
+ console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
6154
+ if (await restartToApply(args)) return;
6155
+ console.log("");
6156
+ printOverwriteList();
6157
+ }
6158
+ var SUBCOMMANDS2 = [
6159
+ { name: "on", aliases: ["enable"], description: "\u542F\u7528\u8986\u5199", handler: (args) => setOverwrite(true, args) },
6160
+ { name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
6161
+ ];
6162
+ async function cmdOverwrite(args) {
6163
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
6164
+ // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6165
+ fallback: () => {
6166
+ console.log("");
6167
+ printOverwriteList();
6168
+ },
6169
+ onUnknown: (action) => {
6170
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6171
+ const suggestion = suggestSimilar(action, names);
6172
+ throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6173
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6174
+ });
6175
+ }
6176
+ });
6177
+ }
6178
+
6179
+ // src/commands/subscription.ts
6180
+ function printRestartHintIfRunning() {
6181
+ if (getRunningState().running) {
6182
+ console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C mihomo start \u4F7F\u66F4\u65B0\u751F\u6548"));
6183
+ console.log("");
6184
+ }
6185
+ }
6186
+ function printSubscriptionList() {
6187
+ const subs = getSubscriptionsWithCache();
6188
+ if (subs.length === 0) {
6189
+ console.log("\u6CA1\u6709\u8BA2\u9605");
6190
+ console.log("");
6191
+ console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
6192
+ console.log("");
6193
+ return;
6194
+ }
6195
+ const activeSub = getActiveSubscription();
6196
+ console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
6197
+ subs.forEach((s, i) => {
6198
+ const rel = formatRelativeTime(s.updated_at);
6199
+ const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
6200
+ const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
6201
+ const interval = resolveUpdateInterval(s.update_interval);
6202
+ console.log(` ${i + 1}. ${s.name}${defaultMark}`);
6203
+ console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
6204
+ if (s.username) {
6205
+ console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
6206
+ }
6207
+ const traffic = formatTraffic(s.upload, s.download, s.total);
6208
+ if (traffic) {
6209
+ console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
6210
+ }
6211
+ if (s.expire !== void 0) {
6212
+ console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
6213
+ }
6214
+ if (s.web_page_url) {
6215
+ console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
6216
+ }
6217
+ });
6218
+ console.log("");
6219
+ console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
6220
+ console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
6221
+ console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
6222
+ console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
6223
+ console.log("");
6224
+ }
6225
+ function assertNotFlagLike(name, usage) {
6226
+ if (name.startsWith("-")) {
6227
+ throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
6228
+ label: "\u53C2\u6570\u9519\u8BEF",
6229
+ hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
6230
+ });
6231
+ }
6232
+ }
6233
+ async function subAdd(args) {
6234
+ const url = args[2]?.trim();
6235
+ const name = args[3] || "default";
6236
+ if (!url) {
6237
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL");
6238
+ }
6239
+ if (!isValidHttpUrl(url)) {
6240
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
6241
+ }
6242
+ assertNotFlagLike(name, "mihomo sub add <url> [name]");
6243
+ console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
6244
+ addSubscription(url, name);
6245
+ try {
6246
+ const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
6247
+ setDefaultSubscription(name);
6248
+ console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
6249
+ } catch (e) {
6250
+ removeSubscription(name);
6251
+ if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
6252
+ throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
6253
+ }
6254
+ console.log("");
6255
+ printSubscriptionList();
6256
+ }
6257
+ async function subUpdate(args) {
6258
+ const name = args[2];
6259
+ const subs = getSubscriptions();
6260
+ if (subs.length === 0) {
6261
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605");
6262
+ }
6263
+ if (!name) {
6264
+ console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
6265
+ const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
6266
+ let ok = 0;
6267
+ for (const r of results) {
6268
+ if (r.success) ok++;
6269
+ printUpdateResult(r);
6270
+ }
6271
+ if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
6272
+ console.log("");
6273
+ printRestartHintIfRunning();
6274
+ printSubscriptionList();
6275
+ return;
6276
+ }
6277
+ const target = resolveSubscription(subs, name);
6278
+ console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
6279
+ const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
6280
+ if (!result.success) {
6281
+ throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
6282
+ }
6283
+ console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
6284
+ console.log("");
6285
+ printRestartHintIfRunning();
6286
+ printSubscriptionList();
6287
+ }
6288
+ async function subUse(args) {
6289
+ const name = args[2];
6290
+ const subs = getSubscriptions();
6291
+ if (subs.length === 0) {
6292
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
6293
+ }
6294
+ if (!name) {
6295
+ throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
6296
+ hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
6297
+ });
6298
+ }
6299
+ const target = resolveSubscription(subs, name);
6300
+ const currentDefault = getActiveSubscription();
6301
+ const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
6302
+ if (isAlreadyDefault) {
6303
+ console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
6304
+ console.log("");
6305
+ printSubscriptionList();
6306
+ return;
6307
+ }
6308
+ const success = setDefaultSubscription(target.name);
6309
+ if (!success) {
6310
+ throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
6311
+ }
6312
+ console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
6313
+ if (await restartToApply(args)) return;
6314
+ console.log("");
6315
+ printSubscriptionList();
6316
+ }
6317
+ async function subRemove(args) {
6318
+ const name = getNonFlagArg(args, 2);
6319
+ const subs = getSubscriptions();
6320
+ if (!name) {
6321
+ throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
6322
+ hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
6323
+ });
6324
+ }
6325
+ const target = resolveSubscription(subs, name);
6326
+ const isExact = target.name === name;
6327
+ const skipConfirm = hasFlag(args, "-y", "--yes");
6328
+ if (!isExact && !skipConfirm) {
6329
+ console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
6330
+ if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
6331
+ nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
6332
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
6333
+ })) {
6334
+ console.log("\u5DF2\u53D6\u6D88");
6335
+ return;
6336
+ }
6337
+ }
6338
+ const switchedTo = removeSubscription(target.name);
6339
+ console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
6340
+ if (switchedTo) {
6341
+ console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
6342
+ }
6343
+ console.log("");
6344
+ printSubscriptionList();
5798
6345
  }
5799
- async function confirmPrompt(question) {
5800
- if (!process.stdin.isTTY) return false;
5801
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5802
- const answer = await new Promise((resolve) => {
5803
- rl.question(`${question} (y/N) `, (a) => {
5804
- rl.close();
5805
- resolve(a);
5806
- });
6346
+ var SUBCOMMANDS3 = [
6347
+ { name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: subAdd },
6348
+ { name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: subUpdate },
6349
+ { name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: subUse },
6350
+ { name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
6351
+ ];
6352
+ async function cmdSubscription(args) {
6353
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
6354
+ // 无子命令 → 列表;未知子命令 → 报错
6355
+ fallback: printSubscriptionList,
6356
+ onUnknown: (action) => {
6357
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6358
+ const suggestion = suggestSimilar(action, names);
6359
+ throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
6360
+ 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"]
6361
+ });
6362
+ }
5807
6363
  });
5808
- return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
5809
6364
  }
5810
- async function confirmOrThrow(question, opts) {
5811
- if (!process.stdin.isTTY) {
5812
- throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6365
+
6366
+ // src/commands/completion.ts
6367
+ function commandWords(commands) {
6368
+ return commands.filter((c) => !c.hidden).map((c) => ({ word: c.name, desc: c.usage[0]?.description ?? "" }));
6369
+ }
6370
+ function subWords(subs) {
6371
+ return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
6372
+ }
6373
+ function subGroups(commands) {
6374
+ const groupOf = (name, subs) => {
6375
+ const cmd = commands.find((c) => c.name === name);
6376
+ return { tokens: cmd ? [cmd.name, ...cmd.aliases] : [name], words: subWords(subs) };
6377
+ };
6378
+ return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
6379
+ }
6380
+ var DIR_TARGETS = ["root", "subs", "logs", "data", "runtime", "kernel"];
6381
+ var UI_NAMES = ["zash", "dash", "yacd"];
6382
+ var SHELLS = ["zsh", "bash", "fish"];
6383
+ function buildZsh(commands, groups) {
6384
+ const lines = [
6385
+ "#compdef mihomo mhm mh mihomo-cli",
6386
+ "",
6387
+ '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: \u5199\u5165 ~/.zsh/completions/_mihomo \u6216 eval "$(mihomo completion zsh)"\uFF09',
6388
+ "",
6389
+ "_mihomo() {",
6390
+ " local -a commands subcmds",
6391
+ " commands=(",
6392
+ ...commandWords(commands).map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
6393
+ " )",
6394
+ "",
6395
+ " _arguments -C \\",
6396
+ " '1: :->cmd' \\",
6397
+ " '*::arg:->args'",
6398
+ "",
6399
+ " case $state in",
6400
+ " cmd)",
6401
+ " _describe 'command' commands",
6402
+ " ;;",
6403
+ " args)",
6404
+ " case ${words[1]} in"
6405
+ ];
6406
+ for (const group of groups) {
6407
+ const aliases = group.tokens.join("|");
6408
+ lines.push(` ${aliases})`);
6409
+ lines.push(" subcmds=(");
6410
+ for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
6411
+ lines.push(" )");
6412
+ lines.push(" if (( CURRENT == 2 )); then");
6413
+ lines.push(" _describe 'subcommand' subcmds");
6414
+ lines.push(" else");
6415
+ lines.push(" _files");
6416
+ lines.push(" fi");
6417
+ lines.push(" ;;");
5813
6418
  }
5814
- return confirmPrompt(question);
6419
+ lines.push(
6420
+ " directory|dir|dirs|directories)",
6421
+ " if (( CURRENT == 3 )); then",
6422
+ ` _values 'target' ${DIR_TARGETS.join(" ")}`,
6423
+ " fi",
6424
+ " ;;",
6425
+ " logs)",
6426
+ " _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:'",
6427
+ " ;;",
6428
+ " ui)",
6429
+ ` _values 'ui' ${UI_NAMES.join(" ")}`,
6430
+ " ;;",
6431
+ " kernel)",
6432
+ " _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:' '--no-mirror[\u76F4\u8FDE\u4E0B\u8F7D]'",
6433
+ " ;;",
6434
+ " reset)",
6435
+ ` _values 'target' subs logs data runtime settings kernel overwrites service`,
6436
+ " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
6437
+ " ;;",
6438
+ " completion)",
6439
+ ` _values 'shell' ${SHELLS.join(" ")}`,
6440
+ " ;;",
6441
+ " *)",
6442
+ " _files",
6443
+ " ;;",
6444
+ " esac",
6445
+ " ;;",
6446
+ " esac",
6447
+ "}",
6448
+ "",
6449
+ '_mihomo "$@"'
6450
+ );
6451
+ return lines.join("\n");
6452
+ }
6453
+ function buildBash(commands, groups) {
6454
+ const top = commandWords(commands).map((c) => c.word).join(" ");
6455
+ const subCase = groups.map((group) => {
6456
+ const aliases = group.tokens.join("|");
6457
+ const words = group.words.map((w) => w.word).join(" ");
6458
+ if (group.tokens[0] === "directory") {
6459
+ return ` ${aliases})
6460
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
6461
+ COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
6462
+ elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
6463
+ COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
6464
+ fi
6465
+ ;;`;
6466
+ }
6467
+ return ` ${aliases})
6468
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
6469
+ COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
6470
+ fi
6471
+ ;;`;
6472
+ }).join("\n");
6473
+ return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
6474
+
6475
+ _mihomo_completions() {
6476
+ local cur prev
6477
+ COMPREPLY=()
6478
+ cur="\${COMP_WORDS[COMP_CWORD]}"
6479
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
6480
+
6481
+ if [[ \${COMP_CWORD} -eq 1 ]]; then
6482
+ COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
6483
+ return 0
6484
+ fi
6485
+
6486
+ case "\${COMP_WORDS[1]}" in
6487
+ ${subCase}
6488
+ logs)
6489
+ COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
6490
+ ;;
6491
+ ui)
6492
+ COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
6493
+ ;;
6494
+ kernel)
6495
+ COMPREPLY=( $(compgen -W "--mirror --no-mirror" -- "\${cur}") )
6496
+ ;;
6497
+ reset)
6498
+ COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
6499
+ ;;
6500
+ completion)
6501
+ COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
6502
+ ;;
6503
+ esac
5815
6504
  }
5816
- async function restartToApply(args) {
5817
- if (!isRestartNeededOnChange()) return false;
5818
- const currentMode = getRuntimeMode();
5819
- console.log("");
5820
- await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
5821
- return true;
6505
+ complete -F _mihomo_completions mihomo mhm mh mihomo-cli
6506
+ `;
5822
6507
  }
5823
- function cleanupLegacyInstallOrThrow() {
5824
- try {
5825
- cleanupLegacySystemInstall();
5826
- } catch (e) {
5827
- if (e instanceof CliError) throw e;
5828
- throw new CliError(e.message, {
5829
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5830
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
6508
+ function buildFish(commands, groups) {
6509
+ const lines = [
6510
+ "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
6511
+ "",
6512
+ "for cmd in mihomo mhm mh mihomo-cli"
6513
+ ];
6514
+ for (const c of commandWords(commands)) {
6515
+ lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
6516
+ }
6517
+ for (const group of groups) {
6518
+ const seen = group.tokens.join(" ");
6519
+ for (const s of group.words) {
6520
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${seen}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
6521
+ }
6522
+ }
6523
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
6524
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
6525
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
6526
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
6527
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
6528
+ lines.push("end");
6529
+ return lines.join("\n");
6530
+ }
6531
+ function buildCompletionScript(shell, commands) {
6532
+ const groups = subGroups(commands);
6533
+ switch (shell) {
6534
+ case "zsh":
6535
+ return buildZsh(commands, groups);
6536
+ case "bash":
6537
+ return buildBash(commands, groups);
6538
+ case "fish":
6539
+ return buildFish(commands, groups);
6540
+ default: {
6541
+ const suggestion = suggestSimilar(shell, [...SHELLS]);
6542
+ throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
6543
+ label: "\u53C2\u6570\u9519\u8BEF",
6544
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
6545
+ });
6546
+ }
6547
+ }
6548
+ }
6549
+ function cmdCompletion(args, commands) {
6550
+ const shell = args[1];
6551
+ if (!shell) {
6552
+ throw new CliError("\u8BF7\u6307\u5B9A shell", {
6553
+ 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']
5831
6554
  });
5832
6555
  }
6556
+ console.log(buildCompletionScript(shell, commands));
5833
6557
  }
5834
6558
 
5835
- // src/commands/directory.ts
5836
- function openDirectory(args) {
5837
- const target = args[2];
5838
- if (!target || target === "root") {
5839
- console.log("\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55");
5840
- const success = openUrl(USER_DATA_DIR);
5841
- if (!success) {
5842
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${USER_DATA_DIR}`);
6559
+ // src/commands/doctor.ts
6560
+ import { spawnSync as spawnSync5 } from "child_process";
6561
+ import fs10 from "fs";
6562
+ function isPortListening(port) {
6563
+ try {
6564
+ const r = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
6565
+ return r.status === 0 && (r.stdout || "").trim().length > 0;
6566
+ } catch {
6567
+ return false;
6568
+ }
6569
+ }
6570
+ async function collectChecks() {
6571
+ const checks = [];
6572
+ const push = (name, status, detail, fix) => {
6573
+ checks.push({ name, status, detail, fix });
6574
+ };
6575
+ if (!hasKernel()) {
6576
+ push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
6577
+ } else {
6578
+ const v = getKernelVersion();
6579
+ const r = spawnSync5(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
6580
+ if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
6581
+ push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
6582
+ } else {
6583
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
5843
6584
  }
5844
- return;
5845
6585
  }
5846
- const key = target.toLowerCase();
5847
- const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
5848
- if (targetInfo) {
5849
- const targetPath = targetInfo.path || USER_DATA_DIR;
5850
- console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label}`);
5851
- const success = openUrl(targetPath);
5852
- if (!success) {
5853
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${targetPath}`);
6586
+ try {
6587
+ fs10.accessSync(USER_DATA_DIR, fs10.constants.W_OK);
6588
+ push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
6589
+ } catch {
6590
+ push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
6591
+ }
6592
+ if (fs10.existsSync(PATHS.settingsFile)) {
6593
+ if (isValidSettingsContent(fs10.readFileSync(PATHS.settingsFile, "utf8"))) {
6594
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
6595
+ } else {
6596
+ push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
5854
6597
  }
5855
- return;
6598
+ } else {
6599
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
5856
6600
  }
5857
- const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
5858
- for (const [k, val] of Object.entries(DIRECTORY_TARGETS)) {
5859
- if (k !== "root") {
5860
- hint.push(` ${k.padEnd(14)}${val.label}`);
6601
+ const subs = getSubscriptionsWithCache();
6602
+ const active = getActiveSubscription();
6603
+ if (subs.length === 0) {
6604
+ push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
6605
+ } else {
6606
+ push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
6607
+ if (active) {
6608
+ if (!readSubscriptionRawConfig(active.name)) {
6609
+ 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}`);
6610
+ } else {
6611
+ push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
6612
+ }
6613
+ const cached = subs.find((s) => s.name === active.name);
6614
+ if (cached?.updated_at) {
6615
+ const rel = formatRelativeTime(cached.updated_at);
6616
+ const intervalH = resolveUpdateInterval(cached.update_interval);
6617
+ const ageH = (Date.now() - new Date(cached.updated_at).getTime()) / 36e5;
6618
+ if (ageH > intervalH) {
6619
+ 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");
6620
+ } else {
6621
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
6622
+ }
6623
+ }
5861
6624
  }
5862
6625
  }
5863
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u76EE\u6807 "${target}"`, { hint });
6626
+ const service = getServiceStatus();
6627
+ const legacy = detectLegacySystemInstall();
6628
+ if (legacy) {
6629
+ 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");
6630
+ } else if (!service.installed && !service.loaded) {
6631
+ push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
6632
+ } else if (!service.installed) {
6633
+ push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
6634
+ } else if (service.running) {
6635
+ const exitNote = service.lastExitCode !== null && service.lastExitCode !== 0 ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${service.lastExitCode}\uFF09` : "";
6636
+ push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${exitNote}`);
6637
+ if (service.lastExitCode !== null && service.lastExitCode !== 0) {
6638
+ 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");
6639
+ }
6640
+ } else {
6641
+ if (!service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
6642
+ push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo stop \u505C\u6B62\u91CD\u8BD5");
6643
+ } else {
6644
+ push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
6645
+ }
6646
+ }
6647
+ const state = getRunningState();
6648
+ const info = getConfigInfo();
6649
+ const mixedPort = info?.mixedPort ?? 7890;
6650
+ if (state.running) {
6651
+ if (isPortListening(mixedPort)) {
6652
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
6653
+ } else {
6654
+ push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6655
+ }
6656
+ } else if (isPortListening(mixedPort)) {
6657
+ 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`);
6658
+ } else {
6659
+ push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
6660
+ }
6661
+ if (active) {
6662
+ try {
6663
+ const mode = info?.tun ? "tun" : "mixed";
6664
+ prepareConfigForStart(mode, active.name);
6665
+ push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u53EF\u6B63\u5E38\u6784\u5EFA\uFF08${mode}\uFF09`);
6666
+ } catch (e) {
6667
+ push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start");
6668
+ }
6669
+ } else {
6670
+ push("\u914D\u7F6E\u6784\u5EFA", "warn", "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
6671
+ }
6672
+ if (state.running && info?.mixedPort) {
6673
+ const probe = await probeProxyConnectivity(info.mixedPort);
6674
+ if (probe.ok) {
6675
+ push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
6676
+ } else {
6677
+ push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
6678
+ }
6679
+ } else {
6680
+ push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
6681
+ }
6682
+ return checks;
5864
6683
  }
5865
- function printDirectoryInfo() {
5866
- const entries = Object.entries(DIRECTORY_TARGETS).filter(([key]) => key !== "root");
5867
- const pathWidth = Math.max(...entries.map(([, val]) => val.path.replace(USER_DATA_DIR, ".").length));
6684
+ async function cmdDoctor() {
6685
+ const checks = await collectChecks();
5868
6686
  console.log("");
5869
- console.log(`\u6570\u636E\u76EE\u5F55: ${USER_DATA_DIR}`);
5870
- console.log("");
5871
- for (const [key, val] of entries) {
5872
- const rel = val.path.replace(USER_DATA_DIR, ".");
5873
- console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
6687
+ for (const c of checks) {
6688
+ const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
6689
+ console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
6690
+ if (c.status !== "ok" && c.status !== "skip" && c.fix) {
6691
+ console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
6692
+ }
5874
6693
  }
6694
+ const ok = checks.filter((c) => c.status === "ok").length;
6695
+ const warn = checks.filter((c) => c.status === "warn").length;
6696
+ const fail = checks.filter((c) => c.status === "fail").length;
6697
+ const skip = checks.filter((c) => c.status === "skip").length;
5875
6698
  console.log("");
5876
- console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
5877
- console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6699
+ console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38${skip > 0 ? `\uFF0C${skip} \u9879\u8DF3\u8FC7` : ""}`);
5878
6700
  console.log("");
5879
- }
5880
- var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
5881
- async function cmdDirectory(args) {
5882
- await dispatchSubcommand(args, SUBCOMMANDS, {
5883
- fallback: printDirectoryInfo,
5884
- onUnknown: (action) => {
5885
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
5886
- const suggestion = suggestSimilar(action, names);
5887
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
5888
- 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>"]
5889
- });
5890
- }
5891
- });
6701
+ if (fail > 0) {
6702
+ throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
6703
+ label: "\u4F53\u68C0\u672A\u901A\u8FC7",
6704
+ hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
6705
+ });
6706
+ }
5892
6707
  }
5893
6708
 
5894
6709
  // src/kernel.ts
5895
- import { spawnSync as spawnSync5 } from "child_process";
5896
- import fs10 from "fs";
5897
- import path7 from "path";
6710
+ import { spawnSync as spawnSync6 } from "child_process";
6711
+ import fs11 from "fs";
6712
+ import path8 from "path";
5898
6713
 
5899
6714
  // node_modules/compare-versions/lib/esm/utils.js
5900
6715
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
@@ -6032,10 +6847,10 @@ async function checkUpdate() {
6032
6847
  }
6033
6848
  function findBinaryInDir(dir, maxDepth = 4) {
6034
6849
  if (maxDepth <= 0) return null;
6035
- const files = fs10.readdirSync(dir);
6850
+ const files = fs11.readdirSync(dir);
6036
6851
  for (const f of files) {
6037
- const fullPath = path7.join(dir, f);
6038
- const stat = fs10.lstatSync(fullPath);
6852
+ const fullPath = path8.join(dir, f);
6853
+ const stat = fs11.lstatSync(fullPath);
6039
6854
  if (stat.isDirectory()) {
6040
6855
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6041
6856
  if (found) return found;
@@ -6063,7 +6878,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6063
6878
  }
6064
6879
  assertTrustedAssetUrl(asset.browser_download_url);
6065
6880
  const downloadUrl = withMirror(asset.browser_download_url, mirror);
6066
- const tempPath = path7.join(DIRS.kernel, path7.basename(asset.name));
6881
+ const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
6067
6882
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
6068
6883
  if (mirror && progressCallback) {
6069
6884
  progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
@@ -6072,7 +6887,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6072
6887
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
6073
6888
  }
6074
6889
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
6075
- const curlResult = spawnSync5(
6890
+ const curlResult = spawnSync6(
6076
6891
  "curl",
6077
6892
  [
6078
6893
  "-L",
@@ -6101,19 +6916,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6101
6916
  }
6102
6917
  if (curlResult.status !== 0) {
6103
6918
  try {
6104
- fs10.unlinkSync(tempPath);
6919
+ fs11.unlinkSync(tempPath);
6105
6920
  } catch {
6106
6921
  }
6107
6922
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6108
6923
  }
6109
- if (!fs10.existsSync(tempPath)) {
6924
+ if (!fs11.existsSync(tempPath)) {
6110
6925
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6111
6926
  }
6112
6927
  if (Number.isFinite(asset.size) && asset.size > 0) {
6113
- const actual = fs10.statSync(tempPath).size;
6928
+ const actual = fs11.statSync(tempPath).size;
6114
6929
  if (actual !== asset.size) {
6115
6930
  try {
6116
- fs10.unlinkSync(tempPath);
6931
+ fs11.unlinkSync(tempPath);
6117
6932
  } catch {
6118
6933
  }
6119
6934
  throw new Error(
@@ -6129,7 +6944,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6129
6944
  let extractedBinary = null;
6130
6945
  try {
6131
6946
  if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
6132
- const listResult = spawnSync5("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6947
+ const listResult = spawnSync6("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6133
6948
  if (listResult.error) throw listResult.error;
6134
6949
  if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
6135
6950
  for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6137,7 +6952,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6137
6952
  throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
6138
6953
  }
6139
6954
  }
6140
- const typeResult = spawnSync5("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6955
+ const typeResult = spawnSync6("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6141
6956
  if (typeResult.error) throw typeResult.error;
6142
6957
  if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
6143
6958
  for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6146,24 +6961,24 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6146
6961
  throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
6147
6962
  }
6148
6963
  }
6149
- const tarResult = spawnSync5("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6964
+ const tarResult = spawnSync6("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6150
6965
  stdio: ["ignore", "ignore", "inherit"],
6151
6966
  timeout: 6e4
6152
6967
  });
6153
6968
  if (tarResult.error) throw tarResult.error;
6154
6969
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
6155
6970
  } else if (tempPath.endsWith(".gz")) {
6156
- const baseName = path7.basename(tempPath, ".gz");
6157
- const outputPath = path7.join(extractPath, baseName);
6158
- const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6971
+ const baseName = path8.basename(tempPath, ".gz");
6972
+ const outputPath = path8.join(extractPath, baseName);
6973
+ const gzipResult = spawnSync6("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6159
6974
  if (gzipResult.error) throw gzipResult.error;
6160
6975
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6161
- fs10.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6976
+ fs11.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6162
6977
  extractedBinary = outputPath;
6163
6978
  }
6164
6979
  } catch (e) {
6165
6980
  try {
6166
- fs10.unlinkSync(tempPath);
6981
+ fs11.unlinkSync(tempPath);
6167
6982
  } catch {
6168
6983
  }
6169
6984
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6171,35 +6986,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6171
6986
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6172
6987
  if (!foundBinary) {
6173
6988
  try {
6174
- fs10.unlinkSync(tempPath);
6989
+ fs11.unlinkSync(tempPath);
6175
6990
  } catch {
6176
6991
  }
6177
6992
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6178
6993
  }
6179
6994
  const targetPath = PATHS.mihomoBinary;
6180
6995
  if (foundBinary !== targetPath) {
6181
- if (fs10.existsSync(targetPath)) {
6182
- fs10.chmodSync(targetPath, 493);
6996
+ if (fs11.existsSync(targetPath)) {
6997
+ fs11.chmodSync(targetPath, 493);
6183
6998
  try {
6184
- fs10.unlinkSync(targetPath);
6999
+ fs11.unlinkSync(targetPath);
6185
7000
  } catch {
6186
7001
  }
6187
7002
  }
6188
- fs10.renameSync(foundBinary, targetPath);
7003
+ fs11.renameSync(foundBinary, targetPath);
6189
7004
  }
6190
- fs10.chmodSync(targetPath, 493);
7005
+ fs11.chmodSync(targetPath, 493);
6191
7006
  if (progressCallback) {
6192
7007
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6193
7008
  }
6194
- const check = spawnSync5(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
7009
+ const check = spawnSync6(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6195
7010
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6196
7011
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6197
7012
  try {
6198
- fs10.unlinkSync(targetPath);
7013
+ fs11.unlinkSync(targetPath);
6199
7014
  } catch {
6200
7015
  }
6201
7016
  try {
6202
- fs10.unlinkSync(tempPath);
7017
+ fs11.unlinkSync(tempPath);
6203
7018
  } catch {
6204
7019
  }
6205
7020
  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 +7022,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6207
7022
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6208
7023
  }
6209
7024
  try {
6210
- fs10.unlinkSync(tempPath);
7025
+ fs11.unlinkSync(tempPath);
6211
7026
  } catch {
6212
7027
  }
6213
7028
  clearKernelVersionCache();
@@ -6234,28 +7049,23 @@ function assertKnownKernelFlags(args) {
6234
7049
  }
6235
7050
  async function cmdKernel(args) {
6236
7051
  assertKnownKernelFlags(args);
6237
- const mirrorInfo = parseMirrorArg(args);
7052
+ const savedMirror = readSettings().kernel_mirror ?? null;
7053
+ const mirrorInfo = parseMirrorArg(args, savedMirror);
6238
7054
  const effectiveMirror = mirrorInfo.mirror;
7055
+ if (mirrorInfo.remember) {
7056
+ writeSettings({ kernel_mirror: mirrorInfo.mirror ?? void 0 });
7057
+ } else if (mirrorInfo.clearSaved && savedMirror) {
7058
+ writeSettings({ kernel_mirror: void 0 });
7059
+ }
6239
7060
  if (effectiveMirror) {
6240
- console.log(`\u955C\u50CF: ${effectiveMirror} (\u4EC5\u4E0B\u8F7D\u8D70\u955C\u50CF\uFF0C\u7248\u672C\u67E5\u8BE2\u6052\u76F4\u8FDE)`);
7061
+ const host = effectiveMirror.replace(/^https?:\/\//, "").replace(/\/$/, "");
7062
+ 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";
7063
+ console.log(`\u955C\u50CF: ${host} (${note})`);
6241
7064
  console.log("");
6242
7065
  }
6243
- console.log("\u68C0\u67E5\u5185\u6838\u66F4\u65B0...");
7066
+ let info;
6244
7067
  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
- }
7068
+ info = await withSpinner("\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09", () => checkUpdate());
6259
7069
  } catch (e) {
6260
7070
  if (e instanceof CliError) throw e;
6261
7071
  const err = e;
@@ -6270,12 +7080,25 @@ async function cmdKernel(args) {
6270
7080
  hint.push(
6271
7081
  "",
6272
7082
  "\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",
7083
+ " 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
7084
  ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
6275
7085
  );
6276
7086
  }
6277
7087
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
6278
7088
  }
7089
+ console.log(`\u5F53\u524D: ${info.current}`);
7090
+ console.log(`\u6700\u65B0: ${info.latest}`);
7091
+ if (!info.needsUpdate) {
7092
+ console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
7093
+ } else {
7094
+ console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
7095
+ const result = await downloadKernel((msg) => console.log(msg), mirrorInfo.mirror, info.release);
7096
+ console.log(`
7097
+ \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
7098
+ if (getRunningState().running) {
7099
+ 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"));
7100
+ }
7101
+ }
6279
7102
  }
6280
7103
 
6281
7104
  // src/commands/log.ts
@@ -6307,110 +7130,43 @@ function cmdLogs(args) {
6307
7130
  viewLogWithTail(logPath, { follow, lines });
6308
7131
  return;
6309
7132
  }
6310
- const logs = listLogs();
6311
- const all = [];
6312
- if (logs.current) all.push(logs.current);
6313
- all.push(...logs.archives);
6314
- if (all.length === 0) {
6315
- console.log("\u6682\u65E0\u65E5\u5FD7");
6316
- return;
6317
- }
6318
- console.log("");
6319
- console.log("\u65E5\u5FD7\u5217\u8868:");
6320
- console.log("");
6321
- let archiveCounter = 0;
6322
- for (const log of all) {
6323
- let num;
6324
- if (log.isCurrent) {
6325
- num = " 0";
6326
- } else {
6327
- archiveCounter++;
6328
- num = archiveCounter < 10 ? ` ${archiveCounter}` : `${archiveCounter}`;
6329
- }
6330
- const time = formatDate(log.mtime);
6331
- const size = formatBytes(log.size);
6332
- const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
6333
- console.log(` ${num}. ${name}`);
6334
- console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
6335
- if (!log.isCurrent) {
6336
- console.log(` \u67E5\u770B: mihomo logs ${archiveCounter} \u6216 mihomo logs ${archiveCounter} -o`);
6337
- }
6338
- console.log("");
6339
- }
6340
- console.log("\u7528\u6CD5:");
6341
- console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
6342
- console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
6343
- console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
6344
- console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
6345
- console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
6346
- console.log("");
6347
- }
6348
-
6349
- // src/commands/overwrite.ts
6350
- import path8 from "path";
6351
- function printOverwriteList() {
6352
- const info = listOverwriteFile();
6353
- const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6354
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6355
- console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6356
- console.log("");
6357
- if (info.files.length === 0) {
6358
- console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6359
- console.log("");
6360
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6361
- console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6362
- console.log("");
6363
- } else {
6364
- console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
6365
- console.log("");
6366
- info.files.forEach((f, i) => {
6367
- const num = i < 10 ? ` ${i}` : `${i}`;
6368
- console.log(` ${num}. ${f.name}`);
6369
- if (f.scope) {
6370
- console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6371
- }
6372
- if (f.keys.length > 0) {
6373
- console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6374
- }
6375
- });
6376
- console.log("");
6377
- }
6378
- console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6379
- console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6380
- console.log("");
6381
- }
6382
- async function setOverwrite(enabled, args) {
6383
- if (isOverwriteEnabled() === enabled) {
6384
- console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
6385
- console.log("");
6386
- printOverwriteList();
7133
+ const logs = listLogs();
7134
+ const all = [];
7135
+ if (logs.current) all.push(logs.current);
7136
+ all.push(...logs.archives);
7137
+ if (all.length === 0) {
7138
+ console.log("\u6682\u65E0\u65E5\u5FD7");
6387
7139
  return;
6388
7140
  }
6389
- setOverwriteEnabled(enabled);
6390
- console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
6391
- if (await restartToApply(args)) return;
6392
7141
  console.log("");
6393
- printOverwriteList();
6394
- }
6395
- var SUBCOMMANDS2 = [
6396
- { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
6397
- { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
6398
- ];
6399
- async function cmdOverwrite(args) {
6400
- await dispatchSubcommand(args, SUBCOMMANDS2, {
6401
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6402
- fallback: () => {
6403
- console.log("");
6404
- printOverwriteList();
6405
- },
6406
- onUnknown: (action) => {
6407
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6408
- const suggestion = suggestSimilar(action, names);
6409
- throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6410
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6411
- });
7142
+ console.log("\u65E5\u5FD7\u5217\u8868:");
7143
+ console.log("");
7144
+ let archiveCounter = 0;
7145
+ for (const log of all) {
7146
+ let num;
7147
+ if (log.isCurrent) {
7148
+ num = " 0";
7149
+ } else {
7150
+ archiveCounter++;
7151
+ num = archiveCounter < 10 ? ` ${archiveCounter}` : `${archiveCounter}`;
6412
7152
  }
6413
- });
7153
+ const time = formatDate(log.mtime);
7154
+ const size = formatBytes(log.size);
7155
+ const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
7156
+ console.log(` ${num}. ${name}`);
7157
+ console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
7158
+ if (!log.isCurrent) {
7159
+ console.log(` \u67E5\u770B: mihomo logs ${archiveCounter} \u6216 mihomo logs ${archiveCounter} -o`);
7160
+ }
7161
+ console.log("");
7162
+ }
7163
+ console.log("\u7528\u6CD5:");
7164
+ console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
7165
+ console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
7166
+ console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
7167
+ console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
7168
+ console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
7169
+ console.log("");
6414
7170
  }
6415
7171
 
6416
7172
  // src/commands/removed.ts
@@ -6421,30 +7177,30 @@ function removedCommand(name, version, hint) {
6421
7177
  }
6422
7178
 
6423
7179
  // src/commands/reset.ts
6424
- import fs12 from "fs";
7180
+ import fs13 from "fs";
6425
7181
 
6426
7182
  // src/process-stop.ts
6427
- import { spawnSync as spawnSync6 } from "child_process";
6428
- import fs11 from "fs";
7183
+ import { spawnSync as spawnSync7 } from "child_process";
7184
+ import fs12 from "fs";
6429
7185
  var PROCESS_WAIT_ATTEMPTS = 50;
6430
7186
  var PROCESS_WAIT_INTERVAL = 100;
6431
7187
  var BATCH_KILL_THRESHOLD = 3;
6432
7188
  function clearRuntime() {
6433
- if (fs11.existsSync(DIRS.runtime)) {
7189
+ if (fs12.existsSync(DIRS.runtime)) {
6434
7190
  rmrf(DIRS.runtime);
6435
7191
  }
6436
7192
  ensureDirs();
6437
7193
  }
6438
7194
  function clearPid() {
6439
- if (!fs11.existsSync(PATHS.pidFile)) return;
7195
+ if (!fs12.existsSync(PATHS.pidFile)) return;
6440
7196
  if (isPidFileOwnedByRoot()) {
6441
7197
  try {
6442
- spawnSync6("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
7198
+ spawnSync7("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
6443
7199
  } catch {
6444
7200
  }
6445
7201
  } else {
6446
7202
  try {
6447
- fs11.unlinkSync(PATHS.pidFile);
7203
+ fs12.unlinkSync(PATHS.pidFile);
6448
7204
  } catch {
6449
7205
  }
6450
7206
  }
@@ -6462,7 +7218,7 @@ function killAllMihomo(forceSudo = false) {
6462
7218
  const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
6463
7219
  const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
6464
7220
  try {
6465
- const result = spawnSync6(argv[0], argv[1], options);
7221
+ const result = spawnSync7(argv[0], argv[1], options);
6466
7222
  if (result.error) return false;
6467
7223
  return result.status === 0 || result.status === 1;
6468
7224
  } catch {
@@ -6591,8 +7347,8 @@ var RESET_TARGETS = [
6591
7347
  label: "\u8986\u5199",
6592
7348
  paths: () => {
6593
7349
  const dir = USER_DATA_DIR;
6594
- if (!fs12.existsSync(dir)) return [];
6595
- return fs12.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7350
+ if (!fs13.existsSync(dir)) return [];
7351
+ return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6596
7352
  },
6597
7353
  needsStop: false
6598
7354
  },
@@ -6733,7 +7489,7 @@ async function cmdReset(args) {
6733
7489
  }
6734
7490
  for (const t of targets) {
6735
7491
  for (const p of t.paths()) {
6736
- if (fs12.existsSync(p)) {
7492
+ if (fs13.existsSync(p)) {
6737
7493
  try {
6738
7494
  rmrf(p);
6739
7495
  } catch (e) {
@@ -6751,7 +7507,7 @@ async function cmdReset(args) {
6751
7507
  }
6752
7508
 
6753
7509
  // src/commands/service.ts
6754
- import fs13 from "fs";
7510
+ import fs14 from "fs";
6755
7511
  async function handleLegacyInstall() {
6756
7512
  if (!detectLegacySystemInstall()) return;
6757
7513
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -6786,7 +7542,7 @@ async function cmdInstall(_args) {
6786
7542
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
6787
7543
  } else {
6788
7544
  console.log("\u542F\u52A8: mihomo start");
6789
- if (!fs13.existsSync(PATHS.configFile)) {
7545
+ if (!fs14.existsSync(PATHS.configFile)) {
6790
7546
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
6791
7547
  }
6792
7548
  }
@@ -6862,190 +7618,15 @@ async function cmdStop(args) {
6862
7618
  console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
6863
7619
  }
6864
7620
 
6865
- // src/commands/subscription.ts
6866
- function printRestartHintIfRunning() {
6867
- if (getRunningState().running) {
6868
- console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C mihomo start \u4F7F\u66F4\u65B0\u751F\u6548"));
6869
- console.log("");
6870
- }
6871
- }
6872
- function printSubscriptionList() {
6873
- const subs = getSubscriptionsWithCache();
6874
- if (subs.length === 0) {
6875
- console.log("\u6CA1\u6709\u8BA2\u9605");
6876
- console.log("");
6877
- console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
6878
- console.log("");
6879
- return;
6880
- }
6881
- const activeSub = getActiveSubscription();
6882
- console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
6883
- subs.forEach((s, i) => {
6884
- const time = formatDate(s.updated_at);
6885
- const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
6886
- const interval = resolveUpdateInterval(s.url, s.update_interval);
6887
- console.log(` ${i + 1}. ${s.name}${defaultMark}`);
6888
- console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
6889
- if (s.username) {
6890
- console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
6891
- }
6892
- const traffic = formatTraffic(s.upload, s.download, s.total);
6893
- if (traffic) {
6894
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
6895
- }
6896
- if (s.expire !== void 0) {
6897
- console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
6898
- }
6899
- if (s.web_page_url) {
6900
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
6901
- }
6902
- });
6903
- console.log("");
6904
- console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
6905
- console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
6906
- console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
6907
- console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
6908
- console.log("");
6909
- }
6910
- function assertNotFlagLike(name, usage) {
6911
- if (name.startsWith("-")) {
6912
- throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
6913
- label: "\u53C2\u6570\u9519\u8BEF",
6914
- hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
6915
- });
6916
- }
6917
- }
6918
- async function subAdd(args) {
6919
- const url = args[2]?.trim();
6920
- const name = args[3] || "default";
6921
- if (!url) {
6922
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL");
6923
- }
6924
- if (!isValidHttpUrl(url)) {
6925
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
6926
- }
6927
- assertNotFlagLike(name, "mihomo sub add <url> [name]");
6928
- console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
6929
- addSubscription(url, name);
7621
+ // src/commands/ui.ts
7622
+ import { spawnSync as spawnSync8 } from "child_process";
7623
+ function copyToClipboard(text) {
6930
7624
  try {
6931
- const info = await downloadSubscription(url, name);
6932
- setDefaultSubscription(name);
6933
- console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
6934
- } catch (e) {
6935
- removeSubscription(name);
6936
- if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
6937
- throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
6938
- }
6939
- console.log("");
6940
- printSubscriptionList();
6941
- }
6942
- async function subUpdate(args) {
6943
- const name = args[2];
6944
- const subs = getSubscriptions();
6945
- if (subs.length === 0) {
6946
- throw new CliError("\u6CA1\u6709\u8BA2\u9605");
6947
- }
6948
- if (!name) {
6949
- console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
6950
- const results = await Promise.all(subs.map((sub) => tryUpdateOne(sub)));
6951
- let ok = 0;
6952
- for (const r of results) {
6953
- if (r.success) ok++;
6954
- printUpdateResult(r);
6955
- }
6956
- if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
6957
- console.log("");
6958
- printRestartHintIfRunning();
6959
- printSubscriptionList();
6960
- return;
6961
- }
6962
- const target = resolveSubscription(subs, name);
6963
- console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
6964
- const result = await tryUpdateOne(target);
6965
- if (!result.success) {
6966
- throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
6967
- }
6968
- console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
6969
- console.log("");
6970
- printRestartHintIfRunning();
6971
- printSubscriptionList();
6972
- }
6973
- async function subUse(args) {
6974
- const name = args[2];
6975
- const subs = getSubscriptions();
6976
- if (!name) {
6977
- 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
6979
- });
6980
- }
6981
- const target = resolveSubscription(subs, name);
6982
- const currentDefault = getActiveSubscription();
6983
- const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
6984
- if (isAlreadyDefault) {
6985
- console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
6986
- console.log("");
6987
- printSubscriptionList();
6988
- return;
6989
- }
6990
- const success = setDefaultSubscription(target.name);
6991
- if (!success) {
6992
- throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
6993
- }
6994
- console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
6995
- if (await restartToApply(args)) return;
6996
- console.log("");
6997
- printSubscriptionList();
6998
- }
6999
- async function subRemove(args) {
7000
- const name = getNonFlagArg(args, 2);
7001
- const subs = getSubscriptions();
7002
- if (!name) {
7003
- throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
7004
- hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
7005
- });
7006
- }
7007
- const target = resolveSubscription(subs, name);
7008
- const isExact = target.name === name;
7009
- const skipConfirm = hasFlag(args, "-y", "--yes");
7010
- if (!isExact && !skipConfirm) {
7011
- console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7012
- if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7013
- nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7014
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7015
- })) {
7016
- console.log("\u5DF2\u53D6\u6D88");
7017
- return;
7018
- }
7019
- }
7020
- const switchedTo = removeSubscription(target.name);
7021
- console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
7022
- if (switchedTo) {
7023
- console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
7625
+ return spawnSync8("pbcopy", [], { input: text }).status === 0;
7626
+ } catch {
7627
+ return false;
7024
7628
  }
7025
- console.log("");
7026
- printSubscriptionList();
7027
- }
7028
- var SUBCOMMANDS3 = [
7029
- { name: "add", handler: subAdd },
7030
- { name: "update", handler: subUpdate },
7031
- { name: "use", handler: subUse },
7032
- { name: "remove", aliases: ["rm", "delete"], handler: subRemove }
7033
- ];
7034
- async function cmdSubscription(args) {
7035
- await dispatchSubcommand(args, SUBCOMMANDS3, {
7036
- // 无子命令 → 列表;未知子命令 → 报错
7037
- fallback: printSubscriptionList,
7038
- onUnknown: (action) => {
7039
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7040
- const suggestion = suggestSimilar(action, names);
7041
- throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7042
- 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"]
7043
- });
7044
- }
7045
- });
7046
7629
  }
7047
-
7048
- // src/commands/ui.ts
7049
7630
  function cmdUI(args) {
7050
7631
  const uiName = args[1] || "zash";
7051
7632
  if (!Object.hasOwn(UI_URLS, uiName)) {
@@ -7060,7 +7641,9 @@ function cmdUI(args) {
7060
7641
  console.log(`\u5730\u5740: ${url}`);
7061
7642
  const secret = readSettings().controller_secret;
7062
7643
  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");
7644
+ console.log(
7645
+ 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"
7646
+ );
7064
7647
  }
7065
7648
  const success = openUrl(url);
7066
7649
  if (!success) {
@@ -7069,13 +7652,13 @@ function cmdUI(args) {
7069
7652
  }
7070
7653
 
7071
7654
  // src/commands/update.ts
7072
- import { execFile, spawn as spawn2 } from "child_process";
7073
- import { promisify } from "util";
7074
- var execFileAsync = promisify(execFile);
7655
+ import { execFile as execFile2, spawn as spawn2 } from "child_process";
7656
+ import { promisify as promisify2 } from "util";
7657
+ var execFileAsync2 = promisify2(execFile2);
7075
7658
  var NPM_VIEW_TIMEOUT_MS = 15e3;
7076
7659
  async function getLatestNpmVersion() {
7077
7660
  try {
7078
- const { stdout } = await execFileAsync("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
7661
+ const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
7079
7662
  const version = stdout.trim().split("\n").pop()?.trim();
7080
7663
  return version || null;
7081
7664
  } catch {
@@ -7085,8 +7668,7 @@ async function getLatestNpmVersion() {
7085
7668
  async function cmdUpdate() {
7086
7669
  console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7087
7670
  console.log("");
7088
- console.log("\u6B63\u5728\u68C0\u67E5\u6700\u65B0\u7248\u672C...");
7089
- const latest = await getLatestNpmVersion();
7671
+ const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7090
7672
  if (latest && latest === VERSION) {
7091
7673
  console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7092
7674
  return;
@@ -7105,16 +7687,16 @@ async function cmdUpdate() {
7105
7687
  if (code === 0) {
7106
7688
  resolve();
7107
7689
  } else {
7108
- reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u53EF\u5C1D\u8BD5: sudo npm install -g mihomo-cli", { exitCode: code || 1 }));
7690
+ reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
7109
7691
  }
7110
7692
  });
7111
7693
  npm.on("error", (e) => {
7112
7694
  const perm = e.message.includes("EACCES") || e.message.includes("permission");
7113
- reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF0C\u53EF\u5C1D\u8BD5: sudo npm install -g mihomo-cli") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7695
+ reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7114
7696
  });
7115
7697
  });
7116
7698
  try {
7117
- const { stdout } = await execFileAsync("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7699
+ const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
7118
7700
  const result = JSON.parse(stdout);
7119
7701
  const newVersion = result.dependencies?.[PKG_NAME]?.version;
7120
7702
  console.log("");
@@ -7141,10 +7723,10 @@ var COMMANDS = [
7141
7723
  },
7142
7724
  {
7143
7725
  name: "start",
7144
- aliases: [],
7726
+ aliases: ["restart"],
7145
7727
  handler: cmdStart,
7146
7728
  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" }]
7729
+ 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
7730
  },
7149
7731
  {
7150
7732
  name: "tun",
@@ -7173,7 +7755,7 @@ var COMMANDS = [
7173
7755
  aliases: [],
7174
7756
  handler: printStatus,
7175
7757
  group: "control",
7176
- usage: [{ signature: "status", description: "\u67E5\u770B\u72B6\u6001" }]
7758
+ usage: [{ signature: "status [-j|--json] [--no-probe]", description: "\u67E5\u770B\u72B6\u6001" }]
7177
7759
  },
7178
7760
  // === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
7179
7761
  {
@@ -7188,21 +7770,24 @@ var COMMANDS = [
7188
7770
  "\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
7189
7771
  ]),
7190
7772
  group: "meta",
7191
- usage: []
7773
+ usage: [],
7774
+ hidden: true
7192
7775
  },
7193
7776
  {
7194
7777
  name: "up",
7195
7778
  aliases: [],
7196
7779
  handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
7197
7780
  group: "meta",
7198
- usage: []
7781
+ usage: [],
7782
+ hidden: true
7199
7783
  },
7200
7784
  {
7201
7785
  name: "down",
7202
7786
  aliases: [],
7203
7787
  handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
7204
7788
  group: "meta",
7205
- usage: []
7789
+ usage: [],
7790
+ hidden: true
7206
7791
  },
7207
7792
  // === 界面 ===
7208
7793
  {
@@ -7213,13 +7798,14 @@ var COMMANDS = [
7213
7798
  usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
7214
7799
  },
7215
7800
  {
7216
- // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
7801
+ // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空),也不进补全词表
7217
7802
  name: "log",
7218
7803
  aliases: [],
7219
7804
  handler: cmdLogs,
7220
7805
  rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
7221
7806
  group: "interface",
7222
- usage: []
7807
+ usage: [],
7808
+ hidden: true
7223
7809
  },
7224
7810
  {
7225
7811
  name: "logs",
@@ -7229,6 +7815,15 @@ var COMMANDS = [
7229
7815
  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
7816
  },
7231
7817
  // === 订阅 ===
7818
+ {
7819
+ // 顶层快捷方式:`mihomo use <name>` = `mihomo subscription use <name>`(与 tun 同范式)
7820
+ name: "use",
7821
+ aliases: [],
7822
+ handler: cmdSubscription,
7823
+ rewrite: (args) => ["subscription", "use", ...args.slice(1)],
7824
+ group: "subscription",
7825
+ usage: [{ signature: "use <name>", description: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF0C\u81EA\u52A8\u91CD\u542F\uFF09" }]
7826
+ },
7232
7827
  {
7233
7828
  name: "subscription",
7234
7829
  aliases: ["sub", "subs", "subscriptions"],
@@ -7285,6 +7880,20 @@ var COMMANDS = [
7285
7880
  group: "system",
7286
7881
  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
7882
  },
7883
+ {
7884
+ name: "doctor",
7885
+ aliases: [],
7886
+ handler: cmdDoctor,
7887
+ group: "system",
7888
+ 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" }]
7889
+ },
7890
+ {
7891
+ name: "completion",
7892
+ aliases: [],
7893
+ handler: (args) => cmdCompletion(args, COMMANDS),
7894
+ group: "system",
7895
+ usage: [{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C\uFF08eval \u6216\u5199\u5165\u8865\u5168\u76EE\u5F55\uFF09" }]
7896
+ },
7288
7897
  // === meta(不在分组清单展示,help 末尾单列) ===
7289
7898
  {
7290
7899
  name: "help",